forked from sindresorhus/np
/
git-util.js
183 lines (151 loc) · 5.1 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
'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', '--stat', '--diff-filter=A', await this.latestTag(), 'HEAD']);
const result = stdout.trim().split('\n').slice(0, -1).map(row => row.slice(0, row.indexOf('|')).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.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 allowedBranches = releaseBranch ? [releaseBranch] : ['main', 'master'];
const currentBranch = await exports.currentBranch();
if (!allowedBranches.includes(currentBranch)) {
throw new Error(`Not on ${allowedBranches.map(branch => `\`${branch}\``).join('/')} 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;
}
};
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);
};