Added copyright headers
[src/xds/xds-agent.git] / webapp / src / app / pages / build / build.component.ts
1 /**
2 * @license
3 * Copyright (C) 2017 "IoT.bzh"
4 * Author Sebastien Douheret <sebastien@iot.bzh>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 import { Component, ViewEncapsulation, AfterViewChecked, ElementRef, ViewChild, OnInit, Input } from '@angular/core';
20 import { Observable } from 'rxjs/Observable';
21 import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
22 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
23
24 import 'rxjs/add/operator/scan';
25 import 'rxjs/add/operator/startWith';
26
27 import { BuildSettingsModalComponent } from './build-settings-modal/build-settings-modal.component';
28
29 import { XDSAgentService, ICmdOutput } from '../../@core-xds/services/xdsagent.service';
30 import { ProjectService, IProject } from '../../@core-xds/services/project.service';
31 import { AlertService, IAlert } from '../../@core-xds/services/alert.service';
32 import { SdkService } from '../../@core-xds/services/sdk.service';
33
34 @Component({
35   selector: 'xds-panel-build',
36   templateUrl: './build.component.html',
37   styleUrls: ['./build.component.scss'],
38   encapsulation: ViewEncapsulation.None,
39 })
40
41 export class BuildComponent implements OnInit, AfterViewChecked {
42   @ViewChild('scrollOutput') private scrollContainer: ElementRef;
43
44   // FIXME workaround of https://github.com/angular/angular-cli/issues/2034
45   // should be removed with angular 5
46   //  @Input() curProject: IProject;
47   @Input() curProject = <IProject>null;
48
49   public buildIsCollapsed = false;
50   public cmdOutput: string;
51   public cmdInfo: string;
52   public curPrj: IProject;
53
54   private startTime: Map<string, number> = new Map<string, number>();
55
56   constructor(
57     private prjSvr: ProjectService,
58     private xdsSvr: XDSAgentService,
59     private alertSvr: AlertService,
60     private sdkSvr: SdkService,
61     private modalService: NgbModal,
62   ) {
63     this.cmdOutput = '';
64     this.cmdInfo = '';       // TODO: to be remove (only for debug)
65   }
66
67   ngOnInit() {
68     // Retreive current project
69     this.prjSvr.curProject$.subscribe(p => this.curPrj = p);
70
71     // Command output data tunneling
72     this.xdsSvr.CmdOutput$.subscribe(data => {
73       this.cmdOutput += data.stdout;
74       this.cmdOutput += data.stderr;
75     });
76
77     // Command exit
78     this.xdsSvr.CmdExit$.subscribe(exit => {
79       if (this.startTime.has(exit.cmdID)) {
80         this.cmdInfo = 'Last command duration: ' + this._computeTime(this.startTime.get(exit.cmdID));
81         this.startTime.delete(exit.cmdID);
82       }
83
84       if (exit && exit.code !== 0) {
85         this.cmdOutput += '--- Command exited with code ' + exit.code + ' ---\n\n';
86       }
87     });
88
89     this._scrollToBottom();
90   }
91
92   ngAfterViewChecked() {
93     this._scrollToBottom();
94   }
95
96   resetOutput() {
97     this.cmdOutput = '';
98   }
99
100   isSetupValid(): boolean {
101     return (typeof this.curPrj !== 'undefined');
102   }
103
104   settingsShow() {
105     if (!this.isSetupValid()) {
106       return this.alertSvr.warning('Please select first a valid project.', true);
107     }
108
109     const activeModal = this.modalService.open(BuildSettingsModalComponent, { size: 'lg', container: 'nb-layout' });
110     activeModal.componentInstance.modalHeader = 'Large Modal';
111   }
112
113   execCmd(cmdName: string) {
114     if (!this.isSetupValid()) {
115       return this.alertSvr.warning('Please select first a valid project.', true);
116     }
117
118     if (!this.curPrj.uiSettings) {
119       return this.alertSvr.warning('Invalid setting structure', true);
120     }
121
122     let cmd = '';
123     switch (cmdName) {
124       case 'clean':
125         cmd = this.curPrj.uiSettings.cmdClean;
126         break;
127       case 'prebuild':
128         cmd = this.curPrj.uiSettings.cmdPrebuild;
129         break;
130       case 'build':
131         cmd = this.curPrj.uiSettings.cmdBuild;
132         break;
133       case 'populate':
134         cmd = this.curPrj.uiSettings.cmdPopulate;
135         break;
136       case 'exec':
137         if (this.curPrj.uiSettings.cmdArgs instanceof Array)  {
138           cmd = this.curPrj.uiSettings.cmdArgs.join(' ');
139         } else {
140           cmd = this.curPrj.uiSettings.cmdArgs;
141         }
142         break;
143       default:
144         return this.alertSvr.warning('Unknown command name ' + cmdName);
145     }
146
147     const prjID = this.curPrj.id;
148     const dir = this.curPrj.uiSettings.subpath;
149     const args: string[] = [];
150     const sdkid = this.sdkSvr.getCurrentId();
151
152     let env = '';
153     if (this.curPrj.uiSettings.envVars instanceof Array) {
154       env = this.curPrj.uiSettings.envVars.join(' ');
155     } else {
156       env = this.curPrj.uiSettings.envVars;
157     }
158
159     this.cmdOutput += this._outputHeader();
160
161     // Detect key=value in env string to build array of string
162     const envArr = [];
163     env.split(';').forEach(v => envArr.push(v.trim()));
164
165     const t0 = performance.now();
166     this.cmdInfo = 'Start build of ' + prjID + ' at ' + t0;
167
168     this.xdsSvr.exec(prjID, dir, cmd, sdkid, args, envArr)
169       .subscribe(res => {
170         this.startTime.set(String(res.cmdID), t0);
171       },
172       err => {
173         this.cmdInfo = 'Last command duration: ' + this._computeTime(t0);
174         this.alertSvr.error('ERROR: ' + err);
175       });
176   }
177
178   private _scrollToBottom(): void {
179     try {
180       this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
181     } catch (err) { }
182   }
183
184   private _computeTime(t0: number, t1?: number): string {
185     const enlap = Math.round((t1 || performance.now()) - t0);
186     if (enlap < 1000.0) {
187       return enlap.toFixed(2) + ' ms';
188     } else {
189       return (enlap / 1000.0).toFixed(3) + ' seconds';
190     }
191   }
192
193   private _outputHeader(): string {
194     return '--- ' + new Date().toString() + ' ---\n';
195   }
196
197   private _outputFooter(): string {
198     return '\n';
199   }
200 }