git.js 1.6 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';
6
Object.defineProperty(exports, "__esModule", { value: true });
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
var path = require("path");
var fs = require("fs");
/**
 * Returns the sha1 commit version of a repository or undefined in case of failure.
 */
function getVersion(repo) {
    var git = path.join(repo, '.git');
    var headPath = path.join(git, 'HEAD');
    var head;
    try {
        head = fs.readFileSync(headPath, 'utf8').trim();
    }
    catch (e) {
        return void 0;
    }
    if (/^[0-9a-f]{40}$/i.test(head)) {
        return head;
    }
    var refMatch = /^ref: (.*)$/.exec(head);
    if (!refMatch) {
        return void 0;
    }
    var ref = refMatch[1];
    var refPath = path.join(git, ref);
    try {
        return fs.readFileSync(refPath, 'utf8').trim();
    }
    catch (e) {
35
        // noop
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    }
    var packedRefsPath = path.join(git, 'packed-refs');
    var refsRaw;
    try {
        refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
    }
    catch (e) {
        return void 0;
    }
    var refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
    var refsMatch;
    var refs = {};
    while (refsMatch = refsRegex.exec(refsRaw)) {
        refs[refsMatch[2]] = refsMatch[1];
    }
    return refs[ref];
}
exports.getVersion = getVersion;