Skip to content

Commit

Permalink
fix: correctly restore untracked files from backup stash
Browse files Browse the repository at this point in the history
  • Loading branch information
iiroj committed Nov 14, 2019
1 parent d1da3fc commit c7d0592
Showing 1 changed file with 10 additions and 39 deletions.
49 changes: 10 additions & 39 deletions lib/gitWorkflow.js
@@ -1,7 +1,6 @@
'use strict'

const debug = require('debug')('lint-staged:git')
const normalize = require('normalize-path')
const path = require('path')

const execGit = require('./execGit')
Expand Down Expand Up @@ -69,28 +68,6 @@ class GitWorkflow {
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
Expand Down Expand Up @@ -155,22 +132,16 @@ class GitWorkflow {
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 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
}

/**
Expand Down

0 comments on commit c7d0592

Please sign in to comment.