Exemplo n.º 1
0
    def check(self):
        """ See if a folder's contents were modified or created. """
        try:
            self.read_cache_file()
            local_branch = Branch.open_containing(self.folder)[0]
            remote_branch = Branch.open_containing(local_branch.get_parent())[0]
            if local_branch.get_parent() != None:
                self.remote_branch_label = local_branch.get_parent().replace("%7E", "~")
                self.local_extra, self.remote_extra = find_unmerged(local_branch, remote_branch)

                if len(self.local_extra) != 0:
                    if int(self.local_extra[len(self.local_extra) - 1][0]) > self.local_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if len(self.remote_extra) != 0:
                    if int(self.remote_extra[len(self.remote_extra) - 1][0]) > self.remote_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if not self.local_extra and not self.remote_extra:
                    self.mark_as_read()
            else:
                self.set_error(_("No parent branch available, you will not be notified of differences and changes."))

        except NotBranchError, e:
            self.set_error(str(e))
Exemplo n.º 2
0
    def check(self):
        """ See if a folder's contents were modified or created. """
        try:
            self.read_cache_file()
            local_branch = Branch.open_containing(self.folder)[0]
            remote_branch = Branch.open_containing(
                local_branch.get_parent())[0]
            if local_branch.get_parent() != None:
                self.remote_branch_label = local_branch.get_parent().replace(
                    "%7E", "~")
                self.local_extra, self.remote_extra = find_unmerged(
                    local_branch, remote_branch)

                if len(self.local_extra) != 0:
                    if int(self.local_extra[len(self.local_extra) -
                                            1][0]) > self.local_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if len(self.remote_extra) != 0:
                    if int(self.remote_extra[len(self.remote_extra) -
                                             1][0]) > self.remote_branch_:
                        self.actually_changed = True
                        self.write_cache_file()

                if not self.local_extra and not self.remote_extra:
                    self.mark_as_read()
            else:
                self.set_error(
                    _("No parent branch available, you will not be notified of differences and changes."
                      ))

        except NotBranchError, e:
            self.set_error(str(e))
Exemplo n.º 3
0
 def from_source_tree(cls, source_tree):
     """
     Initialize :class:`~versiontools.bzr_support.BzrIntegration` by
     pointing at the source tree.  Any file or directory inside the
     source tree may be used.
     """
     branch = None
     try:
         import bzrlib
         if bzrlib.__version__ >= (2, 2, 1):
             # Python 2.4 the with keyword is not supported
             # and so you need to use the context manager manually, sigh.
             library_state = bzrlib.initialize()
             library_state.__enter__()
             try:
                 from bzrlib.branch import Branch
                 branch = Branch.open_containing(source_tree)[0]
             finally:
                 library_state.__exit__(None, None, None)
         else:
             from bzrlib.branch import Branch
             branch = Branch.open_containing(source_tree)[0]
     except Exception:
         from versiontools import get_exception_message
         message = get_exception_message(*sys.exc_info())
         logging.debug("Unable to get branch revision because "
                       "directory %r is not a bzr branch. Erorr: %s",
                       (source_tree, message))
     if branch:
         return cls(branch)
Exemplo n.º 4
0
 def from_source_tree(cls, source_tree):
     """
     Initialize :class:`~versiontools.bzr_support.BzrIntegration` by
     pointing at the source tree.  Any file or directory inside the
     source tree may be used.
     """
     branch = None
     try:
         import bzrlib
         if bzrlib.__version__ >= (2, 2, 1):
             # Python 2.4 the with keyword is not supported
             # and so you need to use the context manager manually, sigh.
             library_state = bzrlib.initialize()
             library_state.__enter__()
             try:
                 from bzrlib.branch import Branch
                 branch = Branch.open_containing(source_tree)[0]
             finally:
                 library_state.__exit__(None, None, None)
         else:
             from bzrlib.branch import Branch
             branch = Branch.open_containing(source_tree)[0]
     except Exception:
         from versiontools import get_exception_message
         message = get_exception_message(*sys.exc_info())
         logging.debug(
             "Unable to get branch revision because "
             "directory %r is not a bzr branch. Erorr: %s",
             (source_tree, message))
     if branch:
         return cls(branch)
Exemplo n.º 5
0
 def test_open_containing(self):
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url(''))
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url('g/p/q'))
     branch = self.make_branch('.')
     branch, relpath = Branch.open_containing(self.get_readonly_url(''))
     self.assertEqual('', relpath)
     branch, relpath = Branch.open_containing(self.get_readonly_url('g/p/q'))
     self.assertEqual('g/p/q', relpath)
Exemplo n.º 6
0
 def test_open_containing(self):
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url(''))
     self.assertRaises(NotBranchError, Branch.open_containing,
                       self.get_readonly_url('g/p/q'))
     branch = self.make_branch('.')
     branch, relpath = Branch.open_containing(self.get_readonly_url(''))
     self.assertEqual('', relpath)
     branch, relpath = Branch.open_containing(
         self.get_readonly_url('g/p/q'))
     self.assertEqual('g/p/q', relpath)
Exemplo n.º 7
0
def get_vcs_details():
    """Return (branch_nick, revno, revision_id) of this VCS branch.

    If this is a Git branch, then revno will be None.

    Returns (None, None, None) if the tree this code is running from
    is not a VCS branch.
    """
    global _vcs_details_cache
    if _vcs_details_cache is None:
        top = os.path.dirname(os.path.dirname(SCHEMA_DIR))
        if os.path.exists(os.path.join(top, ".git")):
            branch_nick = subprocess.check_output(
                ["git", "rev-parse", "--abbrev-ref", "HEAD"],
                universal_newlines=True).rstrip("\n")
            revno = None
            revision_id = subprocess.check_output(
                ["git", "rev-parse", "HEAD"],
                universal_newlines=True).rstrip("\n")
        else:
            try:
                branch = Branch.open_containing(SCHEMA_DIR)[0]
                revno, revision_id = branch.last_revision_info()
                branch_nick = branch.get_config().get_nickname()
            except NotBranchError:
                log.warning("Not a Bazaar branch - branch details unavailable")
                revision_id, revno, branch_nick = None, None, None
        _vcs_details_cache = (branch_nick, revno, revision_id)
    return _vcs_details_cache
