forked from microsoft/azure-pipelines-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-util.js
1147 lines (976 loc) · 38.4 KB
/
make-util.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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var admZip = require('adm-zip');
var check = require('validator');
var fs = require('fs');
var minimatch = require('minimatch');
var os = require('os');
var path = require('path');
var process = require('process');
var ncp = require('child_process');
var semver = require('semver');
var shell = require('shelljs');
var syncRequest = require('sync-request');
// global paths
var downloadPath = path.join(__dirname, '_download');
var makeOptions = require('./make-options.json');
// list of .NET culture names
var cultureNames = ['cs', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'pl', 'pt-BR', 'ru', 'tr', 'zh-Hans', 'zh-Hant'];
//------------------------------------------------------------------------------
// shell functions
//------------------------------------------------------------------------------
var shellAssert = function () {
var errMsg = shell.error();
if (errMsg) {
throw new Error(errMsg);
}
}
var cd = function (dir) {
var cwd = process.cwd();
if (cwd != dir) {
console.log('');
console.log(`> cd ${path.relative(cwd, dir)}`);
shell.cd(dir);
shellAssert();
}
}
exports.cd = cd;
var cp = function (options, source, dest) {
if (dest) {
shell.cp(options, source, dest);
}
else {
shell.cp(options, source);
}
shellAssert();
}
exports.cp = cp;
var mkdir = function (options, target) {
if (target) {
shell.mkdir(options, target);
}
else {
shell.mkdir(options);
}
shellAssert();
}
exports.mkdir = mkdir;
var rm = function (options, target) {
if (target) {
shell.rm(options, target);
}
else {
shell.rm(options);
}
shellAssert();
}
exports.rm = rm;
var test = function (options, p) {
var result = shell.test(options, p);
shellAssert();
return result;
}
exports.test = test;
//------------------------------------------------------------------------------
var assert = function (value, name) {
if (!value) {
throw new Error('"' + name + '" cannot be null or empty.');
}
}
exports.assert = assert;
var banner = function (message, noBracket) {
console.log();
if (!noBracket) {
console.log('------------------------------------------------------------');
}
console.log(message);
if (!noBracket) {
console.log('------------------------------------------------------------');
}
}
exports.banner = banner;
var rp = function (relPath) {
return path.join(pwd() + '', relPath);
}
exports.rp = rp;
var fail = function (message) {
console.error('ERROR: ' + message);
process.exit(1);
}
exports.fail = fail;
var ensureExists = function (checkPath) {
assert(checkPath, 'checkPath');
var exists = test('-d', checkPath) || test('-f', checkPath);
if (!exists) {
fail(checkPath + ' does not exist');
}
}
exports.ensureExists = ensureExists;
var pathExists = function (checkPath) {
return test('-d', checkPath) || test('-f', checkPath);
}
exports.pathExists = pathExists;
/**
* Given a module path, gets the info used for generating a pack file
*/
var getCommonPackInfo = function (modOutDir) {
// assert the module has a package.json
var packageJsonPath = path.join(modOutDir, 'package.json');
if (!test('-f', packageJsonPath)) {
fail(`Common module package.json does not exist: '${packageJsonPath}'`);
}
// assert the package name and version
var packageJson = JSON.parse(fs.readFileSync(packageJsonPath));
if (!packageJson || !packageJson.name || !packageJson.version) {
fail(`The common module's package.json must define a name and version: ${packageJsonPath}`);
}
var packFileName = `${packageJson.name}-${packageJson.version}.tgz`;
return {
"packageName": packageJson.name,
"packFilePath": path.join(path.dirname(modOutDir), packFileName)
};
}
exports.getCommonPackInfo = getCommonPackInfo;
var buildNodeTask = function (taskPath, outDir) {
var originalDir = pwd();
cd(taskPath);
var packageJsonPath = rp('package.json');
if (test('-f', packageJsonPath)) {
// verify no dev dependencies
var packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
if (packageJson.devDependencies && Object.keys(packageJson.devDependencies).length != 0) {
fail('The package.json should not contain dev dependencies. Move the dev dependencies into a package.json file under the Tests sub-folder. Offending package.json: ' + packageJsonPath);
}
run('npm install');
}
if (test('-f', rp(path.join('Tests', 'package.json')))) {
cd(rp('Tests'));
run('npm install');
cd(taskPath);
}
run('tsc --outDir ' + outDir + ' --rootDir ' + taskPath);
cd(originalDir);
}
exports.buildNodeTask = buildNodeTask;
var copyTaskResources = function (taskMake, srcPath, destPath) {
assert(taskMake, 'taskMake');
assert(srcPath, 'srcPath');
assert(destPath, 'destPath');
// copy the globally defined set of default task resources
var toCopy = makeOptions['taskResources'];
toCopy.forEach(function (item) {
matchCopy(item, srcPath, destPath, { noRecurse: true, matchBase: true });
});
// copy the locally defined set of resources
if (taskMake.hasOwnProperty('cp')) {
copyGroups(taskMake.cp, srcPath, destPath);
}
// remove the locally defined set of resources
if (taskMake.hasOwnProperty('rm')) {
removeGroups(taskMake.rm, destPath);
}
}
exports.copyTaskResources = copyTaskResources;
var matchFind = function (pattern, root, options) {
assert(pattern, 'pattern');
assert(root, 'root');
// create a copy of the options
var clone = {};
Object.keys(options || {}).forEach(function (key) {
clone[key] = options[key];
});
options = clone;
// determine whether to recurse
var noRecurse = options.hasOwnProperty('noRecurse') && options.noRecurse;
delete options.noRecurse;
// normalize first, so we can substring later
root = path.resolve(root);
// determine the list of items
var items;
if (noRecurse) {
items = fs.readdirSync(root)
.map(function (name) {
return path.join(root, name);
});
}
else {
items = find(root)
.filter(function (item) { // filter out the root folder
return path.normalize(item) != root;
});
}
return minimatch.match(items, pattern, options);
}
exports.matchFind = matchFind;
var matchCopy = function (pattern, sourceRoot, destRoot, options) {
assert(pattern, 'pattern');
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
console.log(`copying ${pattern}`);
// normalize first, so we can substring later
sourceRoot = path.resolve(sourceRoot);
destRoot = path.resolve(destRoot);
matchFind(pattern, sourceRoot, options)
.forEach(function (item) {
// create the dest dir based on the relative item path
var relative = item.substring(sourceRoot.length + 1);
assert(relative, 'relative'); // should always be filterd out by matchFind
var dest = path.dirname(path.join(destRoot, relative));
mkdir('-p', dest);
cp('-Rf', item, dest + '/');
});
}
exports.matchCopy = matchCopy;
var run = function (cl, inheritStreams, noHeader) {
if (!noHeader) {
console.log();
console.log('> ' + cl);
}
var options = {
stdio: inheritStreams ? 'inherit' : 'pipe'
};
var rc = 0;
var output;
try {
output = ncp.execSync(cl, options);
}
catch (err) {
if (!inheritStreams) {
console.error(err.output ? err.output.toString() : err.message);
}
process.exit(1);
}
return (output || '').toString().trim();
}
exports.run = run;
var ensureTool = function (name, versionArgs, validate) {
console.log(name + ' tool:');
var toolPath = which(name);
if (!toolPath) {
fail(name + ' not found. might need to run npm install');
}
if (versionArgs) {
var result = exec(name + ' ' + versionArgs);
if (typeof validate == 'string') {
if (result.output.trim() != validate) {
fail('expected version: ' + validate);
}
}
else {
validate(result.output.trim());
}
}
console.log(toolPath + '');
}
exports.ensureTool = ensureTool;
var installNode = function (nodeVersion) {
switch (nodeVersion || '') {
case '':
case '6':
nodeVersion = 'v6.10.3';
break;
case '5':
nodeVersion = 'v5.10.1';
break;
default:
fail(`Unexpected node version '${nodeVersion}'. Expected 5 or 6.`);
}
if (nodeVersion === run('node -v')) {
console.log('skipping node install for tests since correct version is running');
return;
}
// determine the platform
var platform = os.platform();
if (platform != 'darwin' && platform != 'linux' && platform != 'win32') {
throw new Error('Unexpected platform: ' + platform);
}
var nodeUrl = 'https://nodejs.org/dist';
switch (platform) {
case 'darwin':
var nodeArchivePath = downloadArchive(nodeUrl + '/' + nodeVersion + '/node-' + nodeVersion + '-darwin-x64.tar.gz');
addPath(path.join(nodeArchivePath, 'node-' + nodeVersion + '-darwin-x64', 'bin'));
break;
case 'linux':
var nodeArchivePath = downloadArchive(nodeUrl + '/' + nodeVersion + '/node-' + nodeVersion + '-linux-x64.tar.gz');
addPath(path.join(nodeArchivePath, 'node-' + nodeVersion + '-linux-x64', 'bin'));
break;
case 'win32':
var nodeDirectory = path.join(downloadPath, `node-${nodeVersion}`);
var marker = nodeDirectory + '.completed';
if (!test('-f', marker)) {
var nodeExePath = downloadFile(nodeUrl + '/' + nodeVersion + '/win-x64/node.exe');
var nodeLibPath = downloadFile(nodeUrl + '/' + nodeVersion + '/win-x64/node.lib');
rm('-Rf', nodeDirectory);
mkdir('-p', nodeDirectory);
cp(nodeExePath, path.join(nodeDirectory, 'node.exe'));
cp(nodeLibPath, path.join(nodeDirectory, 'node.lib'));
fs.writeFileSync(marker, '');
}
addPath(nodeDirectory);
break;
}
}
exports.installNode = installNode;
var downloadFile = function (url) {
// validate parameters
if (!url) {
throw new Error('Parameter "url" must be set.');
}
// skip if already downloaded
var scrubbedUrl = url.replace(/[/\:?]/g, '_');
var targetPath = path.join(downloadPath, 'file', scrubbedUrl);
var marker = targetPath + '.completed';
if (!test('-f', marker)) {
console.log('Downloading file: ' + url);
// delete any previous partial attempt
if (test('-f', targetPath)) {
rm('-f', targetPath);
}
// download the file
mkdir('-p', path.join(downloadPath, 'file'));
var result = syncRequest('GET', url);
fs.writeFileSync(targetPath, result.getBody());
// write the completed marker
fs.writeFileSync(marker, '');
}
return targetPath;
}
exports.downloadFile = downloadFile;
var downloadArchive = function (url, omitExtensionCheck) {
// validate parameters
if (!url) {
throw new Error('Parameter "url" must be set.');
}
var isZip;
var isTargz;
if (omitExtensionCheck) {
isZip = true;
}
else {
if (url.match(/\.zip$/)) {
isZip = true;
}
else if (url.match(/\.tar\.gz$/) && (process.platform == 'darwin' || process.platform == 'linux')) {
isTargz = true;
}
else {
throw new Error('Unexpected archive extension');
}
}
// skip if already downloaded and extracted
var scrubbedUrl = url.replace(/[/\:?]/g, '_');
var targetPath = path.join(downloadPath, 'archive', scrubbedUrl);
var marker = targetPath + '.completed';
if (!test('-f', marker)) {
// download the archive
var archivePath = downloadFile(url);
console.log('Extracting archive: ' + url);
// delete any previously attempted extraction directory
if (test('-d', targetPath)) {
rm('-rf', targetPath);
}
// extract
mkdir('-p', targetPath);
if (isZip) {
var zip = new admZip(archivePath);
zip.extractAllTo(targetPath);
}
else if (isTargz) {
var originalCwd = process.cwd();
cd(targetPath);
try {
run(`tar -xzf "${archivePath}"`);
}
finally {
cd(originalCwd);
}
}
// write the completed marker
fs.writeFileSync(marker, '');
}
return targetPath;
}
exports.downloadArchive = downloadArchive;
var copyGroup = function (group, sourceRoot, destRoot) {
// example structure to copy a single file:
// {
// "source": "foo.dll"
// }
//
// example structure to copy an array of files/folders to a relative directory:
// {
// "source": [
// "foo.dll",
// "bar",
// ],
// "dest": "baz/",
// "options": "-R"
// }
//
// example to multiply the copy by .NET culture names supported by TFS:
// {
// "source": "<CULTURE_NAME>/foo.dll",
// "dest": "<CULTURE_NAME>/"
// }
//
// validate parameters
assert(group, 'group');
assert(group.source, 'group.source');
if (typeof group.source == 'object') {
assert(group.source.length, 'group.source.length');
group.source.forEach(function (s) {
assert(s, 'group.source[i]');
});
}
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
// multiply by culture name (recursive call to self)
if (group.dest && group.dest.indexOf('<CULTURE_NAME>') >= 0) {
cultureNames.forEach(function (cultureName) {
// culture names do not contain any JSON-special characters, so this is OK (albeit a hack)
var localizedGroupJson = JSON.stringify(group).replace(/<CULTURE_NAME>/g, cultureName);
copyGroup(JSON.parse(localizedGroupJson), sourceRoot, destRoot);
});
return;
}
// build the source array
var source = typeof group.source == 'string' ? [group.source] : group.source;
source = source.map(function (val) { // root the paths
return path.join(sourceRoot, val);
});
// create the destination directory
var dest = group.dest ? path.join(destRoot, group.dest) : destRoot + '/';
dest = path.normalize(dest);
mkdir('-p', dest);
// copy the files
if (group.hasOwnProperty('options') && group.options) {
cp(group.options, source, dest);
}
else {
cp(source, dest);
}
}
var copyGroups = function (groups, sourceRoot, destRoot) {
assert(groups, 'groups');
assert(groups.length, 'groups.length');
groups.forEach(function (group) {
copyGroup(group, sourceRoot, destRoot);
})
}
exports.copyGroups = copyGroups;
var removeGroup = function (group, pathRoot) {
// example structure to remove an array of files/folders:
// {
// "items": [
// "foo.dll",
// "bar",
// ],
// "options": "-R"
// }
// validate parameters
assert(group, 'group');
assert(group.items, 'group.items');
if (typeof group.items != 'object') {
throw new Error('Expected group.items to be an array');
} else {
assert(group.items.length, 'group.items.length');
group.items.forEach(function (p) {
assert(p, 'group.items[i]');
});
}
assert(group.options, 'group.options');
assert(pathRoot, 'pathRoot');
// build the rooted items array
var rootedItems = group.items.map(function (val) { // root the paths
return path.join(pathRoot, val);
});
// remove the items
rm(group.options, rootedItems);
}
var removeGroups = function (groups, pathRoot) {
assert(groups, 'groups');
assert(groups.length, 'groups.length');
groups.forEach(function (group) {
removeGroup(group, pathRoot);
})
}
exports.removeGroups = removeGroups;
var addPath = function (directory) {
console.log('');
console.log(`> prepending PATH ${directory}`);
var separator;
if (os.platform() == 'win32') {
separator = ';';
}
else {
separator = ':';
}
var existing = process.env['PATH'];
if (existing) {
process.env['PATH'] = directory + separator + existing;
}
else {
process.env['PATH'] = directory;
}
}
exports.addPath = addPath;
var getExternals = function (externals, destRoot) {
assert(externals, 'externals');
assert(destRoot, 'destRoot');
// .zip files
if (externals.hasOwnProperty('archivePackages')) {
var archivePackages = externals.archivePackages;
archivePackages.forEach(function (archive) {
assert(archive.url, 'archive.url');
assert(archive.dest, 'archive.dest');
// download and extract the archive package
var archiveSource = downloadArchive(archive.url);
// copy the files
var archiveDest = path.join(destRoot, archive.dest);
mkdir('-p', archiveDest);
cp('-R', path.join(archiveSource, '*'), archiveDest)
});
}
// external NuGet V2 packages
if (externals.hasOwnProperty('nugetv2')) {
var nugetPackages = externals.nugetv2;
nugetPackages.forEach(function (package) {
// validate the structure of the data
assert(package.name, 'package.name');
assert(package.version, 'package.version');
assert(package.repository, 'package.repository');
assert(package.cp, 'package.cp');
assert(package.cp, 'package.cp.length');
// download and extract the NuGet V2 package
var url = package.repository.replace(/\/$/, '') + '/package/' + package.name + '/' + package.version;
var packageSource = downloadArchive(url, /*omitExtensionCheck*/true);
// copy specific files
copyGroups(package.cp, packageSource, destRoot);
});
}
// for any file type that has to be shipped with task
if (externals.hasOwnProperty('files')) {
var files = externals.files;
files.forEach(function (file) {
assert(file.url, 'file.url');
assert(file.dest, 'file.dest');
// download the file from url
var fileSource = downloadFile(file.url);
// copy the files
var fileDest = path.join(destRoot, file.dest);
mkdir('-p', path.dirname(fileDest));
cp(fileSource, fileDest);
});
}
}
exports.getExternals = getExternals;
//------------------------------------------------------------------------------
// task.json functions
//------------------------------------------------------------------------------
var createResjson = function (task, taskPath) {
var resources = {};
if (task.hasOwnProperty('friendlyName')) {
resources['loc.friendlyName'] = task.friendlyName;
}
if (task.hasOwnProperty('helpMarkDown')) {
resources['loc.helpMarkDown'] = task.helpMarkDown;
}
if (task.hasOwnProperty('description')) {
resources['loc.description'] = task.description;
}
if (task.hasOwnProperty('instanceNameFormat')) {
resources['loc.instanceNameFormat'] = task.instanceNameFormat;
}
if (task.hasOwnProperty('releaseNotes')) {
resources['loc.releaseNotes'] = task.releaseNotes;
}
if (task.hasOwnProperty('groups')) {
task.groups.forEach(function (group) {
if (group.hasOwnProperty('name')) {
resources['loc.group.displayName.' + group.name] = group.displayName;
}
});
}
if (task.hasOwnProperty('inputs')) {
task.inputs.forEach(function (input) {
if (input.hasOwnProperty('name')) {
resources['loc.input.label.' + input.name] = input.label;
if (input.hasOwnProperty('helpMarkDown') && input.helpMarkDown) {
resources['loc.input.help.' + input.name] = input.helpMarkDown;
}
}
});
}
if (task.hasOwnProperty('messages')) {
Object.keys(task.messages).forEach(function (key) {
resources['loc.messages.' + key] = task.messages[key];
});
}
var resjsonPath = path.join(taskPath, 'Strings', 'resources.resjson', 'en-US', 'resources.resjson');
mkdir('-p', path.dirname(resjsonPath));
fs.writeFileSync(resjsonPath, JSON.stringify(resources, null, 2));
};
exports.createResjson = createResjson;
var createTaskLocJson = function (taskPath) {
var taskJsonPath = path.join(taskPath, 'task.json');
var taskLoc = JSON.parse(fs.readFileSync(taskJsonPath));
taskLoc.friendlyName = 'ms-resource:loc.friendlyName';
taskLoc.helpMarkDown = 'ms-resource:loc.helpMarkDown';
taskLoc.description = 'ms-resource:loc.description';
taskLoc.instanceNameFormat = 'ms-resource:loc.instanceNameFormat';
if (taskLoc.hasOwnProperty('releaseNotes')) {
taskLoc.releaseNotes = 'ms-resource:loc.releaseNotes';
}
if (taskLoc.hasOwnProperty('groups')) {
taskLoc.groups.forEach(function (group) {
if (group.hasOwnProperty('name')) {
group.displayName = 'ms-resource:loc.group.displayName.' + group.name;
}
});
}
if (taskLoc.hasOwnProperty('inputs')) {
taskLoc.inputs.forEach(function (input) {
if (input.hasOwnProperty('name')) {
input.label = 'ms-resource:loc.input.label.' + input.name;
if (input.hasOwnProperty('helpMarkDown') && input.helpMarkDown) {
input.helpMarkDown = 'ms-resource:loc.input.help.' + input.name;
}
}
});
}
if (taskLoc.hasOwnProperty('messages')) {
Object.keys(taskLoc.messages).forEach(function (key) {
taskLoc.messages[key] = 'ms-resource:loc.messages.' + key;
});
}
fs.writeFileSync(path.join(taskPath, 'task.loc.json'), JSON.stringify(taskLoc, null, 2));
};
exports.createTaskLocJson = createTaskLocJson;
// Validates the structure of a task.json file.
var validateTask = function (task) {
if (!task.id || !check.isUUID(task.id)) {
fail('id is a required guid');
};
if (!task.name || !check.isAlphanumeric(task.name)) {
fail('name is a required alphanumeric string');
}
if (!task.friendlyName || !check.isLength(task.friendlyName, 1, 40)) {
fail('friendlyName is a required string <= 40 chars');
}
if (!task.instanceNameFormat) {
fail('instanceNameFormat is required');
}
};
exports.validateTask = validateTask;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// package functions
//------------------------------------------------------------------------------
var linkNonAggregatedLayoutContent = function (sourceRoot, destRoot, metadataOnly) {
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
var metadataFileNames = ['TASK.JSON', 'TASK.LOC.JSON', 'STRINGS', 'ICON.PNG'];
// process each file/folder within the source root
fs.readdirSync(sourceRoot).forEach(function (itemName) {
var taskSourcePath = path.join(sourceRoot, itemName);
var taskDestPath = path.join(destRoot, itemName);
// skip the Common folder and skip files
if (itemName == 'Common' || !fs.statSync(taskSourcePath).isDirectory()) {
return;
}
mkdir('-p', taskDestPath);
// process each file/folder within each task folder
fs.readdirSync(taskSourcePath).forEach(function (itemName) {
// skip the Tests folder
if (itemName == 'Tests') {
return;
}
// when metadataOnly=true, skip non-metadata items
if (metadataOnly && metadataFileNames.indexOf(itemName.toUpperCase()) < 0) {
return;
}
// create a junction point for directories, hardlink files
var itemSourcePath = path.join(taskSourcePath, itemName);
var itemDestPath = path.join(taskDestPath, itemName);
if (fs.statSync(itemSourcePath).isDirectory()) {
fs.symlinkSync(itemSourcePath, itemDestPath, 'junction');
}
else {
fs.linkSync(itemSourcePath, itemDestPath);
}
});
});
}
var linkAggregatedLayoutContent = function (sourceRoot, destRoot, release, commit, taskDestMap) {
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
assert(commit, 'commit');
console.log();
console.log(`> Linking ${path.basename(sourceRoot)}`);
mkdir('-p', destRoot);
// process each file/folder within the non-aggregated layout
fs.readdirSync(sourceRoot).forEach(function (itemName) {
// skip files
var taskSourcePath = path.join(sourceRoot, itemName);
if (!fs.statSync(taskSourcePath).isDirectory()) {
return;
}
// load the source task.json
var sourceTask = JSON.parse(fs.readFileSync(path.join(taskSourcePath, 'task.json')));
if (typeof sourceTask.version.Major != 'number' ||
typeof sourceTask.version.Minor != 'number' ||
typeof sourceTask.version.Patch != 'number') {
fail(`Expected task.version.Major/Minor/Patch to be numbers (${taskSourcePath})`);
}
// determine the dest folder based on the major version
assert(sourceTask.id, 'sourceTask.id');
var taskDestKey = sourceTask.id + '@' + sourceTask.version.Major;
var taskDestPath = taskDestMap[taskDestKey];
if (!taskDestPath) {
taskDestPath = path.join(destRoot, itemName + `__v${sourceTask.version.Major}`);
taskDestMap[taskDestKey] = taskDestPath;
}
if (test('-e', taskDestPath)) {
// validate that a newer minor+patch does not exist in an older release
// (newer releases should be linked first)
var destTask = JSON.parse(fs.readFileSync(path.join(taskDestPath, 'task.json')));
var sourceVersion = `${sourceTask.version.Major}.${sourceTask.version.Minor}.${sourceTask.version.Patch}`;
var destVersion = `${destTask.version.Major}.${destTask.version.Minor}.${destTask.version.Patch}`;
if (semver.gt(sourceVersion, destVersion)) {
fail(`Expected minor+patch version for task already in the aggregate layout, to be greater or equal than non-aggregated layout being merged. Source task: ${taskSourcePath}`);
}
}
else {
// create a junction point
fs.symlinkSync(taskSourcePath, taskDestPath, 'junction');
// write a human-friendly metadata file
fs.writeFileSync(taskDestPath + (release ? `_m${release}` : '') + `_${commit}`, '');
}
});
}
var getNonAggregatedLayout = function (packagePath, release, commit) {
assert(packagePath, 'packagePath');
assert(release, 'release');
assert(commit, 'commit');
// validate the zip is in the cache
var localappdata = process.env.LOCALAPPDATA;
assert(localappdata, 'LOCALAPPDATA');
var zipPath = path.join(localappdata, 'vsts-tasks', `non-aggregated-tasks_m${release}_${commit}.zip`);
var markerPath = `${zipPath}.completed`;
if (!test('-f', markerPath)) {
fail(`Non-aggregated layout for m${release} (${commit}) not found in the cache. Publish the latest m${release} and then try again.`);
}
// extract
console.log();
console.log(`> Expanding ${path.basename(zipPath)}`);
var destPath = path.join(packagePath, `non-aggregated-layout-m${release}`);
run(`powershell.exe -NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "& '${path.join(__dirname, 'Expand-Tasks.ps1')}' -ZipPath '${zipPath}' -TargetPath '${destPath}'"`, /*inheritStreams:*/false, /*noHeader*/true);
return destPath;
}
var getRefs = function () {
console.log();
console.log('> Getting branch/commit info')
var info = {};
var branch;
if (process.env.TF_BUILD) {
// during CI agent checks out a commit, not a branch.
// $(build.sourceBranch) indicates the branch name, e.g. releases/m108
branch = process.env.BUILD_SOURCEBRANCH;
}
else {
// assumes user has checked out a branch. this is a fairly safe assumption.
// this code only runs during "package" and "publish" build targets, which
// is not typically run locally.
branch = run('git symbolic-ref HEAD', /*inheritStreams*/false, /*noHeader*/true);
}
assert(branch, 'branch');
var commit = run('git rev-parse --short=8 HEAD', /*inheritStreams*/false, /*noHeader*/true);
var release;
if (branch.match(/^(refs\/heads\/)?releases\/m[0-9]+$/)) {
release = parseInt(branch.split('/').pop().substr(1));
}
// get the ref info for HEAD
var info = {
head: {
branch: branch, // e.g. refs/heads/releases/m108
commit: commit, // leading 8 chars only
release: release // e.g. 108 or undefined if not a release branch
},
releases: {}
};
// get the ref info for each release branch within range
run('git branch --list --remotes "origin/releases/m*"', /*inheritStreams*/false, /*noHeader*/true)
.split('\n')
.forEach(function (branch) {
branch = branch.trim();
if (!branch.match(/^origin\/releases\/m[0-9]+$/)) {
return;
}
var release = parseInt(branch.split('/').pop().substr(1));
// filter out releases less than 108 and greater than HEAD
if (release < 108 ||
release > (info.head.release || 999)) {
return;
}
branch = 'refs/remotes/' + branch;
var commit = run(`git rev-parse --short=8 "${branch}"`, /*inheritStreams*/false, /*noHeader*/true);
info.releases[release] = {
branch: branch,
commit: commit,
release: release
};
});
return info;
}
exports.getRefs = getRefs;
var compressTasks = function (sourceRoot, destPath, individually) {
assert(sourceRoot, 'sourceRoot');
assert(destPath, 'destPath');
run(`powershell.exe -NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "& '${path.join(__dirname, 'Compress-Tasks.ps1')}' -SourceRoot '${sourceRoot}' -TargetPath '${destPath}' -Individually:${individually ? '$true' : '$false'}"`, /*inheritStreams:*/true, /*noHeader*/true);
}
exports.compressTasks = compressTasks;
var createNonAggregatedZip = function (buildPath, packagePath) {
assert(buildPath, 'buildPath');
assert(packagePath, 'packagePath');
// build the layout for the nested task zips
console.log();
console.log('> Linking content for nested task zips');
var nestedZipsContentPath = path.join(packagePath, 'nested-zips-layout');
linkNonAggregatedLayoutContent(buildPath, nestedZipsContentPath, /*metadataOnly*/false);
// create the nested task zips (part of the non-aggregated tasks layout)
console.log();
console.log('> Creating nested task zips (content for non-aggregated tasks layout)');
var nonAggregatedLayoutPath = path.join(packagePath, 'non-aggregated-layout');
compressTasks(nestedZipsContentPath, nonAggregatedLayoutPath, /*individually:*/true);
// link the task metadata into the non-aggregated tasks layout
console.log();
console.log('> Linking metadata content for non-aggregated tasks layout');
linkNonAggregatedLayoutContent(buildPath, nonAggregatedLayoutPath, /*metadataOnly*/true);
// mark the layout with a version number.
// servicing supports both this new format and the legacy layout format as well.
fs.writeFileSync(path.join(nonAggregatedLayoutPath, 'layout-version.txt'), '2');
// create the non-aggregated tasks zip
console.log();
console.log('> Zipping non-aggregated tasks layout');
var nonAggregatedZipPath = path.join(packagePath, 'non-aggregated-tasks.zip');