Python git.Repo.init() Examples

The following are 30 code examples of git.Repo.init(). 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.Repo , or try the search function .
Example #1
Source File: updater.py    From friendly-telegram with GNU Affero General Public License v3.0 7 votes vote down vote up
def download_common(self):
        try:
            repo = Repo(os.path.dirname(utils.get_base_dir()))
            origin = repo.remote("origin")
            r = origin.pull()
            new_commit = repo.head.commit
            for info in r:
                if info.old_commit:
                    for d in new_commit.diff(info.old_commit):
                        if d.b_path == "requirements.txt":
                            return True
            return False
        except git.exc.InvalidGitRepositoryError:
            repo = Repo.init(os.path.dirname(utils.get_base_dir()))
            origin = repo.create_remote("origin", self.config["GIT_ORIGIN_URL"])
            origin.fetch()
            repo.create_head("master", origin.refs.master)
            repo.heads.master.set_tracking_branch(origin.refs.master)
            repo.heads.master.checkout(True)
            return False  # Heroku never needs to install dependencies because we redeploy 
Example #2
Source File: hook_test.py    From rdm with MIT License 6 votes vote down vote up
def tmp_repo(tmpdir):
    # initialize new repository and change working directory
    directory = str(tmpdir)
    repo = Repo.init(directory)
    os.chdir(directory)

    # set up logging and trace
    logging.basicConfig()
    logging.root.setLevel(logging.INFO)
    type(repo.git).GIT_PYTHON_TRACE = 'full'

    # create initial commit
    file_path = os.path.join(directory, 'initial-commit.txt')
    subprocess.check_call(['touch', file_path])
    repo.git.add('--all')
    subprocess.check_call(['git', 'config', 'user.email', 'test@innolitics.com'])
    subprocess.check_call(['git', 'config', 'user.name', 'Tester Bot'])
    repo.git.commit('-m', '\'message\'', '--no-verify')

    subprocess.check_call(['rdm', 'hooks'])

    yield repo

    subprocess.check_call(['rm', '-rf', directory]) 
Example #3
Source File: test_repository.py    From gatorgrader with GNU General Public License v3.0 6 votes vote down vote up
def test_one_commit_in_new_repository(tmpdir):
    """Ensure that it is possible to detect one commit in a new Git repository."""
    temp_file = tmpdir.mkdir("sub").join("hello.txt")
    temp_file.write("content")
    assert temp_file.read() == "content"
    assert len(tmpdir.listdir()) == 1
    testing_repository = Repo.init(tmpdir)
    # create an empty file and perform a commit on it
    testing_repository.index.add([str(temp_file)])
    testing_repository.index.commit("Add the hello.txt file.")
    # since the repository was created in the tmpdir
    # the check for the existence of a repository should be True
    detected_git_repository = repository.is_git_repository(str(tmpdir))
    assert detected_git_repository is True
    # since an empty file was committed, the count should be 1
    commits = repository.get_commits(str(tmpdir))
    assert len(commits) == 1 
Example #4
Source File: repository.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def init_repository(self, force=False):
        """Initialize an empty Renku repository."""
        from git import Repo
        from renku.core.models.provenance.agents import Person

        # verify if folder is empty
        if self.repo is not None and not force:
            raise errors.InvalidFileOperation(
                'Folder {0} already contains file. Use --force to overwrite'.
                format(self.repo.git_dir)
            )

        # initialize repo
        path = self.path.absolute()
        self.repo = Repo.init(str(path))

        # verify if author information is available
        Person.from_git(self.repo) 
Example #5
Source File: test_release.py    From flocker with Apache License 2.0 6 votes vote down vote up
def create_git_repository(test_case, bare=False):
    """
    Create a git repository with a ``master`` branch and ``README``.

    :param test_case: The ``TestCase`` calling this.
    """
    directory = FilePath(test_case.mktemp())
    repository = Repo.init(path=directory.path, bare=bare)

    if not bare:
        directory.child('README').makedirs()
        directory.child('README').touch()
        repository.index.add(['README'])
        repository.index.commit('Initial commit')
        repository.create_head('master')
    return repository 
Example #6
Source File: release.py    From pluggy with MIT License 5 votes vote down vote up
def create_branch(version):
    """Create a fresh branch from upstream/master"""
    repo = Repo.init(".")
    if repo.is_dirty(untracked_files=True):
        raise RuntimeError("Repository is dirty, please commit/stash your changes.")

    branch_name = f"release-{version}"
    print(f"{Fore.CYAN}Create {branch_name} branch from upstream master")
    upstream = get_upstream(repo)
    upstream.fetch()
    release_branch = repo.create_head(branch_name, upstream.refs.master, force=True)
    release_branch.checkout()
    return repo 
