/
gitWorkflow.js
191 lines (169 loc) Β· 6.64 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
'use strict'
const debug = require('debug')('lint-staged:git')
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({ gitDir, stagedFileChunks }) {
this.execGit = (args, options = {}) => execGit(args, { ...options, cwd: gitDir })
this.unstagedDiff = null
this.gitDir = gitDir
this.stagedFileChunks = stagedFileChunks
/**
* These three files hold state about an ongoing git merge
* Resolve paths during constructor
*/
this.mergeHeadFile = path.resolve(this.gitDir, '.git', MERGE_HEAD)
this.mergeModeFile = path.resolve(this.gitDir, '.git', MERGE_MODE)
this.mergeMsgFile = path.resolve(this.gitDir, '.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!')
}
// Get diff of staged modifications. This will be applied back to the index. after stashing all changes.
// The `git stash save --keep-index` option cannot be used since it resurrects deleted files on
// git versions before v2.23.0 (https://github.com/git/git/blob/master/Documentation/RelNotes/2.23.0.txt#L322)
const stagedDiff = await this.execGit(['diff', '--binary', '--cached'])
// Save stash of entire original state, including unstaged and untracked changes.
// This should remove all changes from the index.
await this.execGit(['stash', 'save', '--quiet', '--include-untracked', STASH])
// Apply staged modifications back to the index
await this.execGit([...gitApplyArgs, '--index'], { input: `${stagedDiff}\n` })
this.unstagedDiff = await this.execGit([
'diff',
'--binary',
'--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 Promise.all(
// stagedFileChunks includes staged files that lint-staged originally detected.
// Add only these files so any 3rd-party edits to other files won't be included in the commit.
this.stagedFileChunks.map(stagedFiles => this.execGit(['add', ...stagedFiles]))
)
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!')
}
// Restore untracked files by reading from the third commit associated with the backup stash
// Git will return with error code if the commit doesn't exist
// See https://stackoverflow.com/a/52357762
try {
const backupStash = await this.getBackupStash()
const output = await this.execGit(['show', '--format=%b', `${backupStash}^3`])
const untrackedDiff = output.replace(/^\n*/, '') // remove empty lines from start of output
if (!untrackedDiff) return
await this.execGit([...gitApplyArgs], { input: `${untrackedDiff}\n` })
} catch (err) {} // eslint-disable-line no-empty
}
/**
* 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