-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.ts
executable file
·2628 lines (2424 loc) · 73.5 KB
/
cli.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
#!/usr/bin/env node
import ora from 'ora';
import chalk from 'chalk';
import { Minimatch } from 'minimatch';
import dateFns from 'date-fns';
import fs from 'fs';
import http from 'http';
import inquirer from 'inquirer';
import jwt from 'jsonwebtoken';
import { loadJsonFile } from 'load-json-file';
import logSymbols from 'log-symbols';
import open from 'open';
import path from 'path';
import pify from 'pify';
import portfinder from 'portfinder';
import querystring from 'querystring';
import got from 'got'; // eslint-disable-line import/no-unresolved
import semver from 'semver';
import updateNotifier from 'update-notifier';
import url from 'url';
import util from 'util';
import { v4 as uuidv4 } from 'uuid';
import walk from 'ignore-walk';
import writeFile from 'write';
import { writeJsonFile } from 'write-json-file';
import Configstore from 'configstore';
import { AvoInspector, AvoInspectorEnv } from 'node-avo-inspector';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import httpShutdown from 'http-shutdown';
import fuzzypath from 'inquirer-fuzzy-path';
import * as report from './reporter.js';
import Avo from './Avo.js';
declare global {
namespace NodeJS {
interface ImportMeta {
url: string;
}
}
}
const pkg = JSON.parse(
fs.readFileSync(new URL('package.json', import.meta.url), 'utf-8'),
);
/// //////////////////////////////////////////////////////////////////////
// LOGGING
const { cyan, gray, red, bold, underline } = chalk;
function cmd(command) {
return `${gray('`')}${cyan(command)}${gray('`')}`;
}
function link(text) {
return underline(text);
}
function file(text) {
return underline(text);
}
function email(text) {
return underline(text);
}
// to cancel spinners globally
let _cancel = null;
let cancelWait = () => {
if (_cancel !== null) {
_cancel();
_cancel = null;
}
};
function wait(message, timeOut = 300) {
cancelWait();
let running = false;
let spinner;
let stopped = false;
setTimeout(() => {
if (stopped) return;
spinner = ora(gray(message));
spinner.color = 'gray';
spinner.start();
running = true;
}, timeOut);
const cancel = () => {
stopped = true;
if (running) {
spinner.stop();
running = false;
}
process.removeListener('nowExit', cancel);
};
process.on('nowExit', cancel);
cancelWait = cancel;
}
// register inquirer-file-path
inquirer.registerPrompt('fuzzypath', fuzzypath);
updateNotifier({ pkg }).notify();
const conf = new Configstore(pkg.name);
if (!conf.has('avo_install_id')) {
conf.set('avo_install_id', uuidv4());
}
const FIFTEEN_MINUTES_IN_MS = 15 * 60 * 1000;
const nonce = (1 + Math.random() * (2 << 29)).toString();
function isString(str) {
if (str != null && typeof str.valueOf() === 'string') {
return true;
}
return false;
}
const sum = (base, value) => base + value;
portfinder.basePort = 9005;
const _getPort = portfinder.getPortPromise;
type ErrorOptions = {
status?: number;
exit?: number;
original?: Error;
context?: Object;
};
function AvoError(message, options: ErrorOptions = {}) {
this.name = 'AvoError';
this.message = message;
this.status = options.status ?? 500;
this.exit = options.exit ?? 1;
this.stack = new Error().stack;
this.original = options.original;
this.context = options.context;
}
AvoError.prototype = Object.create(Error.prototype);
const INVALID_CREDENTIAL_ERROR = new AvoError(
`Authentication Error: Your credentials are no longer valid. Please run ${cmd(
'avo logout; avo login',
)}`,
{ exit: 1 },
);
type ApiTokenResult = {
idToken?: string;
refreshToken?: string;
expiresIn: number;
};
// in-memory cache, so we have it for successive calls
type LastAccessToken = {
expiresAt?: number;
refreshToken?: string;
idToken?: string;
};
let lastAccessToken: LastAccessToken = {};
let accessToken;
let refreshToken;
/// //////////////////////////////////////////////////////////////////////
// REQUEST HANDLING
function responseToError(response, error) {
if (!response) {
return new AvoError(error, {});
}
let { body } = response;
if (typeof body === 'string' && response.statusCode === 404) {
body = {
error: {
message: 'Not Found',
},
};
}
if (response.statusCode < 400) {
return null;
}
if (typeof body !== 'object') {
try {
body = JSON.parse(body);
} catch (e) {
body = {};
}
}
if (!body.error) {
const getMessage = (statusCode) => {
switch (statusCode) {
case 401:
return 'Unauthorized';
case 403:
return 'Forbidden. Do you have the required permissions? Some commands require editor or admin access.';
case 404:
return 'Not Found';
default:
return 'Unknown Error';
}
};
body.error = {
message: getMessage(response.statusCode),
};
}
const message = `HTTP Error: ${response.statusCode}, ${
body.error.message ?? body.error
}`;
let exitCode;
if (response.statusCode >= 500) {
// 5xx errors are unexpected
exitCode = 2;
} else {
// 4xx errors happen sometimes
exitCode = 1;
}
delete response.request.headers;
return new AvoError(message, {
context: {
body,
response,
},
exit: exitCode,
});
}
function _request(options) {
return new Promise((resolve, reject) => {
got(options)
.then((response) => {
if (response.statusCode >= 400) {
return reject(responseToError(response, null));
}
return resolve(JSON.parse(response.body));
})
.catch((err) => {
const responseError = responseToError(err.response, err);
if (responseError != null) {
reject(responseError);
} else {
reject(
new AvoError(`Server Error. ${err.message}`, {
original: err,
exit: 2,
}),
);
}
});
});
}
const _appendQueryData = (urlPath, data) => {
let returnPath = urlPath;
if (data && Object.keys(data).length > 0) {
returnPath += returnPath.includes('?') ? '&' : '?';
returnPath += querystring.stringify(data);
}
return returnPath;
};
function _refreshAccessToken(refreshToken) {
return api // eslint-disable-line
.request('POST', '/auth/refresh', {
origin: api.apiOrigin, // eslint-disable-line
json: {
token: refreshToken,
},
})
.then(
(data: ApiTokenResult) => {
if (!isString(data.idToken)) {
throw INVALID_CREDENTIAL_ERROR;
}
lastAccessToken = {
expiresAt: Date.now() + data.expiresIn * 1000,
refreshToken,
...data,
};
const currentRefreshToken = conf.get('tokens').refreshToken;
if (refreshToken === currentRefreshToken) {
conf.set('tokens', lastAccessToken);
}
return lastAccessToken;
},
() => {
throw INVALID_CREDENTIAL_ERROR;
},
);
}
function _haveValidAccessToken(refreshToken) {
if (Object.keys(lastAccessToken).length === 0) {
const tokens = conf.get('tokens');
if (refreshToken === tokens.refreshToken) {
lastAccessToken = tokens;
}
}
return (
lastAccessToken.idToken &&
lastAccessToken.refreshToken === refreshToken &&
lastAccessToken.expiresAt &&
lastAccessToken.expiresAt > Date.now() + FIFTEEN_MINUTES_IN_MS
);
}
function getAccessToken(refreshToken) {
if (_haveValidAccessToken(refreshToken)) {
return Promise.resolve(lastAccessToken);
}
return _refreshAccessToken(refreshToken);
}
type ReqOptions = {
method: string;
decompress: boolean;
headers: object; // Should be stricter
json?: object;
form?: object; // Is it?
url?: string;
};
const api = {
authOrigin: 'https://www.avo.app',
apiOrigin: 'https://api.avo.app',
setRefreshToken(token) {
refreshToken = token;
},
setAccessToken(token) {
accessToken = token;
},
getAccessToken() {
return accessToken
? Promise.resolve({ idToken: accessToken })
: getAccessToken(refreshToken);
},
addRequestHeaders(reqOptions) {
// Runtime fetch of Auth singleton to prevent circular module dependencies
return api.getAccessToken().then((result) => ({
...reqOptions,
headers: {
...reqOptions.headers,
'User-Agent': `AvoCLI/${pkg.version}`,
'X-Client-Version': `AvoCLI/${pkg.version}`,
authorization: `Bearer ${result.idToken}`,
},
}));
},
request(method, resource, options) {
const validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
const reqOptions: ReqOptions = {
method: validMethods.includes(method) ? method : 'GET',
decompress: true,
headers: options.headers ?? {},
};
let urlPath = resource;
if (options.query) {
urlPath = _appendQueryData(urlPath, options.query);
}
if (reqOptions.method === 'GET') {
urlPath = _appendQueryData(urlPath, options.json);
} else if (Object.keys(options.json).length > 0) {
reqOptions.json = options.json;
} else if (Object.keys(options.form).length > 0) {
reqOptions.form = options.form;
}
reqOptions.url = options.origin + urlPath;
let requestFunction = () => _request(reqOptions);
if (options.auth === true) {
requestFunction = () =>
api
.addRequestHeaders(reqOptions)
.then((reqOptionsWithToken) => _request(reqOptionsWithToken));
}
return requestFunction().catch((err) => {
if (
options.retryCodes &&
options.retryCodes.includes(err.context.response.statusCode)
) {
return new Promise((resolve) => {
setTimeout(resolve, 1000);
}).then(requestFunction);
}
return Promise.reject(err);
});
},
};
const customAnalyticsDestination = {
make: function make(production) {
this.production = production;
},
logEvent: (userId, eventName, eventProperties) => {
api
.request('POST', '/c/v1/track', {
origin: api.apiOrigin,
json: {
userId,
eventName,
eventProperties,
},
})
.catch(() => {
// don't crash on tracking errors
});
return undefined;
},
setUserProperties: () => undefined, // noop
};
const inspector = new AvoInspector({
apiKey: '3UWtteG9HenZ825cYoYr',
env: AvoInspectorEnv.Prod,
version: pkg.version,
appName: 'Avo CLI',
});
// setup Avo analytics
Avo.initAvo(
{ env: Avo.AvoEnv.Prod, inspector },
{ client: Avo.Client.CLI, version: pkg.version },
{},
customAnalyticsDestination,
);
type Branch = {
name: string;
id: string;
};
type Schema = {
id: string;
name: string;
};
type Source = {
id: string;
name: string;
path: string;
actionId: string;
branchId: string;
updatedAt: string;
interfacePath?: string;
analysis?: {
glob: string;
module?: string;
};
filenameHint?: string;
canHaveInterfaceFile?: boolean;
};
type AvoJson = {
avo: {
version: number;
};
schema: Schema;
branch: Branch;
force?: boolean;
forceFeatures?: string;
sources?: Source[];
};
function isLegacyAvoJson(json): boolean {
// check if legacy avo.json or un-initialized project
return json.types ?? !json.schema;
}
function avoNeedsUpdate(json: AvoJson): boolean {
// if avo.json has version, and this binary has lower version number it needs updating
return (
json.avo && json.avo.version && semver.major(pkg.version) < json.avo.version
);
}
const MERGE_CONFLICT_ANCESTOR = '|||||||';
const MERGE_CONFLICT_END = '>>>>>>>';
const MERGE_CONFLICT_SEP = '=======';
const MERGE_CONFLICT_START = '<<<<<<<';
function hasMergeConflicts(str: string): boolean {
return (
str.includes(MERGE_CONFLICT_START) &&
str.includes(MERGE_CONFLICT_SEP) &&
str.includes(MERGE_CONFLICT_END)
);
}
function extractConflictingFiles(str: string): [string, string] {
const files = [[], []];
const lines = str.split(/\r?\n/g);
let skip = false;
while (lines.length) {
const line = lines.shift();
if (line.startsWith(MERGE_CONFLICT_START)) {
while (lines.length) {
const conflictLine = lines.shift();
if (conflictLine === MERGE_CONFLICT_SEP) {
skip = false;
break;
} else if (skip || conflictLine.startsWith(MERGE_CONFLICT_ANCESTOR)) {
skip = true;
} else {
files[0].push(conflictLine);
}
}
while (lines.length) {
const conflictLine = lines.shift();
if (conflictLine.startsWith(MERGE_CONFLICT_END)) {
break;
} else {
files[1].push(conflictLine);
}
}
} else {
files[0].push(line);
files[1].push(line);
}
}
return [files[0].join('\n'), files[1].join('\n')];
}
enum BranchStatus {
BRANCH_UP_TO_DATE = 'branch-up-to-date',
BRANCH_NOT_UP_TO_DATE = 'branch-not-up-to-date',
}
function getMasterStatus(json: AvoJson): Promise<BranchStatus> {
if (json.branch.id === 'master') {
return Promise.resolve(BranchStatus.BRANCH_UP_TO_DATE);
}
return api
.request('POST', '/c/v1/master', {
origin: api.apiOrigin,
auth: true,
json: {
schemaId: json.schema.id,
branchId: json.branch.id,
},
})
.then(({ pullRequired }) =>
pullRequired
? BranchStatus.BRANCH_NOT_UP_TO_DATE
: BranchStatus.BRANCH_UP_TO_DATE,
);
}
function pullMaster(json: AvoJson): Promise<AvoJson> {
if (json.branch.name === 'main') {
report.info('Your current branch is main');
return Promise.resolve(json);
}
wait(
json.force ? 'Force pulling main into branch' : 'Pulling main into branch',
);
return api
.request('POST', '/c/v1/master/pull', {
origin: api.apiOrigin,
auth: true,
json: {
schemaId: json.schema.id,
branchId: json.branch.id,
force: json.force,
},
})
.then(() => {
cancelWait();
report.success('Branch is up to date with main');
return json;
});
}
function promptPullMaster(json: AvoJson): Promise<AvoJson> {
wait('Check if branch is up to date with main');
return getMasterStatus(json)
.then((branchStatus) => {
cancelWait();
if (branchStatus === BranchStatus.BRANCH_NOT_UP_TO_DATE) {
return inquirer
.prompt([
{
type: 'confirm',
name: 'pull',
default: true,
message: `Your branch '${bold(
json.branch.name,
)}' is not up to date with the Avo main branch. Would you like to pull main into your branch?`,
},
])
.then((answer) => Promise.resolve([branchStatus, answer]));
}
// We're expecting branchStatus === BRANCH_UP_TO_DATE
return Promise.resolve([branchStatus]);
})
.then(([branchStatus, answer]) => {
if (branchStatus === BranchStatus.BRANCH_UP_TO_DATE) {
report.success('Branch is up to date with main');
return Promise.resolve(json);
}
if (answer.pull) {
return pullMaster(json);
}
report.info('Did not pull main into branch');
return Promise.resolve(json);
});
}
const installIdOrUserId = (): string =>
conf.get('user')?.user_id ?? conf.get('avo_install_id');
const invokedByCi = (): boolean => process.env.CI !== undefined;
function requireAuth<T>(
argv: { token?: string; user?: string; tokens?: any },
cb: () => T,
): T {
const tokens = conf.get('tokens');
const user = conf.get('user');
const tokenOpt = argv.token ?? process.env.AVO_TOKEN;
if (tokenOpt) {
api.setRefreshToken(tokenOpt);
return cb();
}
if (!user || !tokens) {
report.error(`Command requires authentication. Run ${cmd('avo login')}`);
process.exit(1);
}
argv.user = user; // eslint-disable-line no-param-reassign
argv.tokens = tokens; // eslint-disable-line no-param-reassign
api.setRefreshToken(tokens.refreshToken);
return cb();
}
type ApiWorkspacesResult = {
workspaces: [{ lastUsedAt: number; name: string; id: string }];
};
function init(): Promise<AvoJson> {
const makeAvoJson = (schema: {
id: string;
name: string;
}): Promise<AvoJson> => {
report.success(`Initialized for workspace ${cyan(schema.name)}`);
return Promise.resolve({
avo: {
version: semver.major(pkg.version),
},
schema: {
id: schema.id,
name: schema.name,
},
branch: {
id: 'master',
name: 'main',
},
});
};
wait('Initializing');
return api
.request('GET', '/c/v1/workspaces', {
origin: api.apiOrigin,
auth: true,
})
.then(({ workspaces }: ApiWorkspacesResult) => {
cancelWait();
const schemas = [...workspaces].sort(
(a, b) => a.lastUsedAt - b.lastUsedAt,
);
if (schemas.length > 1) {
const choices = schemas.map((schema) => ({
value: schema,
name: schema.name,
}));
return inquirer
.prompt([
{
type: 'list',
name: 'schema',
message: 'Select a workspace to initialize',
choices,
},
])
.then((answer) => makeAvoJson(answer.schema));
}
if (schemas.length === 0) {
throw new AvoError(
`No workspaces to initialize. Go to ${link(
'wwww.avo.app',
)} to create one`,
);
} else {
const schema = schemas[0];
return makeAvoJson(schema);
}
});
}
function validateAvoJson(json: AvoJson): Promise<AvoJson> {
if (avoNeedsUpdate(json)) {
throw new AvoError('Your avo CLI is outdated, please update');
}
if (isLegacyAvoJson(json)) {
return init();
}
// augment the latest major version into avo.json
return Promise.resolve({
...json,
avo: { ...json.avo, version: semver.major(pkg.version) },
});
}
type ApiBranchesResult = {
branches: [{ name: string; id: string }];
};
function fetchBranches(json: AvoJson): Promise<Branch[]> {
wait('Fetching open branches');
const payload = {
origin: api.apiOrigin,
auth: true,
json: {
schemaId: json.schema.id,
},
};
return api
.request('POST', '/c/v1/branches', payload)
.then((data: ApiBranchesResult) => {
cancelWait();
const branches = [...data.branches].sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
// The api still returns master for backwards comparability so we manually
// update the branch name to main
return branches.map((branch) =>
branch.name === 'master' ? { ...branch, name: 'main' } : branch,
);
});
}
function checkout(branchToCheckout: string, json: AvoJson): Promise<AvoJson> {
return fetchBranches(json).then((branches) => {
if (!branchToCheckout) {
const choices = branches.map((branch) => ({
value: branch,
name: branch.name,
}));
const currentBranch = branches.find(({ id }) => id === json.branch.id);
return inquirer
.prompt([
{
type: 'list',
name: 'branch',
message: 'Select a branch',
default:
currentBranch ?? branches.find(({ id }) => id === 'master'),
choices,
pageSize: 15,
},
])
.then((answer) => {
if (answer.branch === currentBranch) {
report.info(`Already on '${currentBranch.name}'`);
return json;
}
const { branch } = answer;
report.success(`Switched to branch '${branch.name}'`);
return {
...json,
branch: {
id: branch.id,
name: branch.name,
},
};
});
}
if (branchToCheckout === 'master') {
report.info(
"The master branch has been renamed to main. Continuing checkout with main branch...'",
);
}
const adjustedBranchToCheckout =
branchToCheckout === 'master' ? 'main' : branchToCheckout;
if (adjustedBranchToCheckout === json.branch.name) {
// XXX should check here if json.branch.id === branch.id from server
// if not, it indicates branch delete, same branch re-created and client is out of sync
report.info(`Already on '${adjustedBranchToCheckout}'`);
return json;
}
const branch = branches.find(
({ name }) => name === adjustedBranchToCheckout,
);
if (!branch) {
report.error(
`Branch '${adjustedBranchToCheckout}' does not exist. Run ${cmd(
'avo checkout',
)} to list available branches`,
);
}
report.success(`Switched to branch '${branch.name}'`);
return {
...json,
branch: {
id: branch.id,
name: branch.name,
},
};
});
}
function resolveAvoJsonConflicts(
avoFile: string,
{ argv, skipPullMaster }: { argv: any; skipPullMaster: boolean },
): Promise<AvoJson> {
report.info('Resolving Avo merge conflicts');
const files = extractConflictingFiles(avoFile);
const head = JSON.parse(files[0]);
const incoming = JSON.parse(files[1]);
Avo.cliConflictResolveAttempted({
userId_: installIdOrUserId(),
cliInvokedByCi: invokedByCi(),
schemaId: head.schema.id,
schemaName: head.schema.name,
branchId: head.branch.id,
branchName: head.branch.name,
});
if (
head.avo.version !== incoming.avo.version ||
head.schema.id !== incoming.schema.id
) {
Avo.cliConflictResolveFailed({
userId_: installIdOrUserId(),
cliInvokedByCi: invokedByCi(),
schemaId: head.schema.id,
schemaName: head.schema.name,
branchId: head.branch.id,
branchName: head.branch.name,
});
throw new Error(
"Could not automatically resolve merge conflicts in avo.json. Resolve merge conflicts in avo.json before running 'avo pull' again.",
);
}
if (
JSON.stringify(head.sources.map((s) => s.id)) !==
JSON.stringify(incoming.sources.map((s) => s.id))
) {
Avo.cliConflictResolveFailed({
userId_: installIdOrUserId(),
cliInvokedByCi: invokedByCi(),
schemaId: head.schema.id,
schemaName: head.schema.name,
branchId: head.branch.id,
branchName: head.branch.name,
});
throw new Error(
"Could not automatically resolve merge conflicts in avo.json. Resolve merge conflicts in sources list in avo.json before running 'avo pull' again.",
);
}
const nextAvoJson = {
avo: head.avo,
schema: head.schema,
branch: head.branch,
sources: head.sources,
};
return requireAuth(argv, () =>
fetchBranches(nextAvoJson).then((branches) => {
const isHeadBranchOpen = branches.find(
(branch) => branch.id === nextAvoJson.branch.id,
);
const isIncomingBranchOpen = branches.find(
(branch) => branch.id === incoming.branch.id,
);
function switchBranchIfRequired(json) {
if (isHeadBranchOpen) {
return Promise.resolve(json);
}
report.info(
`Your current branch '${json.branch.name}' has been closed or merged. Go to another branch:`,
);
return checkout(null, json);
}
return switchBranchIfRequired(nextAvoJson)
.then((json) => {
if (
head.branch.id === incoming.branch.id ||
incoming.branch.id === 'master'
) {
return Promise.resolve([true, json]);
}
return Promise.resolve([false, json]);
})
.then(([isDone, json]) => {
if (!isDone && isIncomingBranchOpen && argv.force) {
report.warn(
`Incoming branch, ${
incoming.branch.name
}, has not been merged to Avo main. To review and merge go to: ${link(
`https://www.avo.app/schemas/${nextAvoJson.schema.id}/branches/${incoming.branch.id}/diff`,
)}`,
);
return Promise.resolve(json);
}
if (!isDone && isIncomingBranchOpen) {
Avo.cliConflictResolveFailed({
userId_: installIdOrUserId(),
cliInvokedByCi: invokedByCi(),
schemaId: head.schema.id,
schemaName: head.schema.name,
branchId: head.branch.id,
branchName: head.branch.name,
});
throw new Error(
`Incoming branch, ${
incoming.branch.name
}, has not been merged to Avo main.\n\nTo review and merge go to:\n${link(
`https://www.avo.app/schemas/${nextAvoJson.schema.id}/branches/${incoming.branch.id}/diff`,
)}\n\nOnce merged, run 'avo pull'. To skip this check use the --force flag.`,
);
} else {
return Promise.resolve(json);
}
})
.then((json) => {
if (skipPullMaster) {
return Promise.resolve(json);
}
return promptPullMaster(json);
})
.then((json) => {
Avo.cliConflictResolveSucceeded({
userId_: installIdOrUserId(),
cliInvokedByCi: invokedByCi(),
schemaId: head.schema.id,
schemaName: head.schema.name,
branchId: head.branch.id,
branchName: head.branch.name,
});
report.success('Successfully resolved Avo merge conflicts');
return validateAvoJson(json);
});
}),
);
}
function loadAvoJson(): Promise<AvoJson> {