1import fs = require("fs"); 2import path = require("path"); 3 4function instrumentForRecording(fn: string, tscPath: string) { 5 instrument(tscPath, ` 6ts.sys = Playback.wrapSystem(ts.sys); 7ts.sys.startRecord("${ fn }");`, `ts.sys.endRecord();`); 8} 9 10function instrumentForReplay(logFilename: string, tscPath: string) { 11 instrument(tscPath, ` 12ts.sys = Playback.wrapSystem(ts.sys); 13ts.sys.startReplay("${ logFilename }");`); 14} 15 16function instrument(tscPath: string, prepareCode: string, cleanupCode = "") { 17 const bak = `${tscPath}.bak`; 18 fs.exists(bak, (backupExists: boolean) => { 19 let filename = tscPath; 20 if (backupExists) { 21 filename = bak; 22 } 23 24 fs.readFile(filename, "utf-8", (err: any, tscContent: string) => { 25 if (err) throw err; 26 27 fs.writeFile(bak, tscContent, (err: any) => { 28 if (err) throw err; 29 30 fs.readFile(path.resolve(path.dirname(tscPath) + "/loggedIO.js"), "utf-8", (err: any, loggerContent: string) => { 31 if (err) throw err; 32 33 const invocationLine = "ts.executeCommandLine(ts.sys.args);"; 34 const index1 = tscContent.indexOf(invocationLine); 35 if (index1 < 0) { 36 throw new Error(`Could not find ${invocationLine}`); 37 } 38 39 const index2 = index1 + invocationLine.length; 40 const newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + "\r\n"; 41 fs.writeFile(tscPath, newContent, err => { 42 if (err) throw err; 43 }); 44 }); 45 }); 46 }); 47 }); 48} 49 50const isJson = (arg: string) => arg.indexOf(".json") > 0; 51 52const record = process.argv.indexOf("record"); 53const tscPath = process.argv[process.argv.length - 1]; 54if (record >= 0) { 55 console.log(`Instrumenting ${tscPath} for recording`); 56 instrumentForRecording(process.argv[record + 1], tscPath); 57} 58else if (process.argv.some(isJson)) { 59 const filename = process.argv.filter(isJson)[0]; 60 instrumentForReplay(filename, tscPath); 61} 62 63 64