Returns the sha1 commit version of a repository or undefined in case of failure.
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];
}
1158590
def fetch_compare(older, newer)
      unless @compares["#{older}...#{newer}"]
        compare_data = check_github_response { @client.compare(user_project, older, newer || "HEAD") }
        raise StandardError, "Sha #{older} and sha #{newer} are not related; please file a github-changelog-generator issues and describe how to replicate this issue." if compare_data["status"] == "diverged"

        @compares["#{older}...#{newer}"] = stringify_keys_deep(compare_data.to_hash)
      end
      @compares["#{older}...#{newer}"]
    end
431199
def sha1(s):
    
    h = hashlib.new('sha1')
    h.update(s)
    return h.hexdigest()
1336641
def get_version():
        
        try:
            return check_output(
                "git describe --tags".split(" ")
                ).decode('utf-8').strip()
        except CalledProcessError:
            return check_output(
                "git rev-parse --short HEAD".split(" ")
                ).decode('utf-8').strip()
1253305
def patch_ref(self, sha):
        
        uri = "{api}/repos/{origin}/git/refs/heads/{branch}".format(
            api=self.github_api_url,
            origin=self.origin,
            branch=self.master_fork
        )
        data = {
            "sha": sha,
            "force": True
        }
        reply = self.request(
            "PATCH",
            uri,
            data=data
        )
        if reply.status_code == 200:
            dic = json.loads(reply.content.decode("utf-8"))
            return dic["object"]["sha"]
        else:
            dic = json.loads(reply.content.decode("utf-8"))
            return self.ProxyError(
                reply.status_code,
                (dic, "message"),
                step="patch",
                context={
                    "uri": uri,
                    "data": data
                }
            )
101719
def _getEngineVersionHash(self):
		
		versionDetails = self._getEngineVersionDetails()
		hash = hashlib.sha256()
		hash.update(json.dumps(versionDetails, sort_keys=True, indent=0).encode('utf-8'))
		return hash.hexdigest()
303349
def commit_hash(dir='.'):
    

    cmd = ['git', 'rev-parse', 'HEAD']

    try:
        with open(os.devnull, 'w') as devnull:
            revision_hash = subprocess.check_output(
                cmd,
                cwd=dir,
                stderr=devnull
            )
        if sys.version_info.major > 2:
            revision_hash = revision_hash.decode('ascii')

        return revision_hash.strip()

    except subprocess.CalledProcessError:
        return None
1096024
def get_git_tag(self, sha):
        
        assert isinstance(sha, (str, unicode)), sha
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/git/tags/" + sha
        )
        return github.GitTag.GitTag(self._requester, headers, data, completed=True)
386786
def version
      return ExtPubkey.version_from_purpose(number) if depth == 1
      ver ? ver : Bitcoin.chain_params.extended_pubkey_version
    end
339376
def commit():
    

    session_token = request.headers['session_token']
    repository    = request.headers['repository']

    #===
    current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
    if current_user is False: return fail(user_auth_fail_msg)

    #===
    repository_path = config['repositories'][repository]['path']

    def with_exclusive_lock():
        if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)

        #===
        data_store = versioned_storage(repository_path)
        if not data_store.have_active_commit(): return fail(no_active_commit_msg)

        result = {}
        if request.headers['mode'] == 'commit':
            new_head = data_store.commit(request.headers['commit_message'], current_user['username'])
            result = {'head' : new_head}
        else:
            data_store.rollback()

        # Release the user lock
        update_user_lock(repository_path, None)
        return success(result)
    return lock_access(repository_path, with_exclusive_lock)
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
1194717
def get_commits(self, since_sha=None):
        
        assert self.tempdir

        cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
        if since_sha:
            commits = [self.get_commit(since_sha)]
            cmd.append('{}..HEAD'.format(since_sha))
        else:
            commits = []
            cmd.append('HEAD')

        output = cmd_output(*cmd, cwd=self.tempdir)

        for sha, date in chunk_iter(output.splitlines(), 2):
            commits.append(Commit(sha, int(date)))

        return commits
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
795533
def r_update(self):
        

        # Getting Master Branch
        upstream = self.get_ref(self.master_upstream, origin=self.upstream)
        if isinstance(upstream, bool):
            return (ProxyError(
                404, "Upstream Master branch '{0}' does not exist".format(self.master_upstream),
                step="get_upstream_ref"
            )).response()
        elif isinstance(upstream, self.ProxyError):
            return upstream.response()

        # Patching
        new_sha = self.patch_ref(upstream)
        if isinstance(new_sha, self.ProxyError):
            return new_sha.response()

        self.logger.info("Updated repository {} to sha {}".format(self.origin, new_sha), extra={"former_sha": upstream})
        return jsonify({
            "status": "success",
            "commit": new_sha
        })
133913
def _get_version(name, results):
    '''
    
    '''
    for line in salt.utils.itertools.split(results, '\n'):
        if not line:
            continue
        try:
            pkgname, pkgver = line.rsplit('-', 1)
        except ValueError:
            continue
        if pkgname == name:
            return pkgver
    return None
433669
private static boolean ensureVersion(Version existing, Version expected) {
        return existing != Version.UNDEFINED && existing.greaterThanOrEqualTo(expected);
    }
117435
def get_pom_from_sha1(file)
      log.debug("Attempting SHA1 POM lookup for #{file}")
      begin
        if File.file?(file)
          site = MavenWebsite.new
          sha1 = Digest::SHA1.hexdigest File.read(file)
          results = site.search_by_sha1(sha1).select { |result| result["ec"].include?(".pom") }
          result = results.first
          unless result.nil?
            log.info("pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\
              (#{result['g']}:#{result['a']}:#{result['v']})"
                    )
            group_id, artifact_id, version = site.get_maven_id_from result
            return site.download_pom(group_id, artifact_id, version), :found_via_sha1
          end
        end
      rescue NotFoundOnMavenWebsiteError
        log.warn("Got a 404 error while looking for #{file}'s SHA1 in search.maven.org")
      end
      nil
    end