Total Complexity | 10 |
Complexity/F | 10 |
Lines of Code | 62 |
Function Count | 1 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import {createReadStream} from 'fs' |
||
2 | import {createInterface} from 'readline' |
||
3 | import { |
||
4 | $close, |
||
5 | $exists, |
||
6 | $open, |
||
7 | $rename, |
||
8 | $write, |
||
9 | tempFileName |
||
10 | } from "./fs" |
||
11 | |||
12 | export = rewrite |
||
13 | |||
14 | async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) { |
||
15 | const {length} = lines |
||
16 | , fileExists = await $exists(filename) |
||
17 | |||
18 | if (fileExists) { |
||
19 | const lineReader = createInterface({ |
||
20 | input: createReadStream(filename), |
||
21 | crlfDelay: Infinity, |
||
22 | historySize: 0 |
||
23 | }) |
||
24 | |||
25 | let isSame = true |
||
26 | , row = 0 |
||
27 | |||
28 | for await (const line of lineReader) { |
||
29 | if (line !== lines[row]) { |
||
30 | isSame = false |
||
31 | break |
||
32 | } |
||
33 | row++ |
||
34 | } |
||
35 | |||
36 | lineReader.close() |
||
37 | |||
38 | if (isSame) { |
||
39 | if (lines[row] === "") |
||
40 | row++ |
||
41 | if (length === row) |
||
42 | return |
||
43 | } |
||
44 | } |
||
45 | |||
46 | if (checkMode) |
||
47 | throw new Error(`Content of "${filename}" should be another`) |
||
48 | |||
49 | const tempFile = await tempFileName() |
||
50 | , fd = await $open(tempFile, "w") |
||
51 | |||
52 | for (let i = 0; i < length; i++) |
||
53 | await $write(fd, `${ |
||
54 | i ? eol : '' |
||
55 | }${ |
||
56 | lines[i] |
||
57 | }`) |
||
58 | |||
59 | await $close(fd) |
||
60 | await $rename(tempFile, filename) |
||
61 | } |
||
62 |