-
Notifications
You must be signed in to change notification settings - Fork 10
/
run-ts.js
89 lines (79 loc) · 2.08 KB
/
run-ts.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var scriptsFolder = 'scripts';
var scriptsOutputFolder = 'outts';
var pattern_ts = /\.ts$/;
var tsFilePath = findFile(path.join(process.cwd(), scriptsFolder, process.argv[2]), ['', '.ts']);
if (tsFilePath && tsFilePath.match(pattern_ts))
runTypeScript(tsFilePath, process.argv.slice(3));
else
console.error("Usage: node run-ts <example[.ts]> [exampleArg1 [exampleArg2 [...]]]");
function runTypeScript(tsFilePath, args)
{
var infile = tsFilePath;
var outfile = path.join(path.dirname(tsFilePath), scriptsOutputFolder, path.basename(tsFilePath).replace(pattern_ts, '.js'));
var in_mtime = get_mtime(infile);
var out_mtime = get_mtime(outfile);
// if outfile missing or infile modified after outfile, recompile
if (!isFile(outfile) || in_mtime > out_mtime)
{
var tsc = process.cwd().indexOf('/') < 0 ? 'tsc.cmd' : 'tsc';
run(tsc, ['--project', scriptsFolder]).error;
}
// method 1: spawn a new task
// run('node', [outfile].concat(process.argv.slice(3)));
// method 2: use require() to run the script
// make argv look like the outfile script was called directly
process.argv.splice(1, 2, outfile);
// load the outfile script
var outResult = require(outfile);
// if the outfile script exports a function, call that function
if (typeof outResult == 'function')
outResult(process.argv.slice(2));
}
function findFile(fileNoExt, extensions)
{
for (var ext of extensions)
if (isFile(fileNoExt + ext))
return fileNoExt + ext;
return null;
}
function isFile(file)
{
try
{
return fs.statSync(file).isFile();
}
catch (e)
{
return false;
}
}
function get_mtime(file)
{
try
{
return fs.statSync(file).mtime;
}
catch (e)
{
return NaN;
}
}
function run(cmd, args)
{
console.log('>', cmd, args.join(' '));
var result = child_process.spawnSync(
cmd,
args,
{
cwd: process.cwd(),
env: process.env,
stdio: 'inherit'
}
);
if (result.error)
throw result.error;
return result;
}