Starts the detection of unsynced Git data.
490866
def start_push_sync(self):
        
        self.active_thread = True
        self.active_push = True

        self.thread_push_instance = Thread(target=self.thread_push)
        self.thread_push_instance.daemon = True
        self.thread_push_instance.start()
31329
def _is_gitted(self):
        
        from os import waitpid
        from subprocess import Popen, PIPE
    
        premote = Popen("cd {}; git remote -v".format(self.repodir),
                        shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
        waitpid(premote.pid, 0)
        remote = premote.stdout.readlines()
        remerr = premote.stderr.readlines()

        pbranch = Popen("cd {}; git branch".format(self.repodir),
                        shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
        waitpid(pbranch.pid, 0)
        branch = pbranch.stdout.readlines()
        braerr = pbranch.stderr.readlines()

        if len(remote) > 0 and len(remerr) > 0 and len(branch) > 0:
            return ((".git" in remote[0] and "fatal" not in remerr[0])
                    and any(["testing" in b for b in branch]))
        elif self.testmode and len(remote) == 0 and len(branch) == 0 and len(remerr) == 0:
            return True
        else:
            return False
713495
@Override
  protected void startUp() {
    log.info("Starting the " + getClass().getSimpleName());
    log.info("Polling git with interval {} ", this.pollingInterval);

    // Schedule the job config fetch task
    this.scheduledExecutor.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        try {
          if (shouldPollGit()) {
            processGitConfigChanges();
          }
        } catch (GitAPIException | IOException e) {
          log.error("Failed to process git config changes", e);
          // next run will try again since errors could be intermittent
        }
      }
    }, 0, this.pollingInterval, TimeUnit.SECONDS);
  }
304195
def _repos_checked(self, worker, output, error):
        """"""
        if worker.repo in self._checking_repos:
            self._checking_repos.remove(worker.repo)

        if output:
            self._valid_repos.append(worker.repo)

        if len(self._checking_repos) == 0:
            self._download_repodata(self._valid_repos)
542257
def git_try_describe(repo_path):
    
    try:
        p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
                             cwd=repo_path, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        output, _ = p.communicate()
    except:
        return None
    else:
        if p.returncode == 0:
            return output.strip()

    return None
630021
private function doSaveStash()
    {
        $pending = $this->repository->getWorkingCopy()->getDiffPending();
        if (!\count($pending->getFiles())) {
            return;
        }

        try {
            $this->io->write(['<fg=yellow>Detected unstaged changes... Stashing them!</fg=yellow>']);
            $this->repository->run('stash', ['save', '--quiet', '--keep-index', uniqid('grumphp')]);
        } catch (Exception $e) {
            // No worries ...
            $this->io->write([sprintf('<fg=red>Failed stashing changes: %s</fg=red>', $e->getMessage())]);

            return;
        }

        $this->stashIsApplied = true;
        $this->registerShutdownHandler();
    }
283825
def probe_git():
    """"""
    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
