forked from microsoft/azure-pipelines-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
949 lines (822 loc) · 34.8 KB
/
gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
// node built-ins
var cp = require('child_process');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var fs = require('fs-extra');
var path = require('path');
var os = require('os');
var tsc = require('gulp-tsc');
// build/test script
var admZip = require('adm-zip');
var minimist = require('minimist');
var mocha = require('gulp-mocha');
var Q = require('q');
var semver = require('semver');
var shell = require('shelljs');
var syncRequest = require('sync-request');
var request = require('request');
var xml2js = require('xml2js');
// gulp modules
var del = require('del');
var gts = require('gulp-typescript');
var gulp = require('gulp');
var gutil = require('gulp-util');
var nuget = null;//require('gulp-nuget');
var pkgm = require('./package');
var util = require('./package-utils');
var typescript = require('typescript');
var args = require('yargs').argv;
// validation
var NPM_MIN_VER = '3.0.0';
var MIN_NODE_VER = '4.0.0';
if (semver.lt(process.versions.node, MIN_NODE_VER)) {
console.error('requires node >= ' + MIN_NODE_VER + '. installed: ' + process.versions.node);
process.exit(1);
}
//
// Options
//
var mopts = {
string: 'suite',
boolean: ['perf', 'e2e'],
default: { suite: '**', perf: false, e2e: false }
};
var options = minimist(process.argv.slice(2), mopts);
//
// Paths
//
var _buildRoot = "_build";
var _packageRoot = "_package";
var _extnBuildRoot = "_build/Extensions/";
var _taskModuleBuildRoot = "_build/TaskModules/";
var sourcePaths = "@(definitions|Extensions)/**/*";
var ExtensionFolder = "Extensions";
var taskModulesSourcePath = "TaskModules/**/*"
var TaskModulesFolder = "TaskModules"
var TaskModulesTestRoot = path.join(_taskModuleBuildRoot, 'powershell', 'Tests');
var TaskModulesTestTemp = path.join(TaskModulesTestRoot, 'Temp');
var _tempPath = path.join(__dirname, '_temp');
var _testRoot = "_build/";
var _testTemp = "_build/Temp";
var nugetPath = "_nuget";
var cultures = ['en-US', 'de-DE', 'es-ES', 'fr-FR', 'it-IT', 'ja-JP', 'ko-KR', 'ru-RU', 'zh-CN', 'zh-TW'];
//-----------------------------------------------------------------------------------------------------------------
// Build Tasks
//-----------------------------------------------------------------------------------------------------------------
function errorHandler(err) {
process.exit(1);
}
var proj = gts.createProject('./tsconfig.json', { typescript: typescript, declaration: true });
var ts = gts(proj);
gulp.task("clean", function() {
return del([_buildRoot, _packageRoot, nugetPath, _taskModuleBuildRoot]);
});
gulp.task("compilePS", ["clean"], function() {
if(args.testAreaPath === undefined )
{
return gulp.src(sourcePaths, { base: "." }).pipe(gulp.dest(_buildRoot));
}
else
{
var areaPathArgument = args.testAreaPath;
if(areaPathArgument.length > 0 )
{
console.log('Compiling updated modules - ' + areaPathArgument);
var areaPaths = areaPathArgument.trim().split(',');
var filter = [];
for (var n = 0; n < areaPaths.length; n++) {
filter.push(ExtensionFolder + '/' + areaPaths[n] + '/**/*')
}
return gulp.src(filter, { base: "." }).pipe(gulp.dest(_buildRoot));
}
else
{
console.log('No module is updated with given change-set');
// Create a _build/Extensions folder which will be empty
return gulp.src(ExtensionFolder, { base: "." }).pipe(gulp.dest(_buildRoot));
}
}
});
gulp.task("TaskModuleBuild", ["clean"], function() {
gulp.src(taskModulesSourcePath, { base: "."}).pipe(gulp.dest(_buildRoot));
});
gulp.task("clean:TaskModuleTest", function(cb) {
return del([TaskModulesTestRoot], cb);
});
gulp.task('compile:TaskModuleTest', ['clean:TaskModuleTest'], function (cb) {
var testsPath = path.join('TaskModules', 'powershell', 'Tests', '**/*.ts');
var testsLibPath = path.join('Extensions', 'Common', 'lib', '**/*.ts');
var tsconfigPath = path.join('TaskModules', 'powershell', 'Tests', 'tsconfig.json');
if (fs.existsSync(tsconfigPath)) {
var projLocal = gts.createProject(tsconfigPath, { typescript: typescript });
var tsLocal = gts(projLocal);
gulp.src([testsLibPath, 'definitions/*.d.ts'])
.pipe(ts)
.on("error", errorHandler)
.pipe(gulp.dest(path.join(_extnBuildRoot, 'Common', 'lib')));
return gulp.src([testsPath, 'definitions/*.d.ts'])
.pipe(tsLocal)
.on('error', errorHandler)
.pipe(gulp.dest(TaskModulesTestRoot));
}
});
gulp.task('copy:TaskModuleTest', ['compile:TaskModuleTest'], function (cb) {
gulp.src([path.join('Extensions', 'Common', 'lib', '**/*')])
.pipe(gulp.dest(path.join(_extnBuildRoot, 'Common', 'lib')));
return gulp.src([path.join('TaskModules', 'powershell', 'Tests', '**/*')])
.pipe(gulp.dest(TaskModulesTestRoot));
});
gulp.task("TaskModuleTest", ['copy:TaskModuleTest'], function() {
process.env['TASK_TEST_TEMP'] = TaskModulesTestTemp;
shell.rm('-rf', TaskModulesTestTemp);
shell.mkdir('-p', TaskModulesTestTemp);
var testSuitePath = path.join(TaskModulesTestRoot, options.suite + '/L0.js');
var tfBuild = ('' + process.env['TF_BUILD']).toLowerCase() == 'true'
gulp.src([testSuitePath])
.pipe(mocha({ reporter: 'spec', ui: 'bdd', useColors: !tfBuild }));
});
gulp.task('prepublish:TaskModulePublish', function (done) {
return del([TaskModulesTestRoot], done);
});
gulp.task('TaskModulePublish', ['prepublish:TaskModulePublish'], function (done) {
var powershellModulesDirectory = path.join(_taskModuleBuildRoot, 'powershell', '**/*');
if(options.outputDir){
var outputModulesDirectory = path.join(options.outputDir, 'ps_modules');
shell.mkdir('-p', outputModulesDirectory);
gulp.src(powershellModulesDirectory).pipe(gulp.dest(outputModulesDirectory));
}
});
gulp.task("compileNode", ["compilePS"], function(cb){
try {
// Cache all externals in the download directory.
var allExternalsJson = shell.find(path.join(__dirname, 'Extensions'))
.filter(function (file) {
return file.match(/(\/|\\)externals\.json$/);
})
.concat(path.join(__dirname, 'externals.json'));
allExternalsJson.forEach(function (externalsJson) {
// Load the externals.json file.
console.log('Loading ' + externalsJson);
var externals = require(externalsJson);
// Check for NPM externals.
if (externals.npm) {
// Walk the dictionary.
var packageNames = Object.keys(externals.npm);
packageNames.forEach(function (packageName) {
// Cache the NPM package.
var packageVersion = externals.npm[packageName];
cacheNpmPackage(packageName, packageVersion);
});
}
// Check for NuGetV2 externals.
if (externals.nugetv2) {
// Walk the dictionary.
var packageNames = Object.keys(externals.nugetv2);
packageNames.forEach(function (packageName) {
// Cache the NuGet V2 package.
var packageVersion = externals.nugetv2[packageName].version;
var packageRepository = externals.nugetv2[packageName].repository;
cacheNuGetV2Package(packageRepository, packageName, packageVersion);
})
}
// Check for archive files.
if (externals.archivePackages) {
// Walk the array.
externals.archivePackages.forEach(function (archive) {
// Cache the archive file.
cacheArchiveFile(archive.url);
});
}
// check of task modules
if(externals.taskModule) {
var taskModules = Object.keys(externals.taskModule);
taskModules.forEach(function (moduleIndex) {
var module = externals.taskModule[moduleIndex];
var srcPath = path.join("TaskModules", module['type'], module['name']);
var relativeExternalsPath = path.dirname(externalsJson).replace(new RegExp('/','g'),'\\').replace(path.join(__dirname),'');
if(relativeExternalsPath.startsWith('\\')) {
relativeExternalsPath = relativeExternalsPath.substring(1);
}
var destPath = path.join(_buildRoot, relativeExternalsPath, module['dest']);
shell.mkdir('-p', destPath);
shell.cp('-R', srcPath, destPath);
});
}
});
}
catch (err) {
console.log('error:' + err.message);
cb(new gutil.PluginError('compileTasks', err.message));
return;
}
// Compile UIExtensions
fs.readdirSync( path.join(__dirname, 'Extensions/')).filter(function (file) {
return fs.statSync(path.join(_extnBuildRoot, file)).isDirectory() && file != "Common";
}).forEach(compileUIExtensions);
//Foreach task under extensions copy common modules
fs.readdirSync(_extnBuildRoot).filter(function (file) {
return fs.statSync(path.join(_extnBuildRoot, file)).isDirectory() && file != "Common";
}).forEach(copyCommonModules);
var artifactEnginePath = path.join(__dirname, '_build/Extensions/ArtifactEngine');
runNpmInstall(artifactEnginePath);
// Compile tasks
var taskFiles = path.join(__dirname, '_build/Extensions/**/Tasks/**/*.ts');
var artifactEngineFiles = path.join(__dirname, '_build/Extensions/**/ArtifactEngine/**/*.ts');
gulp.src(['definitions/*.d.ts', taskFiles, artifactEngineFiles, '!**/node_modules/**', '!**/Extensions/ArtifactEngine/definitions/**'])
.pipe(ts)
.pipe(gulp.dest(path.join(_buildRoot, 'Extensions')))
.on('error', errorHandler);
// Generate loc files
createResjson(cb);
})
function createResjson(callback) {
try {
var allLibJson = shell.find(path.join(__dirname, 'Extensions'))
.filter(function (file) {
return file.match(/(\/|\\)lib\.json$/);
});
allLibJson.forEach(function (libJson) {
console.log('Generating resJson for ' + libJson);
// create a key->value map of the default strings
var defaultStrings = {};
var lib = JSON.parse(fs.readFileSync(libJson));
if (lib.messages) {
for (var key of Object.keys(lib.messages)) {
// skip resjson-style comments for localizers
if (!key || key.match(/^_.+\.comment$/)) {
continue;
}
defaultStrings[`loc.messages.${key}`] = lib.messages[key];
}
}
// create the culture-specific resjson files
for (var culture of cultures) {
// initialize the culture-specific strings from the default strings
var cultureStrings = {};
for (var key of Object.keys(defaultStrings)) {
cultureStrings[key] = defaultStrings[key];
}
// load the culture-specific xliff file
var xliffPath = path.join(path.dirname(libJson), 'xliff', `${culture}.xlf`);
var stats;
try {
stats = fs.statSync(xliffPath);
}
catch (err) {
if (err.code != 'ENOENT') {
throw err;
}
}
if (stats) {
// parse the culture-specific xliff contents
var parser = new xml2js.Parser();
var xliff;
parser.parseString(
fs.readFileSync(xliffPath),
function (err, result) {
if (err) {
throw err;
}
xliff = result;
});
// overlay the translated strings
for (var unit of xliff.xliff.file[0].body[0]['trans-unit']) {
if (unit.target[0].$.state == 'translated' &&
defaultStrings.hasOwnProperty(unit.$.id) &&
defaultStrings[unit.$.id] == unit.source[0]) {
cultureStrings[unit.$.id] = unit.target[0]._;
}
}
}
// write the culture-specific resjson file
var resjsonPath = path.join(path.dirname(libJson), 'Strings', 'resources.resjson', culture, 'resources.resjson');
var resjsonContents = JSON.stringify(cultureStrings, null, 2);
shell.mkdir('-p', path.dirname(resjsonPath));
fs.writeFileSync(resjsonPath, resjsonContents);
}
});
}
catch (err) {
console.log('error:' + err.message);
callback(new gutil.PluginError('compileTasks', err.message));
throw err;
}
}
function handoff(callback) {
// create a key->value map of default strings and comments for localizers
//
// resjson-style resources:
// "greeting": "Hello",
// "_greeting.comment": "A welcome greeting.",
//
// for more details about resjson: https://msdn.microsoft.com/en-us/library/windows/apps/hh465254.aspx
try {
var allLibJson = shell.find(path.join(__dirname, 'Extensions'))
.filter(function (file) {
return file.match(/(\/|\\)lib\.json$/);
});
allLibJson.forEach(function (libJson) {
console.log('Generating xliff for ' + libJson);
var defaultStrings = {};
var comments = {};
var lib = JSON.parse(fs.readFileSync(libJson));
if (lib.messages) {
for (var key of Object.keys(lib.messages)) {
if (!key) {
throw new Error('key cannot be empty: lib.messages.<key>');
}
if (key.match(/^_.+\.comment$/)) {
var commentKey = key;
var valueKey = commentKey.substr( // trim leading "_"
'_'.length, // trim trailing ".comment"
commentKey.length - '_.comment'.length);
comments[`loc.messages.${valueKey}`] = lib.messages[commentKey];
continue;
}
else {
defaultStrings[`loc.messages.${key}`] = lib.messages[key];
}
}
}
// create or update the culture-specific xlf files
for (var culture of cultures) {
if (culture.toUpperCase() == 'EN-US') {
continue;
}
// test whether xliff file exists
var xliffPath = path.join(path.dirname(libJson), 'xliff', `${culture}.xlf`);
var stats;
try {
stats = fs.statSync(xliffPath);
}
catch (err) {
if (err.code != 'ENOENT') {
throw err;
}
}
var xliff;
if (stats) {
// parse the file
var parser = new xml2js.Parser();
parser.parseString(
fs.readFileSync(xliffPath),
function (err, result) {
if (err) {
throw err;
}
xliff = result;
}
)
}
else {
// create the initial xliff object
xliff = {
"xliff": {
"$": {
"version": "1.2"
},
"file": [
{
"$": {
"original": "lib.json",
"source-language": "en-US",
"target-language": culture,
"datatype": "plaintext"
},
"body": [
{
"trans-unit": []
}
]
}
]
}
}
}
// create a map of trans-unit
var unitMap = {};
for (var unit of xliff.xliff.file[0].body[0]['trans-unit']) {
unitMap[unit['$'].id] = unit;
}
for (var key of Object.keys(defaultStrings)) {
// add the trans-unit
if (!unitMap.hasOwnProperty(key)) {
unitMap[key] = {
"$": {
"id": key
},
"source": [
defaultStrings[key]
],
"target": [
{
"$": {
"state": "new"
},
"_": ""
}
]
};
}
// update the source, target state, and note
else if (unitMap[key].source[0] != defaultStrings[key]) {
unitMap[key].source = [
defaultStrings[key]
];
if (unitMap[key].target[0]['$'].state != 'new') {
unitMap[key].target[0]['$'].state = "needs-translation";
}
}
// always update the note
unitMap[key].note = [
(comments[key] || "")
];
}
for (var key of Object.keys(unitMap)) {
// delete the trans-unit
if (!defaultStrings.hasOwnProperty(key)) {
delete unitMap[key];
}
}
// update the body of the xliff object
xliff.xliff.file[0].body[0]['trans-unit'] = [];
for (var key of Object.keys(unitMap).sort()) {
xliff.xliff.file[0].body[0]['trans-unit'].push(unitMap[key]);
}
// write the xliff file
var options = {
"renderOpts": {
"pretty": true,
"indent": " ",
"newline": os.EOL
},
"xmldec": {
"version": "1.0",
"encoding": "utf-8"
}
};
var builder = new xml2js.Builder(options);
var xml = builder.buildObject(xliff);
shell.mkdir('-p', path.dirname(xliffPath));
fs.writeFileSync(xliffPath, '\ufeff' + xml);
}
});
}
catch (err) {
console.log('error:' + err.message);
callback(new gutil.PluginError('compileTasks', err.message));
throw err;
}
}
function runNpmInstall(packagePath) {
var originalDir = shell.pwd();
util.cd(packagePath);
var packageJsonPath = util.rp('package.json');
if (util.test('-f', packageJsonPath)) {
util.run('npm install');
}
util.cd(originalDir);
}
function compileUIExtensions(extensionRoot) {
var uiExtensionsPath = path.join(_buildRoot,"Extensions", extensionRoot, 'Src', 'UIExtensions');
var tsconfigPath = path.join(uiExtensionsPath,"tsconfig.json");
if (fs.existsSync(tsconfigPath)) {
var projLocal = gts.createProject(tsconfigPath, { typescript: typescript });
var tsLocal = gts(projLocal);
var uiFilePath = path.join(uiExtensionsPath, '**/**/*.ts');
return gulp.src([uiFilePath])
.pipe(tsLocal)
.on('error', errorHandler)
.pipe(gulp.dest(uiExtensionsPath));
};
}
gulp.task("build", ["compileNode"], function() {
});
gulp.task("handoff", function(cb) {
handoff(cb);
});
gulp.task("default", ["build"]);
//-----------------------------------------------------------------------------------------------------------------
// Test Tasks
//-----------------------------------------------------------------------------------------------------------------
gulp.task('compileTests', function () {
var testsPath = path.join(__dirname, 'Extensions/**/Tests', '**/*.ts');
return gulp.src([testsPath, 'definitions/*.d.ts'])
.pipe(ts)
.on('error', errorHandler)
.pipe(gulp.dest(_testRoot+"\\Extensions"));
});
gulp.task('testLib', ['compileTests'], function () {
return gulp.src(['Extensions/Common/lib/**/*'])
.pipe(gulp.dest(path.join(_testRoot,'Extensions/Common/lib/')));
});
gulp.task('copyTestData', ['compileTests'], function () {
return gulp.src(['Extensions/**/Tests/**/data/**'], { dot: true })
.pipe(gulp.dest(_testRoot+"\\Extensions"));
});
gulp.task('tstests', ['compileTests'], function () {
return gulp.src(['Extensions/**/Tests/**/*.ts', 'Extensions/**/Tests/**/*.json', 'Extensions/**/Tests/**/*.js'])
.pipe(gulp.dest(_testRoot+"\\Extensions"));
});
gulp.task('ps1tests', ['compileTests'], function () {
return gulp.src(['Extensions/**/Tests/**/*.ps1', 'Extensions/**/Tests/**/*.json'])
.pipe(gulp.dest(_testRoot+"\\Extensions"));
});
gulp.task('testLib_NodeModules', ['testLib'], function () {
return gulp.src(path.join(__dirname, 'Extensions/Common/lib/vsts-task-lib/**/*'))
.pipe(gulp.dest(path.join(_testRoot, 'Extensions/Common/lib/node_modules/vsts-task-lib')));
});
gulp.task('testResources', ['testLib_NodeModules', 'ps1tests', 'tstests', 'copyTestData']);
gulp.task("_mochaTests", ["testResources"], function(){
process.env['TASK_TEST_TEMP'] =path.join(__dirname, _testTemp);
shell.rm('-rf', _testTemp);
shell.mkdir('-p', _testTemp);
if (options.suite.indexOf("ArtifactEngine") >= 0 && options.e2e) {
var suitePath = path.join(_testRoot, "Extensions/" + options.suite + "/**/*E2E.js");
console.log(suitePath);
var tfBuild = ('' + process.env['TF_BUILD']).toLowerCase() == 'true'
return gulp.src([suitePath])
.pipe(mocha({ reporter: 'spec', ui: 'bdd', useColors: !tfBuild }));
}
if (options.suite.indexOf("ArtifactEngine") >= 0 && options.perf) {
var suitePath = path.join(_testRoot, "Extensions/" + options.suite + "/**/*Perf.js");
console.log(suitePath);
var tfBuild = ('' + process.env['TF_BUILD']).toLowerCase() == 'true'
return gulp.src([suitePath])
.pipe(mocha({ reporter: 'spec', ui: 'bdd', useColors: !tfBuild }));
}
var suitePath = path.join(_testRoot,"Extensions/" + options.suite + "/Tests/Tasks", options.suite + '/_suite.js');
console.log(suitePath);
var tfBuild = ('' + process.env['TF_BUILD']).toLowerCase() == 'true'
gulp.src([suitePath])
.pipe(mocha({ reporter: 'spec', ui: 'bdd', useColors: !tfBuild }));
var suitePath = path.join(_testRoot, "Extensions/" + options.suite + "/**/*Tests.js");
console.log(suitePath);
var tfBuild = ('' + process.env['TF_BUILD']).toLowerCase() == 'true'
return gulp.src([suitePath])
.pipe(mocha({ reporter: 'spec', ui: 'bdd', useColors: !tfBuild }));
});
gulp.task("test", ["_mochaTests"],function(done){
// Runs powershell pester tests ( Unit Test)
var pester = spawn('powershell.exe', ['.\\InvokePester.ps1'], { stdio: 'inherit' });
pester.on('exit', function(code, signal) {
if (code != 0) {
throw new gulpUtil.PluginError({
plugin: 'test',
message: 'Pester Tests Failed!!!'
});
}
else { done();
}
});
pester.on('error', function(err) {
gutil.log('We may be in a non-windows machine or powershell.exe is not in path. Skip pester tests.');
done();
});
});
//-----------------------------------------------------------------------------------------------------------------
// Package//-----------------------------------------------------------------------------------------------------------------
var publisherName = null;
gulp.task("package", function() {
if(args.publisher){
publisherName = args.publisher;
}
// use gulp package --extension=<Extension_Name> to package an individual package
if(args.extension){
createVsixPackage(args.extension); return;
}
fs.readdirSync(_extnBuildRoot).filter(function (file) {
return fs.statSync(path.join(_extnBuildRoot, file)).isDirectory() && file != "Common";
}).forEach(createVsixPackage);
});
gulp.task('nuget-download', function(done) {
console.log("> Checking for nuget.exe");
if(fs.existsSync('nuget.exe')) {
return done();
}
console.log("> Downloading nuget.exe");
return request.get('http://nuget.org/nuget.exe')
.pipe(fs.createWriteStream('nuget.exe'));
});
gulp.task("package_nuget", ['nuget-download'], function() {
// nuspec
var version = options.version;
if (!version) {
console.error('ERROR: supply version with --version');
process.exit(1);
}
if (!semver.valid(version)) {
console.error('ERROR: invalid semver version: ' + version);
process.exit(1);
}
if(!options.extension) {
console.error('ERROR: supply extension name with --extension');
process.exit(1);
}
if(!fs.existsSync("_package\\"+options.extension)) {
console.error('ERROR: mentioned extension does not exist');
process.exit(1);
}
// Nuget package
// Copying extension to contents
var extensionPath = path.join("_package", options.extension);
shell.rm("-rf", nugetPath);
var contentsPath = path.join(nugetPath,'pack-source', 'contents');
shell.mkdir("-p", contentsPath);
shell.cp(path.join(extensionPath,"*"), contentsPath);
// nuspec
var pkgName = 'Mseng.MS.TF.RM.Extensions';
console.log();
console.log('> Generating .nuspec file');
var contents = '<?xml version="1.0" encoding="utf-8"?>' + os.EOL;
contents += '<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">' + os.EOL;
contents += ' <metadata>' + os.EOL;
contents += ' <id>' + pkgName + '</id>' + os.EOL;
contents += ' <version>' + version + '</version>' + os.EOL;
contents += ' <authors>bigbldt</authors>' + os.EOL;
contents += ' <owners>bigbldt,Microsoft</owners>' + os.EOL;
contents += ' <requireLicenseAcceptance>false</requireLicenseAcceptance>' + os.EOL;
contents += ' <description>For VSS internal use only</description>' + os.EOL;
contents += ' <tags>VSSInternal</tags>' + os.EOL;
contents += ' </metadata>' + os.EOL;
contents += '</package>' + os.EOL;
console.log('> Generated .nuspec file');
console.log();
console.log('> Copying extension to package');
var nuspecPath = path.join(nugetPath, 'pack-source', pkgName + '.nuspec');
fs.writeFileSync(nuspecPath, contents);
console.log('> Copied extension to package');
// package
console.log();
console.log('> Beginning package...');
var nupkgPath = path.join(nugetPath, 'pack-target');
var exePath = './nuget.exe';
gulp.src(nuspecPath)
.pipe(nuget.pack({ nuget: exePath, version: options.version }))
.pipe(gulp.dest(nupkgPath));
console.log();
console.log('> Package Successful');
if (options.server) {
console.log();
console.log('> Publishing .nupkg file to server');
gulp.src(path.join(nupkgPath, pkgName + "." + options.version + ".nupkg"))
.pipe(nuget.push({ source: options.server, nuget: exePath, apiKey: 'SkyRise' }));
console.log('> Publish Successful');
}
});
gulp.task("locCommon",function(){
return gulp.src(path.join(__dirname, 'Extensions/Common/**/module.json'))
.pipe(pkgm.LocCommon());
});
var copyCommonModules = function(extensionName) {
var commonDeps = require('./common.json');
var commonSrc = path.join(__dirname, 'Extensions/Common');
var currentExtnRoot = path.join(__dirname, "_build/Extensions" ,extensionName);
return gulp.src(path.join(currentExtnRoot, '**/task.json'))
.pipe(pkgm.copyCommonModules(currentExtnRoot, commonDeps, commonSrc));
}
var createVsixPackage = function(extensionName) {
var extnOutputPath = path.join(_packageRoot, extensionName);
var extnManifestPath = path.join(_extnBuildRoot, extensionName, "Src");
del(extnOutputPath);
if (publisherName){
var manifest = JSON.parse(fs.readFileSync(path.join(extnManifestPath,"vss-extension.json")));
manifest.publisher = publisherName;
fs.writeFileSync(path.join(extnManifestPath,"vss-extension.json"), JSON.stringify(manifest));
}
shell.mkdir("-p", extnOutputPath);
var packagingCmd = "tfx extension create --manifest-globs vss-extension.json --root " + extnManifestPath + " --output-path " + extnOutputPath;
executeCommand(packagingCmd, function() {});
}
var executeCommand = function(cmd, callback) {
shell.exec(cmd, {silent: true}, function(code, output) {
if(code != 0) {
console.error("command failed: " + cmd + "\nManually execute to debug");
}
else {
callback();
}
});
}
var cacheArchiveFile = function (url) {
// Validate the parameters.
if (!url) {
throw new Error('Parameter "url" cannot be null or empty.');
}
// Short-circuit if already downloaded.
var scrubbedUrl = url.replace(/[/\:?]/g, '_');
var targetPath = path.join(_tempPath, 'archive', scrubbedUrl);
if (shell.test('-d', targetPath)) {
console.log('Archive file already cached: ' + url);
return;
}
console.log('Downloading archive file: ' + url);
// Delete any previous partial attempt.
var partialPath = path.join(_tempPath, 'partial', 'archive', scrubbedUrl);
if (shell.test('-d', partialPath)) {
shell.rm('-rf', partialPath);
}
// Download the archive file.
shell.mkdir('-p', partialPath);
var file = path.join(partialPath, 'file.zip');
var result = syncRequest('GET', url);
fs.writeFileSync(file, result.getBody());
// Extract the archive file.
console.log("Extracting archive.");
var directory = path.join(partialPath, "dir");
var zip = new admZip(file);
zip.extractAllTo(directory);
// Move the extracted directory.
shell.mkdir('-p', path.dirname(targetPath));
shell.mv(directory, targetPath);
// Remove the remaining partial directory.
shell.rm('-rf', partialPath);
}
var cacheNpmPackage = function (name, version) {
// Validate the parameters.
if (!name) {
throw new Error('Parameter "name" cannot be null or empty.');
}
if (!version) {
throw new Error('Parameter "version" cannot be null or empty.');
}
// Short-circuit if already downloaded.
gutil.log('Downloading npm package ' + name + '@' + version);
var targetPath = path.join(_tempPath, 'npm', name, version);
if (shell.test('-d', targetPath)) {
console.log('Package already cached. Skipping.');
return;
}
// Delete any previous partial attempt.
var partialPath = path.join(_tempPath, 'partial', 'npm', name, version);
if (shell.test('-d', partialPath)) {
shell.rm('-rf', partialPath);
}
// Write a temporary package.json file to npm install warnings.
//
// Note, write the file higher up in the directory hierarchy so it is not included
// when the partial directory is moved into the target location
shell.mkdir('-p', partialPath);
var pkg = {
"name": "temp",
"version": "1.0.0",
"description": "temp to avoid warnings",
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"repository": "http://norepo/but/nowarning",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT"
};
fs.writeFileSync(
path.join(_tempPath, 'partial', 'npm', 'package.json'),
JSON.stringify(pkg, null, 2));
// Validate npm is in the PATH.
var npmPath = shell.which('npm');
if (!npmPath) {
throw new Error('npm not found. ensure npm 3 or greater is installed');
}
// Validate the version of npm.
var versionOutput = cp.execSync('"' + npmPath + '" --version');
var npmVersion = versionOutput.toString().replace(/[\n\r]+/g, '')
console.log('npm version: "' + npmVersion + '"');
if (semver.lt(npmVersion, NPM_MIN_VER)) {
throw new Error('npm version must be at least ' + NPM_MIN_VER + '. Found ' + npmVersion);
}
// Make a node_modules directory. Otherwise the modules will be installed in a node_modules
// directory further up the directory hierarchy.
shell.mkdir('-p', path.join(partialPath, 'node_modules'));
// Run npm install.
shell.pushd(partialPath);
try {
var cmdline = '"' + npmPath + '" install ' + name + '@' + version;
var result = cp.execSync(cmdline);
gutil.log(result.toString());
if (result.status > 0) {
throw new Error('npm failed with exit code ' + result.status);
}
}
finally {
shell.popd();
}
// Move the intermediate directory to the target location.
shell.mkdir('-p', path.dirname(targetPath));
shell.mv(partialPath, targetPath);
}
var cacheNuGetV2Package = function (repository, name, version) {
// Validate the parameters.
if (!repository) {
throw new Error('Parameter "repository" cannot be null or empty.');
}
if (!name) {
throw new Error('Parameter "name" cannot be null or empty.');
}
if (!version) {
throw new Error('Parameter "version" cannot be null or empty.');
}
// Cache the archive file.
cacheArchiveFile(repository.replace(/\/$/, '') + '/package/' + name + '/' + version);
}