1from __future__ import print_function, unicode_literals 2 3import os 4 5from rbtools.api.errors import APIError 6from rbtools.commands import Command, CommandError, Option 7 8 9class Attach(Command): 10 """Attach a file to a review request.""" 11 12 name = 'attach' 13 author = 'The Review Board Project' 14 args = '<review-request-id> <file>' 15 option_list = [ 16 Option('--filename', 17 dest='filename', 18 default=None, 19 help='Custom filename for the file attachment.'), 20 Option('--caption', 21 dest='caption', 22 default=None, 23 help='Caption for the file attachment.'), 24 Command.server_options, 25 Command.repository_options, 26 ] 27 28 def main(self, review_request_id, path_to_file): 29 self.repository_info, self.tool = self.initialize_scm_tool( 30 client_name=self.options.repository_type) 31 server_url = self.get_server_url(self.repository_info, self.tool) 32 api_client, api_root = self.get_api(server_url) 33 34 try: 35 review_request = api_root.get_review_request( 36 review_request_id=review_request_id) 37 except APIError as e: 38 raise CommandError('Error getting review request %s: %s' 39 % (review_request_id, e)) 40 41 try: 42 with open(path_to_file, 'rb') as f: 43 content = f.read() 44 except IOError: 45 raise CommandError('%s is not a valid file.' % path_to_file) 46 47 # Check if the user specified a custom filename, otherwise 48 # use the original filename. 49 filename = self.options.filename or os.path.basename(path_to_file) 50 51 try: 52 review_request.get_file_attachments().upload_attachment( 53 filename, content, self.options.caption) 54 except APIError as e: 55 raise CommandError('Error uploading file: %s' % e) 56 57 print('Uploaded %s to review request %s.' % 58 (path_to_file, review_request_id)) 59