forked from microsoft/azure-pipelines-tasks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
appcenterdistribute.ts
693 lines (579 loc) · 26.4 KB
/
appcenterdistribute.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
import path = require('path');
import tl = require('vsts-task-lib/task');
import request = require('request');
import Q = require('q');
import fs = require('fs');
import os = require('os');
import { AzureBlobUploadHelper } from './azure-blob-upload-helper';
import { ToolRunner } from 'vsts-task-lib/toolrunner';
import { McFile, McFusNodeUploader } from "./lib/mc-fus-uploader/mc-fus-uploader";
import {
McFusMessageLevel,
McFusUploader,
McFusUploadState,
IProgress,
LogProperties,
IUploadStats,
IInitializeSettings,
} from "./lib/mc-fus-uploader/mc-fus-uploader-types";
import utils = require('./utils');
import { inspect } from 'util';
class UploadInfo {
upload_id: string;
upload_url: string;
}
class SymbolsUploadInfo {
symbol_upload_id: string;
upload_url: string;
expiration_date: string;
}
type DestinationType = "groups" | "store";
const DestinationType = {
Groups: "groups" as DestinationType,
Store: "store" as DestinationType
}
const DestinationTypeParameter = {
[DestinationType.Groups]: "groups",
[DestinationType.Store]: "stores"
}
let mcFusUploader: McFusUploader = null;
interface Release {
version: string;
short_version: string;
}
type ApiSymbolType = "Apple" | "AndroidProguard" | "Breakpad" | "UWP";
type TaskSymbolType = "Apple" | "Android" | "UWP";
function getEndpointDetails(endpointInputFieldName) {
var errorMessage = tl.loc("CannotDecodeEndpoint");
var endpoint = tl.getInput(endpointInputFieldName, true);
if (!endpoint) {
throw new Error(errorMessage);
}
let url = tl.getEndpointUrl(endpoint, false);
let apiServer = url.substr(0, url.lastIndexOf('/'));
let apiVersion = url.substr(url.lastIndexOf('/') + 1);
let authToken = tl.getEndpointAuthorizationParameter(endpoint, 'apitoken', false);
return {
apiServer: apiServer,
apiVersion: apiVersion,
authToken: authToken
};
}
function responseHandler(defer, err, res, body, handler: () => void) {
if (body) {
tl.debug(`---- ${JSON.stringify(body)}`);
}
if (err) {
tl.debug(`---- Failed with error: ${err}`);
defer.reject(err);
return;
}
if (!res) {
defer.reject(tl.loc("NoResponseFromServer"));
return;
}
tl.debug(`---- http call status code: ${res.statusCode}`);
if (res.statusCode < 200 || res.statusCode >= 300) {
let message = JSON.stringify(body);
if (!message) {
message = `http response code: ${res.statusCode}`;
} else {
message = message.concat(os.EOL + `http response code: ${res.statusCode}`);
}
defer.reject(message);
return;
}
handler();
}
function beginReleaseUpload(apiServer: string, apiVersion: string, appSlug: string, token: string, userAgent: string, buildVersion: string): Q.Promise<any> {
tl.debug("-- Prepare for uploading release.");
let defer = Q.defer<UploadInfo>();
let beginUploadUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/uploads/releases`;
tl.debug(`---- url: ${beginUploadUrl}`);
let headers = {
"Content-Type": "application/json",
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
const requestOptions: request.UrlOptions & request.CoreOptions = { url: beginUploadUrl, headers };
if (buildVersion) {
requestOptions.body = JSON.stringify({
"build_version": buildVersion
});
}
request.post(requestOptions, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
let response = JSON.parse(body);
if (!response.package_asset_id || (response.statusCode && response.statusCode !== 200)) {
defer.reject(`failed to create release upload. ${response.message}`)
}
defer.resolve(response);
});
});
return defer.promise;
}
function loadReleaseIdUntilSuccess(apiServer: string, apiVersion: string, appSlug: string, uploadId: string, token: string, userAgent: string): Q.Promise<any> {
let defer = Q.defer<void>();
const timerId = setInterval(async () => {
const response = await getReleaseId(apiServer, apiVersion, appSlug, uploadId, token, userAgent);
const releaseId = response.release_distinct_id;
tl.debug(`---- Received release id is ${releaseId}`);
if (response.upload_status === "readyToBePublished" && releaseId) {
clearInterval(timerId);
defer.resolve(releaseId);
} else if (response.upload_status === "error") {
clearInterval(timerId);
defer.reject(new Error(`Loading release id failed: ${response.error_details}`));
}
}, 2000);
return defer.promise;
}
function uploadRelease(releaseUploadParams: any, file: string): Q.Promise<void> {
const assetId = releaseUploadParams.package_asset_id;
const urlEncodedToken = releaseUploadParams.url_encoded_token;
const uploadDomain = releaseUploadParams.upload_domain;
tl.debug("-- Uploading release...");
let defer = Q.defer<void>();
const uploadSettings: IInitializeSettings = {
assetId: assetId,
urlEncodedToken: urlEncodedToken,
uploadDomain: uploadDomain,
tenant: "distribution",
onProgressChanged: (progress: IProgress) => {
tl.debug("---- onProgressChanged: " + progress.percentCompleted);
},
onMessage: (message: string, properties: LogProperties, level: McFusMessageLevel) => {
tl.debug(`---- onMessage: ${message} \nMessage properties: ${JSON.stringify(properties)}`);
if (level === McFusMessageLevel.Error) {
mcFusUploader.cancel();
defer.reject(new Error(`Uploading file error: ${message}`));
}
},
onStateChanged: (status: McFusUploadState): void => {
tl.debug(`---- onStateChanged: ${status.toString()}`);
},
onCompleted: (uploadStats: IUploadStats) => {
tl.debug("---- Upload completed, total time: " + uploadStats.totalTimeInSeconds);
defer.resolve();
},
};
mcFusUploader = new McFusNodeUploader(uploadSettings);
const fullFile = path.resolve(file);
const appFile = new McFile(fullFile);
mcFusUploader.start(appFile);
return defer.promise;
}
function tryAbort(apiServer: string, apiVersion: string, appSlug: string, upload_id: string, token: string, userAgent: string, error: Error): Q.Promise<void> {
try {
return abortReleaseUpload(apiServer, apiVersion, appSlug, upload_id, token, userAgent);
} catch (abortError) {
tl.debug("---- Failed to abort release upload");
}
}
function abortReleaseUpload(apiServer: string, apiVersion: string, appSlug: string, upload_id: string, token: string, userAgent: string): Q.Promise<void> {
tl.debug("-- Aborting release...");
let defer = Q.defer<void>();
let patchReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/uploads/releases/${upload_id}`;
tl.debug(`---- url: ${patchReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
let abortedBody = { "upload_status": "aborted" };
request.patch({ url: patchReleaseUrl, headers: headers, json: abortedBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
const { _, message } = body;
if (err) {
defer.reject(`Failed to abort release upload: ${message}`);
}
defer.resolve();
});
})
return defer.promise;
}
function patchRelease(apiServer: string, apiVersion: string, appSlug: string, upload_id: string, token: string, userAgent: string): Q.Promise<void> {
tl.debug("-- Finishing uploading release...");
let defer = Q.defer<void>();
let patchReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/uploads/releases/${upload_id}`;
tl.debug(`---- url: ${patchReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
let uploadFinishedBody = { "upload_status": "uploadFinished" };
request.patch({ url: patchReleaseUrl, headers: headers, json: uploadFinishedBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
const { upload_status, message } = body;
if (upload_status !== "uploadFinished") {
defer.reject(`Failed to patch release upload: ${message}`);
}
defer.resolve();
});
})
return defer.promise;
}
function publishRelease(apiServer: string, apiVersion: string, appSlug: string, releaseId: string, destinationType: DestinationType, isMandatory: boolean, isSilent: boolean, destinationId: string, token: string, userAgent: string) {
tl.debug("-- Mark package available.");
let defer = Q.defer<void>();
let publishReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/releases/${releaseId}/${DestinationTypeParameter[destinationType]}`;
tl.debug(`---- url: ${publishReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
let publishBody = {
"id": destinationId
};
if (destinationType === DestinationType.Groups) {
publishBody["mandatory_update"] = isMandatory;
if (isSilent) {
publishBody["notify_testers"] = false;
}
}
// Builds started by App Center has the commit message set when distribution is enabled
const commitMessage = process.env['LASTCOMMITMESSAGE'];
// Updating the internal_request_source to distinguish the AppCenter triggered build and custom build
if (!!commitMessage) {
headers["internal-request-source"] = "VSTS-APPCENTER";
}
request.post({ url: publishReleaseUrl, headers: headers, json: publishBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
defer.resolve();
});
})
return defer.promise;
}
function updateRelease(apiServer: string, apiVersion: string, appSlug: string, releaseId: string, releaseNotes: string, token: string, userAgent: string) {
tl.debug("-- Updating release.");
let defer = Q.defer<void>();
let publishReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/releases/${releaseId}`;
tl.debug(`---- url: ${publishReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
let publishBody = {
"release_notes": releaseNotes
};
let branchName = process.env['BUILD_SOURCEBRANCH'];
branchName = getBranchName(branchName);
const sourceVersion = process.env['BUILD_SOURCEVERSION'];
const buildId = process.env['BUILD_BUILDID'];
// Builds started by App Center has the commit message set when distribution is enabled
const commitMessage = process.env['LASTCOMMITMESSAGE'];
// Updating the internal_request_source to distinguish the AppCenter triggered build and custom build
if (!!commitMessage) {
headers["internal-request-source"] = "VSTS-APPCENTER";
}
// Including these information for distribution notification to have additional context
// Commit message is optional
if (branchName && sourceVersion) {
const build = {
id: buildId,
branch: branchName,
commit_hash: sourceVersion
}
if (commitMessage) {
build['commit_message'] = commitMessage;
}
publishBody = Object.assign(publishBody, { build: build });
}
request.put({ url: publishReleaseUrl, headers: headers, json: publishBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
defer.resolve();
});
})
return defer.promise;
}
function getReleaseId(apiServer: string, apiVersion: string, appSlug: string, releaseId: string, token: string, userAgent: string): Q.Promise<any> {
tl.debug("-- Getting release id.");
let defer = Q.defer<Release>();
let getReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/uploads/releases/${releaseId}`;
tl.debug(`---- url: ${getReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
request.get({ url: getReleaseUrl, headers: headers }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
defer.resolve(JSON.parse(body));
});
})
return defer.promise;
}
function getRelease(apiServer: string, apiVersion: string, appSlug: string, releaseId: string, token: string, userAgent: string): Q.Promise<Release> {
tl.debug("-- Getting release.");
let defer = Q.defer<Release>();
let getReleaseUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/releases/${releaseId}`;
tl.debug(`---- url: ${getReleaseUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
request.get({ url: getReleaseUrl, headers: headers }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
defer.resolve(JSON.parse(body));
});
})
return defer.promise;
}
function getBranchName(ref: string): string {
const gitRefsHeadsPrefix = 'refs/heads/';
if (ref) {
return ref.indexOf(gitRefsHeadsPrefix) === 0 ? ref.substr(gitRefsHeadsPrefix.length) : ref;
}
}
/**
* If the input is a single file, upload this file without any processing.
* If the input is a single folder, zip it's content. The archive name is the folder's name
* If the input is a set of folders or files, zip them so they appear on the root of the archive. The archive name is the parent folder's name.
*/
function prepareSymbols(symbolsPaths: string[], forceArchive: boolean = false): Q.Promise<string> {
tl.debug("-- Prepare symbols");
let defer = Q.defer<string>();
if (!forceArchive && symbolsPaths.length === 1 && fs.statSync(symbolsPaths[0]).isFile()) {
tl.debug(`.. a single symbols file: ${symbolsPaths[0]}`)
// single file - Android source mapping txt file
defer.resolve(symbolsPaths[0]);
} else if (symbolsPaths.length > 0) {
tl.debug(`.. archiving: ${symbolsPaths}`);
let symbolsRoot = utils.findCommonParent(symbolsPaths);
let zipPath = utils.getArchivePath(symbolsRoot);
let zipStream = utils.createZipStream(symbolsPaths, symbolsRoot);
utils.createZipFile(zipStream, zipPath).
then(() => {
tl.debug(`---- symbols archive file: ${zipPath}`)
defer.resolve(zipPath);
});
} else {
defer.resolve(null);
}
return defer.promise;
}
function beginSymbolUpload(apiServer: string, apiVersion: string, appSlug: string, symbol_type: ApiSymbolType, token: string, userAgent: string, version?: string, build?: string): Q.Promise<SymbolsUploadInfo> {
tl.debug("-- Begin symbols upload")
let defer = Q.defer<SymbolsUploadInfo>();
let beginSymbolUploadUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/symbol_uploads`;
tl.debug(`---- url: ${beginSymbolUploadUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
const symbolsUploadBody = { "symbol_type": symbol_type };
if (symbol_type === "AndroidProguard") {
symbolsUploadBody["file_name"] = "mapping.txt";
symbolsUploadBody["version"] = version;
symbolsUploadBody["build"] = build;
}
request.post({ url: beginSymbolUploadUrl, headers: headers, json: symbolsUploadBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
let symbolsUploadInfo: SymbolsUploadInfo = {
symbol_upload_id: body['symbol_upload_id'],
upload_url: body['upload_url'],
expiration_date: body['expiration_date']
}
defer.resolve(symbolsUploadInfo);
});
})
return defer.promise;
}
async function uploadSymbols(uploadUrl: string, file: string): Promise<void> {
tl.debug("-- Uploading symbols...");
tl.debug(`---- url: ${uploadUrl}`);
try {
const azureBlobUploadHelper = new AzureBlobUploadHelper(tl.debug);
await azureBlobUploadHelper.upload(uploadUrl, file);
} catch (e) {
tl.error(inspect(e));
throw e;
}
tl.debug('-- Symbol uploaded.');
}
function commitSymbols(apiServer: string, apiVersion: string, appSlug: string, symbol_upload_id: string, token: string, userAgent: string): Q.Promise<void> {
tl.debug("-- Finishing uploading symbols...");
let defer = Q.defer<void>();
let commitSymbolsUrl: string = `${apiServer}/${apiVersion}/apps/${appSlug}/symbol_uploads/${symbol_upload_id}`;
tl.debug(`---- url: ${commitSymbolsUrl}`);
let headers = {
"X-API-Token": token,
"User-Agent": userAgent,
"internal-request-source": "VSTS"
};
let commitBody = { "status": "committed" };
request.patch({ url: commitSymbolsUrl, headers: headers, json: commitBody }, (err, res, body) => {
responseHandler(defer, err, res, body, () => {
defer.resolve();
});
})
return defer.promise;
}
function expandSymbolsPaths(symbolsType: string, pattern: string, continueOnError: boolean, packParentFolder: boolean): string[] {
tl.debug("-- Expanding symbols path pattern to a list of paths");
let symbolsPaths: string[] = [];
if (symbolsType === "Apple" || symbolsType === "Breakpad") {
// User can specifay a symbols path pattern that selects
// multiple symbols folder paths.
const symbolPaths = utils.resolvePaths(pattern, continueOnError, packParentFolder);
// Resolved paths can be null if continueIfSymbolsNotFound is true and the file/folder does not exist.
if (symbolPaths) {
symbolPaths.forEach(symbolFolder => {
if (symbolFolder) {
const folderPath = utils.checkAndFixFilePath(symbolFolder, continueOnError);
// The path can be null if continueIfSymbolsNotFound is true and the folder does not exist.
if (folderPath) {
symbolsPaths.push(folderPath);
}
}
})
}
} else {
// For all other application types user can specify a symbols path pattern
// that selects only one file or one folder.
let symbolsFile = utils.resolveSinglePath(pattern, continueOnError, packParentFolder);
// Resolved paths can be null if continueIfSymbolsNotFound is true and the file/folder does not exist.
if (symbolsFile) {
let filePath = utils.checkAndFixFilePath(symbolsFile, continueOnError);
// The path can be null if continueIfSymbolsNotFound is true and the file/folder does not exist.
if (filePath) {
symbolsPaths.push(filePath);
}
}
}
return symbolsPaths;
}
async function run() {
try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
// Get build inputs
let apiEndpointData = getEndpointDetails('serverEndpoint');
let apiToken: string = apiEndpointData.authToken;
let apiServer: string = apiEndpointData.apiServer;
let apiVersion: string = apiEndpointData.apiVersion;
let userAgent = tl.getVariable('MSDEPLOY_HTTP_USER_AGENT');
if (!userAgent) {
userAgent = 'VSTS';
}
userAgent = userAgent + ' (Task:VSMobileCenterUpload)';
var effectiveApiServer = process.env['SONOMA_API_SERVER'] || apiServer;
var effectiveApiVersion = process.env['SONOMA_API_VERSION'] || apiVersion;
tl.debug(`Effective API Url: ${effectiveApiServer}/${effectiveApiVersion}`);
let appSlug: string = tl.getInput('appSlug', true);
let appFilePattern: string = tl.getInput('app', true);
/* The task has support for different symbol types but App Center server only support Apple currently, add back these types in the task.json when support is available in App Center.
"AndroidNative": "Android (native C/C++)",
"Windows": "Windows 8.1",
"UWP": "Universal Windows Platform (UWP)"
*/
const symbolType: TaskSymbolType = tl.getInput('symbolsType', false) as TaskSymbolType;
const symbolsLookup: { symbolType: ApiSymbolType, fieldName: string, forceArchive?: boolean }[] = [];
switch (symbolType) {
case "Apple":
symbolsLookup.push({ symbolType, fieldName: "dsymPath" });
break;
case "Android":
symbolsLookup.push({ symbolType: "AndroidProguard", fieldName: "mappingTxtPath" });
symbolsLookup.push({ symbolType: "Breakpad", fieldName: "nativeLibrariesPath", forceArchive: true });
break;
case "UWP":
symbolsLookup.push({ symbolType, fieldName: "appxsymPath" });
break;
default:
symbolsLookup.push({ symbolType, fieldName: "symbolsPath" });
}
let buildVersion: string = tl.getInput('buildVersion', false);
let packParentFolder: boolean = tl.getBoolInput('packParentFolder', false);
let releaseNotesSelection = tl.getInput('releaseNotesSelection', true);
let releaseNotes: string = null;
if (releaseNotesSelection === 'file') {
let releaseNotesFile = tl.getPathInput('releaseNotesFile', true, true);
releaseNotes = fs.readFileSync(releaseNotesFile).toString('utf8');
} else {
releaseNotes = tl.getInput('releaseNotesInput', true);
}
let isMandatory: boolean = tl.getBoolInput('isMandatory', false);
const destinationType = tl.getInput('destinationType', false) as DestinationType || DestinationType.Groups;
const destinationsInputName = destinationType === DestinationType.Groups ? 'destinationGroupIds' : 'destinationStoreId';
const destinationIsMandatory = destinationType === DestinationType.Store;
let destinations = tl.getInput(destinationsInputName, destinationIsMandatory) || "00000000-0000-0000-0000-000000000000";
tl.debug(`Effective destinationIds: ${destinations}`);
let destinationIds = destinations.split(/[, ;]+/).map(id => id.trim()).filter(id => id);
// Validate inputs
if (!apiToken) {
throw new Error(tl.loc("NoApiTokenFound"));
}
if (!destinationIds.length) {
throw new Error(tl.loc("InvalidDestinationInput"));
}
if (destinationType === DestinationType.Store && destinationIds.length > 1) {
throw new Error(tl.loc("CanNotDistributeToMultipleStores"));
}
const isSilent: boolean = destinationType === DestinationType.Groups && (tl.getBoolInput('isSilent', false) || false);
let app = utils.resolveSinglePath(appFilePattern);
tl.checkPath(app, "Binary file");
let continueIfSymbolsNotFoundVariable = tl.getVariable('VSMobileCenterUpload.ContinueIfSymbolsNotFound');
let continueIfSymbolsNotFound = false;
if (continueIfSymbolsNotFoundVariable && continueIfSymbolsNotFoundVariable.toLowerCase() === 'true') {
continueIfSymbolsNotFound = true;
}
// Begin release upload
let uploadInfo: any = await beginReleaseUpload(effectiveApiServer, effectiveApiVersion, appSlug, apiToken, userAgent, buildVersion);
const uploadId = uploadInfo.id;
let releaseId;
try {
// Perform the upload
await uploadRelease(uploadInfo, app).catch(async error => {
console.log("ff");
await tryAbort(effectiveApiServer, effectiveApiVersion, appSlug, uploadId, apiToken, userAgent, error);
console.log("ff1");
tl.setResult(tl.TaskResult.Failed, `${error}`);
console.log("ff2");
return;
});
await patchRelease(effectiveApiServer, effectiveApiVersion, appSlug, uploadId, apiToken, userAgent);
releaseId = await loadReleaseIdUntilSuccess(effectiveApiServer, effectiveApiVersion, appSlug, uploadId, apiToken, userAgent);
} catch (error) {
console.log("ff4");
await tryAbort(effectiveApiServer, effectiveApiVersion, appSlug, uploadId, apiToken, userAgent, error);
tl.setResult(tl.TaskResult.Failed, `${error}`);
return;
}
await updateRelease(effectiveApiServer, effectiveApiVersion, appSlug, releaseId, releaseNotes, apiToken, userAgent);
await Q.all(destinationIds.map(destinationId => {
return publishRelease(effectiveApiServer, effectiveApiVersion, appSlug, releaseId, destinationType, isMandatory, isSilent, destinationId, apiToken, userAgent);
}));
for (const { fieldName, symbolType, forceArchive } of symbolsLookup) {
const symbolsPathPattern: string = tl.getInput(fieldName, false);
// Expand symbols path pattern to a list of paths
const symbolsPaths = expandSymbolsPaths(symbolType, symbolsPathPattern, continueIfSymbolsNotFound, packParentFolder);
// Prepare symbols
const symbolsFile = await prepareSymbols(symbolsPaths, forceArchive);
if (symbolsFile) {
// Begin preparing upload symbols
let version: string;
let build: string;
if (symbolType === "AndroidProguard") {
const release = await getRelease(effectiveApiServer, effectiveApiVersion, appSlug, releaseId, apiToken, userAgent);
version = release.short_version;
build = release.version;
}
const symbolsUploadInfo = await beginSymbolUpload(effectiveApiServer, effectiveApiVersion, appSlug, symbolType, apiToken, userAgent, version, build);
// upload symbols
await uploadSymbols(symbolsUploadInfo.upload_url, symbolsFile);
// Commit the symbols upload
await commitSymbols(effectiveApiServer, effectiveApiVersion, appSlug, symbolsUploadInfo.symbol_upload_id, apiToken, userAgent);
}
}
tl.setResult(tl.TaskResult.Succeeded, tl.loc("Succeeded"));
} catch (err) {
tl.setResult(tl.TaskResult.Failed, `${err}`);
}
}
run();