Python git.InvalidGitRepositoryError() Examples

The following are 30 code examples of git.InvalidGitRepositoryError(). 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_context.py    From mlflow with Apache License 2.0 6 votes vote down vote up
def _get_git_commit(path):
    try:
        import git
    except ImportError as e:
        _logger.warning(
            "Failed to import Git (the Git executable is probably not on your PATH),"
            " so Git SHA is not available. Error: %s", e)
        return None
    try:
        if os.path.isfile(path):
            path = os.path.dirname(path)
        repo = git.Repo(path, search_parent_directories=True)
        commit = repo.head.commit.hexsha
        return commit
    except (git.InvalidGitRepositoryError, git.GitCommandNotFound, ValueError, git.NoSuchPathError):
        return None 
Example #2
Source File: tools.py    From overiva with MIT License 6 votes vote down vote up
def get_git_hash(directory, length=10):
    '''
    This function will check the state of the git repository.

    * If there is no repo, an InvalidGitRepositoryError is raised.
    * If the repo is dirty, a DirtyRepositoryException is raised.
    * If none of the above applies, the hash of the HEAD commit is returned.

    Parameters
    ----------
    directory: str
        The path to the directory to check.
    length: int
        The number of characters of the hash to return (default 10).
    '''

    # Check the state of the github repository
    repo = Repo(directory, search_parent_directories=True)
    if repo.is_dirty():
        raise DirtyGitRepositoryError('The git repo has uncommited modifications. Aborting simulation.')
    else:
        return repo.head.commit.hexsha[:length] 
Example #3
Source File: git_fs.py    From gigantum-client with MIT License 6 votes vote down vote up
def set_working_directory(self, directory):
        """Method to change the current working directory. Will reset the self.repo reference

        Args:
            directory(str): Absolute path to the working dir

        Returns:
            None
        """
        # Make sure you expand a user dir string
        directory = os.path.expanduser(directory)

        # Update the working dir
        self.working_directory = directory

        # Check to see if the working dir is already a repository
        try:
            self.repo = Repo(directory)
        except InvalidGitRepositoryError:
            # Make sure the working dir exists
            if not os.path.exists(directory):
                os.makedirs(directory)

            # Empty Dir
            self.repo = None 
Example #4
Source File: db_interface.py    From tfutils with MIT License 6 votes vote down vote up
def version_check_and_info(module):
    """Return either git info or standard module version if not a git repo.

    Args:
        module (module): python module object to get info for.

    Returns:
        dict: dictionary of info

    """
    srcpath = inspect.getsourcefile(module)
    try:
        repo = git.Repo(srcpath, search_parent_directories=True)
    except git.InvalidGitRepositoryError:
        log.info('module %s not in a git repo, checking package version' %
                 module.__name__)
        info = version_info(module)
    else:
        info = git_info(repo)
    info['source_path'] = srcpath
    return info 
Example #5
Source File: helpers.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def get_git_version():
    '''
    return the current git version
    '''
    
    import git
    wd = os.getcwd()

    while wd != "/":
        try:
            repo = git.Repo(wd)
            commit = repo.commit()
            return get_commit_version(commit)

        except git.InvalidGitRepositoryError:
            wd = os.path.dirname(wd)
            
    raise Exception("Not in a git Tree") 
Example #6
Source File: version_control.py    From recipy with Apache License 2.0 6 votes vote down vote up
def add_git_info(run, scriptpath):
    """Add information about the git repository holding the source file to the database"""
    try:
        repo = Repo(scriptpath, search_parent_directories=True)
        run["gitrepo"] = repo.working_dir
        run["gitcommit"] = repo.head.commit.hexsha
        run["gitorigin"] = get_origin(repo)

        if not option_set('ignored metadata', 'diff'):
            whole_diff = ''
            diffs = repo.index.diff(None, create_patch=True)
            for diff in diffs:
                whole_diff += "\n\n\n" + "--- {}\n+++ {}\n".format(
                    diff.a_path, diff.b_path) + diff.diff.decode("utf-8")

            run['diff'] = whole_diff
    except (InvalidGitRepositoryError, ValueError):
        # We can't store git info for some reason, so just skip it
        pass


