/
gitWorkflow.js
187 lines (169 loc) Β· 6.1 KB
/
gitWorkflow.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
'use strict'
const debug = require('debug')('lint-staged:git')
const normalize = require('normalize-path')
const path = require('path')
const execGit = require('./execGit')
const { checkFile, readBufferFromFile, writeBufferToFile } = require('./file')
const MERGE_HEAD = 'MERGE_HEAD'
const MERGE_MODE = 'MERGE_MODE'
const MERGE_MSG = 'MERGE_MSG'
const STASH = 'lint-staged automatic backup'
const gitApplyArgs = ['apply', '-v', '--whitespace=nowarn', '--recount', '--unidiff-zero']
class GitWorkflow {
constructor(cwd) {
this.execGit = (args, options = {}) => execGit(args, { ...options, cwd })
this.unstagedDiff = null
this.cwd = cwd
/**
* These three files hold state about an ongoing git merge
* Resolve paths during constructor
*/
this.mergeHeadFile = path.resolve(this.cwd, '.git', MERGE_HEAD)
this.mergeModeFile = path.resolve(this.cwd, '.git', MERGE_MODE)
this.mergeMsgFile = path.resolve(this.cwd, '.git', MERGE_MSG)
}
/**
* Get name of backup stash
*
* @param {Object} [options]
* @returns {Promise<Object>}
*/
async getBackupStash() {
const stashes = await this.execGit(['stash', 'list'])
const index = stashes.split('\n').findIndex(line => line.includes(STASH))
return `stash@{${index}}`
}
/**
* Create backup stashes, one of everything and one of only staged changes
* Leves stages files in index for running tasks
*
* @param {Object} [options]
* @returns {Promise<void>}
*/
async stashBackup() {
debug('Backing up original state...')
// Git stash loses metadata about a possible merge mode
// Manually check and backup if necessary
if (await checkFile(this.mergeHeadFile)) {
debug('Detected current merge mode!')
debug('Backing up merge state...')
await Promise.all([
readBufferFromFile(this.mergeHeadFile).then(
mergeHead => (this.mergeHeadBuffer = mergeHead)
),
readBufferFromFile(this.mergeModeFile).then(
mergeMode => (this.mergeModeBuffer = mergeMode)
),
readBufferFromFile(this.mergeMsgFile).then(mergeMsg => (this.mergeMsgBuffer = mergeMsg))
])
debug('Done backing up merge state!')
}
// Git stash ignores new, untracked files, so back them up separately
// Use `git ls-files` to list untracked files:
// `--others includes` all untracked files, including ignored files
// `--exclude-standard` excludes ignored files, the .git/ dir and so on...
let untrackedFiles = await this.execGit(['ls-files', '--others', '--exclude-standard'])
if (untrackedFiles) {
debug('Detected untracked files:')
debug(untrackedFiles)
debug('Backing up untracked files...')
// Resolve untrackedFiles output into filenames
untrackedFiles = untrackedFiles
.split('\n')
.map(file => normalize(path.resolve(this.cwd, file)))
this.untrackedFiles = new Map()
const readPromises = []
for (const file of untrackedFiles) {
// Read all untracked files into buffers, and save them into internal Map
readPromises.push(
readBufferFromFile(file).then(buffer => this.untrackedFiles.set(file, buffer))
)
}
await Promise.all(readPromises)
debug('Done backing up untracked files!')
}
// Get stash of entire original state, including unstaged changes
// Keep index so that tasks only work on those files
await this.execGit(['stash', 'save', '--quiet', '--include-untracked', '--keep-index', STASH])
// Since only staged files are now present, get a diff of unstaged changes
// by comparing current index against original stash, but in reverse
const original = await this.getBackupStash()
this.unstagedDiff = await this.execGit([
'diff',
'--unified=0',
'--no-color',
'--no-ext-diff',
'-p',
original,
'-R'
])
debug('Done backing up original state!')
}
/**
* Resets everything and applies back unstaged and staged changes,
* possibly with modifications by tasks
*
* @param {Object} [options]
* @returns {Promise<void>}
*/
async restoreUnstagedChanges() {
debug('Restoring unstaged changes...')
if (this.unstagedDiff) {
try {
await this.execGit(gitApplyArgs, { input: `${this.unstagedDiff}\n` })
} catch (error) {
debug('Error when restoring changes:')
debug(error)
debug('Retrying with 3-way merge')
// Retry with `--3way` if normal apply fails
await this.execGit([...gitApplyArgs, '--3way'], { input: `${this.unstagedDiff}\n` })
}
}
debug('Done restoring unstaged changes!')
if (this.untrackedFiles) {
debug('Restoring untracked files...')
const writePromises = []
this.untrackedFiles.forEach((buffer, file) => {
writePromises.push(writeBufferToFile(file, buffer))
})
await Promise.all(writePromises)
debug('Done restoring untracked files!')
}
}
/**
* Restore original HEAD state in case of errors
*
* @param {Object} [options]
* @returns {Promise<void>}
*/
async restoreOriginalState() {
debug('Restoring original state...')
const original = await this.getBackupStash()
await this.execGit(['reset', '--hard', 'HEAD'])
await this.execGit(['stash', 'apply', '--quiet', '--index', original])
debug('Done restoring original state!')
}
/**
* Drop the created stashes after everything has run
*
* @param {Object} [options]
* @returns {Promise<void>}
*/
async dropBackup() {
debug('Dropping backup stash...')
const original = await this.getBackupStash()
await this.execGit(['stash', 'drop', '--quiet', original])
debug('Done dropping backup stash!')
if (this.mergeHeadBuffer) {
debug('Detected backup merge state!')
debug('Restoring merge state...')
await Promise.all([
writeBufferToFile(this.mergeHeadFile, this.mergeHeadBuffer),
writeBufferToFile(this.mergeModeFile, this.mergeModeBuffer),
writeBufferToFile(this.mergeMsgFile, this.mergeMsgBuffer)
])
debug('Done restoring merge state!')
}
}
}
module.exports = GitWorkflow