forked from kevinchappell/formBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
355 lines (322 loc) · 10.4 KB
/
utils.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import fs from 'fs'
import { execSync } from 'child_process'
import semver from 'semver'
import open from 'opener'
import 'colors'
import replace from 'replace-in-file'
import pkg from '../package.json'
/* eslint-disable no-console */
export const spinner = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']
export const releasePlural = releaseType => (releaseType === 'release' ? `${releaseType}s` : `${releaseType}es`)
export const txts = {
error: '\n----- Error -----\n'.red,
status: {
current: '',
gathering: 'Gathering information...',
},
unStagedChanges: 'Unstaged changes found. Please stash or commit your work before continuing.',
questions: { releaseType: verb => `What type of release are you ${verb}?` },
fetchingLogs: branch => `Fetching git logs from origin/${branch}`,
releaseCreated: releaseTitle =>
[
`${releaseTitle.green} was successfully generated.\n`,
'Next steps:',
' - Merge the request in Gitlab',
` - ${'npm run release finish'.bgWhite.green} to complete the release`,
].join('\n'),
uCanceled: 'User Canceled',
whatVersionRelease: 'What version will you be releasing?',
whichUnfinishedRelease: releaseType =>
`Multiple unfinished ${releasePlural(releaseType)} found. Which one would you like to finish?`,
invalidVersion: version =>
`${version.red} is not a valid version number. Please enter a valid Semantic Version number`,
}
/**
* Synchronously exec shell command
* @param {String} command
* @return {String} trimmed stdout
*/
export const execTrim = command =>
execSync(command)
.toString()
.trim()
/**
* Check if there are unstaged changes
* @return {String} git diff
*/
export const checkUnstagedChanges = () => {
return execTrim('git diff --color')
}
/**
* Find existing, unfinished release branches
* @param {String} releaseType hotfix or release
* @return {Array} Array of potential unfinished branches
*/
export const findUnfinishedReleases = releaseType => {
const unfinishedReleases = execTrim('git branch -l')
.split('\n')
.filter(branchName => new RegExp(`${releaseType}/.+`).test(branchName))
if (!unfinishedReleases.length) {
console.log(`There are no unfinished ${releasePlural(releaseType)}`)
process.exit(0)
}
return unfinishedReleases.map(String.trim)
}
/**
* Read a package.json from master branch
* extract version
* @return {String} version
*/
export const getCurrentVersion = () => {
const pkgJSON = execTrim('git show master:package.json')
return JSON.parse(pkgJSON).version
}
/**
* Check next version based on semver
* @param {String|Number} version
* @return {Number} newVersion
*/
export const getNewVersion = version => {
const currentVersion = getCurrentVersion()
const semverTypes = ['major', 'minor', 'patch']
let newVersion
if (semverTypes.includes(version)) {
newVersion = semver.inc(currentVersion, version)
} else {
newVersion = version
}
return newVersion
}
/**
* Capitalizes a string
* @param {String} str uncapitalized string
* @return {String} str capitalized string
*/
export const capitalize = str => str.replace(/\b\w/g, match => match.toUpperCase())
/**
* Update the projects version number
* @param {Object} version
* @return {Buffer} updated file
*/
export function updatePackageJSON(props) {
const packageJSON = JSON.parse(fs.readFileSync('./package.json'))
const updatedPackageJSON = JSON.stringify(deepMerge(packageJSON, props), null, ' ')
return fs.writeFileSync('./package.json', `${updatedPackageJSON}\n`)
}
export const releaseVersionDate = version => {
const today = new Date()
const releaseDate = `${today.getDate()}/${today.getUTCMonth() + 1}/${today.getFullYear()}`
return `## ${version} - ${releaseDate}`
}
/**
* Updates README AND CHANGELOG
* @param {Object} version current and new version
* @param {String} releaseLog tickets in this release
* @return {void}
*/
export function updateChangelog(version, releaseLog) {
const changelog = fs.readFileSync('./CHANGELOG.md', 'utf8').split('\n')
const fromLine = changelog.find(line => line.match(/##(\s|)\[unreleased\]?.+/i)) || changelog[0]
return replace({
files: 'CHANGELOG.md',
from: fromLine,
to: `${fromLine}\n\n${releaseVersionDate(version)}\n\n${releaseLog}`,
})
.then(changedFiles => {
console.log('Modified files:', changedFiles.join(', '))
})
.catch(error => {
console.error('Error occurred:', error)
})
}
/**
* Fetch and compare the difference in
* git logs between 2 branches
* @param {String} source branch
* @param {String} target branch
* @return {Array} of commits
*/
export function getLogDiff(source, target) {
const sourceHEAD = execTrim(`git rev-parse ${source}`)
const targetHEAD = execTrim(`git rev-parse ${target}`)
return execTrim(`git log --pretty=format:%n%b%n----- ${sourceHEAD}...${targetHEAD}`)
.split('-----')
.filter(String)
}
export const git = {
parseLogs,
getLogDiff,
get currentBranch() {
return execTrim('git symbolic-ref --short -q HEAD')
},
get releaseLog() {
return parseLogs(getLogDiff('develop', 'master'))
},
get tempBranchName() {
return Math.random()
.toString(36)
.slice(2)
},
openMR: (source, target = 'develop') => {
const { gitlab } = pkg.config
const mrUrl = `${gitlab.url}/${gitlab.project}/merge_requests/new`
if (!source) {
source = git.currentBranch
}
execSync(`git push origin ${source}`)
open(`${mrUrl}?merge_request[source_branch]=${source}&merge_request[target_branch]=${target}`)
},
/**
* Fetch updates from repo for provided branches
* @param {Array} branches
*/
fetchLatest: branches => {
const fetchingLatest = 'Fetching latest from'
const currentBranch = git.currentBranch
const tempBranch = git.tempBranchName
execSync(`git checkout -b ${tempBranch}`)
branches.forEach(branch => {
console.log(`${fetchingLatest} origin/${branch}`.dim)
execSync(`git fetch origin ${branch}:${branch}`)
})
console.log('Cleaning up'.dim)
execSync(`git checkout ${currentBranch} && git branch -D ${tempBranch}`)
},
}
/**
* Format an array of parsed git logs
* @param {Array} parsedGitLog
* @return {String} formattedGitLogs
*/
export const formatGitLog = parsedGitLog => {
return Object.entries(parsedGitLog)
.reduce((filtered, [type, log]) => {
if (log.length) {
filtered.push(`### ${capitalize(type)}\n\n${log.join('\n')}`)
}
return filtered
}, [])
.join('\n\n')
}
/**
* Remove duplicates from an array of elements
* @param {Array} array array with possible duplicates
* @return {Array} array with only unique values
*/
export const uniqueArray = array => array.filter((elem, pos, arr) => arr.indexOf(elem) === pos)
/**
* Takes an array of commits and sorts them
* by the type of changes eg. 'Changed', 'Added', 'Fixed'
* @param {Array} gitlogs
* @return {Array} parsed commits
*/
export function parseLogs(gitlogs) {
// case insensitive matcher for past, present and future ie. "fixed, fix, fixes"
const typeMap = {
added: /add(ed\b|es\b|\b):/gi,
changed: /(change|update)+(d\b|s\b|\b):/gi,
improved: /improve(d\b|s\b|ment):/gi,
fixed: /fix(ed\b|es\b|\b):/gi,
}
const { jira } = pkg.config
const inlineAttributionRegExp = /(\((@.+) in ([A-Z]+-\d+)\))/gim
const defaultAttributionRegExp = /^\(@.+ in [A-Z]+-\d+\)/gi
const parsedLog = Object.keys(typeMap).reduce((acc, curr) => {
acc[curr] = []
return acc
}, {})
gitlogs.reverse().forEach(commitLog => {
if (commitLog) {
const msg = commitLog.split('\n').filter(String)
const defaultAttribution = msg.find(log => log.match(defaultAttributionRegExp))
if (msg.length) {
msg.forEach(log => {
const replacer = (match, developer, taskId) => {
const task = taskId.toUpperCase() // ensure correct case or link won't work
return ` (${developer} in [${task}](${jira}/browse/${task}))`
}
let attribution = `${log.split(inlineAttributionRegExp)[1] || defaultAttribution || ''}`
attribution = attribution.replace(/\((@.+) in ([A-Z]+-\d+)\)/gim, replacer)
const types = Object.entries(typeMap)
if (types.length) {
types.forEach(([type, typeRegExp]) => {
if (log.match(typeRegExp)) {
log = log
.replace(typeRegExp, '')
.replace(inlineAttributionRegExp, '')
.trim()
const typeLog = `${log}${attribution}\n`
parsedLog[type].push(typeLog)
}
})
}
})
}
}
})
// Ensure all entries are unique
Reflect.ownKeys(parsedLog).forEach(type => {
parsedLog[type] = uniqueArray(parsedLog[type])
})
return formatGitLog(parsedLog)
}
export const defaultNewVersion = ({ releaseType }) => {
let version
if (releaseType === 'hotfix') {
version = getNewVersion('patch')
}
return version
}
export const validateVersion = version => {
let response
if (semver.valid(version)) {
response = true
} else {
response = 'Invalid version number'
}
return response
}
export const deepMerge = (obj1, obj2) => {
const mergedObj = Object.assign({}, obj1, obj2)
Reflect.ownKeys(obj2).forEach(prop => {
if (Array.isArray(obj2[prop])) {
mergedObj[prop] = Array.isArray(obj1[prop]) ? uniqueArray(obj1[prop].concat(obj2[prop])) : obj2[prop]
} else if (typeof obj2[prop] === 'object') {
mergedObj[prop] = deepMerge(obj1[prop], obj2[prop])
} else {
mergedObj[prop] = obj2[prop]
}
})
return mergedObj
}
/**
* Save a changelog
* @param {Float} version
*/
export const saveLog = (version, log) => {
const wstream = fs.createWriteStream(`.git/${version}`)
wstream.write(log)
wstream.end()
}
/**
* Load the saved changelog
* @param {Float} version
* @return {String} Changelog for the requested version
*/
export const loadLog = version => fs.readFileSync(`.git/${version}`).toString()
/**
* Remove the saved changelog
* @param {Float} version
* @return {String} removedFile
*/
export const removeLog = version => fs.unlinkSync(`.git/${version}`)
/**
* Returns the values of an object in a specific order
* @param {Object} obj
* @param {Array} order
* @return {Array} orderedValues
*/
export const orderedValues = (obj, order) => {
const newOrder = order.map(key => obj[key] || null).filter(Boolean)
return uniqueArray(newOrder.concat(Object.values(obj)))
}