/
util.js
86 lines (76 loc) 路 2.4 KB
/
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
const fs = require('fs');
const { EOL } = require('os');
const _ = require('lodash');
const gitUrlParse = require('git-url-parse');
const semver = require('semver');
const Log = require('./log');
const { TimeoutError } = require('./errors');
const log = new Log();
const format = (template = '', context = {}) => {
try {
template = template.startsWith('git log')
? template.replace('[REV_RANGE]', '${latestTag}...HEAD')
: template.replace(/%s/g, '${version}');
return _.template(template)(context);
} catch (error) {
log.error(`Unable to render template with context:\n${template}\n${JSON.stringify(context)}`);
log.error(error);
throw error;
}
};
const truncateLines = (input, maxLines = 10, surplusText = null) => {
const lines = input.split(EOL);
const surplus = lines.length - maxLines;
const output = lines.slice(0, maxLines).join(EOL);
return surplus > 0 ? (surplusText ? `${output}${surplusText}` : `${output}${EOL}...and ${surplus} more`) : output;
};
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const rejectAfter = ms =>
wait(ms).then(() => {
throw new TimeoutError(`Timed out after ${ms}ms.`);
});
const parseGitUrl = remoteUrl => {
const normalizedUrl = remoteUrl.replace(/\\/g, '/');
const parsedUrl = gitUrlParse(normalizedUrl);
const { resource: host, name: project, protocol, href: remote } = parsedUrl;
const owner = protocol === 'file' ? _.last(parsedUrl.owner.split('/')) : parsedUrl.owner;
const repository = `${owner}/${project}`;
return { host, owner, project, protocol, remote, repository };
};
const reduceUntil = async (collection, fn) => {
let result;
for (const item of collection) {
if (result) break;
result = await fn(item);
}
return result;
};
const hasAccess = path => {
try {
fs.accessSync(path);
return true;
} catch (err) {
return false;
}
};
const parseVersion = raw => {
if (!raw) return { version: null, isPreRelease: false, preReleaseId: null };
const version = semver.valid(raw) ? raw : semver.coerce(raw);
const parsed = new semver(version);
const isPreRelease = parsed.prerelease.length > 0;
const preReleaseId = isPreRelease && isNaN(parsed.prerelease[0]) ? parsed.prerelease[0] : null;
return {
version,
isPreRelease,
preReleaseId
};
};
module.exports = {
format,
truncateLines,
rejectAfter,
reduceUntil,
parseGitUrl,
hasAccess,
parseVersion
};