forked from tinybeachthor/gitbot-format
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
64 lines (52 loc) · 1.47 KB
/
Copy pathformat.ts
File metadata and controls
64 lines (52 loc) · 1.47 KB
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
import fs from 'fs'
import path from 'path'
import { spawnSync } from 'child_process'
import tempWrite from 'temp-write'
const extensions =
['.c', '.h', '.cpp', '.hpp', '.C', '.H', '.cc', '.hh', '.cxx', '.hxx']
export default async function formatFile (
{filename, content}: types.File,
style: string | null
) {
if (!extensions.includes(path.extname(filename))) {
return {filename, content, touched: false}
}
const transformed = await clangFormat(filename, content, style)
return {
filename,
content: transformed,
touched: transformed != content,
}
}
async function clangFormat (
filename: string,
content: string,
style: string | null
) {
const formattedStyle = Buffer.from(style ? style : 'Google')
const options = [
"-style="+formattedStyle.toString('utf8'),
"-i", // in-place
]
// format until file does not change anymore
let input
let output = content
do {
input = output
const file = tempWrite.sync(input, path.basename(filename))
await spawnAndPipe(file, options),
output = fs.readFileSync(file).toString()
// remove temp file
fs.unlink(file, (err) => err && console.error(err))
} while (input !== output)
return output
}
function spawnAndPipe (filePath: string, options: string[]) {
return new Promise((resolve, reject) => {
const p = spawnSync('clang-format', [...options, filePath], {
stdio: 'ignore',
timeout: 60 * 1000,
})
p.error ? reject(p.error) : resolve(0)
})
}