-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathgit.js
More file actions
94 lines (86 loc) · 2.61 KB
/
git.js
File metadata and controls
94 lines (86 loc) · 2.61 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const path = require('path');
const { promisify } = require('util');
const fs = require('fs-extra');
const execFile = promisify(require('child_process').execFile);
module.exports.author = async function author (opts = {}) {
try {
const [name, email] = (await Promise.all([
execFile('git', ['config', '--get', 'user.name'], { cwd: opts.cwd }),
execFile('git', ['config', '--get', 'user.email'], { cwd: opts.cwd })
])).map((p) => p.stdout.trim());
if (!name) {
return;
}
return `${name}${email ? ` <${email}>` : ''}`;
} catch (e) {
// Ignore errors
}
};
// Taken from npm: https://github.com/npm/init-package-json/blob/latest/default-input.js#L188-L208
async function gitRemote (opts = {}) {
try {
const cwd = opts.cwd || process.cwd();
let conf = await fs.readFile(path.join(cwd, '.git', 'config'), 'utf8');
conf = conf.split(/\r?\n/);
const i = conf.indexOf('[remote "origin"]');
let u;
if (i !== -1) {
// Check if one of the next two lines is the remote url
u = conf[i + 1];
if (!u.match(/^\s*url =/)) {
u = conf[i + 2];
}
if (!u.match(/^\s*url =/)) {
u = null;
} else {
u = u.replace(/^\s*url = /, '');
}
}
// @TODO support bitbucket and gitlab urls
// Replace github url
if (u && u.match(/^git@github.com:/)) {
u = u.replace(/^git@github.com:/, 'https://github.com/');
}
return u;
} catch (e) {
// ignore error
}
}
module.exports.remote = gitRemote;
module.exports.repository = async function (cwd, pkg) {
if (!pkg || !pkg.repository) {
const remote = await gitRemote({ cwd });
if (remote) {
return remote;
}
}
if (pkg && typeof pkg.repository === 'string') {
return pkg.repository;
}
if (pkg && typeof pkg.repository !== 'undefined' && pkg.repository.url) {
return pkg.repository.url;
}
};
module.exports.repositoryRoot = async function repositoryRoot (cwd) {
try {
// Since we call this *before* creating the new pacakge directory in a monorepo,
// we need to find the first real directory above `cwd` because otherwise this
// command will succeede but use the system cwd instead
let _cwd = cwd;
while (_cwd !== '/') {
try {
const p = await fs.realpath(_cwd);
await fs.access(p, fs.constants.W_OK | fs.constants.R_OK);
_cwd = p;
break;
} catch (e) {
_cwd = path.dirname(_cwd);
}
}
const out = await execFile('git', ['rev-parse', '--show-toplevel'], { cwd: _cwd });
return out.stdout.trim();
} catch (e) {
// Ignore errors
}
};