Exemplo n.º 8
0
def find_version_number(show_nick=False):
    path = os.path.join(os.path.dirname(__file__), "..")

    # We're using a package
    if path.startswith('/usr'):
        output = subprocess.Popen(["dpkg-query", "-W", "python-launchpad-bugs"], 
                                   stdout=subprocess.PIPE).communicate()[0]
        try:
            return output.split()[1]
        except:
            # not installed as a package
            return "unknown"
    if HAVE_BZR:
        try:
            trace.be_quiet()
            trace.enable_default_logging()
            version = get_version_from_changelog(path)
            if os.path.islink(os.path.dirname(__file__)):
                path = os.path.realpath(os.path.dirname(__file__))
            branch = Branch.open_containing(path)[0]
            bzr_revno = branch.revno()
            if show_nick:
                nick = branch.nick
                return "%sr%s, branch nick: %s" % (version, bzr_revno, nick)
            else:
                return "%sr%s" % (version, bzr_revno)
        except:
            pass
    return "unknown"
Exemplo n.º 9
0
    def run(self, location=None, remember=False, directory=None, 
            no_rebase=False):
        from bzrlib import urlutils
        from bzrlib.bzrdir import BzrDir
        from bzrlib.errors import BzrCommandError, NoWorkingTree
        from bzrlib.trace import info
        from bzrlib.workingtree import WorkingTree
        from upgrade import update_workingtree_fileids

        if directory is None:
            directory = "."
        try:
            source_wt = WorkingTree.open_containing(directory)[0]
            source_branch = source_wt.branch
        except NoWorkingTree:
            source_branch = Branch.open_containing(directory)[0]
            source_wt = None
        stored_loc = source_branch.get_push_location()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No push location known or specified.")
            else:
                display_url = urlutils.unescape_for_display(stored_loc,
                        self.outf.encoding)
                self.outf.write("Using saved location: %s\n" % display_url)
                location = stored_loc

        bzrdir = BzrDir.open(location)
        target_branch = bzrdir.open_branch()
        target_branch.lock_write()
        try:
            if not isinstance(target_branch, ForeignBranch):
                info("target branch is not a foreign branch, using regular push.")
                target_branch.pull(source_branch)
                no_rebase = True
            else:
                revid_map = target_branch.dpull(source_branch)
            # We successfully created the target, remember it
            if source_branch.get_push_location() is None or remember:
                source_branch.set_push_location(target_branch.base)
            if not no_rebase:
                _, old_last_revid = source_branch.last_revision_info()
                new_last_revid = revid_map[old_last_revid]
                if source_wt is not None:
                    source_wt.pull(target_branch, overwrite=True, 
                                   stop_revision=new_last_revid)
                    source_wt.lock_write()
                    try:
                        update_workingtree_fileids(source_wt, 
                            source_wt.branch.repository.revision_tree(old_last_revid),
                            source_wt.branch.repository.revision_tree(new_last_revid))
                    finally:
                        source_wt.unlock()
                else:
                    source_branch.pull(target_branch, overwrite=True, 
                                       stop_revision=new_last_revid)
        finally:
            target_branch.unlock()
Exemplo n.º 10
0
 def set_title(self, command=None):
     try:
         b = Branch.open_containing('.')[0]
         version = "%s:%d" % (b.nick, b.revno())
     except:
         version = "[no version]"
     if command is None:
         command = ""
     sys.stdout.write(terminal.term_title("bzr %s %s" % (command, version)))
Exemplo n.º 11
0
 def set_title(self, command=None):
     try:
         b = Branch.open_containing('.')[0]
         version = "%s:%d" % (b.nick, b.revno())
     except:
         version = "[no version]"
     if command is None:
         command = ""
     sys.stdout.write(terminal.term_title("bzr %s %s" % (command, version)))
Exemplo n.º 12
0
 def _time_read_write(self):
     branch, relpath = Branch.open_containing("a")
     revision_history = branch.revision_history()
     bundle_text = StringIO()
     self.time(write_bundle, branch.repository, revision_history[-1],
               NULL_REVISION, bundle_text)
     bundle_text.seek(0)
     target_tree = self.make_branch_and_tree('b')
     bundle = self.time(read_bundle, bundle_text)
     self.time(install_bundle, target_tree.branch.repository, bundle)
Exemplo n.º 13
0
 def _time_read_write(self):
     branch, relpath = Branch.open_containing("a")
     revision_history = branch.revision_history()
     bundle_text = StringIO()
     self.time(write_bundle, branch.repository, revision_history[-1],
               NULL_REVISION, bundle_text)
     bundle_text.seek(0)
     target_tree = self.make_branch_and_tree('b')
     bundle = self.time(read_bundle, bundle_text)
     self.time(install_bundle, target_tree.branch.repository, bundle)
Exemplo n.º 14
0
 def _on_encoding_changed(self, encoding):
     """Event handler for EncodingSelector.
     It sets file text to browser again with new encoding.
     """
     self.encoding = encoding
     branch = self.branch
     if branch is None:
         branch = Branch.open_containing(self.filename)[0]
     if branch:
         get_set_encoding(encoding, branch)
     self._set_text(self.browser.edit, self.filename, self.text, self.encoding)
Exemplo n.º 15
0
    def run(self, from_location, to_location, revision=None):
        branch = Branch.open_containing('.')[0]
        root = local_path_from_url(branch.base)

        # select what do it
        if isdir(pathjoin(root, to_location, '.bzr')) or isdir(pathjoin(root, to_location, '.svn')):
            if branch.get_bound_location():
                cmd = ['update', to_location]
            else:
                cmd = ['pull', from_location, '--directory', to_location]
        else:
            if branch.get_bound_location():
                cmd = ['checkout', from_location, to_location]
            else:
                cmd = ['branch', from_location, to_location]

            # command branch don't create recursive directory
            dirs = to_location.rpartition('/')
            if dirs[0] != '' and not isdir(dirs[0]):
                os.makedirs(dirs[0].encode(get_user_encoding()))

        # if use revision options but not for 'update'
        if revision is not None:# and cmd[0] != 'update':
            cmd += ['--revision', revision[0].user_spec]

        note('Add external ' + ' '.join(cmd))
        run_bzr_catch_user_errors(cmd)

        bzrmeta = pathjoin(root, '.bzrmeta')
        if not isdir(bzrmeta):
            os.mkdir(bzrmeta)

        # add new branch to config and snapshot files
        line = from_location + ' ' + self._quoted_if_need(to_location)
        if revision:
            line += ' ' + revision[0].user_spec
        self._add_to_file(root, externals.CONFIG_PATH, line)
        self._add_to_file(root, externals.SNAPSHOT_PATH, line)

        # add ignore mask
        from bzrlib import IGNORE_FILENAME
        self._add_to_file(root, IGNORE_FILENAME, './' + to_location)

        # add config files to repository
        cmd = ['add',
            '.bzrignore',
            '.bzrmeta/externals',
            '.bzrmeta/externals-snapshot']
        run_bzr_catch_user_errors(cmd)
