forked from ivanseidel/node-ssl-vision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadProtoFile.js
57 lines (45 loc) · 1.43 KB
/
readProtoFile.js
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
const fs = require('fs')
const path = require('path')
/*
* This method will import files from protobuf files recursivelly and include
* in the output, removing the import statements.
*/
module.exports = function mergeProtoFiles(mainFile, {loaded} = {}) {
if (!mainFile.startsWith('/'))
throw new Error('File must be absolute and start with `/`')
// Parse directory and file name
let dir = path.dirname(mainFile)
let name = path.dirname(mainFile)
// Keep track of imports
loaded = loaded || {}
// Keep track of outputLines
let outputLines = []
// Check if it's already imported
if (loaded[mainFile]){
return ''
}
// Save file as imported
loaded[mainFile] = true
// Check if file exists
if (!fs.existsSync(mainFile))
throw new Error(`Import file does not exists: ${mainFile}`)
// Read contents of the file and split lines
let contents = String(fs.readFileSync(mainFile))
let lines = contents.split('\n')
// Iterate lines
for (let line of lines) {
// Check for `syntax` statement
if (line.startsWith('syntax'))
continue
// Check if it's an import statement
let importStatement = line.match(/^import "(.*)";$/)
if (importStatement) {
let importName = importStatement[1]
let importPath = path.join(dir, importName)
outputLines.push(mergeProtoFiles(importPath, {loaded}))
continue
}
outputLines.push(line)
}
return outputLines.join('\n')
}