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 |
|
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 |
|
37 |
|
38 |
|
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 |
|
53 |
|
54 |
|
55 |
|
56 | header(header) {
|
57 | this._addToChain('header', () => {
|
58 | this.analyzerContext.addHeader(header(this.source))
|
59 | });
|
60 | return this;
|
61 | }
|
62 |
|
63 | |
64 |
|
65 |
|
66 |
|
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 |
|
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 |
|
90 |
|
91 | for(const item of ['header', 'step', 'enrich']){
|
92 |
|
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 |
|
116 | module.exports = Analyzer;
|