Example #7
Source File: __main__.py    From git-gud with MIT License 5 votes vote down vote up
def handle_status(self, args):
        if self.is_initialized():
            try:
                level = self.file_operator.get_level()
                level.status()
            except KeyError:
                level_name = self.file_operator.read_level_file()
                print('Currently on unregistered level: "{}"'
                      .format(level_name))
        else:
            print("Git Gud not initialized.")
            print('Initialize using "git gud init"') 
Example #8
Source File: __main__.py    From git-gud with MIT License 5 votes vote down vote up
def parse(self):
        args, _ = self.parser.parse_known_args()
        if args.command is None:
            if not self.is_initialized():
                print('Currently in an uninitialized directory.')
                print('Get started by running "git gud init" in an empty directory!')  # noqa: E501
            else:
                self.parser.print_help()
        else:
            try:
                self.command_dict[args.command](args)
            except InitializationError as error:
                print(error) 
Example #9
Source File: git_fs.py    From gigantum-client with MIT License 5 votes vote down vote up
def initialize(self, bare=False):
        """Initialize a new repo

        Args:
            bare(bool): If True, use the --bare option

        Returns:
            None
        """
        if self.repo:
            raise ValueError("Cannot init an existing git repository. Choose a different working directory")

        logger.info("Initializing Git repository in {}".format(self.working_directory))
        self.repo = Repo.init(self.working_directory, bare=bare) 
Example #10
Source File: git_fs.py    From gigantum-client with MIT License 5 votes vote down vote up
def clone(self, source: str, directory: str, branch: Optional[str] = None, single_branch=False):
        """Clone a repo

        Args:
            source: Git ssh or https string to clone - should be a bare path, or include '/' as a final delimiter
            directory: Directory to clone into
            branch: The name of the desired branch to be checked out (defaults to master)
            single_branch: Fetch ONLY the contents of the specified branch

        Returns:
            None
        """
        if self.repo:
            raise ValueError("Cannot init an existing git repository. Choose a different working directory")

        logger.info("Cloning Git repository from {} into {}".format(source, directory))
        args = []
        if branch is not None:
            args.extend(['--branch', branch])
        if single_branch:
            args.append('--single-branch')

        command_string = ['git', 'clone'] + args + [source, directory]

        clone_process = subprocess.run(command_string, stderr=subprocess.PIPE, cwd=directory)
        if clone_process.returncode == 0:
            self.set_working_directory(directory)
        else:
            raise GitFsException(clone_process.stderr)

    # LOCAL CHANGE METHODS 
Example #11
Source File: git_fs.py    From gigantum-client with MIT License 5 votes vote down vote up
def update_submodules(self, init=True):
        """Method to update submodules and optionally init if needed

        Args:
            init(bool): Flag indicating if submodules should be initialized

        Returns:
            None
        """
        self.repo.submodule_update(init=init) 
Example #12
Source File: git_interface_mixin.py    From gigantum-client with MIT License 5 votes vote down vote up
def mock_initialized_filesystem_with_remote():
    """Create an initialized git lib instance and also create a bare initialized repo

        returns a clone of the repo on master, the working dir for that repo, the bare repo, and the working bare dir

    Returns:
        (gitlib.git.GitRepoInterface, str, gitlib.git.GitRepoInterface, str)
    """
    # Create temporary working directory for the bare repo
    bare_working_dir = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex)
    os.makedirs(bare_working_dir)
    bare_repo = Repo.init(bare_working_dir, bare=True)
    populate_bare_repo(bare_working_dir)

    # Create temporary working directory
    working_dir = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex)
    os.makedirs(working_dir)

    config = {"backend": get_backend(), "working_directory": working_dir}

    # Init the empty repo
    git = get_fs_class()(config)
    git.clone(bare_working_dir, working_dir)

    yield git, working_dir, bare_repo, bare_working_dir  # provide the fixture value

    # Force delete the directory
    shutil.rmtree(bare_working_dir)
    shutil.rmtree(working_dir) 
Example #13
Source File: git_interface_mixin.py    From gigantum-client with MIT License 5 votes vote down vote up
def create_dummy_repo(working_dir):
    """Helper method to create a dummy repo with a file in it"""
    filename = "dummy.txt"
    repo = Repo.init(working_dir)
    with open(os.path.join(working_dir, filename), 'wt') as dt:
        dt.write("entry 1")

    repo.index.add([os.path.join(working_dir, filename)])
    repo.index.commit("initial commit") 
Example #14
Source File: install_hooks_test.py    From rdm with MIT License 5 votes vote down vote up
def tmp_repo(tmpdir):
    directory = str(tmpdir)
    repo = Repo.init(directory)
    os.chdir(directory)
    yield repo
    subprocess.call(['rm', '-rf', directory]) 
