Detect GIT information by folder.

    :param git_folder: Folder
    :param verbose: Verbosity, boolean, default is False
    :return: dict
344321
def get_git_info(git_folder, verbose=False):
    
    if verbose:
        print("detect GIT info by folder: '%s'" % git_folder)
    try:
        git_info = {
            "commitid": get_commit_id(git_folder),
            "branch": get_current_branch(git_folder),
            "git_path": get_git_file_path(git_folder),
            "url": get_remote_url(git_folder),
            "scm": "unknown",
            "scm_group": "unknown",
            "scm_path": "unknown",
            "scm_link": ""
        }
        if is_git_root_dirty(git_folder):
            git_info['dirty'] = True
    except Exception as err:  # pylint: disable=broad-except
        print("GitTool exception:")
        print(err)
        return {}

    if isinstance(git_info['url'], str):
        match = re.search(r"github\.com:(.*)\/(.*)", git_info['url'])
        if match:
            git_info["scm"] = "github.com"
            git_info["scm_path"] = match.group(2)
            git_info["scm_group"] = match.group(1)
            scm_link_end = " %s/%s" % (git_info["scm_group"],
                                       git_info["scm_path"].replace(".git", ""))
            git_info["scm_link"] = "https://github.com/" + scm_link_end
            git_info["scm_link"] += "/tree/%s/%s" % (git_info['commitid'], git_info["git_path"])

    if verbose:
        print("all git_info:")
        print(git_info)

    return git_info
197167
def _set_verbosity(self):
        '''
        
        '''
        # If more than one target file was specified, enable verbose mode; else, there is
        # nothing in some outputs to indicate which scan corresponds to which
        # file.
        if len(self.target_files) > 1 and not self.verbose:
            self.verbose = True
406292
def get_directory_relative_to_git_root(directory: str):
    
    return os.path.relpath(os.path.realpath(directory), get_git_root_directory(directory))
965267
function git(format, options, callback) {
    var joined = path.join(options.repo, '.git');

    if (!fs.existsSync(joined)) {
        callback(new Error('No .git folder detected in the directory \'' + options.repo + '\''), null);
        return;
    }

    var stdout = '';
    var stderr = '';
    var child = spawn(options.git, ['--git-dir=' + joined, 'log', '--pretty=' + format, '-1'], {cwd: process.cwd()});

    child.stdout.setEncoding('utf8');
    child.stdout.on('data', function (data) {
        stdout += data;
    });

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function (data) {
        stderr += data;
    });

    child.on('close', function() {
        if (stderr.length > 0) {
            callback(new Error('An error occurred: \'' + stderr + '\''), null);
        } else {
            var normalized = stdout.replace(/(?:\r\n|\r|\n)/g, '');
            callback(null, normalized);
        }
    });
}
862376
def create_env_by_folder(folder):
    
    global _default_filters
    global _default_tests
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(folder))

    for k, f in _default_filters.iteritems():
        env.filters[k] = f

    for k, f in _default_tests.iteritems():
        env.tests[k] = f

    return env
971161
def tree_lookup(self, target_path, commit):
        
        segments = target_path.split("/")
        tree_or_blob = commit.tree
        path = ''
        while segments:
            dirent = segments.pop(0)
            if isinstance(tree_or_blob, pygit2.Tree):
                if dirent in tree_or_blob:
                    tree_or_blob = self.repo[tree_or_blob[dirent].oid]
                    # self.logger.debug("  %s in %s" % (dirent, path))
                    if path:
                        path += '/'
                    path += dirent
                else:
                    # This is probably because we were called on a
                    # commit whose parent added a new directory.
                    self.logger.debug("        %s not in %s in %s" %
                                      (dirent, path, commit.hex[:8]))
                    return None
            else:
                self.logger.debug("        %s not a tree in %s" %
                                  (tree_or_blob, commit.hex[:8]))
                return None
        return tree_or_blob
