-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
247 lines (208 loc) · 7.61 KB
/
index.ts
File metadata and controls
247 lines (208 loc) · 7.61 KB
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
import * as tmp from 'tmp';
import { cliux } from '@contentstack/cli-utilities';
import * as importer from '../seed/importer';
import ContentstackClient, { Organization, Stack } from '../seed/contentstack/client';
import {
inquireOrganization,
inquireProceed,
inquireRepo,
inquireStack,
InquireStackResponse,
} from '../seed/interactive';
import GitHubClient from './github/client';
import GithubError from './github/error';
const DEFAULT_OWNER = 'contentstack';
const DEFAULT_STACK_PATTERN = 'stack-';
export const ENGLISH_LOCALE = 'en-us';
export interface ContentModelSeederOptions {
parent?: any;
cdaHost: string;
cmaHost: string;
gitHubPath: string | undefined;
orgUid: string | undefined;
stackUid: string | undefined;
stackName: string | undefined;
fetchLimit: string | undefined;
skipStackConfirmation: boolean | undefined;
isAuthenticated: boolean | false;
managementToken?: string | undefined;
alias?: string | undefined;
master_locale?: string | undefined;
}
export default class ContentModelSeeder {
private readonly parent: any = null;
private readonly csClient: ContentstackClient;
private readonly ghClient: GitHubClient;
private readonly _options: ContentModelSeederOptions;
private ghUsername: string = DEFAULT_OWNER;
private ghRepo: string | undefined;
managementToken?: string | undefined;
get ghPath(): string {
return `${this.ghUsername}/${this.ghRepo}`;
}
constructor(public options: ContentModelSeederOptions) {
this.parent = options.parent || null;
this._options = options;
const gh = GitHubClient.parsePath(options.gitHubPath);
this.ghUsername = gh.username || DEFAULT_OWNER;
this.ghRepo = gh.repo;
const limit = Number(this.options.fetchLimit);
this.managementToken = options.managementToken;
this.csClient = new ContentstackClient(options.cmaHost, limit);
this.ghClient = new GitHubClient(this.ghUsername, DEFAULT_STACK_PATTERN);
}
async run() {
let api_key: string;
const { organizationResponse, stackResponse } = await this.getInput();
if (stackResponse.isNew && stackResponse.name) {
api_key = await this.createStack(organizationResponse, stackResponse.name);
} else {
api_key = stackResponse.api_key as string;
const proceed = await this.shouldProceed(api_key);
if (!proceed) {
cliux.print('Exiting. Please re-run the command, if you wish to seed content.');
return;
}
}
const tmpPath = await this.downloadRelease();
cliux.print(`Importing into ${this.managementToken ? 'your stack' : `'${stackResponse.name}'`}.`);
await importer.run({
api_key: api_key,
cdaHost: this.options.cdaHost,
cmaHost: this.options.cmaHost,
master_locale : this.options.master_locale || ENGLISH_LOCALE,
tmpPath: tmpPath,
isAuthenticated: this.options.isAuthenticated,
alias: this.options.alias,
});
return { api_key };
}
async getInput(): Promise<
| {
organizationResponse: Organization;
stackResponse: InquireStackResponse;
}
| any
> {
if (!this.ghRepo) {
await this.inquireGitHubRepo();
}
let repoExists = false;
let repoResponseData: any = {};
try {
const repoCheckResult = await this.ghClient.makeGetApiCall(this.ghRepo as string);
repoExists = repoCheckResult.statusCode === 200;
repoResponseData = { status: repoCheckResult.statusCode, statusMessage: repoCheckResult.statusMessage };
} catch (error) {
throw error;
}
if (repoExists === false) {
cliux.error(
repoResponseData.status === 403
? repoResponseData.statusMessage
: `Could not find GitHub repository '${this.ghPath}'.`,
);
if (this.parent) this.parent.exit(1);
} else {
let organizationResponse: Organization | undefined;
let stackResponse: InquireStackResponse;
let stack: Stack;
if (this.options.stackUid && this.options.managementToken) {
stackResponse = {
isNew: false,
name: 'your stack',
uid: this.options.stackUid,
api_key: this.options.stackUid,
};
} else if (this.options.stackUid) {
stack = await this.csClient.getStack(this.options.stackUid);
stackResponse = {
isNew: false,
name: stack.name,
uid: stack.uid,
api_key: stack.api_key,
};
} else {
if (this.options.orgUid) {
organizationResponse = await this.csClient.getOrganization(this.options.orgUid);
} else {
const organizations = await this.csClient.getOrganizations();
if (!organizations || organizations.length === 0) {
throw new Error(
'You do not have access to any organizations. Please try again or ask an Administrator for assistance.',
);
}
organizationResponse = await inquireOrganization(organizations);
}
const stacks = await this.csClient.getStacks(organizationResponse.uid);
stackResponse = await inquireStack(stacks, this.options.stackName);
}
return { organizationResponse, stackResponse };
}
}
async createStack(organization: Organization, stackName: string) {
cliux.loader(`Creating Stack '${stackName}' within Organization '${organization.name}'`);
const newStack = await this.csClient.createStack({
name: stackName,
description: '',
master_locale: this.options.master_locale || ENGLISH_LOCALE,
org_uid: organization.uid,
});
cliux.loader();
return newStack.api_key;
}
async shouldProceed(api_key: string) {
const stack_details = await this.csClient.getStack(api_key);
const repoMasterLocale = await this.ghClient.getMasterLocaleFromRepo(this.ghRepo as string);
const expectedLocale = repoMasterLocale || this.options.master_locale || ENGLISH_LOCALE;
if (stack_details.master_locale !== expectedLocale) {
cliux.print(
`Repository '${this.ghRepo}' requires the master locale to be set to '${expectedLocale}', but your stack has '${stack_details.master_locale}'.`,
{
color: 'yellow',
bold: true,
},
);
return false;
}
const count = await this.csClient.getContentTypeCount(api_key, this.managementToken);
if (count > 0 && !this._options.skipStackConfirmation) {
const proceed = await inquireProceed();
if (!proceed) {
return false;
}
}
return true;
}
async downloadRelease() {
const tmpDir = tmp.dirSync({
unsafeCleanup: true,
});
cliux.print(`Creating temporary directory '${tmpDir.name}'.`);
cliux.loader('Downloading and extracting Stack');
try {
await this.ghClient.getLatest(this.ghRepo as string, tmpDir.name);
} catch (error) {
if (error instanceof GithubError) {
if (error.status === 404) {
cliux.error(`Unable to find a release for '${this.ghPath}'.`);
}
}
} finally {
cliux.loader();
}
return tmpDir.name;
}
async inquireGitHubRepo() {
try {
const allRepos = await this.ghClient.getAllRepos();
const stackRepos = allRepos.filter((repo: any) => repo.name.startsWith(DEFAULT_STACK_PATTERN));
const repoResponse = await inquireRepo(stackRepos);
this.ghRepo = repoResponse.choice;
} catch (error) {
cliux.error(
`Unable to find any Stack repositories within the '${this.ghUsername}' GitHub account. Please re-run this command with a GitHub repository in the 'account/repo' format. You can also re-run the command without arguments to pull from the official Stack list.`,
);
}
}
}