Example #15
Source File: release.py    From pluggy with MIT License 5 votes vote down vote up
def main():
    init(autoreset=True)
    parser = argparse.ArgumentParser()
    parser.add_argument("version", help="Release version")
    options = parser.parse_args()
    try:
        pre_release(options.version)
    except RuntimeError as e:
        print(f"{Fore.RED}ERROR: {e}")
        return 1 
Example #16
Source File: test_repository.py    From gatorgrader with GNU General Public License v3.0 5 votes vote down vote up
def test_detect_git_repository(tmpdir):
    """Ensure that it is possible to detect that a directory is not a Git repository."""
    # create a Git repository using GitPython
    _ = Repo.init(str(tmpdir))
    # since the repository was created in the tmpdir
    # the check for the existence of a repository should be True
    detected_git_repository = repository.is_git_repository(str(tmpdir))
    assert detected_git_repository is True 
Example #17
Source File: test_repository.py    From gatorgrader with GNU General Public License v3.0 5 votes vote down vote up
def test_no_commits_in_new_git_repository(tmpdir):
    """Ensure that it is possible to detect that a directory is not a Git repository."""
    # create a Git repository using GitPython
    _ = Repo.init(str(tmpdir))
    # since the repository was created in the tmpdir
    # the check for the existence of a repository should be True
    detected_git_repository = repository.is_git_repository(str(tmpdir))
    assert detected_git_repository is True
    commits = repository.get_commits(str(tmpdir))
    assert len(commits) == 0 
Example #18
Source File: pentagon.py    From pentagon with Apache License 2.0 5 votes vote down vote up
def __git_init(self):
        """ Initialize git repository in the project infrastructure path """
        Repo.init(self._repository_directory) 
Example #19
Source File: datastoragemanager.py    From scrooge with MIT License 5 votes vote down vote up
def __init__(self, store_name):
        self.store_name = store_name
        self.store_storage_dir = os.path.join(settings.ST_STORES_DATA_DIR, store_name)

        os.makedirs(self.store_storage_dir, exist_ok=True)

        if not os.path.exists(os.path.join(self.store_storage_dir, '.git/')):
            self.repo = Repo.init(self.store_storage_dir)
        else:
            self.repo = Repo(self.store_storage_dir)
            self.__asert_is_clean() 
Example #20
Source File: pytest_git.py    From pytest-plugins with MIT License 5 votes vote down vote up
def __init__(self):
        super(GitRepo, self).__init__()
        self.api = Repo.init(self.workspace)
        self.uri = "file://%s" % self.workspace 
Example #21
Source File: test_commit.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_ambiguous_arg_iteration(self, rw_dir):
        rw_repo = Repo.init(osp.join(rw_dir, 'test_ambiguous_arg'))
        path = osp.join(rw_repo.working_tree_dir, 'master')
        touch(path)
        rw_repo.index.add([path])
        rw_repo.index.commit('initial commit')
        list(rw_repo.iter_commits(rw_repo.head.ref))  # should fail unless bug is fixed 
Example #22
Source File: test_docs.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_add_file_and_commit(self, rw_dir):
        import git

        repo_dir = os.path.join(rw_dir, 'my-new-repo')
        file_name = os.path.join(repo_dir, 'new-file')

        r = git.Repo.init(repo_dir)
        # This function just creates an empty file ...
        open(file_name, 'wb').close()
        r.index.add([file_name])
        r.index.commit("initial commit")

        # ![test_add_file_and_commit] 
Example #23
Source File: utils.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def push_repo(token, local_repo, remote_repo, author_name=None, author_email=None,
              user=None, organization=None, auto_remove=False):
    """Initialize a git repo and push the code to the target repo."""
    commit_msg = 'Initial commit'
    if not os.path.exists(local_repo):
        raise ValueError("Directory {} does not exist.".format(local_repo))
    repo = Repo.init(local_repo)
    repo.git.add(all=True)
    # TODO: "openshiftio-launchpad" -> config module
    # TODO: "obsidian-leadership@redhat.com" -> config module
    committer = Actor(author_name or os.getenv("GIT_COMMIT_AUTHOR_NAME", "openshiftio-launchpad"),
                      author_email or os.getenv("GIT_COMMIT_AUTHOR_EMAIL",
                                                "obsidian-leadership@redhat.com"))

    # TODO: refactor this code into new function
    if organization is None:
        # try to fetch user instead of organization
        try:
            organization = Github(token).get_user().login
        except RateLimitExceededException:
            raise HTTPError(403, "Github API rate limit exceeded")
        except BadCredentialsException:
            raise HTTPError(401, "Invalid github access token")
        except Exception as exc:
            raise HTTPError(500, "Unable to get the username {}".format(str(exc)))

    repo.index.commit(commit_msg, committer=committer, author=committer)
    remote_uri = 'https://{user}:{token}@github.com/{user}/{remote_repo}'\
        .format(user=organization, token=token, remote_repo=remote_repo)
    try:
        origin = repo.create_remote('origin', remote_uri)
        origin.push('master')
    except Exception as exc:
        raise HTTPError(500, "Unable to Push the code: {}".format(str(exc.stderr)))
    finally:
        if auto_remove and os.path.exists(local_repo):
            shutil.rmtree(local_repo) 