# The released version of PySvn doesn't do local diffs yet, so we have to do
# it the hard way... 
Example #7
Source File: generic.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_repository_status():
        """
        Finds the hashes for every `pyiron` module available.

        Returns:
            pandas.DataFrame: The name of each module and the hash for its current git head.
        """
        module_names = [name for _, name, _ in pkgutil.iter_modules() if name.startswith("pyiron")]

        report = pandas.DataFrame(columns=['Module', 'Git head'], index=range(len(module_names)))
        for i, name in enumerate(module_names):
            try:
                module = importlib.import_module(name)
                repo = Repo(os.path.dirname(os.path.dirname(module.__file__)))
                hash_ = repo.head.reference.commit.hexsha
                report.loc[i] = [name, hash_]
            except InvalidGitRepositoryError:
                report.loc[i] = [name, 'Not a repo']

        return report 
Example #8
Source File: bug_report.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def print_git_info(dirname):
    if not have_gitpython:
        return
    try:
        repo = Repo(dirname, search_parent_directories=True)
    except InvalidGitRepositoryError:
        print("Couldn't find git info")
        return
    cur_commit = repo.commit()
    cur_branch = repo.active_branch
    print("Git info:")
    print("\tCurrent commit %s from branch %s" % (cur_commit.hexsha, cur_branch.name))
    try:
        # EDG: Git is insane, but this should work 99% of the time
        cur_tb = cur_branch.tracking_branch()
        if cur_tb.is_remote():
            remote_name = cur_tb.remote_name
            remote_url = repo.remotes[remote_name].url
            print("\tChecked out from remote %s: %s" % (remote_name, remote_url))
        else:
            print("Tracking local branch %s" % cur_tb.name)
    except:
        print("Could not resolve tracking branch or remote info!") 
Example #9
Source File: vcs.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_update(self, env: ENV_VARS_TYPE) -> Tuple[git.Repo, Any]:
        try:
            repo = self._get_or_create_repo(env)
        except git.InvalidGitRepositoryError:
            logger.info('Convert project [{}] to GIT.'.format(self.proj.id))
            repo = git.Repo.init(self.path)
            repo.create_remote('origin', self.proj.repository)
            with repo.git.custom_environment(**env):
                kwargs = self.options.get("FETCH_KWARGS", dict())
                origin = repo.remote('origin')
                logger.debug('Fetch remote brances for project [{}].'.format(self.proj.id))
                origin.fetch(**kwargs)
                if not list(origin.refs):
                    config_writer = repo.config_writer()
                    config_writer.set_value("user", "email", self.proj.owner.email).release()
                    user_name = self.proj.owner.username
                    if self.proj.owner.last_name and self.proj.owner.first_name:  # nocv
                        user_name = '{u.fist_name} {u.last_name}'.format(u=self.proj.owner)
                    config_writer.set_value("user", "name", user_name).release()
                    repo.git.add(A=True)
                    repo.git.commit(m='Create project from Polemarch.')
                    logger.debug('Push project [{}] as master.'.format(self.proj.id))
                    repo.git.push('--set-upstream', 'origin', 'master')

        results = repo, self.vcs_update(repo, env)
        with raise_context():
            repo.git.checkout(self.target_branch)
        return results 
Example #10
Source File: git.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def clone_kr_to_directory(dir):
    dir = os.path.expanduser(dir)
    if not os.path.exists(dir):
        os.makedirs(dir)
    assert os.path.isdir(dir)

    try:
        repo = git.Repo(dir)
        repo.remote().fetch()
    except git.InvalidGitRepositoryError:
        repo = git.Repo.clone_from(__git_uri__, dir) 
