当前位置: 首页>>代码示例>>Python>>正文


Python Repository.revparse_single方法代码示例

本文整理汇总了Python中pygit2.Repository.revparse_single方法的典型用法代码示例。如果您正苦于以下问题:Python Repository.revparse_single方法的具体用法?Python Repository.revparse_single怎么用?Python Repository.revparse_single使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygit2.Repository的用法示例。


在下文中一共展示了Repository.revparse_single方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_new_articles

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
def get_new_articles():
    blog = PelicanBlog()
    content_dir = blog.get_content_directory()
    repo = Repository(os.path.abspath(os.path.dirname(__file__)))
    diff = repo.revparse_single("HEAD").tree.diff_to_tree()
    existing_articles = set(os.path.relpath(obj.old_file_path, content_dir)
                            for obj in diff
                            if obj.old_file_path.startswith(content_dir))
    all_articles = set(blog.get_posts())
    new_articles = {art for art in all_articles - existing_articles
                    if blog.get_post_lang(art) in (TWITTER_LANGUAGE, "")}
    new_titles = []
    repo.index.read()
    for newart in new_articles:
        title = blog.get_post_title(newart)
        yield Article(title, blog.get_post_url(newart),
                      blog.get_post_authors(newart))
        new_titles.append(title)
        repo.index.add(os.path.join(content_dir, newart))
    blogger = Signature(repo.config["user.name"], repo.config["user.email"])
    repo.create_commit("HEAD", blogger, blogger,
                       "[BLOG] %s" % ", ".join(new_titles),
                       repo.index.write_tree(), [repo.head.peel().oid])
    repo.index.write()
    # TODO(v.markovtsev): implement git push using pygit2
    subprocess.call(("git", "push", "origin", repo.head.shorthand))
开发者ID:ajkxyz,项目名称:veles-blog,代码行数:28,代码来源:tweet.py

示例2: sync_handler

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
def sync_handler(fork_from: str, from_sha: str, repo_name: str,
                 ticket_id: int, pr_url: str):
    output_path = '{}.txt'.format(pr_url.split('/', 3)[3].rsplit('/', 2)[0])
    output_path = os.path.join(WORK_DIR, output_path.replace('/', '_'))
    work_tree = os.path.join(WORK_DIR, fork_from)
    parent_path = os.path.dirname(work_tree)
    if not os.path.exists(parent_path):
        os.makedirs(parent_path)
    if not os.path.exists(work_tree):
        repo = clone_repository(
            '{0}{1}.git'.format(GITHUB_URL, fork_from), work_tree)
    else:
        repo = Repository(work_tree)

    remote_name = repo_name.split('/')[0]
    update_remote(work_tree, repo, repo_name, remote_name)

    if remote_name == 'origin':
        commit = repo.revparse_single(from_sha)
        repo.checkout_tree(commit, strategy=GIT_CHECKOUT_FORCE)
    else:
        ref_name = 'refs/pull/{0}/head'.format(ticket_id)
        try:
            repo.create_reference(ref_name, from_sha)
        except ValueError:
            pass
        ref = repo.lookup_reference(ref_name)
        repo.checkout(ref, strategy=GIT_CHECKOUT_FORCE)
    cwd = os.getcwd()
    os.chdir(work_tree)
    subprocess.call(
        '{} . --output-file={}'.format(FLAKE8_EXECUTABLE, output_path),
        shell=True)
    os.chdir(cwd)
    return output_path
开发者ID:dongweiming,项目名称:gandalf,代码行数:37,代码来源:project.py

示例3: _pygit2_commits

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
def _pygit2_commits(commit, repository):
    from pygit2 import Repository, GIT_SORT_TOPOLOGICAL
    g = Repository(repository)

    if '..' in commit:
        tail, head = commit.split('..', 2)
        head = head or 'HEAD'
    else:
        head = commit
        tail = commit + '^'

    walker = g.walk(g.revparse_single(head).oid, GIT_SORT_TOPOLOGICAL)

    try:
        walker.hide(g.revparse_single(tail).oid)
    except KeyError:
        pass

    return walker
