1 | pathModule = require("path")
|
2 | crypto = require("crypto")
|
3 | fs = require("fs")
|
4 | wrench = require("wrench")
|
5 |
|
6 | program = require("commander").usage("[option] <js-folder-root>")
|
7 | .option("-o,--output-file <path>","specify the output require configs")
|
8 | .option("-r,--root <root patah>","specifty the generated files root name")
|
9 | .option("-f,--force-overwrite","force overwrite the file rather than try merging it")
|
10 | .option("--excludes <folder or file>","exclude certain folder or file by matching the starts, split by ','")
|
11 | .option("--enable-debug","enable debug mode in config")
|
12 | .option("--enable-cache","enable cache in config")
|
13 | .option("--set-version <version>","set version for the config")
|
14 | .option("--main <main module>","set entry module for the config")
|
15 | .parse(process.argv)
|
16 | outputFile = program.outputFile
|
17 | outputFormat = "json"
|
18 | indentCount = 4
|
19 | jsIncludePath = program.args[0] or "./"
|
20 | excludes = (program.excludes or "").split(",").map((item)->item.trim()).filter (item)->item
|
21 | version = program.setVersion or null
|
22 | mainModule = program.main or null
|
23 | enableDebug = program.enableDebug and true or false
|
24 | if outputFormat is "json" and outputFile and not program.forceOverwrite and fs.existsSync outputFile
|
25 | try
|
26 | config = JSON.parse fs.readFileSync outputFile,"utf8"
|
27 | catch e
|
28 | console.error "outputFile #{outputFile} exists, but is not a valid json."
|
29 | console.error "don't overwrite it."
|
30 | process.exit(1)
|
31 | else
|
32 | config = {}
|
33 | config.name = config.name or "leaf-require"
|
34 | config.js = {}
|
35 | config.debug = config.debug or enableDebug
|
36 | config.cache = config.cache or program.enableCache or false
|
37 | if mainModule
|
38 | config.js.main = mainModule
|
39 | if version
|
40 | config.version = version
|
41 | files = wrench.readdirSyncRecursive jsIncludePath
|
42 | fileWhiteList = [/\.js$/i]
|
43 | files = files.filter (file)->
|
44 | filePath = pathModule.resolve pathModule.join jsIncludePath,file
|
45 | for exclude in excludes
|
46 | excludePath = pathModule.resolve exclude
|
47 | if filePath is excludePath or filePath.indexOf(excludePath+"/") is 0
|
48 | return false
|
49 | for white in fileWhiteList
|
50 | if white.test file
|
51 | return true
|
52 | return false
|
53 | files = files.map (file)->
|
54 | hash = crypto.createHash("md5").update(fs.readFileSync (pathModule.join jsIncludePath,file),"utf8").digest("hex").substring(0,6)
|
55 | return {
|
56 | path:file
|
57 | hash:hash
|
58 | }
|
59 | config.js.root = program.root or ""
|
60 | config.js.files = files
|
61 |
|
62 | content = JSON.stringify config,null,indentCount
|
63 | if outputFile
|
64 | fs.writeFileSync outputFile,content
|
65 | else
|
66 | console.log content
|
67 | process.exit(0)
|