All files / create-package/src git-utils.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 3/3
100% Lines 9/9

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 40                            5x         5x 5x 1x   4x     4x     10x       4x   12x        
import { execa } from 'execa';
 
import type { FileMap } from './fs-utils.ts';
 
/**
 * Filters out files from a {@link FileMap} that are ignored by git.
 *
 * @param absoluteFileMap - A map of absolute file paths to file contents.
 * @returns A map of file paths to file contents.
 */
export async function excludeGitIgnored(
  absoluteFileMap: FileMap,
): Promise<FileMap> {
  // See: https://git-scm.com/docs/git-check-ignore
  const execaResult = await execa('git', ['check-ignore', '--stdin'], {
    input: Object.keys(absoluteFileMap).join('\n'),
    reject: false,
  });
 
  let checkIgnoreOutput = '';
  if (execaResult.failed && execaResult.exitCode !== 1) {
    throw execaResult as Error;
  } else {
    checkIgnoreOutput = execaResult.stdout;
  }
 
  const gitIgnoredFiles = new Set(
    checkIgnoreOutput
      .split('\n')
      .map((line) => line.trim())
      .filter(Boolean),
  );
 
  return Object.fromEntries(
    Object.entries(absoluteFileMap).filter(
      ([filePath]) => !gitIgnoredFiles.has(filePath),
    ),
  );
}