开发者ID:inveniosoftware,项目名称:kwalitee,代码行数:21,代码来源:check.py

示例4: get_current_timestamp

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
def get_current_timestamp(path_to_repository):
    """Utility method for getting the timestamp of the last commit from a Git repository.

        Args:
            path_to_repository (str): Path to the Git repository

        Returns:
            str: The timestamp of the last commit in the provided repository.
    """
    repo = Repository(path_to_repository)
    head = repo.revparse_single('HEAD')
    return head.commit_time
开发者ID:cqse,项目名称:teamscale-cli,代码行数:14,代码来源:git_utils.py

示例5: _fast_forward

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
    def _fast_forward(self, local_path, merge_target, branch):
        # fast-forward all the branches.
        # pygit2 repo
        repo = Repository(discover_repository(local_path))

        # convert merge_target from hex into oid.
        fetch_head = repo.revparse_single(merge_target)

        # try to resolve a common anscestor between fetched and local
        try:
            head = repo.revparse_single(branch)
        except KeyError:
            # Doesn't exist.  Create and done.
            repo.create_reference(branch, fetch_head.oid)
            return True, 'Created new branch: %s' % branch

        if head.oid == fetch_head.oid:
            return True, 'Source and target are identical.'

        # raises KeyError if no merge bases found.
        common_oid = repo.merge_base(head.oid, fetch_head.oid)

        # Three different outcomes between the remaining cases.
        if common_oid.hex not in (head.oid.hex, fetch_head.oid.hex):
            # common ancestor is beyond both of these, not going to
            # attempt a merge here and will assume this:
            return False, 'Branch will diverge.'
        elif common_oid.hex == fetch_head.oid.hex:
            # Remote is also the common ancestor, so nothing to do.
            return True, 'No new changes found.'

        # This case remains: common_oid.hex == head.oid.hex, meaning
        # this local repository is the ancestor of further changes
        # fetched from the remote - remote newer, so fast-forward.
        ref = repo.lookup_reference(branch)
        ref.delete()

        repo.create_reference(branch, fetch_head.oid)

        return True, 'Fast-forwarded branch: %s' % branch
开发者ID:repodono,项目名称:repodono.backend_git,代码行数:42,代码来源:utility.py

示例6: __init__

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
class GitObjectRenderer:
    def __init__(self, reponame, cache, revspec, path):
        self.repo = Repository(reponame)
        self.revspec = revspec
        self.path = path
        self.object_map = {
            Blob : self._render_blob,
            Commit : self._render_commit,
            Tag : self._render_tag
        }
        self.cache = cache


    def _render_blob(self, rev):
        data = rev.data.decode('utf-8', errors='ignore')
        formatter = HtmlFormatter(linenos='inline')
        lexer = guess_lexer(data)
        blob = highlight(data, lexer, formatter)
        return render_template("objects/blob.html",
                  repo = self.repo,
                  revspec = 'master', blob = blob, path = self.path)

    def _render_commit(self, rev):
        entries = self.repo[rev.tree[self.path].oid] if self.path else rev.tree
        cached = []
        for entry in entries:
            cache_id = "{0}-commit-{1}".format(self.repo.get_name(), entry.hex)
            hit = self.cache.get(cache_id)
            if hit is not None:
                cached.append((entry, hit))
            else:
                cached.append((entry, None))

        files = sorted(cached, key=lambda x: x[0].filemode)
        return render_template("objects/tree.html",
                  repo = self.repo,
                  revspec = self.revspec, rev = rev, files = files,
                  path = self.path)

    def _render_tag(self, rev):
        obj = self.repo[rev.target]
        url = url_for('obj', reponame=self.repo.get_name(), revspec = obj.hex)
        return redirect(url)

    def render_obj(self):
        rev = self.repo.revparse_single(self.revspec)
        return self.object_map[type(rev)](rev)