1320566
def commit(config, no_verify):
    """"""
    repo = config.repo

    active_branch = repo.active_branch
    if active_branch.name == "master":
        error_out(
            "Can't commit when on the master branch. "
            "You really ought to do work in branches."
        )

    now = time.time()

    def count_files_in_directory(directory):
        count = 0
        for root, _, files in os.walk(directory):
            # We COULD crosscheck these files against the .gitignore
            # if we ever felt overachievious.
            count += len(files)
        return count

    # First group all untracked files by root folder
    all_untracked_files = {}
    for path in repo.untracked_files:
        root = path.split(os.path.sep)[0]
        if root not in all_untracked_files:
            all_untracked_files[root] = {
                "files": [],
                "total_count": count_files_in_directory(root),
            }
        all_untracked_files[root]["files"].append(path)

    # Now filter this based on it being single files or a bunch
    untracked_files = {}
    for root, info in all_untracked_files.items():
        for path in info["files"]:
            age = now - os.stat(path).st_mtime
            # If there's fewer untracked files in its directory, suggest
            # the directory instead.
            if info["total_count"] == 1:
                path = root
            if path in untracked_files:
                if age < untracked_files[path]:
                    # youngest file in that directory
                    untracked_files[path] = age
            else:
                untracked_files[path] = age

    if untracked_files:
        ordered = sorted(untracked_files.items(), key=lambda x: x[1], reverse=True)
        info_out("NOTE! There are untracked files:")
        for path, age in ordered:
            if os.path.isdir(path):
                path = path + "/"
            print("\t", path.ljust(60), humanize_seconds(age), "old")

        # But only put up this input question if one the files is
        # younger than 12 hours.
        young_ones = [x for x in untracked_files.values() if x < 60 * 60 * 12]
        if young_ones:
            ignore = input("Ignore untracked files? [Y/n] ").lower().strip()
            if ignore.lower().strip() == "n":
                error_out(
                    "\n\tLeaving it up to you to figure out what to do "
                    "with those untracked files."
                )
                return 1
            print("")

    state = read(config.configfile)

    try:
        data = load(config.configfile, active_branch.name)
    except KeyError:
        error_out(
            "You're in a branch that was not created with gg.\n"
            "No branch information available."
        )

    print("Commit message: (type a new one if you want to override)")
    msg = data["description"]
    if data.get("bugnumber"):
        if is_bugzilla(data):
            msg = "bug {} - {}".format(data["bugnumber"], data["description"])
            msg = input('"{}" '.format(msg)).strip() or msg
        elif is_github(data):
            msg = input('"{}" '.format(msg)).strip() or msg
            msg += "\n\nPart of #{}".format(data["bugnumber"])

    if data["bugnumber"]:
        question = 'Add the "fixes" mention? [N/y] '
        fixes = input(question).lower().strip()
        if fixes in ("y", "yes"):
            if is_bugzilla(data):
                msg = "fixes " + msg
            elif is_github(data):
                msg = msg.replace("Part of ", "Fixes ")
            else:
                raise NotImplementedError

    # Now we're going to do the equivalent of `git commit -a -m "..."`
    index = repo.index
    files_added = []
    files_removed = []
    for x in repo.index.diff(None):
        if x.deleted_file:
            files_removed.append(x.b_path)
        else:
            files_added.append(x.b_path)
    files_new = []
    for x in repo.index.diff(repo.head.commit):
        files_new.append(x.b_path)

    proceed = True
    if not (files_added or files_removed or files_new):
        info_out("No files to add or remove.")
        proceed = False
        if input("Proceed anyway? [Y/n] ").lower().strip() == "n":
            proceed = True

    if proceed:
        if not repo.is_dirty():
            error_out("Branch is not dirty. There is nothing to commit.")
        if files_added:
            index.add(files_added)
        if files_removed:
            index.remove(files_removed)
        try:
            commit = index.commit(msg)
        except git.exc.HookExecutionError as exception:
            if not no_verify:
                info_out(
                    "Commit hook failed ({}, exit code {})".format(
                        exception.command, exception.status
                    )
                )
                if exception.stdout:
                    error_out(exception.stdout)
                elif exception.stderr:
                    error_out(exception.stderr)
                else:
                    error_out("Commit hook failed.")
            else:
                commit = index.commit(msg, skip_hooks=True)

        success_out("Commit created {}".format(commit.hexsha))

    if not state.get("FORK_NAME"):
        info_out("Can't help you push the commit. Please run: gg config --help")
        return 0

    try:
        repo.remotes[state["FORK_NAME"]]
    except IndexError:
        error_out("There is no remote called '{}'".format(state["FORK_NAME"]))

    push_for_you = (
        input("Push branch to {}? [Y/n] ".format(state["FORK_NAME"])).lower().strip()
    )
    if push_for_you not in ("n", "no"):
        destination = repo.remotes[state["FORK_NAME"]]
        pushed, = destination.push()
        # Was it rejected?
        if (
            pushed.flags & git.remote.PushInfo.REJECTED
            or pushed.flags & git.remote.PushInfo.REMOTE_REJECTED
        ):
            error_out('The push was rejected ("{}")'.format(pushed.summary), False)

            try_force_push = input("Try to force push? [Y/n] ").lower().strip()
            if try_force_push not in ("no", "n"):
                pushed, = destination.push(force=True)
                info_out(pushed.summary)
            else:
                return 0

    else:
        # If you don't want to push, then don't bother with GitHub
        # Pull Request stuff.
        return 0

    if not state.get("GITHUB"):
        if config.verbose:
            info_out(
                "Can't help create a GitHub Pull Request.\n"
                "Consider running: gg github --help"
            )
        return 0

    origin = repo.remotes[state.get("ORIGIN_NAME", "origin")]
    rest = re.split(r"github\.com[:/]", origin.url)[1]
    org, repo = rest.split(".git")[0].split("/", 1)

    # Search for an existing open pull request, and remind us of the link
    # to it.
    search = {
        "head": "{}:{}".format(state["FORK_NAME"], active_branch.name),
        "state": "open",
    }
    for pull_request in github.find_pull_requests(config, org, repo, **search):
        print("Pull Request already created:")
        print("")
        print("\t", pull_request["html_url"])
        break
    else:
        # If no known Pull Request exists, make a link to create a new one.
        github_url = "https://github.com/{}/{}/compare/{}:{}...{}:{}?expand=1"
        github_url = github_url.format(
            org, repo, org, "master", state["FORK_NAME"], active_branch.name
        )
        print("Now, to make a Pull Request, go to:")
        print("")
        success_out(github_url)
    print("(⌘-click to open URLs)")

    return 0
