-
-
Notifications
You must be signed in to change notification settings - Fork 412
/
gitWorkflow.js
215 lines (195 loc) Β· 7.35 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
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
'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
* Staged files are left in the 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()
await Promise.all(
untrackedFiles.map(file =>
readBufferFromFile(file).then(buffer => this.untrackedFiles.set(file, buffer))
)
)
debug('Done backing up untracked files!')
}
// Get stash of entire original state, including unstaged changes
await this.execGit(['stash', 'save', '--quiet', '--include-untracked', STASH])
// Apply index from previous stash back to enable running tasks against
// staged files only. `git stash --keep-index` cannot be used here because of
// a bug affecting deleted files. The bug has been fixed in git v2.23.0
// See https://github.com/git/git/blob/master/Documentation/RelNotes/2.23.0.txt#L322
await this.execGit(['stash', 'apply', '--index', await this.getBackupStash()])
// Clear any unstaged changes since they are saved in the stash,
// and shouldn't be affected by tasks
await this.execGit(['clean', '-df'])
await this.execGit(['checkout', '.'])
// Since only staged files are now present, get a diff of unstaged changes
// by comparing current index against original stash, but in reverse
this.unstagedDiff = await this.execGit([
'diff',
'--unified=0',
'--no-color',
'--no-ext-diff',
'--patch',
await this.getBackupStash(),
'-R' // Show diff in reverse
])
debug('Done backing up original state!')
}
/**
* Applies back task modifications, and unstaged changes hidden in the stash.
* In case of a merge-conflict retry with 3-way merge.
*
* @param {Object} [options]
* @returns {Promise<void>}
*/
async applyModifications() {
let modifiedFiles = await this.execGit(['ls-files', '--modified'])
if (modifiedFiles) {
modifiedFiles = modifiedFiles.split('\n')
debug('Detected files modified by tasks:')
debug(modifiedFiles)
debug('Adding files to index...')
await this.execGit(['add', modifiedFiles])
debug('Done adding files to index!')
}
if (this.unstagedDiff) {
debug('Restoring unstaged changes...')
try {
await this.execGit(gitApplyArgs, { input: `${this.unstagedDiff}\n` })
} catch (error) {
debug('Error while restoring changes:')
debug(error)
debug('Retrying with 3-way merge')
try {
// Retry with `--3way` if normal apply fails
await this.execGit([...gitApplyArgs, '--3way'], { input: `${this.unstagedDiff}\n` })
} catch (error2) {
debug('Error while restoring unstaged changes using 3-way merge:')
debug(error2)
throw new Error('Unstaged changes could not be restored due to a merge conflict!')
}
}
debug('Done restoring unstaged changes!')
}
if (this.untrackedFiles) {
debug('Restoring untracked files...')
try {
// Iterate over Map and await for all to complete
const writePromises = []
this.untrackedFiles.forEach((buffer, file) => {
writePromises.push(writeBufferToFile(file, buffer))
})
await Promise.all(writePromises)
} catch (error) {
debug('Error while restoring untracked changes:')
debug(error)
throw new Error('Untracked changes could not be restored due to an error!')
}
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