UNPKG

2.91 kBJavaScriptView Raw
1const AnalyzerContext = require('./analyzer.context');
2
3const _ = require('lodash');
4const Promise = require('bluebird');
5
6const { stringify, emptyLine }= require('../json-to-yaml');
7const { defaultYaml }= require('../helpers/common');
8
9const fs = require('fs');
10const path = require('path');
11
12class 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 * add step to yaml
33 * @param step
34 * @returns {Analyzer}
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 * add header to yaml (before steps)
49 * @param header
50 * @returns {Analyzer}
51 */
52 header(header) {
53 this._addToChain('header', () => {
54 this.analyzerContext.addHeader(header(this.source))
55 });
56 return this;
57 }
58
59 /**
60 * apply enricher key - value to each existing step
61 * @param enricher
62 * @returns {Analyzer}
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 // handle transforms because result of it not require next actions
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 // process other events from chain
86 // sequence is important there
87 for(const item of ['header', 'step', 'enrich']){
88 // using loop for store order
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
112module.exports = Analyzer;