242115
def _check_status(self):
        """"""
        logger.info('Checking repo status')
        status = self.log_call(
            ['git', 'status', '--porcelain'],
            callwith=subprocess.check_output,
            cwd=self.cwd,
        )
        if status:
            raise DirtyException(status)
467173
def guess_github_repo():
    
    p = subprocess.run(['git', 'ls-remote', '--get-url', 'origin'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
    if p.stderr or p.returncode:
        return False

    url = p.stdout.decode('utf-8').strip()
    m = GIT_URL.fullmatch(url)
    if not m:
        return False
    return m.group(1)
1255795
def git_status(self, r):
        '''
        '''
        ret = self._cachedStatus.get(r.filename, None) if r else None
        return ret if ret else ["//", None, None]
467369
def check_repo_ok(self):
        
        from git import Repo, exc
        # Check that git is at the expected commit and that the repo is not
        # dirty
        if self.runner is not None:
            path = self.runner.path
            try:
                repo = Repo(path)
            except(exc.InvalidGitRepositoryError):
                raise Exception("No git repository detected.\nIn order to "
                                "use SEM and its reproducibility enforcing "
                                "features, please create a git repository at "
                                "the root of your ns-3 project.")
            current_commit = repo.head.commit.hexsha
            campaign_commit = self.db.get_commit()

            if repo.is_dirty(untracked_files=True):
                raise Exception("ns-3 repository is not clean")

            if current_commit != campaign_commit:
                raise Exception("ns-3 repository is on a different commit "
                                "from the one specified in the campaign")
256485
def start(name):
    # type: (str) -> None
    
    hotfix_branch = 'hotfix/' + common.to_branch_name(name)
    master = conf.get('git.master_branch', 'master')

    common.assert_on_branch(master)
    common.git_checkout(hotfix_branch, create=True)
515219
def run(self):
        """"""
        sha = VersionUtils.run_git_command(["rev-parse", "HEAD"], self.git_dir)
        tag = self.distribution.get_version()

        if self.has_tag(tag, sha):
            tags_sha = VersionUtils.run_git_command(["rev-parse", tag], self.git_dir)
            if sha != tags_sha:
                logger.error(
                    "git tag {0} sha does not match the sha requesting to be tagged, you need to increment the version number, Skipped Tagging!".format(
                        tag
                    )
                )
                return
            else:
                logger.info(
                    "git tag {0} already exists for this repo, Skipped Tagging!".format(
                        tag
                    )
                )
                return

        logger.info("Adding tag {0} for commit {1}".format(tag, sha))
        if not self.dry_run:
            VersionUtils.run_git_command(
                ["tag", "-m", '""', tag, sha], self.git_dir, throw_on_error=True
            )
            logger.info("Pushing tag {0} to remote {1}".format(tag, self.remote))
            VersionUtils.run_git_command(
                ["push", self.remote, tag], self.git_dir, throw_on_error=True
            )
1113061
def check_non_single_commit_feature(level = :fail)
      commit_count = git.commits.size
      message = "Your feature branch should have a single commit but found #{commit_count}, squash them together!"

      report(level, message) if feature_branch? && commit_count > 1
    end
100150
def check_git():
    """"""
    try:
        with open(os.devnull, "wb") as devnull:
            subprocess.check_call(["git", "--version"], stdout=devnull, stderr=devnull)
    except:
        raise RuntimeError("Please make sure git is installed and on your path.")
379525
def reset(self):
        """"""
        paths = []
        for filename in os.listdir(self.cached_repo):
            if filename.startswith(".git"):
                continue
            path = os.path.join(self.cached_repo, filename)
            if os.path.isfile(path):
                paths.append(path)
            elif os.path.isdir(path):
                for model in os.listdir(path):
                    paths.append(os.path.join(path, model))
        git.remove(self.cached_repo, paths)
        self.contents = {"models": {}, "meta": {}}