开发者ID:cholin,项目名称:gix,代码行数:49,代码来源:git.py

示例7: len

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
#    print commit.hex
#    print base.revparse_single(commit.hex).message
#    print commit.commit_time
#    print commit.commit_time_offset

git = sh.git.bake(_cwd='/home/heather/research/spoon-knife')

for point in history:
    git.checkout(point)
#    print subprocess.check_output(['ohcount', 'spoon-knife'])

git.checkout(history[0])

i = 0
while i < len(history) - 2:
    t0 = base.revparse_single(history[i])
    t1 = base.revparse_single(history[i+1])
    diff = base.diff(t0,t1)
    patches = [p for p in diff]
    for patch in patches:
        print 'NUM HUNKS: ' + str(len(patch.hunks))
        for hunk in patch.hunks:
#            print hunk.lines
            totesLines = 0
            totesMods = 0
            for line in hunk.lines:
                totesLines += 1
                if line[0] == '-' or line[0] == '+':
                    totesMods += 1
                    print line
            print 'TOTAL LINES: ' + str(totesLines)
开发者ID:dtg3,项目名称:sevo-git-research,代码行数:33,代码来源:hunks.py

示例8: init

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
class prototype:
    repo = ""  # Path to a given repository
    name = ""  # Name of a repository
    base = ""  # Repository as defined in pygit2

    # Initialization. Clones the given repository, placing it in the current directory,
    # and changes to the repository directory.
    def init(self, repository):
        self.repo = repository

        # Use regular expressions to match the last instance of a forward slash
        # followed by the name of the repository, which we wish to extract, followed
        # by ".git". 
        m = re.search('/([^/]+).git$', repository)
        if m:
            self.name = m.group(1)

        if not os.path.isdir(self.name):
            os.system('git clone ' + self.repo) # Get the repository from GitHub

        self.base = Repository(self.name)
        self.base.checkout('HEAD')

    # Destruction. Remove the given repository from memory.
    def destroy(self):
        os.system('cd ' + self.name)
        os.system('rm -rf ' + self.name)

    # Get total LOC by given repository. 
    def totalRepoLOC(self):
        loc = countDirLOC(self.name)
        return loc

    # Get total commits by a given repository
    def totalRepoCommits(self):
        commits = 0
        for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL):
            commits = commits + 1
        return commits

    # Get a list of LOC changed per commit
    def locPerCommit(self):
        loc = []
        oldPath = os.popen('pwd')
        os.chdir(self.name)
        sha1 = 0
        sha2 = 0

        start = 1
        total = self.totalRepoCommits()

        # For each commit within the repository
        for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL):

            print '\r', start, '/', total,
            start += 1

            # Based on the SHA, use git to show the patch for that commit
            sha1 = sha2
            sha2 = commit.hex
            if sha1 != 0:
                p = os.popen('git diff --shortstat ' + sha1 + ' ' + sha2)
                line = p.readline()

                # line contains "# file changed, # insertions(+), # deletions(-)
                # Use regular expressions to find the number of additions and deletions.
                # Additions are found after ", " and before " insertion". Deletions are
                # found after "(+), " and before " deletion".
                m = re.search(', (.*) insertion', line)
                additions = 0
                deletions = 0
                if m:
                    additions = m.group(1)
                m = re.search('\(\+\), (.*) deletion', line)
                if m:
                    deletions = m.group(1)

                # Get the total and append to array
                modifications = int(additions) + int(deletions)
                loc.append(modifications)

        os.chdir('..')
        return loc


    # Get a list containing the total number of line additions and deletions (including
    # whitespace and comments) contained within each hunk that was changed over t
    def locPerHunk(self):
        loc = []
        history = []

        # Get the hex number for each commit within the repository
        for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL):
            sha = commit.hex
            history.append(sha)

        # Compare each revision in the history of the repository with the previous rev.
        i = 0
        while i < len(history) - 1:
            t0 = self.base.revparse_single(history[i])
