Python git.Head() Examples

The following are 10 code examples of git.Head(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module git , or try the search function .
Example #1
Source File: git_fs.py    From gigantum-client with MIT License 6 votes vote down vote up
def list_branches(self) -> Dict[str, List[str]]:
        """Method to list branches. Should return a dictionary of the format:

            {
                "local": [<name>, ...]
                "remote": [<name>, ...]
            }

            where local are branches currently available locally

        Returns:
            dict
        """
        local = []
        remote = []
        for ref in self.repo.refs:
            if type(ref) == Head:
                local.append(ref.name)
            elif type(ref) == RemoteReference:
                remote.append(ref.name)

        return {"local": local, "remote": remote} 
Example #2
Source File: base.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def _set_cache_(self, attr):
        if attr in ('path', '_url', '_branch_path'):
            reader = self.config_reader()
            # default submodule values
            try:
                self.path = reader.get('path')
            except cp.NoSectionError:
                raise ValueError("This submodule instance does not exist anymore in '%s' file"
                                 % osp.join(self.repo.working_tree_dir, '.gitmodules'))
            # end
            self._url = reader.get('url')
            # git-python extension values - optional
            self._branch_path = reader.get_value(self.k_head_option, git.Head.to_full_path(self.k_head_default))
        elif attr == '_name':
            raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially")
        else:
            super(Submodule, self)._set_cache_(attr)
        # END handle attribute name 
Example #3
Source File: release.py    From tox with MIT License 5 votes vote down vote up
def create_release_branch(repo: Repo, version: Version) -> Tuple[Remote, Head]:
    print("create release branch from upstream master")
    upstream = get_upstream(repo)
    upstream.fetch()
    branch_name = f"release-{version}"
    release_branch = repo.create_head(branch_name, upstream.refs.master, force=True)
    upstream.push(refspec=f"{branch_name}:{branch_name}", force=True)
    release_branch.set_tracking_branch(repo.refs[f"{upstream.name}/{branch_name}"])
    release_branch.checkout()
    return upstream, release_branch 
Example #4
Source File: test_git_scraper.py    From probe-scraper with Mozilla Public License 2.0 5 votes vote down vote up
def get_repo(repo_name):
    directory = os.path.join(test_dir, repo_name)
    repo = Repo.init(directory)
    # Ensure the default branch is using a fixed name.
    # User config could change that,
    # breaking tests with implicit assumptions further down the line.
    repo.head.reference = Head(repo, 'refs/heads/master')

    # We need to synthesize the time stamps of commits to each be a second
    # apart, otherwise the commits may be at exactly the same second, which
    # means they won't always sort in order, and thus the merging of identical
    # metrics in adjacent commits may not happen correctly.
    base_time = time.time()

    base_path = os.path.join(base_dir, repo_name)
    for i in range(num_commits):
        files_dir = os.path.join(base_path, str(i))
        if not os.path.exists(files_dir):
            break

        files = os.listdir(files_dir)
        for filename in files:
            print("Copying file " + filename)
            path = os.path.join(base_path, str(i), filename)
            destination = os.path.join(directory, filename)
            shutil.copyfile(path, destination)

        repo.index.add("*")
        commit_date = datetime.datetime.fromtimestamp(base_time + i).isoformat()
        commit_date = commit_date[:commit_date.find('.')]
        repo.index.commit(
            "Commit {index}".format(index=i),
            commit_date=commit_date
        )

    return directory 
Example #5
Source File: base_git.py    From packit with MIT License 5 votes vote down vote up
def create_branch(
        self, branch_name: str, base: str = "HEAD", setup_tracking: bool = False
    ) -> git.Head:
        """
        Create a new git branch in dist-git

        :param branch_name: name of the branch to check out and fetch
        :param base: we base our new branch on this one
        :param setup_tracking: set up remote tracking
               (exc will be raised if the branch is not in the remote)
        :return the branch which was just created
        """
        # it's not an error if the branch already exists
        origin = self.local_project.git_repo.remote("origin")
        if branch_name in self.local_project.git_repo.branches:
            logger.debug(
                f"It seems that branch {branch_name!r} already exists, checking it out."
            )
            head = self.local_project.git_repo.branches[branch_name]
        else:
            head = self.local_project.git_repo.create_head(branch_name, commit=base)

        if setup_tracking:
            if branch_name in origin.refs:
                remote_ref = origin.refs[branch_name]
            else:
                raise PackitException(
                    f"Remote origin doesn't have ref {branch_name!r}."
                )
            # this is important to fedpkg: build can't find the tracking branch otherwise
            head.set_tracking_branch(remote_ref)

        return head 
Example #6
Source File: gitrepository.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def git_branch(self, branch=None):
        if isinstance(branch, git.Head):
            return branch
        if branch is None:
            return self.git.active_branch

        if not isinstance(branch, str):
            raise ValueError("'{}' of type `{}` is not a valid branch descriptor.".format(branch, type(branch)))

        try:
            return self.git.branches[branch]
        except IndexError:
            raise ValueError("Specified branch `{}` does not exist.".format(branch)) 
Example #7
Source File: util.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def mkhead(repo, path):
    """:return: New branch/head instance"""
    return git.Head(repo, git.Head.to_full_path(path)) 
Example #8
Source File: root.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, repo):
        # repo, binsha, mode=None, path=None, name = None, parent_commit=None, url=None, ref=None)
        super(RootModule, self).__init__(
            repo,
            binsha=self.NULL_BIN_SHA,
            mode=self.k_default_mode,
            path='',
            name=self.k_root_name,
            parent_commit=repo.head.commit,
            url='',
            branch_path=git.Head.to_full_path(self.k_head_default)
        ) 
Example #9
Source File: base.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def branch_name(self):
        """:return: the name of the branch, which is the shortest possible branch name"""
        # use an instance method, for this we create a temporary Head instance
        # which uses a repository that is available at least ( it makes no difference )
        return git.Head(self.repo, self._branch_path).name 
Example #10
Source File: base.py    From bazarr with GNU General Public License v3.0 4 votes vote down vote up
def iter_items(cls, repo, parent_commit='HEAD'):
        """:return: iterator yielding Submodule instances available in the given repository"""
        pc = repo.commit(parent_commit)         # parent commit instance
        try:
            parser = cls._config_parser(repo, pc, read_only=True)
        except IOError:
            raise StopIteration
        # END handle empty iterator

        rt = pc.tree                                # root tree

        for sms in parser.sections():
            n = sm_name(sms)
            p = parser.get(sms, 'path')
            u = parser.get(sms, 'url')
            b = cls.k_head_default
            if parser.has_option(sms, cls.k_head_option):
                b = str(parser.get(sms, cls.k_head_option))
            # END handle optional information

            # get the binsha
            index = repo.index
            try:
                sm = rt[p]
            except KeyError:
                # try the index, maybe it was just added
                try:
                    entry = index.entries[index.entry_key(p, 0)]
                    sm = Submodule(repo, entry.binsha, entry.mode, entry.path)
                except KeyError:
                    raise InvalidGitRepositoryError(
                        "Gitmodule path %r did not exist in revision of parent commit %s" % (p, parent_commit))
                # END handle keyerror
            # END handle critical error

            # fill in remaining info - saves time as it doesn't have to be parsed again
            sm._name = n
            if pc != repo.commit():
                sm._parent_commit = pc
            # end set only if not most recent !
            sm._branch_path = git.Head.to_full_path(b)
            sm._url = u

            yield sm
        # END for each section

    #} END iterable interface