-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
66 lines (55 loc) · 1.6 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);
const write = async (filepath, output, dryRun) => {
if (!dryRun) {
await writeFile(filepath, output);
}
return output;
};
const trimArray = arr =>
arr
.join('\n')
.trim()
.split('\n');
module.exports = async ({
patterns = [],
comment = 'managed by ensure-gitignore',
filepath = path.resolve(process.cwd(), '.gitignore'),
dryRun = false
}) => {
let contents = '';
try {
contents = await readFile(filepath, 'utf-8');
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
const sortedPatterns = patterns.sort();
const rawPatterns = contents
.trim()
.split(/\r?\n/)
.filter(pattern => !sortedPatterns.includes(pattern));
const startComment = `# ${comment}`;
const endComment = `# end ${comment}`;
const startIndex = rawPatterns.indexOf(startComment);
const endIndex = rawPatterns.indexOf(endComment);
const before =
startIndex >= 0 ? trimArray(rawPatterns.slice(0, startIndex)) : rawPatterns;
const after =
endIndex >= 0
? trimArray(rawPatterns.slice(rawPatterns.indexOf(endComment) + 1))
: [];
const controlledPatterns =
patterns.length > 0
? [`\n${startComment}`, ...sortedPatterns, `${endComment}\n`]
: [];
const outputPatterns = [...before, ...controlledPatterns, ...after]
.join('\n')
.trim();
const output = `${outputPatterns}\n`;
return contents !== output ? write(filepath, output, dryRun) : output;
};