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