Exemplo n.º 16
0
    def log_cb(self, menu, vfs_file):
        # We can only cope with local files
        if vfs_file.get_uri_scheme() != 'file':
            return

        file = vfs_file.get_uri()

        # We only want to continue here if we get a NotBranchError
        try:
            branch, path = Branch.open_containing(file)
        except NotBranchError:
            return

        pp = start_viz_window(branch, [branch.last_revision()])
        pp.show()
        gtk.main()
Exemplo n.º 17
0
    def run(self, location, revision=None, merge_type=None, directory="."):
        from bzrlib.branch import Branch
        from bzrlib.workingtree import WorkingTree
        from bzrlib import ui
        from bzrlib.plugins.rewrite.rebase import (
            RebaseState1,
            regenerate_default_revid,
            WorkingTreeRevisionRewriter,
            )

        from_branch = Branch.open_containing(location)[0]

        if revision is not None:
            if len(revision) == 1:
                if revision[0] is not None:
                    todo = [revision[0].as_revision_id(from_branch)]
            elif len(revision) == 2:
                from_revno, from_revid = revision[0].in_history(from_branch)
                to_revno, to_revid = revision[1].in_history(from_branch)
                if to_revid is None:
                    to_revno = from_branch.revno()
                todo = []
                for revno in range(from_revno, to_revno + 1):
                    todo.append(from_branch.get_rev_id(revno))
            else:
                raise BzrCommandError(
                    "--revision takes only one or two arguments")
        else:
            raise BzrCommandError("--revision is mandatory")

        wt = WorkingTree.open(directory)
        wt.lock_write()
        try:
            state = RebaseState1(wt)
            replayer = WorkingTreeRevisionRewriter(wt, state, merge_type=merge_type)
            pb = ui.ui_factory.nested_progress_bar()
            try:
                for revid in todo:
                    pb.update("replaying commits", todo.index(revid), len(todo))
                    wt.branch.repository.fetch(from_branch.repository, revid)
                    newrevid = regenerate_default_revid(wt.branch.repository, revid)
                    replayer(revid, newrevid, [wt.last_revision()])
            finally:
                pb.finished()
        finally:
            wt.unlock()
Exemplo n.º 18
0
    def run(self,
            public_url=None,
            product='',
            branch_name='',
            branch_title='',
            branch_description='',
            author='',
            link_bug=None,
            dry_run=False):
        from bzrlib.plugins.launchpad.lp_registration import (
            LaunchpadService, BranchRegistrationRequest, BranchBugLinkRequest,
            DryRunLaunchpadService)
        if public_url is None:
            try:
                b = Branch.open_containing('.')[0]
            except NotBranchError:
                raise BzrCommandError('register-branch requires a public '
                    'branch url - see bzr help register-branch.')
            public_url = b.get_public_branch()
            if public_url is None:
                raise NoPublicBranch(b)

        rego = BranchRegistrationRequest(branch_url=public_url,
                                         branch_name=branch_name,
                                         branch_title=branch_title,
                                         branch_description=branch_description,
                                         product_name=product,
                                         author_email=author,
                                         )
        linko = BranchBugLinkRequest(branch_url=public_url,
                                     bug_id=link_bug)
        if not dry_run:
            service = LaunchpadService()
            # This gives back the xmlrpc url that can be used for future
            # operations on the branch.  It's not so useful to print to the
            # user since they can't do anything with it from a web browser; it
            # might be nice for the server to tell us about an html url as
            # well.
        else:
            # Run on service entirely in memory
            service = DryRunLaunchpadService()
        service.gather_user_credentials()
        branch_object_url = rego.submit(service)
        if link_bug:
            link_bug_url = linko.submit(service)
        print 'Branch registered.'
Exemplo n.º 19
0
def get_bzr_details():
    """Return (branch_nick, revno, revision_id) of this Bazaar branch.

    Returns (None, None, None) if the tree this code is running from
    is not a Bazaar branch.
    """
    global _bzr_details_cache
    if _bzr_details_cache is None:
        try:
            branch = Branch.open_containing(SCHEMA_DIR)[0]
            revno, revision_id = branch.last_revision_info()
            branch_nick = branch.get_config().get_nickname()
        except NotBranchError:
            log.warning("Not a Bazaar branch - branch details unavailable")
            revision_id, revno, branch_nick = None, None, None
        _bzr_details_cache = (branch_nick, revno, revision_id)
    return _bzr_details_cache
Exemplo n.º 20
0
def get_bzr_details():
    """Return (branch_nick, revno, revision_id) of this Bazaar branch.

    Returns (None, None, None) if the tree this code is running from
    is not a Bazaar branch.
    """
    global _bzr_details_cache
    if _bzr_details_cache is None:
        try:
            branch = Branch.open_containing(SCHEMA_DIR)[0]
            revno, revision_id = branch.last_revision_info()
            branch_nick = branch.get_config().get_nickname()
        except NotBranchError:
            log.warning("Not a Bazaar branch - branch details unavailable")
            revision_id, revno, branch_nick = None, None, None
        _bzr_details_cache = (branch_nick, revno, revision_id)
    return _bzr_details_cache
Exemplo n.º 21
0
 def set_rev_bzr_version(self, paths):
     for path in paths:
         try:
             branch, rel_path = Bzr.open_containing(path)
             branch.lock_read()
             # Clean name
             name = branch.get_parent()
             name = name.replace(u'bazaar.launchpad.net/', u'lp:')
             name = name.replace(u'%7E', u'~')
             name = name.replace(u'%2Bbranch/', u'')
             name = name.replace(u'bzr+ssh://', u'')
             self.revnos[name] = u'r%i' % branch.revno()
             branch.unlock()
         except NotBranchError:
             continue
         finally:
             if branch.is_locked():
                 branch.unlock()
Exemplo n.º 22
0
    def _on_merge_clicked(self, widget):
        merge_source = self._combo_source.get_active()
        if merge_source == 0:
            branch = self._filechooser.get_filename()
        elif merge_source == 1:
            branch = self._custom_entry.get_text()
        if branch == "":
            error_dialog(_i18n('Branch not given'),
                         _i18n('Please specify a branch to merge from.'))
            return

        other_branch = Branch.open_containing(branch)[0]

        try:
            conflicts = self.wt.merge_from_branch(other_branch)
        except errors.BzrCommandError, errmsg:
            error_dialog(_i18n('Bazaar command error'), str(errmsg))
            return