Example #24
Source File: test_archiver.py    From wily with Apache License 2.0 5 votes vote down vote up
def test_dirty_git(tmpdir):
    """ Check that repository fails to initialise if unchecked files are in the repo """
    repo = Repo.init(path=tmpdir)
    tmppath = pathlib.Path(tmpdir)

    index = repo.index
    author = Actor("An author", "author@example.com")
    committer = Actor("A committer", "committer@example.com")

    # First commit
    with open(tmppath / ".gitignore", "w") as ignore:
        ignore.write(".wily/")

    index.add([".gitignore"])
    commit1 = index.commit("commit1", author=author, committer=committer)

    # Write a test file to the repo
    with open(tmppath / "blah.py", "w") as ignore:
        ignore.write("*.py[co]\n")
    index.add(["blah.py"])
    repo.close()

    config = DEFAULT_CONFIG
    config.path = tmpdir

    with pytest.raises(DirtyGitRepositoryError):
        archiver = GitArchiver(config)
        archiver.revisions(tmpdir, 2) 
Example #25
Source File: heroku.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_repo():
    """Helper to get the repo, making it if not found"""
    try:
        repo = Repo(os.path.dirname(utils.get_base_dir()))
    except InvalidGitRepositoryError:
        repo = Repo.init(os.path.dirname(utils.get_base_dir()))
        origin = repo.create_remote("origin", "https://gitlab.com/friendly-telegram/friendly-telegram")
        origin.fetch()
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)
    return repo 
Example #26
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 #27
Source File: test_build.py    From wily with Apache License 2.0 5 votes vote down vote up
def test_build_crash(tmpdir):
    """
    Simulate a runtime error in the build.
    """
    repo = Repo.init(path=tmpdir)
    tmppath = pathlib.Path(tmpdir)

    # Write a test file to the repo
    with open(tmppath / "test.py", "w") as test_txt:
        test_txt.write("import abc")

    index = repo.index
    index.add(["test.py"])

    author = Actor("An author", "author@example.com")
    committer = Actor("A committer", "committer@example.com")

    index.commit("basic test", author=author, committer=committer)
    repo.close()

    import wily.commands.build

    with patch.object(
        wily.commands.build.Bar, "finish", side_effect=RuntimeError("arggh")
    ) as bar_finish:
        runner = CliRunner()
        result = runner.invoke(main.cli, ["--path", tmpdir, "build", "test.py"])
        assert bar_finish.called_once
        assert result.exit_code == 1, result.stdout 
Example #28
Source File: test_build.py    From wily with Apache License 2.0 5 votes vote down vote up
def test_build(tmpdir, cache_path):
    """
    Test that build works in a basic repository.
    """
    repo = Repo.init(path=tmpdir)
    tmppath = pathlib.Path(tmpdir)

    # Write a test file to the repo
    with open(tmppath / "test.py", "w") as test_txt:
        test_txt.write("import abc")

    index = repo.index
    index.add(["test.py"])

    author = Actor("An author", "author@example.com")
    committer = Actor("A committer", "committer@example.com")

    commit = index.commit("basic test", author=author, committer=committer)
    repo.close()

    runner = CliRunner()
    result = runner.invoke(
        main.cli,
        ["--debug", "--path", tmpdir, "--cache", cache_path, "build", "test.py"],
    )
    assert result.exit_code == 0, result.stdout

    cache_path = pathlib.Path(cache_path)
    assert cache_path.exists()
    index_path = cache_path / "git" / "index.json"
    assert index_path.exists()
    rev_path = cache_path / "git" / (commit.name_rev.split(" ")[0] + ".json")
    assert rev_path.exists() 
Example #29
Source File: test_build.py    From wily with Apache License 2.0 5 votes vote down vote up
def test_build_no_git_history(tmpdir):
    repo = Repo.init(path=tmpdir)
    repo.close()

    with patch("wily.logger") as logger:
        runner = CliRunner()
        result = runner.invoke(main.cli, ["--path", tmpdir, "build", _path])
        assert result.exit_code == 1, result.stdout 
Example #30
Source File: __main__.py    From git-gud with MIT License 5 votes vote down vote up
def assert_initialized(self, skip_level_check=False):
        if not self.is_initialized():
            raise InitializationError('Git gud has not been initialized. Use "git gud init" to initialize')  # noqa: E501

        if not skip_level_check:
            try:
                self.file_operator.get_level()
            except KeyError:
                level_name = self.file_operator.read_level_file()
                raise InitializationError(
                        'Currently loaded level does not exist: "{}"'
                        .format(level_name))