All files / src/utils check-work-dir.ts

90.48% Statements 19/21
80% Branches 8/10
100% Functions 5/5
94.44% Lines 17/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4015x 15x 15x     15x         15x 3x 3x   3x 3x 3x   3x 33x         15x 4x   4x 1x       3x              
import { join } from 'path'
import git from 'simple-git/promise'
import { isChildPathOf, isEmptyDir } from '@/utils'
 
 
const reminder = [
  'This command may cause some files to be overwritten',
  "If you're sure you want to run this command, rerun it with --force.",
].join('\n')
 
const isWorkDirClean = async(path: string): Promise<boolean> => {
  const isRepo = await git(path).checkIsRepo()
  Iif (!isRepo) throw new Error('The work directory checked should be an repository')
 
  const { files } = await git(path).status()
  let toplevel = await git(path).revparse(['--show-toplevel'])
  toplevel = toplevel.replace(/\n$/, '')
 
  return !files
    .map(file => join(toplevel, file.path))
    .filter(isChildPathOf(path))
    .length
}
 
export default async(path: string): Promise<void> => {
  const isRepo = await git(path).checkIsRepo()
 
  if (!isRepo && !(await isEmptyDir(path))) {
    throw new Error([
      'The project directory is not a git repository and is a non-empty folder.',
      reminder,
    ].join('\n'))
  } else Iif (isRepo && !(await isWorkDirClean(path))) {
    throw new Error([
      'Git working directory not clean',
      reminder,
    ].join('\n'))
  }
}