-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
git-util.js
228 lines (188 loc) · 5.75 KB
/
git-util.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
'use strict';
const execa = require('execa');
const escapeStringRegexp = require('escape-string-regexp');
const ignoreWalker = require('ignore-walk');
const pkgDir = require('pkg-dir');
const {verifyRequirementSatisfied} = require('./version');
exports.latestTag = async () => {
const {stdout} = await execa('git', ['describe', '--abbrev=0', '--tags']);
return stdout;
};
exports.newFilesSinceLastRelease = async () => {
try {
const {stdout} = await execa('git', ['diff', '--name-only', '--diff-filter=A', await this.latestTag(), 'HEAD']);
if (stdout.trim().length === 0) {
return [];
}
const result = stdout.trim().split('\n').map(row => row.trim());
return result;
} catch {
// Get all files under version control
return ignoreWalker({
path: pkgDir.sync(),
ignoreFiles: ['.gitignore']
});
}
};
const firstCommit = async () => {
const {stdout} = await execa('git', ['rev-list', '--max-parents=0', 'HEAD']);
return stdout;
};
exports.previousTagOrFirstCommit = async () => {
const {stdout} = await execa('git', ['tag']);
const tags = stdout.split('\n');
if (tags.length === 0) {
return;
}
if (tags.length === 1) {
return firstCommit();
}
return tags[tags.length - 2];
};
exports.latestTagOrFirstCommit = async () => {
let latest;
try {
// In case a previous tag exists, we use it to compare the current repo status to.
latest = await exports.latestTag();
} catch {
// Otherwise, we fallback to using the first commit for comparison.
latest = await firstCommit();
}
return latest;
};
exports.hasUpstream = async () => {
const escapedCurrentBranch = escapeStringRegexp(await exports.currentBranch());
const {stdout} = await execa('git', ['status', '--short', '--branch', '--porcelain']);
return new RegExp(String.raw`^## ${escapedCurrentBranch}\.\.\..+\/${escapedCurrentBranch}`).test(stdout);
};
exports.currentBranch = async () => {
const {stdout} = await execa('git', ['symbolic-ref', '--short', 'HEAD']);
return stdout;
};
exports.verifyCurrentBranchIsReleaseBranch = async releaseBranch => {
const currentBranch = await exports.currentBranch();
if (currentBranch !== releaseBranch) {
throw new Error(`Not on \`${releaseBranch}\` branch. Use --any-branch to publish anyway, or set a different release branch using --branch.`);
}
};
exports.isWorkingTreeClean = async () => {
try {
const {stdout: status} = await execa('git', ['status', '--porcelain']);
if (status !== '') {
return false;
}
return true;
} catch {
return false;
}
};
exports.verifyWorkingTreeIsClean = async () => {
if (!(await exports.isWorkingTreeClean())) {
throw new Error('Unclean working tree. Commit or stash changes first.');
}
};
exports.isRemoteHistoryClean = async () => {
let history;
try { // Gracefully handle no remote set up.
const {stdout} = await execa('git', ['rev-list', '--count', '--left-only', '@{u}...HEAD']);
history = stdout;
} catch {}
if (history && history !== '0') {
return false;
}
return true;
};
exports.verifyRemoteHistoryIsClean = async () => {
if (!(await exports.isRemoteHistoryClean())) {
throw new Error('Remote history differs. Please pull changes.');
}
};
exports.verifyRemoteIsValid = async () => {
try {
await execa('git', ['ls-remote', 'origin', 'HEAD']);
} catch (error) {
throw new Error(error.stderr.replace('fatal:', 'Git fatal error:'));
}
};
exports.fetch = async () => {
await execa('git', ['fetch']);
};
exports.tagExistsOnRemote = async tagName => {
try {
const {stdout: revInfo} = await execa('git', ['rev-parse', '--quiet', '--verify', `refs/tags/${tagName}`]);
if (revInfo) {
return true;
}
return false;
} catch (error) {
// Command fails with code 1 and no output if the tag does not exist, even though `--quiet` is provided
// https://github.com/sindresorhus/np/pull/73#discussion_r72385685
if (error.stdout === '' && error.stderr === '') {
return false;
}
throw error;
}
};
async function hasLocalBranch(branch) {
try {
await execa('git', [
'show-ref',
'--verify',
'--quiet',
`refs/heads/${branch}`
]);
return true;
} catch {
return false;
}
}
exports.defaultBranch = async () => {
for (const branch of ['main', 'master', 'gh-pages']) {
// eslint-disable-next-line no-await-in-loop
if (await hasLocalBranch(branch)) {
return branch;
}
}
throw new Error(
'Could not infer the default Git branch. Please specify one with the --branch flag or with a np config.'
);
};
exports.verifyTagDoesNotExistOnRemote = async tagName => {
if (await exports.tagExistsOnRemote(tagName)) {
throw new Error(`Git tag \`${tagName}\` already exists.`);
}
};
exports.commitLogFromRevision = async revision => {
const {stdout} = await execa('git', ['log', '--format=%s %h', `${revision}..HEAD`]);
return stdout;
};
exports.pushGraceful = async remoteIsOnGitHub => {
try {
await exports.push();
} catch (error) {
if (remoteIsOnGitHub && error.stderr && error.stderr.includes('GH006')) {
// Try to push tags only, when commits can't be pushed due to branch protection
await execa('git', ['push', '--tags']);
return {pushed: 'tags', reason: 'Branch protection: np can`t push the commits. Push them manually.'};
}
throw error;
}
};
exports.push = async () => {
await execa('git', ['push', '--follow-tags']);
};
exports.deleteTag = async tagName => {
await execa('git', ['tag', '--delete', tagName]);
};
exports.removeLastCommit = async () => {
await execa('git', ['reset', '--hard', 'HEAD~1']);
};
const gitVersion = async () => {
const {stdout} = await execa('git', ['version']);
const match = /git version (?<version>\d+\.\d+\.\d+).*/.exec(stdout);
return match && match.groups.version;
};
exports.verifyRecentGitVersion = async () => {
const installedVersion = await gitVersion();
verifyRequirementSatisfied('git', installedVersion);
};