Example #11
Source File: utils.py    From mlflow with Apache License 2.0 5 votes vote down vote up
def _get_git_url_if_present(uri):
    """
    Return the path git_uri#sub_directory if the URI passed is a local path that's part of
    a Git repo, or returns the original URI otherwise.
    :param uri: The expanded uri
    :return: The git_uri#sub_directory if the uri is part of a Git repo,
             otherwise return the original uri
    """
    if '#' in uri:
        # Already a URI in git repo format
        return uri
    try:
        from git import Repo, InvalidGitRepositoryError, GitCommandNotFound, NoSuchPathError
    except ImportError as e:
        print("Notice: failed to import Git (the git executable is probably not on your PATH),"
              " so Git SHA is not available. Error: %s" % e, file=sys.stderr)
        return uri
    try:
        # Check whether this is part of a git repo
        repo = Repo(uri, search_parent_directories=True)

        # Repo url
        repo_url = "file://%s" % repo.working_tree_dir

        # Sub directory
        rlpath = uri.replace(repo.working_tree_dir, '')
        if (rlpath == ''):
            git_path = repo_url
        elif (rlpath[0] == '/'):
            git_path = repo_url + '#' + rlpath[1:]
        else:
            git_path = repo_url + '#' + rlpath
        return git_path
    except (InvalidGitRepositoryError, GitCommandNotFound, ValueError, NoSuchPathError):
        return uri 
Example #12
Source File: test_git_context.py    From mlflow with Apache License 2.0 5 votes vote down vote up
def test_git_run_context_in_context_false(patch_script_name):
    with mock.patch("git.Repo", side_effect=git.InvalidGitRepositoryError):
        assert not GitRunContext().in_context() 
Example #13
Source File: feedstock_io.py    From conda-smithy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_repo(path, search_parent_directories=True):
    repo = None
    try:
        import git

        repo = git.Repo(
            path, search_parent_directories=search_parent_directories
        )
    except ImportError:
        pass
    except git.InvalidGitRepositoryError:
        pass

    return repo 
Example #14
Source File: plugins.py    From infrared with Apache License 2.0 5 votes vote down vote up
def get_plugin_version(self, plugin_name):
        try:
            repo = git.Repo(os.path.join(self.plugins_dir, plugin_name))
            return str(repo.active_branch) + " / " + str(
                repo.head.commit.hexsha)
        except git.InvalidGitRepositoryError:
            return 'builtin' 
Example #15
Source File: plugins.py    From infrared with Apache License 2.0 5 votes vote down vote up
def freeze(self):
        registry = {}
        for section in self.config.sections():
            if section in ["supported_types", "git_orgs"]:
                continue
            for name, path in self.config.items(section):
                if name not in registry:
                    with open(os.path.join(path, "plugin.spec"), "r") as pls:
                        plugin_spec = yaml.safe_load(pls)
                    # support two types of possible plugin spec files
                    plugin_type = plugin_spec["config"]["plugin_type"] \
                        if "config" in plugin_spec \
                        else plugin_spec["plugin_type"]
                    registry[name] = dict(
                        type=plugin_type,
                        desc=plugin_spec[
                            "subparsers"].items()[0][1]["description"])
                try:
                    repo = git.Repo(path)
                    registry[name]["src"] = list(
                        repo.remote().urls)[-1].encode("ascii")
                    registry[name]["rev"] = repo.head.commit.hexsha.encode(
                        "ascii")
                except git.InvalidGitRepositoryError:
                    registry[name]["src"] = path

        for plugin_name, plugin_dict in registry.items():
            print(yaml.dump({plugin_name: plugin_dict},
                            default_flow_style=False,
                            explicit_start=False, allow_unicode=True)) 
Example #16
Source File: __init__.py    From shoebill with GNU General Public License v3.0 5 votes vote down vote up
def setup_git_repo(site_path):
    global git_repo
    try:
        git_repo = Repo(site_path)
    except InvalidGitRepositoryError:
        print "%s is not a valid Git repository" % site_path 
Example #17
Source File: setup.py    From sumatra with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_tip_revision(self, path=os.getcwd()):
        try:
            import git
        except ImportError:
            return ''
        try:
            repo = git.Repo('.')
        except git.InvalidGitRepositoryError:
            return ''
        return repo.head.commit.hexsha[:7] 
Example #18
Source File: repository_info.py    From fiasko_bro with MIT License 5 votes vote down vote up
def __init__(self, path, directories_to_skip=None):
        if not os.path.isdir(path):
            raise FileNotFoundError('Path "{}" not found or is not a directory.'.format(path))
        self.path = path
        self._parsed_py_files = self._get_parsed_py_files(directories_to_skip)
        try:
            self.repo = LocalRepository(path)
        except git.InvalidGitRepositoryError:
            self.repo = None 
Example #19
Source File: gitrepository.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def __is_valid_repo(self, path):
        try:
            git.Repo(path)
            return True
        except git.InvalidGitRepositoryError:
            return False 
Example #20
Source File: gitrepository.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def create(cls, uri):
        path = uri.replace('git://', '')
        if os.path.exists(path):
            try:
                repo = git.Repo(path)
                logger.warning("Repository already exists for uri '{}'. Checking if configuration is needed...".format(uri))
            except git.InvalidGitRepositoryError:
                if os.path.isdir(path):
                    logger.warning("Upgrading existing directory at '{}' to a git knowledge repository...".format(path))
                else:
                    raise RuntimeError("File exists at nominated path: {}. Cannot proceed with repository initialization.".format(path))

        repo = git.Repo.init(path, mkdir=True)

        # Add README and configuration templates
        added_files = 0

        for filename, template in cls.TEMPLATES.items():
            target = os.path.join(path, filename)
            if not os.path.exists(target):
                shutil.copy(template, target)
                repo.index.add([filename])
                added_files += 1
            else:
                logger.warning("Not overriding existing file '{}'.".format(filename))

        if added_files > 0:
            repo.index.commit("Initial creation of knowledge repository.")

        return GitKnowledgeRepository(path) 
Example #21
Source File: pull.py    From old-sovrin with Apache License 2.0 5 votes vote down vote up
def thisRepo():
    cwd = os.getcwd()
    while True:
        try:
            return Repo(cwd)
        except InvalidGitRepositoryError:
            precwd = cwd
            cwd = os.path.dirname(cwd)
            if precwd == cwd:
                raise RuntimeError("no git repo in path") 
Example #22
Source File: repository.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def default_path():
    """Return default repository path."""
    from git import InvalidGitRepositoryError
    from renku.core.commands.git import get_git_home
    try:
        return get_git_home()
    except InvalidGitRepositoryError:
        return '.' 
Example #23
Source File: git.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def __attrs_post_init__(self):
        """Initialize computed attributes."""
        from git import InvalidGitRepositoryError, Repo

        #: Create an instance of a Git repository for the given path.
        try:
            self.repo = Repo(str(self.path))
        except InvalidGitRepositoryError:
            self.repo = None 
Example #24
Source File: file_writer.py    From torchbeast with Apache License 2.0 5 votes vote down vote up
def gather_metadata() -> Dict:
    date_start = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    # Gathering git metadata.
    try:
        import git

        try:
            repo = git.Repo(search_parent_directories=True)
            git_sha = repo.commit().hexsha
            git_data = dict(
                commit=git_sha,
                branch=None if repo.head.is_detached else repo.active_branch.name,
                is_dirty=repo.is_dirty(),
                path=repo.git_dir,
            )
        except git.InvalidGitRepositoryError:
            git_data = None
    except ImportError:
        git_data = None
    # Gathering slurm metadata.
    if "SLURM_JOB_ID" in os.environ:
        slurm_env_keys = [k for k in os.environ if k.startswith("SLURM")]
        slurm_data = {}
        for k in slurm_env_keys:
            d_key = k.replace("SLURM_", "").replace("SLURMD_", "").lower()
            slurm_data[d_key] = os.environ[k]
    else:
        slurm_data = None
    return dict(
        date_start=date_start,
        date_end=None,
        successful=False,
        git=git_data,
        slurm=slurm_data,
        env=os.environ.copy(),
    ) 