Exemplo n.º 23
0
    def load(self):
        self.throbber.show()
        self.processEvents()
        try:
            if not self.tree:
                branch, relpath = Branch.open_containing(self.filename)
                self.branch = branch
                self.encoding = get_set_encoding(self.encoding, branch)
                self.encoding_selector.encoding = self.encoding

                if self.revision is None:
                    self.tree = branch.basis_tree()
                else:
                    revision_id = self.revision[0].in_branch(branch).rev_id
                    self.tree = branch.repository.revision_tree(revision_id)
                
                self.file_id = self.tree.path2id(relpath)
            
            if not self.file_id:
                self.file_id = self.tree.path2id(self.filename)
                
            if not self.file_id:
                raise errors.BzrCommandError(
                    "%r is not present in revision %s" % (
                        self.filename, self.tree.get_revision_id()))
            
            self.tree.lock_read()
            try:
                kind = self.tree.kind(self.file_id)
                if kind == 'file':
                    text = self.tree.get_file_text(self.file_id)
                elif kind == 'symlink':
                    text = self.tree.get_symlink_target(self.file_id)
                else:
                    text = ''
            finally:
                self.tree.unlock()
            self.processEvents()

            self.text = text
            self.kind = kind
            self._create_and_show_browser(self.filename, text, kind)
        finally:
            self.throbber.hide()
Exemplo n.º 24
0
 def look_up(self, name, url):
     branch = Branch.open_containing('.')[0]
     lookups = {
         'parent': branch.get_parent,
         'submit': branch.get_submit_branch,
         'public': branch.get_public_branch,
         'bound': branch.get_bound_location,
         'push': branch.get_push_location,
         'this': lambda: branch.base
     }
     try:
         method = lookups[url[1:]]
     except KeyError:
         raise errors.InvalidLocationAlias(url)
     else:
         result = method()
     if result is None:
         raise errors.UnsetLocationAlias(url)
     return result
Exemplo n.º 25
0
 def look_up(self, name, url):
     branch = Branch.open_containing('.')[0]
     lookups = {
         'parent': branch.get_parent,
         'submit': branch.get_submit_branch,
         'public': branch.get_public_branch,
         'bound': branch.get_bound_location,
         'push': branch.get_push_location,
         'this': lambda: branch.base
     }
     try:
         method = lookups[url[1:]]
     except KeyError:
         raise errors.InvalidLocationAlias(url)
     else:
         result = method()
     if result is None:
         raise errors.UnsetLocationAlias(url)
     return result
Exemplo n.º 26
0
    def run(
        self,
        source=None,
        destination=None,
        verbose=False,
        git_branch="master",
        checkpoint=10000,
        marks=None,
        import_marks=None,
        export_marks=None,
        revision=None,
        plain=True,
        rewrite_tag_names=False,
        baseline=False,
    ):
        load_fastimport()
        from bzrlib.branch import Branch
        from bzrlib.plugins.fastimport import exporter

        if marks:
            import_marks = export_marks = marks

        # Open the source
        if source is None:
            source = "."
        branch = Branch.open_containing(source)[0]
        outf = exporter._get_output_stream(destination)
        exporter = exporter.BzrFastExporter(
            branch,
            outf=outf,
            ref="refs/heads/%s" % git_branch,
            checkpoint=checkpoint,
            import_marks_file=import_marks,
            export_marks_file=export_marks,
            revision=revision,
            verbose=verbose,
            plain_format=plain,
            rewrite_tags=rewrite_tag_names,
            baseline=baseline,
        )
        return exporter.run()
Exemplo n.º 27
0
 def get_revisions(self):
     res = {}
     curr_date = datetime.now()
     for branch, location in self.locations.items():
         b = Branch.open_containing(location)[0]
         current_revision = b.revno()
         if branch not in self.last_revno:
             self.last_revno[branch] = 0
         if not self.last_revno[branch]:
             self.get_tags(branch, location)
             self.last_revno[branch] = current_revision
             continue
         else:
             revisions = b.revision_history()[self.last_revno[branch]:]
             self.last_revno[branch] = current_revision
             if self.open_file[branch]:
                 fp = open(self.open_file[branch], 'ab+')
             else:
                 self.get_tags(branch, location)
             bugs = []
             for r in revisions:
                 rev = b.repository.get_revision(r)
                 rev_no = b.revision_id_to_revno(r)
                 msg = rev.get_summary().encode('utf-8')
                 app_authors = [rev.get_apparent_author().encode('utf-8')
                                ]  #rev.get_apparent_authors()
                 ass_bugs = [[rev_no, bug] for bug in rev.iter_bugs()]
                 bugs.append(ass_bugs)
                 try:
                     fp.write("%s %s  %s by  %s\r" %
                              (str(rev_no), msg, ','.join(ass_bugs),
                               ','.join(app_authors)))
                 except:
                     nt_str.append(msg)
             for item in bugs:
                 for bug in item:
                     rev_no = bug[0]
                     bug = bug[1]
                     fp.write("%s\t%s\n" % (rev_no, '\t'.join(bug)))
             fp.close()
     return True
Exemplo n.º 28
0
 def get_revisions(self):
     res = {}
     curr_date = datetime.now()        
     for branch, location in self.locations.items():            
         b = Branch.open_containing(location)[0]
         current_revision = b.revno()
         if branch not in self.last_revno:
             self.last_revno[branch] = 0
         if not self.last_revno[branch]:
             self.get_tags(branch,location)
             self.last_revno[branch] = current_revision
             continue
         else:
             revisions = b.revision_history()[self.last_revno[branch]:]
             self.last_revno[branch] = current_revision
             if self.open_file[branch]:
                 fp = open(self.open_file[branch],'ab+')
             else:
                 self.get_tags(branch,location)
             bugs=[]
             for r in revisions:
                 rev = b.repository.get_revision(r)
                 rev_no = b.revision_id_to_revno(r)
                 msg = rev.get_summary().encode('utf-8')
                 app_authors = [rev.get_apparent_author().encode('utf-8')] #rev.get_apparent_authors()
                 ass_bugs =[[rev_no,bug] for bug in rev.iter_bugs()]
                 bugs.append(ass_bugs)
                 try:
                     fp.write("%s %s  %s by  %s\r"%(str(rev_no),msg,','.join(ass_bugs),','.join(app_authors)))
                 except:
                     nt_str.append(msg)
             for item in bugs:
                 for bug in item:
                     rev_no=bug[0]
                     bug=bug[1]
                     fp.write("%s\t%s\n"%(rev_no,'\t'.join(bug)))
             fp.close()
     return True
