|
1 | 1 | import { join } from "./path"
|
2 | 2 | import { removeSync } from "fs-extra"
|
3 | 3 | import klawSync from "klaw-sync"
|
| 4 | +import { spawnSafeSync } from "./spawnSafe" |
| 5 | + |
| 6 | +const gitExcludePaths = (dir: string): RegExp => { |
| 7 | + const anyRegExp = (regExps: RegExp[], flags?: string): RegExp => |
| 8 | + regExps.length <= 0 |
| 9 | + ? /(?!)/ // never matches |
| 10 | + : new RegExp(regExps.map(regExp => regExp.source).join("|"), flags) |
| 11 | + const escapeRegExp = (str: string): string => |
| 12 | + str.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&") |
| 13 | + const gitExcludeFilesResult = spawnSafeSync( |
| 14 | + "git", |
| 15 | + ["ls-files", "-o", "-i", "--exclude-standard"], |
| 16 | + { |
| 17 | + cwd: dir, |
| 18 | + throwOnError: false, |
| 19 | + logStdErrOnError: false, |
| 20 | + }, |
| 21 | + ) |
| 22 | + return anyRegExp( |
| 23 | + gitExcludeFilesResult.status === 0 |
| 24 | + ? gitExcludeFilesResult.stdout |
| 25 | + .toString() |
| 26 | + .split(/\n/g) |
| 27 | + .filter(path => path.length > 0) |
| 28 | + .map(escapeRegExp) |
| 29 | + .map(escaped => new RegExp(escaped)) |
| 30 | + : [], |
| 31 | + "i", |
| 32 | + ) |
| 33 | +} |
4 | 34 |
|
5 | 35 | export function removeIgnoredFiles(
|
6 | 36 | dir: string,
|
7 | 37 | includePaths: RegExp,
|
8 | 38 | excludePaths: RegExp,
|
9 | 39 | ) {
|
| 40 | + const gitIgnoredPaths = gitExcludePaths(dir) |
10 | 41 | klawSync(dir, { nodir: true })
|
11 | 42 | .map(item => item.path.slice(`${dir}/`.length))
|
12 | 43 | .filter(
|
13 | 44 | relativePath =>
|
14 |
| - !relativePath.match(includePaths) || relativePath.match(excludePaths), |
| 45 | + !relativePath.match(includePaths) || |
| 46 | + relativePath.match(excludePaths) || |
| 47 | + relativePath.match(gitIgnoredPaths), |
15 | 48 | )
|
16 | 49 | .forEach(relativePath => removeSync(join(dir, relativePath)))
|
17 | 50 | }
|
0 commit comments