-
Notifications
You must be signed in to change notification settings - Fork 486
/
Copy pathurl_prefix.js
82 lines (79 loc) · 2.76 KB
/
url_prefix.js
1
2
3
4
5
6
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const fs = require('fs');
const path = require('path');
const gitUrlParse = require('git-url-parse');
const ini = require('ini');
/**
* Sometimes git will [pack refs](https://git-scm.com/docs/git-pack-refs)
* in order to save space on disk and
* duck under limits of numbers of files in folders. CircleCI in particular
* does this by default. This method parses that `packed-refs` file
*
* @private
* @param {string} packedRefs string contents of the packed refs file
* @param {string} branchName the branch name to resolve to
* @returns {string} sha hash referring to current tree
*/
function parsePackedRefs(packedRefs, branchName) {
return packedRefs
.split(/\n/)
.filter(line => line[0] !== '#' && line[0] !== '^')
.reduce((memo, line) => {
memo[line.split(' ')[1]] = line.split(' ')[0];
return memo;
}, {})[branchName];
}
/**
* Given a a root directory, find its git configuration and figure out
* the HTTPS URL at the base of that GitHub repository.
*
* @param {string} root path at the base of this local repo
* @returns {string} base HTTPS url of the GitHub repository
* @throws {Error} if the root is not a git repo
*/
function getGithubURLPrefix({ git, root }) {
let sha;
try {
const head = fs.readFileSync(path.join(git, 'HEAD'), 'utf8');
const branch = head.match(/ref: (.*)/);
if (branch) {
const branchName = branch[1];
const branchFileName = path.join(git, branchName);
const packedRefsName = path.join(git, 'packed-refs');
if (fs.existsSync(branchFileName)) {
sha = fs.readFileSync(branchFileName, 'utf8');
} else if (fs.existsSync(packedRefsName)) {
// packed refs are a compacted version of the refs folder. usually
// you have a folder filled with files that just contain sha
// hashes. since this folder can be really big, packed refs
// stores all the refs in one file instead.
sha = parsePackedRefs(
fs.readFileSync(packedRefsName, 'utf8'),
branchName
);
}
} else {
sha = head;
}
if (sha) {
let origin;
if (git.indexOf(root) === 0) {
const config = ini.parse(
fs.readFileSync(path.join(git, 'config'), 'utf8')
);
origin = config['remote "origin"'].url;
} else {
const config = ini.parse(
fs.readFileSync(path.join(git, '..', '..', 'config'), 'utf8')
);
origin = config[`submodule "${path.basename(git)}"`].url;
}
const parsed = gitUrlParse(origin);
parsed.git_suffix = false; // eslint-disable-line
return parsed.toString('https') + '/blob/' + sha.trim() + '/';
}
} catch (e) {
return null;
}
}
module.exports = getGithubURLPrefix;
module.exports.parsePackedRefs = parsePackedRefs;