Exemplo n.º 29
0
def get_version_from_bazaar(version = __version__, full = False):
    """Returns the version number combined with the bzr revision number.
    Set `full` to True for revision id."""

    # If the user does not have bazaar, then return unknown
    try:
        from bzrlib.branch import Branch
        from bzrlib.errors import NotBranchError
    except ImportError:
        return version + "-unknown"

    import os
    # Save the old location
    start_dir = os.path.abspath(os.curdir)

    # Make sure we get the correct branch location.
    # Even with symlinks

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # Try to use the branch.
    try:
        pixelise_branch = Branch.open_containing(os.path.abspath('.'))[0]
    except NotBranchError:
        # Oh well give up and go to the original directory.
        os.chdir(start_dir)
        return version + "-unknown"

    # Go to the original directory.
    os.chdir(start_dir)
    # Add the pixelise branch revison number to the version number.
    version_number = version + "-" + str(pixelise_branch.revno())
    if full:
        # If `full` is true then add the last revision too.
        version_number += "-" + pixelise_branch.last_revision()
    # Return the version number
    return version_number
Exemplo n.º 30
0
    def __init__(self, location, pollinterval=60*60, callback=False):
        """
        @type  location: string
        @param location: the URL of the branch that this poller should watch.
                         This is typically an http: or sftp: URL.

        @type  pollinterval: int
        @param pollinterval: interval in seconds between polls. The default
                             is 3600 seconds (1 hour). Smaller values
                             decrease the latency between the time a change
                             is recorded and the time the buildbot notices
                             it, but it also increases the system load.
        """
        service.MultiService.__init__(self)

        self.location = location
        self.last_revno = 0
        self.pollinterval = pollinterval
        self.overrun_counter = 0
        self.callback = callback
        self.branch = Branch.open_containing(self.location)[0]
        # bzrlib.trace.enable_default_logging()
        timer = internet.TimerService(pollinterval, self.poll)
        timer.setServiceParent(self)
Exemplo n.º 31
0
    def run(self):
        from bzrlib.branch import Branch
        from bzrlib.errors import NoWorkingTree
        from bzrlib.workingtree import WorkingTree
        from bzrlib import urlutils

        import os
        from PyQt4 import QtCore, QtGui
        from qctlib.gui_logic import CommitTool
        from qctlib.vcs.bzr import qctVcsBzr

        def local_path(path):
            if path.startswith("file://"):
                return urlutils.local_path_from_url(path)
            else:
                return urlutils.unescape(path)

        try:
            branch = WorkingTree.open_containing(u'.')[0].branch
        except NoWorkingTree:
            branch = Branch.open_containing(u'.')[0]

        branch_root = branch.bzrdir.root_transport.base
        # print "Branch root at " + branch_root
        os.chdir(local_path(branch_root))
        vcs = qctVcsBzr()
        if vcs.initRepo(None) != 0:
            return

        try:
            app = QtGui.QApplication([])
            dialog = CommitTool(vcs)
            dialog.show()
            app.exec_()
        except SystemExit:
            pass
Exemplo n.º 32
0
    except ImportError:
        raise ImportError("build_py_2to3 not found in distutils - it is required for Python 3.x")
    suffix = "-py3k"
else:
    from distutils.command.build_py import build_py
    from distutils.command.build_scripts import build_scripts
    suffix = ""


import os
mydir = os.path.dirname(__file__)

if os.path.exists(os.path.join(mydir, '.bzr')):

    from bzrlib.branch import Branch
    branch = Branch.open_containing('.')[0]
    revno = branch.revno()
    revid = branch.get_rev_id(revno)
    rtagdict  = branch.tags.get_reverse_tag_dict()
    if revid in rtagdict:
        version = rtagdict[revid][0]
    else:
        version = 'bzr%s' % revno
    f = open(os.path.join(mydir, 'myversion.txt'), 'w')
    print >> f, "version = %s" % version
    f.close()
else:
    version = open(os.path.join(mydir, 'myversion.txt'), 'rU').read().strip()

with open('README.rst') as f:
    long_description = f.read()
Exemplo n.º 33
0
def get_application_version():
    """
    Returns the application version of the running instance of OpenLP::

        {u'full': u'1.9.4-bzr1249', u'version': u'1.9.4', u'build': u'bzr1249'}
    """
    global APPLICATION_VERSION
    if APPLICATION_VERSION:
        return APPLICATION_VERSION
    if u'--dev-version' in sys.argv or u'-d' in sys.argv:
        # If we're running the dev version, let's use bzr to get the version.
        try:
            # If bzrlib is available, use it.
            from bzrlib.branch import Branch
            b = Branch.open_containing('.')[0]
            b.lock_read()
            try:
                # Get the branch's latest revision number.
                revno = b.revno()
                # Convert said revision number into a bzr revision id.
                revision_id = b.dotted_revno_to_revision_id((revno,))
                # Get a dict of tags, with the revision id as the key.
                tags = b.tags.get_reverse_tag_dict()
                # Check if the latest
                if revision_id in tags:
                    full_version = u'%s' % tags[revision_id][0]
                else:
                    full_version = '%s-bzr%s' % (sorted(b.tags.get_tag_dict().keys())[-1], revno)
            finally:
                b.unlock()
        except:
            # Otherwise run the command line bzr client.
            bzr = Popen((u'bzr', u'tags', u'--sort', u'time'), stdout=PIPE)
            output, error = bzr.communicate()
            code = bzr.wait()
            if code != 0:
                raise Exception(u'Error running bzr tags')
            lines = output.splitlines()
            if not lines:
                tag = u'0.0.0'
                revision = u'0'
            else:
                tag, revision = lines[-1].split()
            bzr = Popen((u'bzr', u'log', u'--line', u'-r', u'-1'), stdout=PIPE)
            output, error = bzr.communicate()
            code = bzr.wait()
            if code != 0:
                raise Exception(u'Error running bzr log')
            latest = output.split(u':')[0]
            full_version = latest == revision and tag or u'%s-bzr%s' % (tag, latest)
    else:
        # We're not running the development version, let's use the file.
        filepath = AppLocation.get_directory(AppLocation.VersionDir)
        filepath = os.path.join(filepath, u'.version')
        fversion = None
        try:
            fversion = open(filepath, u'r')
            full_version = unicode(fversion.read()).rstrip()
        except IOError:
            log.exception('Error in version file.')
            full_version = u'0.0.0-bzr000'
        finally:
            if fversion:
                fversion.close()
    bits = full_version.split(u'-')
    APPLICATION_VERSION = {
        u'full': full_version,
        u'version': bits[0],
        u'build': bits[1] if len(bits) > 1 else None
    }
    if APPLICATION_VERSION[u'build']:
        log.info(u'Openlp version %s build %s', APPLICATION_VERSION[u'version'], APPLICATION_VERSION[u'build'])
    else:
        log.info(u'Openlp version %s' % APPLICATION_VERSION[u'version'])
    return APPLICATION_VERSION
