Skip to content

Commit

Permalink
refactor: improvements based on PR review
Browse files Browse the repository at this point in the history
  • Loading branch information
iiroj committed Nov 14, 2019
1 parent fc03fdc commit 6fa9c85
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 43 deletions.
50 changes: 31 additions & 19 deletions lib/gitWorkflow.js
Expand Up @@ -44,7 +44,7 @@ class GitWorkflow {

/**
* Create backup stashes, one of everything and one of only staged changes
* Leves stages files in index for running tasks
* Staged files are left in the index for running tasks
*
* @param {Object} [options]
* @returns {Promise<void>}
Expand Down Expand Up @@ -83,14 +83,11 @@ class GitWorkflow {
.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(
await Promise.all(
untrackedFiles.map(file =>
readBufferFromFile(file).then(buffer => this.untrackedFiles.set(file, buffer))
)
}
await Promise.all(readPromises)
)
debug('Done backing up untracked files!')
}

Expand All @@ -105,42 +102,57 @@ class GitWorkflow {
'--unified=0',
'--no-color',
'--no-ext-diff',
'-p',
'--patch',
original,
'-R'
'-R' // Show diff in reverse
])
debug('Done backing up original state!')
}

/**
* Resets everything and applies back unstaged and staged changes,
* possibly with modifications by tasks
* Applies back unstaged changes that have been hidden in the stash.
* In case of a merge-conflict retry with 3-way merge.
*
* @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 while 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` })

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...')
const writePromises = []
this.untrackedFiles.forEach((buffer, file) => {
writePromises.push(writeBufferToFile(file, buffer))
})
await Promise.all(writePromises)
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!')
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/runAll.js
Expand Up @@ -115,12 +115,12 @@ module.exports = async function runAll(
task: () => new Listr(tasks, { ...listrOptions, concurrent: true, exitOnError: false })
},
{
title: 'Applying unstaged changes...',
title: 'Restoring unstaged changes...',
skip: ctx => ctx.hasErrors && 'Skipped because of errors from tasks',
task: () => git.restoreUnstagedChanges()
},
{
title: 'Restoring original state due to errors...',
title: 'Reverting to original state...',
enabled: ctx => ctx.hasErrors,
task: () => git.restoreOriginalState()
},
Expand Down
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -68,8 +68,8 @@
"jest": "^24.8.0",
"jest-snapshot-serializer-ansi": "^1.0.0",
"jsonlint": "^1.6.3",
"prettier": "1.18.2",
"uuid": "^3.3.3"
"nanoid": "^2.1.1",
"prettier": "1.18.2"
},
"config": {
"commitizen": {
Expand Down
24 changes: 12 additions & 12 deletions test/__snapshots__/runAll.spec.js.snap
Expand Up @@ -10,8 +10,8 @@ LOG echo \\"sample\\" [started]
LOG echo \\"sample\\" [completed]
LOG Running tasks for *.js [completed]
LOG Running tasks... [completed]
LOG Applying unstaged changes... [started]
LOG Applying unstaged changes... [completed]
LOG Restoring unstaged changes... [started]
LOG Restoring unstaged changes... [completed]
LOG Cleaning up... [started]
LOG Cleaning up... [completed]"
`;
Expand All @@ -33,11 +33,11 @@ LOG →
LOG Running tasks for *.js [failed]
LOG →
LOG Running tasks... [failed]
LOG Applying unstaged changes... [started]
LOG Applying unstaged changes... [skipped]
LOG Restoring unstaged changes... [started]
LOG Restoring unstaged changes... [skipped]
LOG → Skipped because of errors from tasks
LOG Restoring original state due to errors... [started]
LOG Restoring original state due to errors... [completed]
LOG Reverting to original state... [started]
LOG Reverting to original state... [completed]
LOG Cleaning up... [started]
LOG Cleaning up... [completed]
LOG {
Expand All @@ -64,11 +64,11 @@ LOG →
LOG Running tasks for *.js [failed]
LOG →
LOG Running tasks... [failed]
LOG Applying unstaged changes... [started]
LOG Applying unstaged changes... [skipped]
LOG Restoring unstaged changes... [started]
LOG Restoring unstaged changes... [skipped]
LOG → Skipped because of errors from tasks
LOG Restoring original state due to errors... [started]
LOG Restoring original state due to errors... [completed]
LOG Reverting to original state... [started]
LOG Reverting to original state... [completed]
LOG Cleaning up... [started]
LOG Cleaning up... [completed]
LOG {
Expand Down Expand Up @@ -103,8 +103,8 @@ LOG echo \\"sample\\" [started]
LOG echo \\"sample\\" [completed]
LOG Running tasks for *.js [completed]
LOG Running tasks... [completed]
LOG Applying unstaged changes... [started]
LOG Applying unstaged changes... [completed]
LOG Restoring unstaged changes... [started]
LOG Restoring unstaged changes... [completed]
LOG Cleaning up... [started]
LOG Cleaning up... [completed]"
`;
5 changes: 2 additions & 3 deletions test/runAll.unmocked.spec.js
Expand Up @@ -3,7 +3,7 @@ import makeConsoleMock from 'consolemock'
import normalize from 'normalize-path'
import os from 'os'
import path from 'path'
import uuid from 'uuid'
import nanoid from 'nanoid'

import execGitBase from '../lib/execGit'
import runAll from '../lib/runAll'
Expand Down Expand Up @@ -36,7 +36,7 @@ const osTmpDir = isAppveyor ? 'C:\\projects' : fs.realpathSync(os.tmpdir())
* @returns {Promise<String>}
*/
const createTempDir = async () => {
const dirname = path.resolve(osTmpDir, 'lint-staged-test', uuid())
const dirname = path.resolve(osTmpDir, 'lint-staged-test', nanoid())
await fs.ensureDir(dirname)
return dirname
}
Expand Down Expand Up @@ -467,6 +467,5 @@ describe('runAll', () => {
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
expect(await readFile('test-untracked.js')).toEqual(testJsFilePretty)
console = makeConsoleMock()
})
})
10 changes: 5 additions & 5 deletions yarn.lock
Expand Up @@ -4173,6 +4173,11 @@ nan@^2.12.1:
resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c"
integrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==

nanoid@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-2.1.1.tgz#524fd4acd45c126e0c87cd43ab5ee8346e695df9"
integrity sha512-0YbJdaL4JFoejIOoawgLcYValFGJ2iyUuVDIWL3g8Es87SSOWFbWdRUMV3VMSiyPs3SQ3QxCIxFX00q5DLkMCw==

nanomatch@^1.2.9:
version "1.2.13"
resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
Expand Down Expand Up @@ -5854,11 +5859,6 @@ uuid@^3.3.2:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131"
integrity sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==

uuid@^3.3.3:
version "3.3.3"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.3.tgz#4568f0216e78760ee1dbf3a4d2cf53e224112866"
integrity sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==

v8-compile-cache@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz#00f7494d2ae2b688cfe2899df6ed2c54bef91dbe"
Expand Down

0 comments on commit 6fa9c85

Please sign in to comment.