1 | const
|
2 | fs = require('fs'),
|
3 | path = require('path'),
|
4 | glob = require('glob'),
|
5 | sgUtil = require('../util'),
|
6 | storedAnalyzes = new Map();
|
7 |
|
8 | class Analyzer {
|
9 |
|
10 | constructor(source, options, dumpData) {
|
11 |
|
12 | this.source = source;
|
13 | this.hash = sgUtil.hashCode(source);
|
14 | this.options = options;
|
15 | this.dumpData = dumpData;
|
16 |
|
17 | this.getFiles = this.getFiles.bind(this);
|
18 | }
|
19 |
|
20 | getFiles() {
|
21 | return glob.sync(this.source, this.options);
|
22 | }
|
23 |
|
24 | getFileContents() {
|
25 | return this.getFiles()
|
26 | .map((filename) => sgUtil.readFileContents(filename)).join('\n')
|
27 | }
|
28 |
|
29 | hasSourceChanged() {
|
30 | const
|
31 | {hash, getFiles} = this,
|
32 | {time = false} = storedAnalyzes.get(hash) || {};
|
33 |
|
34 | let hasChanged = true;
|
35 |
|
36 | if (time !== false) {
|
37 | hasChanged = false;
|
38 | getFiles().some((filename) => {
|
39 | if (time < new Date(fs.statSync(filename).ctime).getTime()) {
|
40 | return hasChanged = true;
|
41 | }
|
42 | });
|
43 | }
|
44 | return hasChanged;
|
45 | }
|
46 |
|
47 | getAnalysis() {
|
48 | const {hasSourceChanged, getStoredData, startWrappedAnalysis} = this;
|
49 |
|
50 | return (hasSourceChanged.call(this) === false) ? getStoredData.call(this) : startWrappedAnalysis.call(this);
|
51 | }
|
52 |
|
53 | getStoredData() {
|
54 | return storedAnalyzes.has(this.hash) ? storedAnalyzes.get(this.hash).data : startWrappedAnalysis.call(this);
|
55 | }
|
56 |
|
57 | getVersion() {
|
58 | return storedAnalyzes.has(this.hash) ? storedAnalyzes.get(this.hash).version : 0;
|
59 | }
|
60 |
|
61 | startWrappedAnalysis() {
|
62 | const
|
63 | {hash, constructor, analyze, getVersion} = this,
|
64 | data = analyze.call(this),
|
65 | version = getVersion.call(this);
|
66 |
|
67 | storedAnalyzes.set(hash, {
|
68 | time: new Date().getTime(),
|
69 | data: data,
|
70 | version: (version + 1)
|
71 | });
|
72 |
|
73 | if (this.dumpData) {
|
74 | sgUtil.dumpData(path.join('.tmp', constructor.name, `${hash}.json`), data);
|
75 | }
|
76 | return data;
|
77 | }
|
78 | }
|
79 |
|
80 | module.exports = Analyzer; |
\ | No newline at end of file |