Passed
Push — master ( 695a88...75a95e )
by Andrii
02:59
created

src/rewrite.ts   A

Complexity

Total Complexity 10
Complexity/F 10

Size

Lines of Code 58
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 49
mnd 9
bc 9
fnc 1
dl 0
loc 58
rs 10
bpm 9
cpm 10
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
C rewrite.ts ➔ rewrite 0 46 10
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