UNPKG

3.05 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
22 await this.analyzerContext.loadRepoInfo()
23 .catch(e => {
24 if (!(source === 'onboarding' && _.get(context, 'repo.git') !== 'github')) throw e;
25 });
26 this.chain = {};
27 }
28
29 _addToChain(key, func) {
30 const values = this.chain[key] || [];
31 values.push(func);
32 this.chain[key] = values;
33 }
34
35 /**
36 * add step to yaml
37 * @param step
38 * @returns {Analyzer}
39 */
40 step(step) {
41 this._addToChain('step', async () => {
42 const res = await step(this.analyzerContext);
43 if(res) {
44 this.analyzerContext.addStep(res);
45 }
46
47 });
48 return this;
49 }
50
51 /**
52 * add header to yaml (before steps)
53 * @param header
54 * @returns {Analyzer}
55 */
56 header(header) {
57 this._addToChain('header', () => {
58 this.analyzerContext.addHeader(header(this.source))
59 });
60 return this;
61 }
62
63 /**
64 * apply enricher key - value to each existing step
65 * @param enricher
66 * @returns {Analyzer}
67 */
68 enrich(enricher) {
69 this._addToChain('enrich', () => enricher(this.analyzerContext));
70 return this;
71 }
72
73 transform(transformer) {
74 this._addToChain('transform', () => transformer(this.analyzerContext));
75 return this;
76 }
77
78 async resolve() {
79 // handle transforms because result of it not require next actions
80 const transformers = _.get(this.chain, 'transform', [])
81 .map(t => t());
82 const result = await Promise.all(transformers);
83 const filteredResult = result.filter(r => r !== null);
84 if (!_.isEmpty(filteredResult)) {
85 return filteredResult[0];
86 }
87
88 try{
89 // process other events from chain
90 // sequence is important there
91 for(const item of ['header', 'step', 'enrich']){
92 // using loop for store order
93 for(const step of this.chain[item]){
94 await step();
95 }
96 }
97 }
98 catch (e) {
99 console.error(e);
100 return this._defaultYaml();
101 }
102
103
104 const steps = this.analyzerContext.getSteps();
105 Object.keys(steps).forEach(stepName => Object.assign(steps[stepName], {[emptyLine()]: true}));
106
107 return stringify({
108 ...this.analyzerContext.getHeaders(),
109 [emptyLine()]: true,
110 steps
111 });
112 }
113
114}
115
116module.exports = Analyzer;