def __init__(self, path, base_path=None): """Construct a FastPath from path.""" if base_path is None: self.base_path = osutils.basename(path) else: self.base_path = base_path self.raw_path = path
def validate_tree_is_controlfilename(self, tree): """check that 'tree' obeys the contract for is_control_filename.""" bzrdirname = basename(tree.bzrdir.transport.base[:-1]) self.assertTrue(tree.is_control_filename(bzrdirname)) self.assertTrue(tree.is_control_filename(bzrdirname + '/subdir')) self.assertFalse(tree.is_control_filename('dir/' + bzrdirname)) self.assertFalse(tree.is_control_filename('dir/' + bzrdirname + '/sub'))
def _default_to_location(self, from_location): """Work out a good To location give a From location. :return: the To location or None if unsure """ # We want to avoid opening the from location here so # we 'guess' the basename using some simple heuristics from_location = from_location.replace('\\', '/').rstrip('/') if from_location.find('/') >= 0: basename = osutils.basename(from_location) else: # Handle 'directory services' like lp: ds_sep = from_location.find(':') if ds_sep >= 0: basename = from_location[ds_sep + 1:] else: return None # Calculate the To location and check it's not the same as the # From location. to_location = osutils.pathjoin(self.parent_dir, basename) if to_location == from_location: return None else: return to_location
def _parse_entry(path, file_id, parent_id, last_modified, content): entry_factory = { 'dir': _dir_to_entry, 'file': _file_to_entry, 'link': _link_to_entry, 'tree': _tree_to_entry, } kind = content[0] if path.startswith('/'): raise AssertionError name = basename(path) return entry_factory[content[0]]( content, name, parent_id, file_id, last_modified)
def test_create_anonymous_heavyweight_checkout(self): """A regular checkout from a readonly branch should succeed.""" tree_a = self.make_branch_and_tree("a") rev_id = tree_a.commit("put some content in the branch") # open the branch via a readonly transport url = self.get_readonly_url(osutils.basename(tree_a.branch.base.rstrip("/"))) t = transport.get_transport_from_url(url) if not tree_a.branch.bzrdir._format.supports_transport(t): raise tests.TestNotApplicable("format does not support transport") source_branch = _mod_branch.Branch.open(url) # sanity check that the test will be valid self.assertRaises((errors.LockError, errors.TransportNotPossible), source_branch.lock_write) checkout = source_branch.create_checkout("c") self.assertEqual(rev_id, checkout.last_revision())
def perform_save(self, window): try: save_path = self.window._get_save_path(osutils.basename(self.path)) except SelectCancelled: return source = open(self.path, 'rb') try: target = open(save_path, 'wb') try: osutils.pumpfile(source, target) finally: target.close() finally: source.close()
def test_create_anonymous_heavyweight_checkout(self): """A regular checkout from a readonly branch should succeed.""" tree_a = self.make_branch_and_tree('a') rev_id = tree_a.commit('put some content in the branch') # open the branch via a readonly transport url = self.get_readonly_url( osutils.basename(tree_a.branch.base.rstrip('/'))) t = transport.get_transport_from_url(url) if not tree_a.branch.bzrdir._format.supports_transport(t): raise tests.TestNotApplicable("format does not support transport") source_branch = _mod_branch.Branch.open(url) # sanity check that the test will be valid self.assertRaises((errors.LockError, errors.TransportNotPossible), source_branch.lock_write) checkout = source_branch.create_checkout('c') self.assertEqual(rev_id, checkout.last_revision())
def _get_base_file_id(self, path, parent_ie): """Look for a file id in the base branch. First, if the base tree has the parent directory, we look for a file with the same name in that directory. Else, we look for an entry in the base tree with the same path. """ if self.base_tree.has_id(parent_ie.file_id): base_path = osutils.pathjoin( self.base_tree.id2path(parent_ie.file_id), osutils.basename(path)) base_id = self.base_tree.path2id(base_path) if base_id is not None: return (base_id, base_path) full_base_path = osutils.pathjoin(self.base_path, path) # This may return None, but it is our last attempt return self.base_tree.path2id(full_base_path), full_base_path
def write_files(self, rev_tree, file_id_list): """ Find the desired revision of each file, write it to our temporary directory. The directory will be removed when the ScratchArea is deleted. """ for file_id in file_id_list: if rev_tree.has_id(file_id): base_name = osutils.basename(rev_tree.id2path(file_id)) # write in binary mode, to avoid OS-specific translations: tmp_file = open(osutils.pathjoin(self.path, base_name), "wb") osutils.pumpfile(rev_tree.get_file(file_id), tmp_file) tmp_file.close() self._make_readonly() return
def write_files(self, rev_tree, file_id_list): """ Find the desired revision of each file, write it to our temporary directory. The directory will be removed when the ScratchArea is deleted. """ for file_id in file_id_list: if rev_tree.has_id(file_id): base_name = osutils.basename(rev_tree.id2path(file_id)) # write in binary mode, to avoid OS-specific translations: tmp_file = open(osutils.pathjoin(self.path, base_name), 'wb') osutils.pumpfile(rev_tree.get_file(file_id), tmp_file) tmp_file.close() self._make_readonly() return
def sendEmail(self, from_addr = '', to_addr = '', mail_subject = '', mail_body = '', attachment = None): ''' TODO - Description''' try: # This will try to send a HELO/EHLO command to check if the server is available, if not raises a exception self.smtpServer = smtp.SMTP('{0}:{1}'.format(self.smtpServerUrl, self.smtpServerPort)) # This flag is set to True only if the previous command succeed self.isSmtpOk = True self.smtpServer.starttls() self.smtpServer.login(self.username, self.password) mail = email.mime.Multipart.MIMEMultipart() mail['Subject'] = mail_subject mail['From'] = from_addr mail['To'] = to_addr body = email.mime.Text.MIMEText(mail_body) mail.attach(body) if attachment: with open (attachment, 'r') as file_path: mail.attach(MIMEApplication(file_path.read(), \ Content_Disposition='attachment; filename="{0}"'.format(basename(attachment)),\ Name=basename(attachment))) self.smtpServer.sendmail(from_addr,[to_addr], mail.as_string()) except smtp.SMTPSenderRefused as e: self.f_log.error("Please provide a valid e-mail address [{1}] - {0}".format(str(e), e.recipients[0])) except smtp.SMTPConnectError as e: self.f_log.error("Unable to connect to smtp server [{0}]".format(str(e))) except smtp.SMTPAuthenticationError as e: self.f_log.error("Please provide the correct username/password combination [{0}]".format(str(e))) except smtp.SMTPDataError as e: self.f_log.error("Unable to send the e-mail body message [{0}]".format(str(e))) except smtp.SMTPResponseException as e: self.f_log.error("ERROR {0}: {1}".format(e.smtp_code, e.smtp_error)) except socket.timeout as e: self.f_log.error("Connection timeout [{0}]".format(str(e))) except socket.gaierror as e: self.f_log.error("Please check your internet connection [{0}]".format(str(e))) except IOError as (errno, strerror): if errno == errno.ENOENT: self.f_log.error("The file attachment does not exists") self.f_log.error("ERROR {0} - {1}".format(errno, strerror))
def _create_temp_file_with_commit_template(infotext, ignoreline=DEFAULT_IGNORE_LINE, start_message=None): """Create temp file and write commit template in it. :param infotext: Text to be displayed at bottom of message for the user's reference; currently similar to 'bzr status'. The text is already encoded. :param ignoreline: The separator to use above the infotext. :param start_message: The text to place above the separator, if any. This will not be removed from the message after the user has edited it. The string is already encoded :return: 2-tuple (temp file name, hasinfo) """ import tempfile tmp_fileno, msgfilename = tempfile.mkstemp(prefix='bzr_log.', dir='.', text=True) msgfilename = osutils.basename(msgfilename) msgfile = os.fdopen(tmp_fileno, 'w') try: if start_message is not None: msgfile.write("%s\n" % start_message) if infotext is not None and infotext != "": hasinfo = True msgfile.write("\n\n%s\n\n%s" %(ignoreline, infotext)) else: hasinfo = False finally: msgfile.close() return (msgfilename, hasinfo)
def _create_temp_file_with_commit_template(infotext, ignoreline=DEFAULT_IGNORE_LINE, start_message=None): """Create temp file and write commit template in it. :param infotext: Text to be displayed at bottom of message for the user's reference; currently similar to 'bzr status'. The text is already encoded. :param ignoreline: The separator to use above the infotext. :param start_message: The text to place above the separator, if any. This will not be removed from the message after the user has edited it. The string is already encoded :return: 2-tuple (temp file name, hasinfo) """ import tempfile tmp_fileno, msgfilename = tempfile.mkstemp(prefix='bzr_log.', dir='.', text=True) msgfilename = osutils.basename(msgfilename) msgfile = os.fdopen(tmp_fileno, 'w') try: if start_message is not None: msgfile.write("%s\n" % start_message) if infotext is not None and infotext != "": hasinfo = True msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext)) else: hasinfo = False finally: msgfile.close() return (msgfilename, hasinfo)
def edit_commit_message_encoded(infotext, ignoreline=DEFAULT_IGNORE_LINE, start_message=None): """Let the user edit a commit message in a temp file. This is run if they don't give a message or message-containing file on the command line. :param infotext: Text to be displayed at bottom of message for the user's reference; currently similar to 'bzr status'. The string is already encoded :param ignoreline: The separator to use above the infotext. :param start_message: The text to place above the separator, if any. This will not be removed from the message after the user has edited it. The string is already encoded :return: commit message or None. """ msgfilename = None try: msgfilename, hasinfo = _create_temp_file_with_commit_template( infotext, ignoreline, start_message) if not msgfilename: return None basename = osutils.basename(msgfilename) msg_transport = transport.get_transport_from_path( osutils.dirname(msgfilename)) reference_content = msg_transport.get_bytes(basename) if not _run_editor(msgfilename): return None edited_content = msg_transport.get_bytes(basename) if edited_content == reference_content: if not ui.ui_factory.confirm_action( u"Commit message was not edited, use anyway", "bzrlib.msgeditor.unchanged", {}): # Returning "" makes cmd_commit raise 'empty commit message # specified' which is a reasonable error, given the user has # rejected using the unedited template. return "" started = False msg = [] lastline, nlines = 0, 0 # codecs.open() ALWAYS opens file in binary mode but we need text mode # 'rU' mode useful when bzr.exe used on Cygwin (bialix 20070430) f = file(msgfilename, 'rU') try: try: for line in codecs.getreader(osutils.get_user_encoding())(f): stripped_line = line.strip() # strip empty line before the log message starts if not started: if stripped_line != "": started = True else: continue # check for the ignore line only if there # is additional information at the end if hasinfo and stripped_line == ignoreline: break nlines += 1 # keep track of the last line that had some content if stripped_line != "": lastline = nlines msg.append(line) except UnicodeDecodeError: raise BadCommitMessageEncoding() finally: f.close() if len(msg) == 0: return "" # delete empty lines at the end del msg[lastline:] # add a newline at the end, if needed if not msg[-1].endswith("\n"): return "%s%s" % ("".join(msg), "\n") else: return "".join(msg) finally: # delete the msg file in any case if msgfilename is not None: try: os.unlink(msgfilename) except IOError, e: trace.warning("failed to unlink %s: %s; ignored", msgfilename, e)
def compare_using(tool, file_list=None, rev1=None, rev2=None): """ Compare two branches or revisions using an external tool. Determine which revisions of the file to compare, extract them if necessary, and run the comparison. Handle repository branches and non-local branches (see get_tree_files). """ tmp_prefix = 'bzr_diff-' # Find the tree(s) and the files associated with each: (b1, work_tree1, file_ids1, remainder) = get_tree_files(file_list) trees_to_lock = [work_tree1] if (len(remainder) > 0): (b2, work_tree2, file_ids2, remainder) = get_tree_files(remainder) b2_in_working_tree = isinstance(work_tree2, workingtree.WorkingTree) trees_to_lock.append(work_tree2) if (len(remainder) > 0): raise errors.BzrCommandError("Cannot compare more than two branches") if rev1 or rev2: raise errors.BzrCommandError("Cannot specify -r with multiple branches") else: b2 = None b2_in_working_tree = False get_read_locks(trees_to_lock) try: kind = work_tree1.inventory.get_file_kind(file_ids1[0]) in_subdir = (kind == 'directory' or kind == 'root_directory') in_working_tree = isinstance(work_tree1, workingtree.WorkingTree) # Decide which mode (tree or files) to use when writing to tmpdir: if (len(file_list) == 1 and not in_subdir): use_tree = False elif (b2 and not in_subdir): use_tree = False else: use_tree = True # Check if we need to adjust our tmpdir paths: if (len(file_list) == 1) or b2: if in_subdir: adjust_path = work_tree1.inventory.id2path(file_ids1[0]) else: adjust_path = osutils.basename(file_list[0]) else: adjust_path = '' cleanup = tool.supports('cleanup') finally: release_read_locks(trees_to_lock) try: # Use the 1st revision as the old version (basis_tree is the default): if rev1: old_tree = b1.repository.revision_tree(rev1.in_history(b1).rev_id) old_hint = "-rev%s" % rev1.in_history(b1).revno elif b2: old_tree = work_tree1 old_hint = '-' + b1.nick else: old_tree = b1.basis_tree() old_hint = "-basis" get_read_locks(trees_to_lock) try: # Use the 2nd revision as the new version (working_tree is the default): if rev2: new_tree = b1.repository.revision_tree(rev2.in_history(b1).rev_id) delta = get_diffs_or_stop(old_tree, new_tree, file_ids1) new_hint = "-rev%s" % rev2.in_history(b1).revno new_tmp_dir = NamedTemporaryDir(tmp_prefix, new_hint, cleanup) new_tmp_dir.write_stuff(new_tree, file_ids1, use_tree) new_path = osutils.pathjoin(new_tmp_dir.path, adjust_path) elif b2_in_working_tree: # Files from two different branches, branch2 has a working tree: delta = get_diffs_or_stop(old_tree, work_tree2, file_ids2) if (len(file_list) == 1): new_path = work_tree2.id2abspath(file_ids2[0]) else: new_path = work_tree2.abspath('') elif b2: # Files from two different branches, branch2 has no working tree: delta = get_diffs_or_stop(old_tree, work_tree2, file_ids2) new_hint = '-' + b2.nick new_tmp_dir = NamedTemporaryDir(tmp_prefix, new_hint, cleanup) new_tmp_dir.write_stuff(work_tree2, file_ids2, use_tree) new_path = osutils.pathjoin(new_tmp_dir.path, adjust_path) elif not in_working_tree: # Repository branch or remote branch, but only one revision: new_tree = b1.basis_tree() delta = get_diffs_or_stop(old_tree, new_tree, file_ids1) new_hint = "-basis" new_tmp_dir = NamedTemporaryDir(tmp_prefix, new_hint, cleanup) new_tmp_dir.write_stuff(new_tree, file_ids1, use_tree) new_path = osutils.pathjoin(new_tmp_dir.path, adjust_path) else: # Item(s) in working tree, just diff it in place: delta = get_diffs_or_stop(old_tree, work_tree1, file_ids1) if (len(file_list) == 1): new_path = work_tree1.id2abspath(file_ids1[0]) else: new_path = work_tree1.abspath('') # No exceptions yet, so we really do need to extract the old version: if b2 and in_working_tree: if (len(file_list) == 1): old_path = work_tree1.id2abspath(file_ids1[0]) else: old_path = work_tree1.abspath('') else: old_tmp_dir = NamedTemporaryDir(tmp_prefix, old_hint, cleanup) old_tmp_dir.write_stuff(old_tree, file_ids1, use_tree) old_path = osutils.pathjoin(old_tmp_dir.path, adjust_path) finally: # Release the locks before we start any interactive tools: release_read_locks(trees_to_lock) # Run the comparison: if (tool.supports('recursive')): result = tool.run(old_path, new_path) elif (len(file_list) == 1 and not in_subdir): result = tool.run(old_path, new_path) else: # Iterative diff: if adjust_path != '': path_list = [path.replace(adjust_path, '.', 1) for (path, file_id, kind, text_mods, meta_mods) in delta.modified if text_mods] else: path_list = [path for (path, file_id, kind, text_mods, meta_mods) in delta.modified if text_mods] result = tool.run(old_path, new_path, path_list) # Set the result, since external tools cannot be trusted to do so: result = 1 except NoDifferencesFound: result = 0 return result