87938
function getGitFolderPath(currentPath) {
  var git = path.resolve(currentPath, '.git')

  if (!exists(git) || !fs.lstatSync(git).isDirectory()) {
    console.log('pre-commit:');
    console.log('pre-commit: Not found .git folder in', git);
    
    var newPath = path.resolve(currentPath, '..');

    // Stop if we on top folder
    if (currentPath === newPath) {
      return null;
    }

    return getGitFolderPath(newPath);
  }

  console.log('pre-commit:');
  console.log('pre-commit: Found .git folder in', git);
  return git;
}
68136
def check_for_git_repo(url):
    """"""
    u = parse.urlparse(url)
    is_git = False

    if os.path.splitext(u.path)[1] == '.git':
        is_git = True
    elif u.scheme in ('', 'file'):
        from git import InvalidGitRepositoryError, Repo

        try:
            Repo(u.path, search_parent_directories=True)
            is_git = True
        except InvalidGitRepositoryError:
            is_git = False
    return is_git
947492
def apply(self, folder):
        
        logger.info("Apply Patch File %s", self.file_path)
        command = "git apply {}".format(self.file_path)
        return_code, stream_data = _run_command_inside_folder(command, folder)

        if return_code:
            msg = "Could not apply patch file at {}. Error: {}".format(self.file_path, stream_data)
            logger.error(msg)
            raise RuntimeError(msg)
1233021
def get_vcs_directory(context, directory):
        """"""
        nested = os.path.join(directory, '.git')
        return nested if context.is_directory(nested) else directory
583134
def _checkout(self, treeish):
        '''
        
        '''

        return self.m(
            'checking out "%s"' % (treeish),
            cmdd=dict(cmd='git checkout %s' % (treeish), cwd=self.local),
            verbose=False
        )
436141
def pull_folder(self, path, decode=False):
        
        driver = self._current_application()
        theFolder = driver.pull_folder(path)
        if decode:
            theFolder = base64.b64decode(theFolder)
        return theFolder
1073510
def snapshot_folder():
    
    logger.info("Snapshot folder")
    try:
        stdout = subprocess.check_output(["git", "show", "-s", "--format=%cI", "HEAD"])
    except subprocess.CalledProcessError as e:
        logger.error("Error: {}".format(e.output.decode('ascii', 'ignore').strip()))
        sys.exit(2)
    except FileNotFoundError as e:
        logger.error("Error: {}".format(e))
        sys.exit(2)
    ds = stdout.decode('ascii', 'ignore').strip()
    dt = datetime.fromisoformat(ds)
    utc = dt - dt.utcoffset()
    return utc.strftime("%Y%m%d_%H%M%S")
1019188
def get_git_info():
    """"""
    start_dir = abspath(curdir)
    try:
        chdir(dirname(abspath(__file__)))
        re_patt_str = (r'commit\s+(?P<commit_hash>\w+).*?Author:\s+'
                       r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+'
                       r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$')
        show_out = check_output(['git', 'show']).decode('ascii')
        revp_out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
        revp_out = revp_out.decode('ascii').strip()
        m = re.search(re_patt_str, show_out, re.DOTALL)
        assert m is not None, \
            "Regex pattern:\n\n\"%s\"\n\n failed to match string:\n\n\"%s\"" \
            % (re_patt_str, show_out)
        ret_dict = m.groupdict()
        ret_dict['branch_name'] = revp_out
    finally:
        chdir(start_dir)
    return ret_dict
474984
def set_ignores(self, folder, *patterns):
        
        if not patterns:
            return {}
        data = {'ignore': list(patterns)}
        return self.post('ignores', params={'folder': folder}, data=data)
544652
def _get_rev(self, fpath):
        
        rev = None
        
        try:
            cmd = ["git", "log", "-n1", "--pretty=format:\"%h\"", fpath]
            rev = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()[0]
        except:
            pass
        
        if not rev:
            try:
                cmd = ["svn", "info", fpath]
                svninfo = Popen(cmd,
                                stdout=PIPE,
                                stderr=PIPE).stdout.readlines()
                for info in svninfo:
                    tokens = info.split(":")
                    if tokens[0].strip() == "Last Changed Rev":
                        rev = tokens[1].strip()
            except:
                pass
        
        return rev
639113
public boolean isValidGitRepository(Path folder) {

        if (Files.exists(folder) && Files.isDirectory(folder)) {

            // If it has been at least initialized
            if (RepositoryCache.FileKey.isGitRepository(folder.toFile(), FS.DETECTED)) {
                // we are assuming that the clone worked at that time, caller should call hasAtLeastOneReference
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }