Get a git version (i.e. a git commit hash) for this instance.
420531
def get_version(self, cached=True):
        """"""
        if hasattr(self.__class__, '_version') and cached:
            version = self.__class__._version
        else:
            repo = self.get_repo()
            if repo is not None:
                head = repo.head
                version = head.commit.hexsha
                if repo.is_dirty():
                    version += "*"
            else:
                version = None
        self.__class__._version = version
        return version
734073
function getSHA() {
      git.exec(versionOptions, function(error, version) {
        version = version.trim();
        createRelease(version);
      });
    }
841875
def get_git_hash():
    
    # Obtain git revision
    githash = ""
    if os.path.isdir(os.path.join(basedir, '.git')):
        try:
            proc = subprocess.Popen(
                ['git', '-C', basedir, 'rev-parse', 'HEAD'],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            rev, err = proc.communicate()
            if proc.returncode == 0:
                githash = rev.strip().decode('ascii')
        except OSError:
            pass
    return githash
1135672
def get_sha(self) -> str:
        
        current_sha: str = self.repo.head.commit.hexsha
        LOGGER.debug('current commit SHA: %s', current_sha)
        return current_sha
652970
def get_version(version):
    ""
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')
    parts = 2 if version[2] == 0 else 3
    main = '.'.join(map(str, version[:parts]))
    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        git_changeset = get_git_changeset()
        if git_changeset:
            sub = '.dev%s' % git_changeset
    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])
    return main + sub
240968
def make_version(ref=None):
    """"""
    cmd = 'git describe --tags --abbrev=6 {}'.format(ref or '')
    with hide('commands'):
        version = local(cmd, capture=True).strip()
    if re.match('^v[0-9]', version):
        version = version[1:]
    # replacements to match semver.org build numbers
    if '-' in version:
        head, _, tail = version.partition('-')
        count, _, sha = tail.partition('-g')
        version = head + '+' + count + '-' + sha
    return version
400665
def _get_repo():
    """"""
    command = ['git', 'rev-parse', '--show-toplevel']
    if six.PY2:
        try:
            return check_output(command).decode('utf-8').strip()    # nosec
        except CalledProcessError:
            return ''
    else:
        return (run(command, stdout=PIPE, stderr=PIPE)
                .stdout.decode('utf-8').strip())
548538
def versions(self, rev=None, index=None):
        """"""
        raise NotImplementedError
        _revisions = [line.split()[0] for line in self.log.split('\n') if line]
        _versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]
        if index is not None and len(_versions) > index:
            _versions = _versions[index]
        return _versions
965835
def get_versions():
    """"""
    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
    # __file__, we can work backwards from there to the root. Some
    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
    # case we can only use expanded keywords.

    cfg = get_config()
    verbose = cfg.verbose

    try:
        return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
                                          verbose)
    except NotThisMethod:
        pass

    try:
        root = os.path.realpath(__file__)
        # versionfile_source is the relative path from the top of the source
        # tree (where the .git directory might live) to this file. Invert
        # this to find the root from __file__.
        for i in cfg.versionfile_source.split('/'):
            root = os.path.dirname(root)
    except NameError:
        return {"version": "0+unknown", "full-revisionid": None,
                "dirty": None,
                "error": "unable to find root of source tree"}

    try:
        pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
        return render(pieces, cfg.style)
    except NotThisMethod:
        pass

    try:
        if cfg.parentdir_prefix:
            return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
    except NotThisMethod:
        pass

    _version_path = os.path.join(os.path.dirname(__file__), '_version')
    if os.path.exists(_version_path):
        with open(_version_path) as f:
            l = f.readline().strip()
            return {
                'version': l,
                'error': None,
                'dirty': None,
                'full-revisionid': l
            }

    return {"version": "0+unknown", "full-revisionid": None,
            "dirty": None,
            "error": "unable to compute version"}
1254428
public function getGitVersion()
    {
        try {
            return $this->getGitTag();
        } catch (RuntimeException $exception) {
            try {
                return $this->getGitHash(true);
            } catch (RuntimeException $exception) {
                throw new RuntimeException(
                    sprintf(
                        'The tag or commit hash could not be retrieved from "%s": %s',
                        dirname($this->file),
                        $exception->getMessage()
                    ),
                    0,
                    $exception
                );
            }
        }
    }
417971
def get_version():
    """"""
    module_path = get_absolute_path('pip_save', '__init__.py')
    with open(module_path) as handle:
        for line in handle:
            match = re.match(r'^__version__\s*=\s*["\']([^"\']+)["\']$', line)
            if match:
                return match.group(1)
    raise Exception("Failed to extract version from %s!" % module_path)
595808
def get_gitpython_version():
    
    # if not in git clone, it doesn't matter
    if not in_git_clone():
        return 'GitPython'

    # otherwise, call out to get the git version
    try:
        gitv = subprocess.check_output('git --version', shell=True)
    except (OSError, IOError, subprocess.CalledProcessError):
        # no git installation, most likely
        git_version = '0.0.0'
    else:
        if isinstance(gitv, bytes):
            gitv = gitv.decode('utf-8')
        git_version = gitv.strip().split()[2]

    # if git>=2.15, we need GitPython>=2.1.8
    if LooseVersion(git_version) >= '2.15':
        return 'GitPython>=2.1.8'
    return 'GitPython'
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
            )
428604
function parseVersion(str) {
  var match = /git version ([0-9\.]+)/.exec(str);

  if (match) {
    return match[1];
  } else {
    throw new Error('Unable to parse version response', str);
  }
}
547575
function getVersion(repo) {
    const git = path.join(repo, '.git');
    const headPath = path.join(git, 'HEAD');
    let head;
    try {
        head = fs.readFileSync(headPath, 'utf8').trim();
    }
    catch (e) {
        return undefined;
    }
    if (/^[0-9a-f]{40}$/i.test(head)) {
        return head;
    }
    const refMatch = /^ref: (.*)$/.exec(head);
    if (!refMatch) {
        return undefined;
    }
    const ref = refMatch[1];
    const refPath = path.join(git, ref);
    try {
        return fs.readFileSync(refPath, 'utf8').trim();
    }
    catch (e) {
        // noop
    }
    const packedRefsPath = path.join(git, 'packed-refs');
    let refsRaw;
    try {
        refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
    }
    catch (e) {
        return undefined;
    }
    const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
    let refsMatch;
    let refs = {};
    while (refsMatch = refsRegex.exec(refsRaw)) {
        refs[refsMatch[2]] = refsMatch[1];
    }
    return refs[ref];
}
39739
def getVersionString():
    
    version_string = None
    try:
        version_string = subprocess.check_output(['git', 'describe'])
    except:
        logger.warning('Command "git describe" is not working')

    if version_string == None:  # noqa
        try:
            path_to_version = os.path.join(path_to_script,
                                           '../.git/refs/heads/master')
            with file(path_to_version) as f:
                version_string = f.read()
        except:
            logger.warning('Problem with reading file ".git/refs/heads/master"')

    if version_string == None:  # noqa
        try:
            path_to_version = os.path.join(path_to_script, '../__VERSION__')
            with file(path_to_version) as f:
                version_string = f.read()
            path_to_version = path_to_version + \
                              '  version number is created manually'

        except:
            logger.warning('Problem with reading file "__VERSION__"')

    return version_string
259161
public Version getVersion() throws GitLabApiException {

        class VersionApi extends AbstractApi {
            VersionApi(GitLabApi gitlabApi) {
                super(gitlabApi);
            }
        }

        Response response = new VersionApi(this).get(Response.Status.OK, null, "version");
        return (response.readEntity(Version.class));
    }