Example #25
Source File: setup.py    From airflow with Apache License 2.0 5 votes vote down vote up
def git_version(version_: str) -> str:
    """
    Return a version to identify the state of the underlying git repo. The version will
    indicate whether the head of the current git-backed working directory is tied to a
    release tag or not : it will indicate the former with a 'release:{version}' prefix
    and the latter with a 'dev0' prefix. Following the prefix will be a sha of the current
    branch head. Finally, a "dirty" suffix is appended to indicate that uncommitted
    changes are present.

    :param str version_: Semver version
    :return: Found Airflow version in Git repo
    :rtype: str
    """
    try:
        import git
        try:
            repo = git.Repo(os.path.join(*[my_dir, '.git']))
        except git.NoSuchPathError:
            logger.warning('.git directory not found: Cannot compute the git version')
            return ''
        except git.InvalidGitRepositoryError:
            logger.warning('Invalid .git directory not found: Cannot compute the git version')
            return ''
    except ImportError:
        logger.warning('gitpython not found: Cannot compute the git version.')
        return ''
    if repo:
        sha = repo.head.commit.hexsha
        if repo.is_dirty():
            return '.dev0+{sha}.dirty'.format(sha=sha)
        # commit is clean
        return '.release:{version}+{sha}'.format(version=version_, sha=sha)
    else:
        return 'no_git_version' 
Example #26
Source File: util.py    From cfn-sphere with Apache License 2.0 5 votes vote down vote up
def get_git_repository_remote_url(working_dir):
    if not working_dir:
        return None

    try:
        repo = Repo(working_dir)
        return repo.remotes.origin.url
    except InvalidGitRepositoryError:
        (head, tail) = os.path.split(working_dir)
        if tail:
            return get_git_repository_remote_url(head)
        else:
            return None 
Example #27
Source File: util_tests.py    From cfn-sphere with Apache License 2.0 5 votes vote down vote up
def test_get_git_repository_remote_url_returns_repo_url_from_parent_dir(self, repo_mock):
        url = "http://config.repo.git"
        repo_object_mock = Mock()
        repo_object_mock.remotes.origin.url = url
        repo_mock.side_effect = [InvalidGitRepositoryError, repo_object_mock]

        self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp())) 
Example #28
Source File: util_tests.py    From cfn-sphere with Apache License 2.0 5 votes vote down vote up
def test_get_git_repository_remote_url_returns_none_if_no_repository_present(self, repo_mock):
        repo_mock.side_effect = InvalidGitRepositoryError
        self.assertEqual(None, util.get_git_repository_remote_url(tempfile.mkdtemp())) 
Example #29
Source File: version.py    From vj4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get():
  try:
    return git.Repo(path.dirname(path.dirname(vj4.__file__))).git.describe(always=True, tags=True, dirty=True)
  except (git.InvalidGitRepositoryError, git.GitCommandError) as e:
    _logger.error('Failed to get repository: %s', repr(e))
    return 'unknown' 
Example #30
Source File: dependencies.py    From sacred with MIT License 4 votes vote down vote up
def get_commit_if_possible(filename, save_git_info):
    """Try to retrieve VCS information for a given file.

    Currently only supports git using the gitpython package.

    Parameters
    ----------
    filename : str

    Returns
    -------
        path: str
            The base path of the repository
        commit: str
            The commit hash
        is_dirty: bool
            True if there are uncommitted changes in the repository
    """
    if save_git_info is False:
        return None, None, None

    try:
        from git import Repo, InvalidGitRepositoryError
    except ImportError as e:
        raise ValueError(
            "Cannot import git (pip install GitPython).\n"
            "Either GitPython or the git executable is missing.\n"
            "You can disable git with:\n"
            "    sacred.Experiment(..., save_git_info=False)"
        ) from e

    directory = os.path.dirname(filename)
    try:
        repo = Repo(directory, search_parent_directories=True)
    except InvalidGitRepositoryError:
        return None, None, None
    try:
        path = repo.remote().url
    except ValueError:
        path = "git:/" + repo.working_dir
    is_dirty = repo.is_dirty()
    commit = repo.head.commit.hexsha
    return path, commit, is_dirty