src/rewrite.ts   A
last analyzed

Complexity

Total Complexity 11
Complexity/F 11

Size

Lines of Code 80
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 70
mnd 10
bc 10
fnc 1
dl 0
loc 80
rs 10
bpm 10
cpm 11
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
C rewrite.ts ➔ rewrite 0 63 11
1
import {createReadStream} from 'fs'
2
import {createInterface} from 'readline'
3
import {
4
  $close,
5
  $exists,
6
  $open,
7
  $rename,
8
  $copy,
9
  $write,
10
  $unlink,
11
  tempFileName,
12
} from "./fs"
13
14
export = rewrite
15
16
async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) {
17
  const {length} = lines
18
  , fileExists = await $exists(filename)
19
20
  let line: string = "undefined"
21
  , row = 0
22
23
  if (fileExists) {
24
    const lineReader = createInterface({
25
      input: createReadStream(filename),
26
      crlfDelay: Infinity,
27
      historySize: 0
28
    })
29
30
    let isSame = true
31
32
    for await (line of lineReader) {
33
      if (line !== lines[row]) {
34
        isSame = false
35
        break
36
      }
37
      row++
38
    }
39
40
    lineReader.close()
41
42
    if (isSame) {
43
      if (lines[row] === "")
44
        row++
45
      if (length === row)
46
        return
47
    }
48
  }
49
50
  if (checkMode)
51
    throw new Error([
52
      `Content of "${filename}:${row + 1}" should be another`,
53
      "- Expected:",
54
      lines[row],
55
      "+ Received:",
56
      line
57
    ].join("\n"))
58
59
  const tempFile = await tempFileName()
60
  , fd = await $open(tempFile, "w")
61
62
  for (let i = 0; i < length; i++)
63
    await $write(fd, `${
64
      i ? eol : ''
65
    }${
66
      lines[i]
67
    }`)
68
69
  await $close(fd)
70
71
  try {
72
    await $rename(tempFile, filename)
73
  } catch (error) {
74
    /* istanbul ignore next https://github.com/askirmas/postcss-d-ts/pull/30 */
75
    await $copy(tempFile, filename)
76
    /* istanbul ignore next https://github.com/askirmas/postcss-d-ts/pull/30 */
77
    await $unlink(tempFile)
78
  }
79
}
80