#.........这里部分代码省略.........
开发者ID:dtg3,项目名称:sevo-git-research,代码行数:103,代码来源:prototype.py

示例9: GitStorage

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]

#.........这里部分代码省略.........

        # not what we were looking for.
        if cls == Tree:
            raise PathNotDirError('path not dir')
        elif cls == Blob:
            raise PathNotFileError('path not file')
        raise PathNotFoundError('path not found')

    @property
    def _commit(self):
        return self.__commit

    @property
    def rev(self):
        if self.__commit:
            return self.__commit.hex
        return None

    @property
    def shortrev(self):
        # TODO this is an interim solution.
        if self.rev:
            return self.rev[:12]

    def basename(self, name):
        return name.split('/')[-1]

    def checkout(self, rev=None):
        # None maps to the default revision.
        if rev is None:
            rev = 'HEAD'

        try:
            self.__commit = self.repo.revparse_single(rev)
        except KeyError:
            if rev == 'HEAD':
                # probably a new repo.
                self.__commit = None
                return
            raise RevisionNotFoundError('revision %s not found' % rev)
            # otherwise a RevisionNotFoundError should be raised.

    def files(self):
        def _files(tree, current_path=None):
            results = []
            for node in tree:
                if current_path:
                    name = '/'.join([current_path, node.name])
                else:
                    name = node.name

                obj = self.repo.get(node.oid)
                if isinstance(obj, Blob):
                    results.append(name)
                elif isinstance(obj, Tree):
                    results.extend(_files(obj, name))
            return results

        if not self._commit:
            return []
        results = _files(self._commit.tree)
        return results

    def file(self, path):
        return self._get_obj(path, Blob).data
开发者ID:repodono,项目名称:repodono.backend_git,代码行数:69,代码来源:utility.py

示例10: GitRepo

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
class GitRepo(object):

    ''' git repo class '''

    def __init__(self, path):
        try:
            self.__repo = Repository(path)
        except Exception as e:
            self.__repo = None
            print(e)

    def get_info(self):
        if not self.__repo:
            return None
        signature = self.__repo.default_signature
        result = {
            'path': self.__repo.path,
            'workdir': self.__repo.workdir,
            'bare': self.__repo.is_bare,
            'empty': self.__repo.is_empty,
            'name': signature.name,
            'email': signature.email,
            'time': signature.time,
            'offset': signature.offset,
        }
        return result

    def get_all_references(self):
        return self.__repo.listall_references()

    def get_reference(self, name):
        if not self.__repo:
            return None
        ref = None
        try:
            ref = self.__repo.lookup_reference(name)
        except Exception as e:
            print(e)
        return ref

    def get_all_branches(self, branch_type=None):
        if not self.__repo:
            return None
        if branch_type:
            return self.__repo.listall_branches(branch_type)
        r = self.__repo.listall_branches(GIT_BRANCH_LOCAL | GIT_BRANCH_REMOTE)
        return r

    def get_branch(self, name, branch_type=GIT_BRANCH_LOCAL):
        if not self.__repo:
            return None
        return self.__repo.lookup_branch(name, branch_type)

    def check_branch(self, name, branch_type=None):
        if not branch_type:
            if '/' in name:
                branch_type = GIT_BRANCH_REMOTE
            else:
                branch_type = GIT_BRANCH_LOCAL
        try:
            result = self.get_branch(name, branch_type)
            return result
        except Exception as e:
            print(e)
            return False

    def get_current_commit(self):
        if not self.__repo:
            return None
        commit = self.__repo.revparse_single('HEAD')
        return self.get_commit(commit)

    def get_commit_by_branch(self, branch):
        if not self.__repo:
            return None
        query = 'refs/'
        if hasattr(branch, 'remote_name'):
            query += 'remotes/'
        else:
            query += 'heads/'
        query += branch.branch_name
        try:
            ref = self.get_reference(query)
            commit = ref.target
            return self.get_commit(commit)
        except Exception as e:
            print(e)
            return None

    def get_commit_by_tag(self, tag):
        if self.__repo is None:
            return None
        if tag:
            commit = tag.get_object()
            return self.get_commit(commit)
        return None

    def get_commit(self, oid_or_commit):
        ''' return a commit w/ json '''
        if not self.__repo or not oid_or_commit:
