Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/build/lib/git.ts
3520 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
import path from 'path';
6
import fs from 'fs';
7
8
/**
9
* Returns the sha1 commit version of a repository or undefined in case of failure.
10
*/
11
export function getVersion(repo: string): string | undefined {
12
const git = path.join(repo, '.git');
13
const headPath = path.join(git, 'HEAD');
14
let head: string;
15
16
try {
17
head = fs.readFileSync(headPath, 'utf8').trim();
18
} catch (e) {
19
return undefined;
20
}
21
22
if (/^[0-9a-f]{40}$/i.test(head)) {
23
return head;
24
}
25
26
const refMatch = /^ref: (.*)$/.exec(head);
27
28
if (!refMatch) {
29
return undefined;
30
}
31
32
const ref = refMatch[1];
33
const refPath = path.join(git, ref);
34
35
try {
36
return fs.readFileSync(refPath, 'utf8').trim();
37
} catch (e) {
38
// noop
39
}
40
41
const packedRefsPath = path.join(git, 'packed-refs');
42
let refsRaw: string;
43
44
try {
45
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
46
} catch (e) {
47
return undefined;
48
}
49
50
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
51
let refsMatch: RegExpExecArray | null;
52
const refs: { [ref: string]: string } = {};
53
54
while (refsMatch = refsRegex.exec(refsRaw)) {
55
refs[refsMatch[2]] = refsMatch[1];
56
}
57
58
return refs[ref];
59
}
60
61