Exemplo n.º 34
0
from __future__ import print_function
from setuptools import setup, find_packages
# import subprocess
# import sys

from distutils.command.build_py import build_py
from distutils.command.build_scripts import build_scripts

import os
import sys
mydir = os.path.dirname(__file__)

if os.path.exists(os.path.join(mydir, '.bzr')):

    from bzrlib.branch import Branch
    branch = Branch.open_containing('.')[0]
    revno = branch.revno()
    revid = branch.get_rev_id(revno)
    rtagdict = branch.tags.get_reverse_tag_dict()
    if revid in rtagdict:
        version = rtagdict[revid][0]
    else:
        version = 'bzr%s' % revno
    f = open(os.path.join(mydir, 'myversion.txt'), 'w')
    print("version = %s" % version, file=f)
    f.close()
else:
    version = open(os.path.join(mydir, 'myversion.txt'), 'r').read().strip()

with open('README.rst') as f:
    long_description = f.read()
Exemplo n.º 35
0
    def get_tags(self,branch,location):
            b = Branch.open_containing(location)[0]
            tags = b.tags.get_tag_dict()
            mappings = b.get_revision_id_to_revno_map()
            n = {}
            t = []
            for k in tags:
                try:
                    n[k] = mappings[tags[k]]
                except:
                    continue
            for k in tags:
                try:
                    t.append(mappings[tags[k]],k)
                except:
                    continue
            ls = [[[v],k] for k,v in n.iteritems()]
            ls.sort()
            #ls=ls[0:2]
            f=ls
            for i in range(0,len(ls)):
                    f[i]=ls[i]
                    temp = [mappings[l] for l in mappings if str(mappings[l]).startswith( '('+str(ls[i][0][0][0])+',')]
                    temp.sort()    
                    index = temp.index(ls[i][0][0])
                    rev_list = temp[1:index]
                    f[i][0].extend(rev_list)
                    f[i][0].sort()
                    if i+1 < len(ls):
                        ls[i+1][0].extend(temp[index:])

            jp = f
            for i in range(0,len(jp)):
                jp[i][0].sort()
                fi = jp[i][0][0][0] + 1
                l = jp[i][0][-1][0]
                for j in range(fi,l):
                        temp1 = [mappings[l] for l in mappings if str(mappings[l]).startswith( '('+str(j)+',')]
                        temp1.sort()
                        jp[i][0].extend(temp1)
                        jp[i][0].sort()
            mapp={}
            for k,v in mappings.iteritems():
                mapp[v] = k
            path = branch.split('/')
            file_path = os.path.join(os.path.realpath(self.logdir),path[0],path[1])             
            try:
                if not os.path.isdir(file_path):
                    os.makedirs(file_path)
            except:
                raise
            file_path = os.path.join(file_path,self.logfile)
            self.open_file[branch] = file_path
            fp = open(file_path,'w')    
            for i in range(0,len(jp)):
                tag_data = jp[i]
                tag = tag_data[1]
                data = tag_data[0]                
                
                fp.write('\n\n%s\n======================================\n'%(tag))
                bugs=[]       
                print 'len of data', len(data)
                for rev_no in data:                    
                    try:
                        r = mapp[rev_no]
                        rev = b.repository.get_revision(r)
                        msg = rev.get_summary().encode('utf-8')
                        app_authors = [rev.get_apparent_author().encode('utf-8')] #rev.get_apparent_authors()                                            
                        try:
                            fp.write("%s (by %s)\r\n"%(msg, ','.join(app_authors)))
                        except Exception, e:
                            print e
                            nt_str.append(msg)
                        #for bug in rev.iter_bugs():
                        #    bugs.append([rev_no,bug])
                    except:
                        nt_revs.append(rev_no)
                        continue
                if bugs:
                    fp.write("\n\n\n")
                    fp.write('Fix bugs : %s\n======================================\n'%(tag))
                    for bug in bugs:
                        rev_no=bug[0]
                        bug=bug[1]
                        fp.write("%s\n"%('\t'.join(bug)))
            fp.close()
Exemplo n.º 36
0
 def __init__(self, base='.'):
     try:
         self.branch = Branch.open_containing(base)[0]
     except NotBranchError:
         self.branch = None
Exemplo n.º 37
0
    def run(self,
            location=None,
            remember=False,
            directory=None,
            no_rebase=False):
        from bzrlib import urlutils
        from bzrlib.bzrdir import BzrDir
        from bzrlib.errors import BzrCommandError, NoWorkingTree
        from bzrlib.trace import info
        from bzrlib.workingtree import WorkingTree
        from upgrade import update_workingtree_fileids

        if directory is None:
            directory = "."
        try:
            source_wt = WorkingTree.open_containing(directory)[0]
            source_branch = source_wt.branch
        except NoWorkingTree:
            source_branch = Branch.open_containing(directory)[0]
            source_wt = None
        stored_loc = source_branch.get_push_location()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No push location known or specified.")
            else:
                display_url = urlutils.unescape_for_display(
                    stored_loc, self.outf.encoding)
                self.outf.write("Using saved location: %s\n" % display_url)
                location = stored_loc

        bzrdir = BzrDir.open(location)
        target_branch = bzrdir.open_branch()
        target_branch.lock_write()
        try:
            if not isinstance(target_branch, ForeignBranch):
                info(
                    "target branch is not a foreign branch, using regular push."
                )
                target_branch.pull(source_branch)
                no_rebase = True
            else:
                revid_map = target_branch.dpull(source_branch)
            # We successfully created the target, remember it
            if source_branch.get_push_location() is None or remember:
                source_branch.set_push_location(target_branch.base)
            if not no_rebase:
                _, old_last_revid = source_branch.last_revision_info()
                new_last_revid = revid_map[old_last_revid]
                if source_wt is not None:
                    source_wt.pull(target_branch,
                                   overwrite=True,
                                   stop_revision=new_last_revid)
                    source_wt.lock_write()
                    try:
                        update_workingtree_fileids(
                            source_wt,
                            source_wt.branch.repository.revision_tree(
                                old_last_revid),
                            source_wt.branch.repository.revision_tree(
                                new_last_revid))
                    finally:
                        source_wt.unlock()
                else:
                    source_branch.pull(target_branch,
                                       overwrite=True,
                                       stop_revision=new_last_revid)
        finally:
            target_branch.unlock()
