quasar

Форк
0
/
prepare-diff.js 
92 строки · 2.6 Кб
1
const path = require('node:path')
2
const fse = require('fs-extra')
3
const { sync: fastGlob, convertPathToPattern } = require('fast-glob')
4
const { createPatch } = require('diff')
5
const { highlight } = require('cli-highlight')
6

7
const rootFolder = path.resolve(__dirname, '..')
8

9
function resolve (_path) {
10
  return path.resolve(rootFolder, _path)
11
}
12

13
function relative (_path) {
14
  return path.relative(rootFolder, _path)
15
}
16

17
/**
18
 * Call this with the path to file (or folder) you want to track, before the file gets updated.
19
 * It will save the current contents and will print the diff before exiting the process.
20
 *
21
 * @param {string} locationPath
22
 */
23
module.exports = function prepareDiff (locationPath) {
24
  const absolutePath = resolve(locationPath)
25

26
  // If there is no "old" file/folder, then there is no diff (everything will be new)
27
  if (!fse.existsSync(absolutePath)) {
28
    return
29
  }
30

31
  let pattern = convertPathToPattern(absolutePath)
32
  // If it's a directory, then query all files in it
33
  if (fse.lstatSync(absolutePath).isDirectory()) {
34
    pattern += '/*'
35
  }
36

37
  const originalsMap = new Map()
38
  const originalFiles = fastGlob(pattern)
39

40
  // If no files, then there is no diff (everything will be new)
41
  if (originalFiles.length === 0) {
42
    return
43
  }
44

45
  // Read the current (old) contents
46
  originalFiles.forEach(filePath => {
47
    originalsMap.set(filePath, fse.readFileSync(filePath, 'utf-8'))
48
  })
49

50
  // Before exiting the process, read the new contents and output the diff
51
  process.on('exit', code => {
52
    if (code !== 0) return
53

54
    const currentFiles = fastGlob(pattern)
55
    const currentMap = new Map()
56

57
    let somethingChanged = false
58

59
    currentFiles.forEach(filePath => {
60
      const relativePath = relative(filePath)
61
      currentMap.set(filePath, true)
62

63
      if (originalsMap.has(filePath) === false) {
64
        console.log(`\n 📜 New file: ${ relativePath }`)
65
        somethingChanged = true
66
        return
67
      }
68

69
      const currentContent = fse.readFileSync(filePath, 'utf-8')
70
      const originalContent = originalsMap.get(filePath)
71

72
      if (originalContent !== currentContent) {
73
        const diffPatch = createPatch(filePath, originalContent, currentContent)
74

75
        console.log(`\n 📜 Changes for ${ relativePath }\n`)
76
        console.log(highlight(diffPatch, { language: 'diff' }))
77
        somethingChanged = true
78
      }
79
    })
80

81
    originalsMap.forEach((_, filePath) => {
82
      if (currentMap.has(filePath) === false) {
83
        console.log(`\n 📜 Removed file: ${ relative(filePath) }\n`)
84
        somethingChanged = true
85
      }
86
    })
87

88
    if (somethingChanged === false) {
89
      console.log('\n 📜 No changes detected.\n')
90
    }
91
  })
92
}
93

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.