1 | const AnalyzerContext = require('./analyzer.context');
|
2 |
|
3 | const _ = require('lodash');
|
4 | const Promise = require('bluebird');
|
5 |
|
6 | const { stringify, emptyLine }= require('../json-to-yaml');
|
7 | const { defaultYaml }= require('../helpers/common');
|
8 |
|
9 | const fs = require('fs');
|
10 | const path = require('path');
|
11 |
|
12 | class Analyzer {
|
13 |
|
14 | async _defaultYaml() {
|
15 | return defaultYaml(this.source);
|
16 | }
|
17 |
|
18 | async init(context, source) {
|
19 | this.analyzerContext = new AnalyzerContext(context);
|
20 | this.source = source;
|
21 | await this.analyzerContext.loadRepoInfo();
|
22 | this.chain = {};
|
23 | }
|
24 |
|
25 | _addToChain(key, func) {
|
26 | const values = this.chain[key] || [];
|
27 | values.push(func);
|
28 | this.chain[key] = values;
|
29 | }
|
30 |
|
31 | |
32 |
|
33 |
|
34 |
|
35 |
|
36 | step(step) {
|
37 | this._addToChain('step', async () => {
|
38 | const res = await step(this.analyzerContext);
|
39 | if(res) {
|
40 | this.analyzerContext.addStep(res);
|
41 | }
|
42 |
|
43 | });
|
44 | return this;
|
45 | }
|
46 |
|
47 | |
48 |
|
49 |
|
50 |
|
51 |
|
52 | header(header) {
|
53 | this._addToChain('header', () => {
|
54 | this.analyzerContext.addHeader(header(this.source))
|
55 | });
|
56 | return this;
|
57 | }
|
58 |
|
59 | |
60 |
|
61 |
|
62 |
|
63 |
|
64 | enrich(enricher) {
|
65 | this._addToChain('enrich', () => enricher(this.analyzerContext));
|
66 | return this;
|
67 | }
|
68 |
|
69 | transform(transformer) {
|
70 | this._addToChain('transform', () => transformer(this.analyzerContext));
|
71 | return this;
|
72 | }
|
73 |
|
74 | async resolve() {
|
75 |
|
76 | const transformers = _.get(this.chain, 'transform', [])
|
77 | .map(t => t());
|
78 | const result = await Promise.all(transformers);
|
79 | const filteredResult = result.filter(r => r !== null);
|
80 | if (!_.isEmpty(filteredResult)) {
|
81 | return filteredResult[0];
|
82 | }
|
83 |
|
84 | try{
|
85 |
|
86 |
|
87 | for(const item of ['header', 'step', 'enrich']){
|
88 |
|
89 | for(const step of this.chain[item]){
|
90 | await step();
|
91 | }
|
92 | }
|
93 | }
|
94 | catch (e) {
|
95 | console.error(e);
|
96 | return this._defaultYaml();
|
97 | }
|
98 |
|
99 |
|
100 | const steps = this.analyzerContext.getSteps();
|
101 | Object.keys(steps).forEach(stepName => Object.assign(steps[stepName], {[emptyLine()]: true}));
|
102 |
|
103 | return stringify({
|
104 | ...this.analyzerContext.getHeaders(),
|
105 | [emptyLine()]: true,
|
106 | steps
|
107 | });
|
108 | }
|
109 |
|
110 | }
|
111 |
|
112 | module.exports = Analyzer;
|