aurum / python / aurum / aubazaar.py

ZyX_I 38b90d6 




































































































































































from __future__ import with_statement
import bzrlib
from bzrlib.errors       import NotBranchError, NoSuchRevision, InvalidRevisionSpec
from bzrlib.workingtree  import WorkingTree
from bzrlib.revisionspec import RevisionSpec
from bzrlib.delta        import report_changes
from aurum.auutils import vim_throw, outermethodgen, autoexportmethodgen, emptystatdct, \
                          get_repo_prop_gen

def flush(repo):
    pass

def g_repo(path):
    try:
        return WorkingTree.open(path)
    except NotBranchError:
        vim_throw('norepo', path)

def bzrmethod(func):
    def f(*args, **kwargs):
        with(bzrlib.initialize()):
            return func(*args, **kwargs)
    return f

outermethod      = outermethodgen(g_repo, flush)
autoexportmethod = autoexportmethodgen(g_repo, globals())

def g_revid(repo, rev):
    try:
        if isinstance(rev, int) or isinstance(rev, long):
            return repo.branch.get_rev_id(rev)
        else:
            return RevisionSpec.from_string(rev).in_history(repo.branch).rev_id
    except (NoSuchRevision, InvalidRevisionSpec):
        vim_throw('norev', rev, repo.basedir)

def g_cs(repo, rev):
    return repo.branch.repository.get_revision(g_revid(repo, rev))

def sorted_str_keys(d):
    r = [key.encode('utf-8') for key in d.iterkeys()]
    r.sort()
    return r

repo_props={
        'branch':        lambda repo: repo.branch.nick,
        'url':           lambda repo: str(repo.branch.get_parent()),
        'bookmarkslist': lambda repo: [],
        'brancheslist':  lambda repo: [],
        'tagslist':      lambda repo: sorted_str_keys(repo.branch.tags.get_tag_dict()),
}

get_repo_prop = outermethod(autoexportmethod()(get_repo_prop_gen(repo_props, pathattr='basedir')))

class StatusReporter(object):
    __slots__ = ('status', 'repo', 'ignored', 'files')

    def __init__(self, repo, ignored, files):
        self.status  = emptystatdct()
        self.repo    = repo
        self.ignored = ignored
        self.files   = files

    def report(self, file_id, paths, track_ch, renamed, modified, exe_ch, kind):
        if paths[1] == '':
            return
        if track_ch == 'unchanged':
            if renamed:
                if paths[0] in self.files:
                    self.status['removed' ].append(paths[0])
                if paths[1] in self.files:
                    self.status['added'   ].append(paths[1])
            elif modified == 'created':
                self.status['added'   ].append(paths[1])
            elif modified in set(('deleted', 'missing')):
                self.status['deleted' ].append(paths[1])
            elif exe_ch or modified in set(('kind changed', 'modified')):
                self.status['modified'].append(paths[1])
            else:
                self.status['clean'   ].append(paths[1])
        elif track_ch == 'removed':
            self.status['removed'].append(paths[0])
        elif track_ch == 'added':
            if modified == 'missing':
                self.status['deleted' ].append(paths[1])
            else:
                self.status['added'   ].append(paths[1])
        elif track_ch == 'unversioned':
            if self.repo.is_ignored(paths[1]):
                if self.ignored:
                    self.status['ignored'].append(paths[1])
            else:
                self.status['unknown'].append(paths[1])

class ReadLock(object):
    def __init__(self, o):
        self.o = o

    def __enter__(self):
        self.o.lock_read()

    def __exit__(self, *args):
        self.o.unlock()

class ContainsEverything(object):
    @staticmethod
    def __contains__(o):
        return True

@outermethod
@autoexportmethod()
@bzrmethod
def get_status(repo, rev1=None, rev2=None, files=None, clean=None, ignored=None):
    if not files:
        files = None

    reverse = False
    if not rev1 and rev2:
        rev1, rev2 = rev2, rev1
        reverse = True

    if rev1 or rev2:
        ignored = False

    old = repo.branch.repository.revision_tree(g_revid(repo, rev1)) if rev1 else repo.basis_tree()
    new = repo.branch.repository.revision_tree(g_revid(repo, rev2)) if rev2 else repo

    reporter = StatusReporter(repo, ignored, set(files) if files else ContainsEverything())

    with ReadLock(repo), ReadLock(old), ReadLock(new):
        changes  = new.iter_changes(old, clean, files, require_versioned=False,
                                    want_unversioned=True)
        report_changes(changes, reporter)

    r = reporter.status

    if reverse:
        r['deleted'], r['unknown'] = r['unknown'], r['deleted']
        r['added'],   r['removed'] = r['removed'], r['added']

    return r

cs_vim_defaults = {
        'phase'     : 'unknown',
        'bookmarks' : [],
}

def set_rev_dict(cs, cs_vim, revid_revno_map, reverse_tag_dict):
    cs_vim['hex']         = cs.revision_id
    cs_vim['rev']         = revid_revno_map[cs.revision_id]
    cs_vim['time']        = int(cs.timestamp)
    cs_vim['description'] = cs.message.encode('utf-8')

    try:
        cs_vim['user']    = cs.get_apparent_authors()[0]
    except IndexError:
        cs_vim['user']    = ''

    cs_vim['parents']     = cs.parent_ids
    cs_vim['branch']      = cs.properties['branch-nick']
    cs_vim['tags']        = [tag.encode('utf-8') for tag in reverse_tag_dict.get(cs.revision_id,[])]

    cs_vim.update(cs_vim_defaults)
    return cs_vim

# vim: ft=python ts=4 sw=4 sts=4 et tw=100
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.