#.........这里部分代码省略.........
开发者ID:hitigon,项目名称:warehouse,代码行数:103,代码来源:git.py

示例11: process

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
def process(repo, history):
	# GET A REPO ON DISK
	base = Repository(repo)
	base.checkout('HEAD')

	file_xsmall = 0
	file_small = 0
	file_medium = 0
	file_large = 0
	file_xlarge = 0
		
	hunk_xsmall = 0
	hunk_small = 0
	hunk_medium = 0
	hunk_large = 0
	hunk_xlarge = 0

	line_xsmall = 0
	line_small = 0
	line_medium = 0
	line_large = 0
	line_xlarge = 0 
	
	i = 0
	while i < len(history) - 1:
		print '\rDiff#: ' + str(i + 1) + ' of ' + str(len(history)-1),

		t0 = base.revparse_single(history[i].hex)
		t1 = base.revparse_single(history[i+1].hex)
		
		try:
			diff = base.diff(t0,t1)
		except ValueError:
			print ''
			print 'Value Error'
			print ''
			i += 1
			continue
		
		files = [p for p in diff]
		
		if len(files) == 1:
			file_xsmall += 1
		if len(files) >= 2 and len(files) <= 4:
			file_small += 1
		if len(files) >= 5 and len(files) <= 7:
			file_medium += 1
		if len(files) >= 8 and len(files) <= 10:
			file_large += 1
		if len(files) >= 11:
			file_xlarge += 1
		
		hunksInCommit = 0
		linesInCommit = 0

		for modfile in files:
			hunksInCommit += len(modfile.hunks)
			for hunk in modfile.hunks:
				for line in hunk.lines:
					if line[0] == '-' or line[0] == '+':
						linesInCommit += 1


		if hunksInCommit <= 1:
			hunk_xsmall += 1
		if hunksInCommit >= 2 and hunksInCommit <= 8:
			hunk_small += 1
		if hunksInCommit >= 9 and hunksInCommit <= 17:
			hunk_medium += 1
		if hunksInCommit >= 18 and hunksInCommit <= 26:
			hunk_large += 1
		if hunksInCommit >= 27:
			hunk_xlarge += 1

		if linesInCommit <= 5:
			line_xsmall += 1
		if linesInCommit >= 6 and linesInCommit <= 46:
			line_small += 1
		if linesInCommit >= 47 and linesInCommit <= 106:
			line_medium += 1
		if linesInCommit >= 107 and linesInCommit <= 166:
			line_large += 1
		if linesInCommit >= 167:
			line_xlarge += 1

		i += 1
	print ''

	ts = time.time()
	st = datetime.datetime.fromtimestamp(ts).strftime('-%Y-%m-%d.%H.%M.%S')
	name = repo.replace('/.git', '') + st + '.txt'
	output = open(name,'w')

	output.write('--------- ' + repo + ' ----------' + '\n')
	output.write('Number of Lines Modified:' + '\n')
	output.write('x-small: ' + str( + line_xsmall) + '\n')
	output.write('small: ' + str(line_small) + '\n')
	output.write('medium: ' + str(line_medium) + '\n')
	output.write('large: ' + str(line_large) + '\n')
	output.write('x-large: ' + str(line_xlarge) + '\n')
