forked from quasarframework/quasar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepare-diff.js
More file actions
91 lines (72 loc) · 2.58 KB
/
prepare-diff.js
File metadata and controls
91 lines (72 loc) · 2.58 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
const fs = require('fs')
const path = require('path')
const { sync: fastGlob } = require('fast-glob')
const { createPatch } = require('diff')
const { highlight } = require('cli-highlight')
const rootFolder = path.resolve(__dirname, '..')
function resolve (_path) {
return path.resolve(rootFolder, _path)
}
function relative (_path) {
return path.relative(rootFolder, _path)
}
/**
* Call this with the path to file (or folder) you want to track, before the file gets updated.
* It will save the current contents and will print the diff before exiting the process.
*
* @param {string} locationPath
*/
module.exports = function prepareDiff (locationPath) {
let absolutePath = resolve(locationPath)
// If there is no "old" file/folder, then there is no diff (everything will be new)
if (!fs.existsSync(absolutePath)) {
return
}
// If it's a directory, then query all files in it
if (fs.lstatSync(absolutePath).isDirectory()) {
absolutePath += '/*'
}
const originalsMap = new Map()
const originalFiles = fastGlob(absolutePath)
// If no files, then there is no diff (everything will be new)
if (originalFiles.length === 0) {
return
}
// Read the current (old) contents
originalFiles.forEach(filePath => {
originalsMap.set(filePath, fs.readFileSync(filePath, { encoding: 'utf-8' }))
})
// Before exiting the process, read the new contents and output the diff
process.on('exit', code => {
if (code !== 0) { return }
const currentFiles = fastGlob(absolutePath)
const currentMap = new Map()
let somethingChanged = false
currentFiles.forEach(filePath => {
const relativePath = relative(filePath)
currentMap.set(filePath, true)
if (originalsMap.has(filePath) === false) {
console.log(`\n 📜 New file: ${ relativePath }`)
somethingChanged = true
return
}
const currentContent = fs.readFileSync(filePath, { encoding: 'utf-8' })
const originalContent = originalsMap.get(filePath)
if (originalContent !== currentContent) {
const diffPatch = createPatch(filePath, originalContent, currentContent)
console.log(`\n 📜 Changes for ${ relativePath }\n`)
console.log(highlight(diffPatch, { language: 'diff' }))
somethingChanged = true
}
})
originalsMap.forEach((_, filePath) => {
if (currentMap.has(filePath) === false) {
console.log(`\n 📜 Removed file: ${ relative(filePath) }\n`)
somethingChanged = true
}
})
if (somethingChanged === false) {
console.log('\n 📜 No changes detected.\n')
}
})
}