-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathtask.ts
2433 lines (2119 loc) · 81.3 KB
/
task.ts
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
import Q = require('q');
import shell = require('shelljs');
import childProcess = require('child_process');
import fs = require('fs');
import path = require('path');
import os = require('os');
import minimatch = require('minimatch');
import im = require('./internal');
import tcm = require('./taskcommand');
import trm = require('./toolrunner');
import semver = require('semver');
export enum TaskResult {
Succeeded = 0,
SucceededWithIssues = 1,
Failed = 2,
Cancelled = 3,
Skipped = 4
}
export enum TaskState {
Unknown = 0,
Initialized = 1,
InProgress = 2,
Completed = 3
}
export enum IssueType {
Error,
Warning
}
export enum ArtifactType {
Container,
FilePath,
VersionControl,
GitRef,
TfvcLabel
}
export enum FieldType {
AuthParameter,
DataParameter,
Url
}
export const IssueSource = im.IssueSource;
/** Platforms supported by our build agent */
export enum Platform {
Windows,
MacOS,
Linux
}
export enum AgentHostedMode {
Unknown,
SelfHosted,
MsHosted
}
//-----------------------------------------------------
// General Helpers
//-----------------------------------------------------
export const setStdStream = im._setStdStream;
export const setErrStream = im._setErrStream;
//-----------------------------------------------------
// Results
//-----------------------------------------------------
/**
* Sets the result of the task.
* Execution will continue.
* If not set, task will be Succeeded.
* If multiple calls are made to setResult the most pessimistic call wins (Failed) regardless of the order of calls.
*
* @param result TaskResult enum of Succeeded, SucceededWithIssues, Failed, Cancelled or Skipped.
* @param message A message which will be logged as an error issue if the result is Failed.
* @param done Optional. Instructs the agent the task is done. This is helpful when child processes
* may still be running and prevent node from fully exiting. This argument is supported
* from agent version 2.142.0 or higher (otherwise will no-op).
* @returns void
*/
export function setResult(result: TaskResult.Succeeded, message?: string, done?: boolean): void;
export function setResult(result: Exclude<TaskResult, 'Succeeded'>, message: string, done?: boolean): void;
export function setResult(result: TaskResult, message: string, done?: boolean): void {
debug('task result: ' + TaskResult[result]);
// add an error issue
if (result == TaskResult.Failed && message) {
error(message, IssueSource.TaskInternal);
}
else if (result == TaskResult.SucceededWithIssues && message) {
warning(message, IssueSource.TaskInternal);
}
// task.complete
var properties = { 'result': TaskResult[result] };
if (done) {
properties['done'] = 'true';
}
command('task.complete', properties, message);
}
/**
* Sets the result of the task with sanitized message.
*
* @param result TaskResult enum of Succeeded, SucceededWithIssues, Failed, Cancelled or Skipped.
* @param message A message which will be logged as an error issue if the result is Failed. Message will be truncated
* before first occurence of wellknown sensitive keyword.
* @param done Optional. Instructs the agent the task is done. This is helpful when child processes
* may still be running and prevent node from fully exiting. This argument is supported
* from agent version 2.142.0 or higher (otherwise will no-op).
* @returns void
*/
export function setSanitizedResult(result: TaskResult, message: string, done?: boolean): void {
const pattern = /password|key|secret|bearer|authorization|token|pat/i;
const sanitizedMessage = im._truncateBeforeSensitiveKeyword(message, pattern);
setResult(result, sanitizedMessage, done);
}
//
// Catching all exceptions
//
process.on('uncaughtException', (err: Error) => {
if (!im.isSigPipeError(err)) {
setResult(TaskResult.Failed, loc('LIB_UnhandledEx', err.message));
error(String(err.stack), im.IssueSource.TaskInternal);
}
});
//
// Catching unhandled rejections from promises and rethrowing them as exceptions
// For example, a promise that is rejected but not handled by a .catch() handler in node 10
// doesn't cause an uncaughtException but causes in Node 16.
// For types definitions(Error | Any) see https://nodejs.org/docs/latest-v16.x/api/process.html#event-unhandledrejection
//
process.on('unhandledRejection', (reason: Error | any) => {
if (reason instanceof Error) {
throw reason;
} else {
throw new Error(reason);
}
});
//-----------------------------------------------------
// Loc Helpers
//-----------------------------------------------------
export const setResourcePath = im._setResourcePath;
export const loc = im._loc;
//-----------------------------------------------------
// Input Helpers
//-----------------------------------------------------
export const getVariable = im._getVariable;
/**
* Asserts the agent version is at least the specified minimum.
*
* @param minimum minimum version version - must be 2.104.1 or higher
*/
export function assertAgent(minimum: string): void {
if (semver.lt(minimum, '2.104.1')) {
throw new Error('assertAgent() requires the parameter to be 2.104.1 or higher');
}
let agent = getVariable('Agent.Version');
if (agent && semver.lt(agent, minimum)) {
throw new Error(`Agent version ${minimum} or higher is required`);
}
}
/**
* Gets a snapshot of the current state of all job variables available to the task.
* Requires a 2.104.1 agent or higher for full functionality.
*
* Limitations on an agent prior to 2.104.1:
* 1) The return value does not include all public variables. Only public variables
* that have been added using setVariable are returned.
* 2) The name returned for each secret variable is the formatted environment variable
* name, not the actual variable name (unless it was set explicitly at runtime using
* setVariable).
*
* @returns VariableInfo[]
*/
export function getVariables(): VariableInfo[] {
return Object.keys(im._knownVariableMap)
.map((key: string) => {
let info: im._KnownVariableInfo = im._knownVariableMap[key];
return <VariableInfo>{ name: info.name, value: getVariable(info.name), secret: info.secret };
});
}
/**
* Sets a variable which will be available to subsequent tasks as well.
*
* @param name name of the variable to set
* @param val value to set
* @param secret whether variable is secret. Multi-line secrets are not allowed. Optional, defaults to false
* @param isOutput whether variable is an output variable. Optional, defaults to false
* @returns void
*/
export function setVariable(name: string, val: string, secret: boolean = false, isOutput: boolean = false): void {
// once a secret always a secret
let key: string = im._getVariableKey(name);
if (im._knownVariableMap.hasOwnProperty(key)) {
secret = secret || im._knownVariableMap[key].secret;
}
// store the value
let varValue = val || '';
debug('set ' + name + '=' + (secret && varValue ? '********' : varValue));
if (secret) {
if (varValue && varValue.match(/\r|\n/) && `${process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']}`.toUpperCase() != 'TRUE') {
throw new Error(loc('LIB_MultilineSecret'));
}
im._vault.storeSecret('SECRET_' + key, varValue);
delete process.env[key];
} else {
process.env[key] = varValue;
}
// store the metadata
im._knownVariableMap[key] = <im._KnownVariableInfo>{ name: name, secret: secret };
// write the setvariable command
command('task.setvariable', { 'variable': name || '', isOutput: (isOutput || false).toString(), 'issecret': (secret || false).toString() }, varValue);
}
/**
* Registers a value with the logger, so the value will be masked from the logs. Multi-line secrets are not allowed.
*
* @param val value to register
*/
export function setSecret(val: string): void {
if (val) {
if (val.match(/\r|\n/) && `${process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']}`.toUpperCase() !== 'TRUE') {
throw new Error(loc('LIB_MultilineSecret'));
}
command('task.setsecret', {}, val);
}
}
/** Snapshot of a variable at the time when getVariables was called. */
export interface VariableInfo {
name: string;
value: string;
secret: boolean;
}
/**
* Gets the value of an input.
* If required is true and the value is not set, it will throw.
*
* @param name name of the input to get
* @param required whether input is required. optional, defaults to false
* @returns string
*/
export function getInput(name: string, required?: boolean): string | undefined {
var inval = im._vault.retrieveSecret('INPUT_' + im._getVariableKey(name));
if (required && !inval) {
throw new Error(loc('LIB_InputRequired', name));
}
debug(name + '=' + inval);
return inval;
}
/**
* Gets the value of an input.
* If the value is not set, it will throw.
*
* @param name name of the input to get
* @returns string
*/
export function getInputRequired(name: string): string {
return getInput(name, true)!;
}
/**
* Gets the value of an input and converts to a bool. Convenience.
* If required is true and the value is not set, it will throw.
* If required is false and the value is not set, returns false.
*
* @param name name of the bool input to get
* @param required whether input is required. optional, defaults to false
* @returns boolean
*/
export function getBoolInput(name: string, required?: boolean): boolean {
return (getInput(name, required) || '').toUpperCase() == "TRUE";
}
/**
* Gets the value of an feature flag and converts to a bool.
* @IMPORTANT This method is only for internal Microsoft development. Do not use it for external tasks.
* @param name name of the feature flag to get.
* @param defaultValue default value of the feature flag in case it's not found in env. (optional. Default value = false)
* @returns boolean
* @deprecated Don't use this for new development. Use getPipelineFeature instead.
*/
export function getBoolFeatureFlag(ffName: string, defaultValue: boolean = false): boolean {
const ffValue = process.env[ffName];
if (!ffValue) {
debug(`Feature flag ${ffName} not found. Returning ${defaultValue} as default.`);
return defaultValue;
}
debug(`Feature flag ${ffName} = ${ffValue}`);
return ffValue.toLowerCase() === "true";
}
/**
* Gets the value of an task feature and converts to a bool.
* @IMPORTANT This method is only for internal Microsoft development. Do not use it for external tasks.
* @param name name of the feature to get.
* @returns boolean
*/
export function getPipelineFeature(featureName: string): boolean {
const variableName = im._getVariableKey(`DistributedTask.Tasks.${featureName}`);
const featureValue = process.env[variableName];
if (!featureValue) {
debug(`Feature '${featureName}' not found. Returning false as default.`);
return false;
}
const boolValue = featureValue.toLowerCase() === "true";
debug(`Feature '${featureName}' = '${featureValue}'. Processed as '${boolValue}'.`);
return boolValue;
}
/**
* Gets the value of an input and splits the value using a delimiter (space, comma, etc).
* Empty values are removed. This function is useful for splitting an input containing a simple
* list of items - such as build targets.
* IMPORTANT: Do not use this function for splitting additional args! Instead use argString(), which
* follows normal argument splitting rules and handles values encapsulated by quotes.
* If required is true and the value is not set, it will throw.
*
* @param name name of the input to get
* @param delim delimiter to split on
* @param required whether input is required. optional, defaults to false
* @returns string[]
*/
export function getDelimitedInput(name: string, delim: string | RegExp, required?: boolean): string[] {
let inputVal = getInput(name, required);
if (!inputVal) {
return [];
}
let result: string[] = [];
inputVal.split(delim).forEach((x: string) => {
if (x) {
result.push(x);
}
});
return result;
}
/**
* Checks whether a path inputs value was supplied by the user
* File paths are relative with a picker, so an empty path is the root of the repo.
* Useful if you need to condition work (like append an arg) if a value was supplied
*
* @param name name of the path input to check
* @returns boolean
*/
export function filePathSupplied(name: string): boolean {
// normalize paths
var pathValue = this.resolve(this.getPathInput(name) || '');
var repoRoot = this.resolve(getVariable('build.sourcesDirectory') || getVariable('system.defaultWorkingDirectory') || '');
var supplied = pathValue !== repoRoot;
debug(name + 'path supplied :' + supplied);
return supplied;
}
/**
* Gets the value of a path input
* It will be quoted for you if it isn't already and contains spaces
* If required is true and the value is not set, it will throw.
* If check is true and the path does not exist, it will throw.
*
* @param name name of the input to get
* @param required whether input is required. optional, defaults to false
* @param check whether path is checked. optional, defaults to false
* @returns string
*/
export function getPathInput(name: string, required?: boolean, check?: boolean): string | undefined {
var inval = getInput(name, required);
if (inval) {
if (check) {
checkPath(inval, name);
}
}
return inval;
}
/**
* Gets the value of a path input
* It will be quoted for you if it isn't already and contains spaces
* If the value is not set, it will throw.
* If check is true and the path does not exist, it will throw.
*
* @param name name of the input to get
* @param check whether path is checked. optional, defaults to false
* @returns string
*/
export function getPathInputRequired(name: string, check?: boolean): string {
return getPathInput(name, true, check)!;
}
//-----------------------------------------------------
// Endpoint Helpers
//-----------------------------------------------------
/**
* Gets the url for a service endpoint
* If the url was not set and is not optional, it will throw.
*
* @param id name of the service endpoint
* @param optional whether the url is optional
* @returns string
*/
export function getEndpointUrl(id: string, optional: boolean): string | undefined {
var urlval = process.env['ENDPOINT_URL_' + id];
if (!optional && !urlval) {
throw new Error(loc('LIB_EndpointNotExist', id));
}
debug(id + '=' + urlval);
return urlval;
}
/**
* Gets the url for a service endpoint
* If the url was not set, it will throw.
*
* @param id name of the service endpoint
* @returns string
*/
export function getEndpointUrlRequired(id: string): string {
return getEndpointUrl(id, false)!;
}
/*
* Gets the endpoint data parameter value with specified key for a service endpoint
* If the endpoint data parameter was not set and is not optional, it will throw.
*
* @param id name of the service endpoint
* @param key of the parameter
* @param optional whether the endpoint data is optional
* @returns {string} value of the endpoint data parameter
*/
export function getEndpointDataParameter(id: string, key: string, optional: boolean): string | undefined {
var dataParamVal = process.env['ENDPOINT_DATA_' + id + '_' + key.toUpperCase()];
if (!optional && !dataParamVal) {
throw new Error(loc('LIB_EndpointDataNotExist', id, key));
}
debug(id + ' data ' + key + ' = ' + dataParamVal);
return dataParamVal;
}
/*
* Gets the endpoint data parameter value with specified key for a service endpoint
* If the endpoint data parameter was not set, it will throw.
*
* @param id name of the service endpoint
* @param key of the parameter
* @returns {string} value of the endpoint data parameter
*/
export function getEndpointDataParameterRequired(id: string, key: string): string {
return getEndpointDataParameter(id, key, false)!;
}
/**
* Gets the endpoint authorization scheme for a service endpoint
* If the endpoint authorization scheme is not set and is not optional, it will throw.
*
* @param id name of the service endpoint
* @param optional whether the endpoint authorization scheme is optional
* @returns {string} value of the endpoint authorization scheme
*/
export function getEndpointAuthorizationScheme(id: string, optional: boolean): string | undefined {
var authScheme = im._vault.retrieveSecret('ENDPOINT_AUTH_SCHEME_' + id);
if (!optional && !authScheme) {
throw new Error(loc('LIB_EndpointAuthNotExist', id));
}
debug(id + ' auth scheme = ' + authScheme);
return authScheme;
}
/**
* Gets the endpoint authorization scheme for a service endpoint
* If the endpoint authorization scheme is not set, it will throw.
*
* @param id name of the service endpoint
* @returns {string} value of the endpoint authorization scheme
*/
export function getEndpointAuthorizationSchemeRequired(id: string): string {
return getEndpointAuthorizationScheme(id, false)!;
}
/**
* Gets the endpoint authorization parameter value for a service endpoint with specified key
* If the endpoint authorization parameter is not set and is not optional, it will throw.
*
* @param id name of the service endpoint
* @param key key to find the endpoint authorization parameter
* @param optional optional whether the endpoint authorization scheme is optional
* @returns {string} value of the endpoint authorization parameter value
*/
export function getEndpointAuthorizationParameter(id: string, key: string, optional: boolean): string | undefined {
var authParam = im._vault.retrieveSecret('ENDPOINT_AUTH_PARAMETER_' + id + '_' + key.toUpperCase());
if (!optional && !authParam) {
throw new Error(loc('LIB_EndpointAuthNotExist', id));
}
debug(id + ' auth param ' + key + ' = ' + authParam);
return authParam;
}
/**
* Gets the endpoint authorization parameter value for a service endpoint with specified key
* If the endpoint authorization parameter is not set, it will throw.
*
* @param id name of the service endpoint
* @param key key to find the endpoint authorization parameter
* @returns {string} value of the endpoint authorization parameter value
*/
export function getEndpointAuthorizationParameterRequired(id: string, key: string): string {
return getEndpointAuthorizationParameter(id, key, false)!;
}
/**
* Interface for EndpointAuthorization
* Contains a schema and a string/string dictionary of auth data
*/
export interface EndpointAuthorization {
/** dictionary of auth data */
parameters: {
[key: string]: string;
};
/** auth scheme such as OAuth or username/password etc... */
scheme: string;
}
/**
* Gets the authorization details for a service endpoint
* If the authorization was not set and is not optional, it will set the task result to Failed.
*
* @param id name of the service endpoint
* @param optional whether the url is optional
* @returns string
*/
export function getEndpointAuthorization(id: string, optional: boolean): EndpointAuthorization | undefined {
var aval = im._vault.retrieveSecret('ENDPOINT_AUTH_' + id);
if (!optional && !aval) {
setResult(TaskResult.Failed, loc('LIB_EndpointAuthNotExist', id));
}
debug(id + ' exists ' + (!!aval));
var auth: EndpointAuthorization | undefined;
try {
if (aval) {
auth = <EndpointAuthorization>JSON.parse(aval);
}
}
catch (err) {
throw new Error(loc('LIB_InvalidEndpointAuth', aval));
}
return auth;
}
//-----------------------------------------------------
// SecureFile Helpers
//-----------------------------------------------------
/**
* Gets the name for a secure file
*
* @param id secure file id
* @returns string
*/
export function getSecureFileName(id: string): string | undefined {
var name = process.env['SECUREFILE_NAME_' + id];
debug('secure file name for id ' + id + ' = ' + name);
return name;
}
/**
* Gets the secure file ticket that can be used to download the secure file contents
*
* @param id name of the secure file
* @returns {string} secure file ticket
*/
export function getSecureFileTicket(id: string): string | undefined {
var ticket = im._vault.retrieveSecret('SECUREFILE_TICKET_' + id);
debug('secure file ticket for id ' + id + ' = ' + ticket);
return ticket;
}
//-----------------------------------------------------
// Task Variable Helpers
//-----------------------------------------------------
/**
* Gets a variable value that is set by previous step from the same wrapper task.
* Requires a 2.115.0 agent or higher.
*
* @param name name of the variable to get
* @returns string
*/
export function getTaskVariable(name: string): string | undefined {
assertAgent('2.115.0');
var inval = im._vault.retrieveSecret('VSTS_TASKVARIABLE_' + im._getVariableKey(name));
if (inval) {
inval = inval.trim();
}
debug('task variable: ' + name + '=' + inval);
return inval;
}
/**
* Sets a task variable which will only be available to subsequent steps belong to the same wrapper task.
* Requires a 2.115.0 agent or higher.
*
* @param name name of the variable to set
* @param val value to set
* @param secret whether variable is secret. optional, defaults to false
* @returns void
*/
export function setTaskVariable(name: string, val: string, secret: boolean = false): void {
assertAgent('2.115.0');
let key: string = im._getVariableKey(name);
// store the value
let varValue = val || '';
debug('set task variable: ' + name + '=' + (secret && varValue ? '********' : varValue));
im._vault.storeSecret('VSTS_TASKVARIABLE_' + key, varValue);
delete process.env[key];
// write the command
command('task.settaskvariable', { 'variable': name || '', 'issecret': (secret || false).toString() }, varValue);
}
//-----------------------------------------------------
// Cmd Helpers
//-----------------------------------------------------
export const command = im._command;
export const warning = im._warning;
export const error = im._error;
export const debug = im._debug;
//-----------------------------------------------------
// Disk Functions
//-----------------------------------------------------
function _checkShell(cmd: string, continueOnError?: boolean) {
var se = shell.error();
if (se) {
debug(cmd + ' failed');
var errMsg = loc('LIB_OperationFailed', cmd, se);
debug(errMsg);
if (!continueOnError) {
throw new Error(errMsg);
}
}
}
export interface FsStats extends fs.Stats {
}
/**
* Get's stat on a path.
* Useful for checking whether a file or directory. Also getting created, modified and accessed time.
* see [fs.stat](https://nodejs.org/api/fs.html#fs_class_fs_stats)
*
* @param path path to check
* @returns fsStat
*/
export function stats(path: string): FsStats {
return fs.statSync(path);
}
export const exist = im._exist;
export function writeFile(file: string, data: string | Buffer, options?: BufferEncoding | fs.WriteFileOptions) {
if (typeof (options) === 'string') {
fs.writeFileSync(file, data, { encoding: options as BufferEncoding });
}
else {
fs.writeFileSync(file, data, options);
}
}
/**
* @deprecated Use `getPlatform`
* Useful for determining the host operating system.
* see [os.type](https://nodejs.org/api/os.html#os_os_type)
*
* @return the name of the operating system
*/
export function osType(): string {
return os.type();
}
/**
* Determine the operating system the build agent is running on.
* @returns {Platform}
* @throws {Error} Platform is not supported by our agent
*/
export function getPlatform(): Platform {
switch (process.platform) {
case 'win32': return Platform.Windows;
case 'darwin': return Platform.MacOS;
case 'linux': return Platform.Linux;
default: throw Error(loc('LIB_PlatformNotSupported', process.platform));
}
}
/**
* Resolves major version of Node.js engine used by the agent.
* @returns {Number} Node's major version.
*/
export function getNodeMajorVersion(): Number {
const version = process?.versions?.node;
if (!version) {
throw new Error(loc('LIB_UndefinedNodeVersion'));
}
const parts = version.split('.').map(Number);
if (parts.length < 1) {
return NaN;
}
return parts[0];
}
/**
* Return hosted type of Agent
* @returns {AgentHostedMode}
*/
export function getAgentMode(): AgentHostedMode {
let agentCloudId = getVariable('Agent.CloudId');
if (agentCloudId === undefined)
return AgentHostedMode.Unknown;
if (agentCloudId)
return AgentHostedMode.MsHosted;
return AgentHostedMode.SelfHosted;
}
/**
* Returns the process's current working directory.
* see [process.cwd](https://nodejs.org/api/process.html#process_process_cwd)
*
* @return the path to the current working directory of the process
*/
export function cwd(): string {
return process.cwd();
}
export const checkPath = im._checkPath;
/**
* Change working directory.
*
* @param path new working directory path
* @returns void
*/
export function cd(path: string): void {
if (path) {
shell.cd(path);
_checkShell('cd');
}
}
/**
* Change working directory and push it on the stack
*
* @param path new working directory path
* @returns void
*/
export function pushd(path: string): void {
shell.pushd(path);
_checkShell('pushd');
}
/**
* Change working directory back to previously pushed directory
*
* @returns void
*/
export function popd(): void {
shell.popd();
_checkShell('popd');
}
/**
* Make a directory. Creates the full path with folders in between
* Will throw if it fails
*
* @param p path to create
* @returns void
*/
export function mkdirP(p: string): void {
if (!p) {
throw new Error(loc('LIB_ParameterIsRequired', 'p'));
}
// build a stack of directories to create
let stack: string[] = [];
let testDir: string = p;
while (true) {
// validate the loop is not out of control
if (stack.length >= Number(process.env['TASKLIB_TEST_MKDIRP_FAILSAFE'] || 1000)) {
// let the framework throw
debug('loop is out of control');
fs.mkdirSync(p);
return;
}
debug(`testing directory '${testDir}'`);
let stats: fs.Stats;
try {
stats = fs.statSync(testDir);
} catch (err) {
if (err.code == 'ENOENT') {
// validate the directory is not the drive root
let parentDir = path.dirname(testDir);
if (testDir == parentDir) {
throw new Error(loc('LIB_MkdirFailedInvalidDriveRoot', p, testDir)); // Unable to create directory '{p}'. Root directory does not exist: '{testDir}'
}
// push the dir and test the parent
stack.push(testDir);
testDir = parentDir;
continue;
}
else if (err.code == 'UNKNOWN') {
throw new Error(loc('LIB_MkdirFailedInvalidShare', p, testDir)) // Unable to create directory '{p}'. Unable to verify the directory exists: '{testDir}'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share.
}
else {
throw err;
}
}
if (!stats.isDirectory()) {
throw new Error(loc('LIB_MkdirFailedFileExists', p, testDir)); // Unable to create directory '{p}'. Conflicting file exists: '{testDir}'
}
// testDir exists
break;
}
// create each directory
while (stack.length) {
let dir = stack.pop()!; // non-null because `stack.length` was truthy
debug(`mkdir '${dir}'`);
try {
fs.mkdirSync(dir);
} catch (err) {
throw new Error(loc('LIB_MkdirFailed', p, err.message)); // Unable to create directory '{p}'. {err.message}
}
}
}
/**
* Resolves a sequence of paths or path segments into an absolute path.
* Calls node.js path.resolve()
* Allows L0 testing with consistent path formats on Mac/Linux and Windows in the mock implementation
* @param pathSegments
* @returns {string}
*/
export function resolve(...pathSegments: any[]): string {
var absolutePath = path.resolve.apply(this, pathSegments);
debug('Absolute path for pathSegments: ' + pathSegments + ' = ' + absolutePath);
return absolutePath;
}
export const which = im._which;
/**
* Returns array of files in the given path, or in current directory if no path provided. See shelljs.ls
* @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..)
* @param {string[]} paths Paths to search.
* @return {string[]} An array of files in the given path(s).
*/
export function ls(options: string, paths: string[]): string[] {
if (options) {
return shell.ls(options, paths);
} else {
return shell.ls(paths);
}
}
/**
* Copies a file or folder.
*
* @param source source path
* @param dest destination path
* @param options string -r, -f or -rf for recursive and force
* @param continueOnError optional. whether to continue on error
* @param retryCount optional. Retry count to copy the file. It might help to resolve intermittent issues e.g. with UNC target paths on a remote host.
*/
export function cp(source: string, dest: string, options?: string, continueOnError?: boolean, retryCount: number = 0): void {
while (retryCount >= 0) {
try {
if (options) {
shell.cp(options, source, dest);
}
else {
shell.cp(source, dest);
}
_checkShell('cp', false);
break;
} catch (e) {
if (retryCount <= 0) {
if (continueOnError) {
warning(e, IssueSource.TaskInternal);
break;
} else {
throw e;
}
} else {
console.log(loc('LIB_CopyFileFailed', retryCount));
retryCount--;
}
}
}
}
/**
* Moves a path.
*
* @param source source path
* @param dest destination path
* @param options string -f or -n for force and no clobber
* @param continueOnError optional. whether to continue on error
*/
export function mv(source: string, dest: string, options?: string, continueOnError?: boolean): void {
if (options) {
shell.mv(options, source, dest);
}
else {
shell.mv(source, dest);
}
_checkShell('mv', continueOnError);
}
/**
* Interface for FindOptions
* Contains properties to control whether to follow symlinks
*/
export interface FindOptions {
/**
* When true, broken symbolic link will not cause an error.
*/
allowBrokenSymbolicLinks: boolean,
/**
* Equivalent to the -H command line option. Indicates whether to traverse descendants if
* the specified path is a symbolic link directory. Does not cause nested symbolic link
* directories to be traversed.
*/
followSpecifiedSymbolicLink: boolean;