#.........这里部分代码省略.........
开发者ID:dtg3,项目名称:sevo-git-research,代码行数:103,代码来源:gitreap.py

示例12: GitMixin

# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import revparse_single [as 别名]
class GitMixin(object):

    tag_or_remote_regex = re.compile('^refs/(tags|remotes)/(.*)')

    def __init__(self):
        where = GitOperations.get_repository_location(self.user, self.name)
        self.ondisk = Repository(where)

    def refresh(self):
        creds = GitOperations.get_credentials(self.git_user, self.user)
        for remote in self.ondisk.remotes:
            remote.credentials = creds
            remote.fetch()
        # update current reference
        master_ref = self.ondisk.lookup_reference('refs/heads/master')
        remote_ref = self.ondisk.lookup_reference('refs/remotes/origin/master')
        master_ref.set_target(remote_ref.target)

    def filter_references(self, regex):
        return [ref for ref in self.ondisk.listall_references()
                if regex.match(ref)]

    def get_commit_time(self, name):
        ref = self.ondisk.revparse_single(name)
        if isinstance(ref, Tag):
            return ref.get_object().commit_time
        if isinstance(ref, Commit):
            return ref.commit_time
        raise GitException('invalid reference: commit time could not be found.') # pragma: no cover

    def get_latest_refs(self, count=None):
        info = self.filter_references(GitMixin.tag_or_remote_regex)
        refs = list(zip(info, map(self.get_commit_time, info)))
        refs.sort(key=itemgetter(1), reverse=True)
        def ref_info(info):
            (ref, commit_time) = info
            what, name = GitMixin.tag_or_remote_regex.findall(ref)[0]
            return (what, name, commit_time)
        refs = map(ref_info, refs)
        if not count:
            return refs
        return islice(refs, count)

    def filter_commits(self, flags=0):
        all_commits = self.ondisk.walk(self.ondisk.head.target, flags)
        emails = [ue.email for ue in self.user.emails.all()]
        return filter(lambda commit: commit.author.email in emails, all_commits)

    def get_commits(self, count=None):
        all_commits = self.filter_commits(GIT_SORT_TOPOLOGICAL)
        if not count:
            return all_commits
        return islice(all_commits, count)

    def get_commit_count(self):
        return len(list(self.filter_commits()))

    def get_shorthand_of_branch(self, branch):
        commit = self.ondisk.lookup_branch(branch)
        if commit:
            return commit.shorthand
        return '(none)'

    def get_sha1_of_branch(self, branch):
        commit = self.ondisk.lookup_branch(branch)
        if commit:
            return str(commit.get_object().id)[:6]
        return '(none)'

    def get_numstat(self, commit):
        diff = None
        try:
            previous_commit = self.ondisk.revparse_single(str(commit.id) + '^')
            diff = self.ondisk.diff(previous_commit, commit)
        except KeyError:
            # likely we hit the very first commit.
            diff = commit.tree.diff_to_tree(swap=True)
        additions, deletions = 0, 0
        for patch in diff:
            additions += patch.additions
            deletions += patch.deletions
        return (len(diff), additions, deletions)

    def get_first_updated(self):
        all_commits = self.ondisk.walk(self.ondisk.head.target,
                                       GIT_SORT_TIME | GIT_SORT_REVERSE)
        first_commit = next(all_commits)
        return first_commit.commit_time

    def get_last_updated(self):
        all_commits = self.ondisk.walk(self.ondisk.head.target,
                                       GIT_SORT_TIME)
        last_commit = next(all_commits)
        return last_commit.commit_time

    def get_file_count(self):
        diff = self.ondisk.head.get_object().tree.diff_to_tree()
        return len([patch.old_file_path for patch in diff])

    def get_line_count(self):
#.........这里部分代码省略.........
开发者ID:cantsin,项目名称:git-tracker,代码行数:103,代码来源:git.py


注:本文中的pygit2.Repository.revparse_single方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。