Exemplo n.º 38
0
def show_missing_xml(self, other_branch=None, reverse=False, mine_only=False,
        theirs_only=False, log_format=None, long=False, short=False, line=False,
        show_ids=False, verbose=False, this=False, other=False):
    """output missing info as xml"""
    if this:
        mine_only = this
    if other:
        theirs_only = other

    local_branch = Branch.open_containing(u".")[0]
    parent = local_branch.get_parent()
    if other_branch is None:
        other_branch = parent
        if other_branch is None:
            raise errors.BzrCommandError("No peer location known"
                                          " or specified.")
    display_url = urlutils.unescape_for_display(other_branch,
                                            self.outf.encoding)

    remote_branch = Branch.open(other_branch)

    if remote_branch.base == local_branch.base:
        remote_branch = local_branch
    local_branch.lock_read()
    try:
        remote_branch.lock_read()
        self.outf.write('<?xml version="1.0" encoding="%s"?>' % \
                        osutils.get_user_encoding())
        self.outf.write('<missing>')
        try:
            self.outf.write('<last_location>' + display_url + \
                            '</last_location>')
            local_extra, remote_extra = find_unmerged(local_branch,
                                                      remote_branch)
            if log_format is None:
                registry = log_formatter_registry
                log_format = registry.get_default(local_branch)
            if reverse is False:
                local_extra.reverse()
                remote_extra.reverse()
            if local_extra and not theirs_only:
                self.outf.write('<extra_revisions size="%d">' %
                                len(local_extra))

                if local_extra > 0:
                    lf = log_format(to_file=self.outf,
                                    show_ids=show_ids,
                                    show_timezone='original')
                    showlogs(self, iter_log_revisions(local_extra,
                                    local_branch.repository,
                                    verbose), lf)
                self.outf.write('</extra_revisions>')
            if remote_extra and not mine_only:
                self.outf.write('<missing_revisions size="%d">' %
                                len(remote_extra))
                if remote_extra > 0:
                    lf = log_format(to_file=self.outf,
                                    show_ids=show_ids,
                                    show_timezone='original')
                    showlogs(self, iter_log_revisions(remote_extra,
                                    remote_branch.repository,
                                    verbose), lf)
                self.outf.write('</missing_revisions>')
            if not remote_extra and not local_extra:
                status_code = 0
                # self.outf.write("Branches are up to date.\n")
            else:
                status_code = 1

        finally:
            remote_branch.unlock()
    finally:
        self.outf.write('</missing>')
        local_branch.unlock()

    if not status_code and parent is None and other_branch is not None:
        local_branch.lock_write()
        try:
            # handle race conditions - a parent might be set while we run.
            if local_branch.get_parent() is None:
                local_branch.set_parent(remote_branch.base)
        finally:
            local_branch.unlock()
    return status_code
Exemplo n.º 39
0
    def run(
        self,
        upstream_location=None,
        onto=None,
        revision=None,
        merge_type=None,
        verbose=False,
        dry_run=False,
        always_rebase_merges=False,
        pending_merges=False,
        directory=".",
    ):
        from bzrlib.branch import Branch
        from bzrlib.revisionspec import RevisionSpec
        from bzrlib.workingtree import WorkingTree
        from bzrlib.plugins.rewrite.rebase import (
            generate_simple_plan,
            rebase,
            RebaseState1,
            WorkingTreeRevisionRewriter,
            regenerate_default_revid,
            rebase_todo,
        )

        if revision is not None and pending_merges:
            raise BzrCommandError(gettext("--revision and --pending-merges are mutually exclusive"))

        wt = WorkingTree.open_containing(directory)[0]
        wt.lock_write()
        try:
            state = RebaseState1(wt)
            if upstream_location is None:
                if pending_merges:
                    upstream_location = directory
                else:
                    upstream_location = wt.branch.get_parent()
                    if upstream_location is None:
                        raise BzrCommandError(gettext("No upstream branch specified."))
                    note(gettext("Rebasing on %s"), upstream_location)
            upstream = Branch.open_containing(upstream_location)[0]
            upstream_repository = upstream.repository
            upstream_revision = upstream.last_revision()
            # Abort if there already is a plan file
            if state.has_plan():
                raise BzrCommandError(
                    gettext(
                        "A rebase operation was interrupted. "
                        "Continue using 'bzr rebase-continue' or abort using 'bzr "
                        "rebase-abort'"
                    )
                )

            start_revid = None
            stop_revid = None
            if revision is not None:
                if len(revision) == 1:
                    if revision[0] is not None:
                        stop_revid = revision[0].as_revision_id(wt.branch)
                elif len(revision) == 2:
                    if revision[0] is not None:
                        start_revid = revision[0].as_revision_id(wt.branch)
                    if revision[1] is not None:
                        stop_revid = revision[1].as_revision_id(wt.branch)
                else:
                    raise BzrCommandError(gettext("--revision takes only one or two arguments"))

            if pending_merges:
                wt_parents = wt.get_parent_ids()
                if len(wt_parents) in (0, 1):
                    raise BzrCommandError(gettext("No pending merges present."))
                elif len(wt_parents) > 2:
                    raise BzrCommandError(gettext("Rebasing more than one pending merge not supported"))
                stop_revid = wt_parents[1]
                assert stop_revid is not None, "stop revid invalid"

            # Check for changes in the working tree.
            if not pending_merges and wt.basis_tree().changes_from(wt).has_changed():
                raise UncommittedChanges(wt)

            # Pull required revisions
            wt.branch.repository.fetch(upstream_repository, upstream_revision)
            if onto is None:
                onto = upstream.last_revision()
            else:
                rev_spec = RevisionSpec.from_string(onto)
                onto = rev_spec.as_revision_id(upstream)

            wt.branch.repository.fetch(upstream_repository, onto)

            if stop_revid is None:
                stop_revid = wt.branch.last_revision()
            repo_graph = wt.branch.repository.get_graph()
            our_new, onto_unique = repo_graph.find_difference(stop_revid, onto)

            if start_revid is None:
                if not onto_unique:
                    self.outf.write(gettext("No revisions to rebase.\n"))
                    return
                if not our_new:
                    self.outf.write(gettext("Base branch is descendant of current " "branch. Pulling instead.\n"))
                    if not dry_run:
                        wt.pull(upstream, onto)
                    return
            # else: include extra revisions needed to make start_revid mean
            # something.

            # Create plan
            replace_map = generate_simple_plan(
                our_new,
                start_revid,
                stop_revid,
                onto,
                repo_graph,
                lambda revid, ps: regenerate_default_revid(wt.branch.repository, revid),
                not always_rebase_merges,
            )

            if verbose or dry_run:
                todo = list(rebase_todo(wt.branch.repository, replace_map))
                note(gettext("%d revisions will be rebased:") % len(todo))
                for revid in todo:
                    note("%s" % revid)

            if not dry_run:
                # Write plan file
                state.write_plan(replace_map)

                replayer = WorkingTreeRevisionRewriter(wt, state, merge_type=merge_type)

                finish_rebase(state, wt, replace_map, replayer)
        finally:
            wt.unlock()
