我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用git.InvalidGitRepositoryError()。
def process(self): """Initialises Mimiron using the configuration found in `config_path`.""" for i, repo in enumerate(self.data['terraformRepositories']): repo['path'] = os.path.expanduser(repo['path']) try: git_repo = Repo(repo['path']) if git_repo.bare: raise _InvalidGitRepositoryError repo['defaultEnvironment'] = repo.get('defaultEnvironment', None) repo['tagEnvironment'] = repo.get('tagEnvironment', None) repo['git'] = git_repo repo['tfvars'] = self._read_tfvars(repo) except _InvalidGitRepositoryError: raise InvalidGitRepository(repo['path']) except _NoSuchPathError: raise DeploymentRepositoriesNotSpecified
def check_multiple_branches(repository): """Check whether a git repository has more than one branch. Parameters ---------- repository : string Path to a git repository Results ------- boolean True if the repository has more than 1 branch, False otherwise Raises ------ git.InvalidGitRepositoryError if repository is a path to a directory but not a git repository git.NoSuchPathError if repository is not a path to a directory """ repo = git.Repo(repository) branches = repo.branches if len(branches) > 1: return True else: return False
def __init__(self, root, testMode=False): super(GitManager, self).__init__() self.root = root self.commitTable = {} # ??????????(submodule, last push binsha)??? self.ownerRepo = None try: self.problemHub = git.Repo(root) self.readLastCommitBinsha() except git.InvalidGitRepositoryError: if not testMode: self.problemHub = self.setup() else: pass except FileNotFoundError: self.commitTable = {} # self.acrot = git.Actor(author, authorEmaill) # def __str__(self):
def history(directory, filename, index): """ Generate a report over a model's git commit history. DIRECTORY: Expect JSON files corresponding to the branch's commit history to be found here. Can also be supplied via the environment variable MEMOTE_DIRECTORY or configured in 'setup.cfg' or 'memote.ini'. """ try: repo = git.Repo() except git.InvalidGitRepositoryError: LOGGER.critical( "The history report requires a git repository in order to check " "the current branch's commit history.") sys.exit(1) api.history_report(repo, directory, filename, index)
def probe_git(): """Return a git repository instance if it exists.""" try: repo = git.Repo() except git.InvalidGitRepositoryError: LOGGER.warning( "We highly recommend keeping your model in a git repository." " It allows you to track changes and to easily collaborate with" " others via online platforms such as https://github.com.\n") return if repo.is_dirty(): LOGGER.critical( "Please git commit or git stash all changes before running" " the memote suite.") sys.exit(1) return repo
def create_wiki(articles_path=None, debug=False): app = Flask(__name__) app.debug = debug app.config['articles_path'] = articles_path if articles_path \ else os.path.abspath(os.path.curdir) try: app.config['bock_core'] = BockCore( articles_path=app.config['articles_path'] ) except InvalidGitRepositoryError: logger.error('{} is not a git repository'.format( app.config['articles_path']) ) sys.exit(1) except NoSuchPathError: logger.error('{} is not a valid filesystem path'.format( app.config['articles_path']) ) sys.exit(1) else: logger.info('Set article path to {}'.format( app.config['articles_path']) ) app.config['github_key'] = os.getenv('BOCK_GITHUB_KEY', 'XXX') logger.info('Set Github key to {}'.format(app.config['github_key'])) # Register API and UI blueprints from .api import api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') from .ui import ui_blueprint app.register_blueprint(ui_blueprint) return app
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
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'
def test_check_multiple_branches_nonexistent_repo(): with pytest.raises(git.InvalidGitRepositoryError): check_multiple_branches('tests/fixtures/pic-folder')
def test_check_for_develop_branch_nonexistent_repo(): with pytest.raises(git.InvalidGitRepositoryError): check_for_develop_branch('tests/fixtures/pic-folder', 'dev')
def test_check_for_multiple_commits_nonexistent_repo(): with pytest.raises(git.InvalidGitRepositoryError): check_for_multiple_commits('tests/fixtures/pic-folder')
def check_for_develop_branch(repository, dev_branch_name): """Check whether a git repository has a branch with a specific name. Parameters ---------- repository : string Path to a git repository dev_branch_name : string Desired branch name to check for Results ------- boolean True if any of the repository's branches are named dev_branch_name Raises ------ git.InvalidGitRepositoryError if repository is a path to a directory but not a git repository git.NoSuchPathError if repository is not a path to a directory """ repo = git.Repo(repository) branches = repo.branches for branch in branches: if dev_branch_name in branch.name: break else: return False return True
def get_git_version(path): try: import git except ImportError: print("Updating and precise version information requires ") print("gitpython to be installed.") print("Try: pip install gitpython") return None try: repo = git.Repo(path) return repo.git.rev_parse('HEAD', short=12) except git.InvalidGitRepositoryError: # path is not a git repository return None
def __is_valid_repo(self, path): try: git.Repo(path) return True except git.InvalidGitRepositoryError: return False
def update(self, branch=None): branch = branch or self.config.published_branch if not self.git_has_remote: return if not self.__remote_available: logger.warning("Cannot connect to remote repository hosted on {}. Continuing locally with potentially outdated code.".format( self.__remote_host)) return logger.info("Fetching updates to the knowledge repository...") self.git_remote.fetch() current_branch = self.git.active_branch self.git.branches.master.checkout() self.git_remote.pull(branch) try: sm = self.git.submodule('embedded_knowledge_repo') except ValueError: # This repository does not use embedded knowledge_repo tools or it is misnamed # Check for misnamed submodule sm = None for submodule in self.git.submodules: if submodule.path == '.resources': sm = submodule break if sm is not None: sm_target_url = sm.config_reader().get_value('url') try: sm_actual_url = sm.module().git.config('--get', 'remote.origin.url') except git.InvalidGitRepositoryError: sm_actual_url = "the uninitialized state" if sm_target_url != sm_actual_url: logging.info('Migrating embedded tooling from {} to {}.'.format(sm_actual_url, sm_target_url)) self.git.git.submodule('sync') self.git.git.submodule('update', '--init', '--recursive', '--remote', '--force', '--checkout') sm.update(init=True, force=True) current_branch.checkout()
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")
def freeze(self): for section in self.config.sections(): if section == "supported_types": continue for name, path in self.config.items(section): if name not in PLUGINS_REGISTRY: with open(os.path.join(path, "plugin.spec"), "r") as pls: plugin_spec = yaml.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"] PLUGINS_REGISTRY[name] = dict( type=plugin_type, desc=plugin_spec[ "subparsers"].items()[0][1]["description"]) try: repo = git.Repo(path) PLUGINS_REGISTRY[name]["src"] = list( repo.remote().urls)[-1].encode("ascii") PLUGINS_REGISTRY[name]["rev"] = repo.head.commit.hexsha.encode("ascii") except git.InvalidGitRepositoryError: PLUGINS_REGISTRY[name]["src"] = path.replace( "".join([os.path.split(PLUGINS_DIR)[0], os.path.sep]), "") with open(PLUGINS_REGISTRY_FILE, "w") as fd: yaml.dump(PLUGINS_REGISTRY, fd, default_flow_style=False, explicit_start=True, allow_unicode=True)
def get(): try: return git.Repo(path.dirname(path.dirname(anubis.__file__))).git.describe(always=True, dirty=True) except (git.InvalidGitRepositoryError, git.GitCommandError) as e: _logger.error('Failed to get respository: %s', repr(e)) return 'unknown'
def __set_url_from_git(self): if not self.url: try: repo = Repo(self.path) self.config.url = repo.remotes.origin.url # TODO remove .git ending? except InvalidGitRepositoryError: return if not self.fullname: self.config.fullname_from_git(self.url, self.name)
def __set_git_vsn(self): if not self.git_tag and self.path: try: repo = Repo(self.path) tag_name = None for tag in repo.tags: if tag.commit == repo.head.commit: tag_name = tag.path if tag_name: paths = tag_name.split('/') [tag] = paths[-1:] self.config.git_tag = tag self.config.git_branch = repo.active_branch.name except (InvalidGitRepositoryError, TypeError): return
def history(model, directory, pytest_args, commits): """ Re-compute test results for the git branch history. This command requires the model file to be supplied either by the environment variable MEMOTE_MODEL or configured in a 'setup.cfg' or 'memote.ini' file. There are two distinct modes: \b 1. Completely re-compute test results for each commit in the git history. This should only be necessary when memote is first used with existing model repositories. 2. By giving memote specific commit hashes, it will re-compute test results for those only. """ if "--tb" not in pytest_args: pytest_args = ["--tb", "no"] + pytest_args try: repo = git.Repo() branch = repo.active_branch # TODO: If no directory was given use system tempdir and create report in # gh-pages. except git.InvalidGitRepositoryError: LOGGER.critical( "The history requires a git repository in order to follow " "the current branch's commit history.") sys.exit(1) if len(commits) > 0: # TODO: Convert hashes to `git.Commit` instances. raise NotImplementedError(u"Coming soon™.") else: commits = list(branch.commit.iter_parents()) commits.insert(0, branch.commit) for commit in commits: repo.git.checkout(commit) LOGGER.info( "Running the test suite for commit '{}'.".format(commit.hexsha)) filename = join(directory, "{}.json".format(commit.hexsha)) proc = Process(target=_test_history, args=(model, filename, pytest_args)) proc.start() proc.join() repo.git.checkout(branch) # repo.head.reset(index=True, working_tree=True) # superfluous?