Exemplo n.º 40
0
    def get_tags(self, branch, location):
        b = Branch.open_containing(location)[0]
        tags = b.tags.get_tag_dict()
        mappings = b.get_revision_id_to_revno_map()
        n = {}
        t = []
        for k in tags:
            try:
                n[k] = mappings[tags[k]]
            except:
                continue
        for k in tags:
            try:
                t.append(mappings[tags[k]], k)
            except:
                continue
        ls = [[[v], k] for k, v in n.iteritems()]
        ls.sort()
        #ls=ls[0:2]
        f = ls
        for i in range(0, len(ls)):
            f[i] = ls[i]
            temp = [
                mappings[l] for l in mappings
                if str(mappings[l]).startswith('(' + str(ls[i][0][0][0]) + ',')
            ]
            temp.sort()
            index = temp.index(ls[i][0][0])
            rev_list = temp[1:index]
            f[i][0].extend(rev_list)
            f[i][0].sort()
            if i + 1 < len(ls):
                ls[i + 1][0].extend(temp[index:])

        jp = f
        for i in range(0, len(jp)):
            jp[i][0].sort()
            fi = jp[i][0][0][0] + 1
            l = jp[i][0][-1][0]
            for j in range(fi, l):
                temp1 = [
                    mappings[l] for l in mappings
                    if str(mappings[l]).startswith('(' + str(j) + ',')
                ]
                temp1.sort()
                jp[i][0].extend(temp1)
                jp[i][0].sort()
        mapp = {}
        for k, v in mappings.iteritems():
            mapp[v] = k
        path = branch.split('/')
        file_path = os.path.join(os.path.realpath(self.logdir), path[0],
                                 path[1])
        try:
            if not os.path.isdir(file_path):
                os.makedirs(file_path)
        except:
            raise
        file_path = os.path.join(file_path, self.logfile)
        self.open_file[branch] = file_path
        fp = open(file_path, 'w')
        for i in range(0, len(jp)):
            tag_data = jp[i]
            tag = tag_data[1]
            data = tag_data[0]

            fp.write('\n\n%s\n======================================\n' %
                     (tag))
            bugs = []
            print 'len of data', len(data)
            for rev_no in data:
                try:
                    r = mapp[rev_no]
                    rev = b.repository.get_revision(r)
                    msg = rev.get_summary().encode('utf-8')
                    app_authors = [rev.get_apparent_author().encode('utf-8')
                                   ]  #rev.get_apparent_authors()
                    try:
                        fp.write("%s (by %s)\r\n" %
                                 (msg, ','.join(app_authors)))
                    except Exception, e:
                        print e
                        nt_str.append(msg)
                    #for bug in rev.iter_bugs():
                    #    bugs.append([rev_no,bug])
                except:
                    nt_revs.append(rev_no)
                    continue
            if bugs:
                fp.write("\n\n\n")
                fp.write(
                    'Fix bugs : %s\n======================================\n' %
                    (tag))
                for bug in bugs:
                    rev_no = bug[0]
                    bug = bug[1]
                    fp.write("%s\n" % ('\t'.join(bug)))
        fp.close()
Exemplo n.º 41
0
def show_missing_xml(self,
                     other_branch=None,
                     reverse=False,
                     mine_only=False,
                     theirs_only=False,
                     log_format=None,
                     long=False,
                     short=False,
                     line=False,
                     show_ids=False,
                     verbose=False,
                     this=False,
                     other=False):
    """output missing info as xml"""
    if this:
        mine_only = this
    if other:
        theirs_only = other

    local_branch = Branch.open_containing(u".")[0]
    parent = local_branch.get_parent()
    if other_branch is None:
        other_branch = parent
        if other_branch is None:
            raise errors.BzrCommandError("No peer location known"
                                         " or specified.")
    display_url = urlutils.unescape_for_display(other_branch,
                                                self.outf.encoding)

    remote_branch = Branch.open(other_branch)

    if remote_branch.base == local_branch.base:
        remote_branch = local_branch
    local_branch.lock_read()
    try:
        remote_branch.lock_read()
        self.outf.write('<?xml version="1.0" encoding="%s"?>' % \
                        osutils.get_user_encoding())
        self.outf.write('<missing>')
        try:
            self.outf.write('<last_location>' + display_url + \
                            '</last_location>')
            local_extra, remote_extra = find_unmerged(local_branch,
                                                      remote_branch)
            if log_format is None:
                registry = log_formatter_registry
                log_format = registry.get_default(local_branch)
            if reverse is False:
                local_extra.reverse()
                remote_extra.reverse()
            if local_extra and not theirs_only:
                self.outf.write('<extra_revisions size="%d">' %
                                len(local_extra))

                if local_extra > 0:
                    lf = log_format(to_file=self.outf,
                                    show_ids=show_ids,
                                    show_timezone='original')
                    showlogs(
                        self,
                        iter_log_revisions(local_extra,
                                           local_branch.repository, verbose),
                        lf)
                self.outf.write('</extra_revisions>')
            if remote_extra and not mine_only:
                self.outf.write('<missing_revisions size="%d">' %
                                len(remote_extra))
                if remote_extra > 0:
                    lf = log_format(to_file=self.outf,
                                    show_ids=show_ids,
                                    show_timezone='original')
                    showlogs(
                        self,
                        iter_log_revisions(remote_extra,
                                           remote_branch.repository, verbose),
                        lf)
                self.outf.write('</missing_revisions>')
            if not remote_extra and not local_extra:
                status_code = 0
                # self.outf.write("Branches are up to date.\n")
            else:
                status_code = 1

        finally:
            remote_branch.unlock()
    finally:
        self.outf.write('</missing>')
        local_branch.unlock()

    if not status_code and parent is None and other_branch is not None:
        local_branch.lock_write()
        try:
            # handle race conditions - a parent might be set while we run.
            if local_branch.get_parent() is None:
                local_branch.set_parent(remote_branch.base)
        finally:
            local_branch.unlock()
    return status_code
Exemplo n.º 42
0
 def __init__(self, base='.'):
     try:
         self.branch = Branch.open_containing(base)[0]
     except NotBranchError:
         self.branch = None