-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.ts
More file actions
292 lines (259 loc) · 10.5 KB
/
stack.ts
File metadata and controls
292 lines (259 loc) · 10.5 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
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
import find from 'lodash/find';
import { resolve as pResolve } from 'node:path';
import {
handleAndLogError,
isAuthenticated,
managementSDKClient,
log,
} from '@contentstack/cli-utilities';
import { PATH_CONSTANTS } from '../../constants';
import BaseClass from './base-class';
import {
fsUtil,
getExportBasePath,
PROCESS_NAMES,
MODULE_CONTEXTS,
PROCESS_STATUS,
MODULE_NAMES,
} from '../../utils';
import { StackConfig, ModuleClassParams } from '../../types';
export default class ExportStack extends BaseClass {
private stackConfig: StackConfig;
private stackFolderPath: string;
private qs: {
include_count: boolean;
skip?: number;
};
constructor({ exportConfig, stackAPIClient }: ModuleClassParams) {
super({ exportConfig, stackAPIClient });
this.stackConfig = exportConfig.modules.stack;
this.qs = { include_count: true };
this.stackFolderPath = pResolve(
getExportBasePath(this.exportConfig),
this.stackConfig.dirName,
);
this.exportConfig.context.module = MODULE_CONTEXTS.STACK;
this.currentModuleName = MODULE_NAMES[MODULE_CONTEXTS.STACK];
}
async start(): Promise<void> {
try {
log.debug('Starting stack export process...', this.exportConfig.context);
// Initial analysis with loading spinner
const [stackData] = await this.withLoadingSpinner('STACK: Analyzing stack configuration...', async () => {
const stackData = isAuthenticated() ? await this.getStack() : null;
return [stackData];
});
// Create nested progress manager
const progress = this.createNestedProgress(this.currentModuleName);
// Add processes based on configuration
let processCount = 0;
if (stackData?.org_uid) {
log.debug(`Found organization UID: '${stackData.org_uid}'.`, this.exportConfig.context);
this.exportConfig.org_uid = stackData.org_uid;
this.exportConfig.sourceStackName = stackData.name;
log.debug(`Set source stack name: ${stackData.name}`, this.exportConfig.context);
}
if (!this.exportConfig.management_token) {
progress.addProcess(PROCESS_NAMES.STACK_SETTINGS, 1);
processCount++;
}
if (!this.exportConfig.preserveStackVersion && !this.exportConfig.hasOwnProperty('master_locale')) {
progress.addProcess(PROCESS_NAMES.STACK_LOCALE, 1);
processCount++;
} else if (this.exportConfig.preserveStackVersion) {
progress.addProcess(PROCESS_NAMES.STACK_DETAILS, 1);
processCount++;
}
// Execute processes
if (!this.exportConfig.management_token) {
progress
.startProcess(PROCESS_NAMES.STACK_SETTINGS)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.STACK_SETTINGS].EXPORTING,
PROCESS_NAMES.STACK_SETTINGS,
);
await this.exportStackSettings();
progress.completeProcess(PROCESS_NAMES.STACK_SETTINGS, true);
} else {
log.info(
'Skipping stack settings export: Operation is not supported when using a management token.',
this.exportConfig.context,
);
}
if (!this.exportConfig.preserveStackVersion && !this.exportConfig.hasOwnProperty('master_locale')) {
progress
.startProcess(PROCESS_NAMES.STACK_LOCALE)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.STACK_LOCALE].FETCHING,
PROCESS_NAMES.STACK_LOCALE,
);
const masterLocale = await this.getLocales();
progress.completeProcess(PROCESS_NAMES.STACK_LOCALE, true);
if (masterLocale?.code) {
this.exportConfig.master_locale = { code: masterLocale.code };
log.debug(`Set master locale: ${masterLocale.code}`, this.exportConfig.context);
}
this.completeProgress(true);
return masterLocale;
} else if (this.exportConfig.preserveStackVersion) {
progress
.startProcess(PROCESS_NAMES.STACK_DETAILS)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.STACK_DETAILS].EXPORTING,
PROCESS_NAMES.STACK_DETAILS,
);
const stackResult = await this.exportStack();
progress.completeProcess(PROCESS_NAMES.STACK_DETAILS, true);
this.completeProgress(true);
return stackResult;
} else {
log.debug('Locale locale already set, skipping locale fetch', this.exportConfig.context);
}
this.completeProgressWithMessage();
} catch (error) {
log.debug('Error occurred during stack export', this.exportConfig.context);
handleAndLogError(error, { ...this.exportConfig.context });
this.completeProgress(false, error?.message || 'Stack export failed');
throw error;
}
}
async getStack(): Promise<any> {
log.debug(`Fetching stack data for: '${this.exportConfig.apiKey}'...`, this.exportConfig.context);
const tempAPIClient = await managementSDKClient({ host: this.exportConfig.host });
log.debug(`Created Management SDK client with host: '${this.exportConfig.host}'.`, this.exportConfig.context);
return await tempAPIClient
.stack({ api_key: this.exportConfig.apiKey })
.fetch()
.then((data: any) => {
log.debug(`Successfully fetched stack data for: '${this.exportConfig.apiKey}'.`, this.exportConfig.context);
return data;
})
.catch((error: any) => {
log.debug(`Failed to fetch stack data for: '${this.exportConfig.apiKey}'.`, this.exportConfig.context);
return {};
});
}
async getLocales(skip: number = 0) {
if (skip) {
this.qs.skip = skip;
log.debug(`Fetching locales with skip: ${skip}.`, this.exportConfig.context);
} else {
log.debug('Fetching locales with initial query...', this.exportConfig.context);
}
log.debug(`Query parameters: ${JSON.stringify(this.qs)}.`, this.exportConfig.context);
return await this.stack
.locale()
.query(this.qs)
.find()
.then(async (data: any) => {
const { items, count } = data;
log.debug(`Fetched ${items?.length || 0} locales out of ${count}.`, this.exportConfig.context);
if (items?.length) {
log.debug(`Processing ${items.length} locales to find master locale`, this.exportConfig.context);
// Track progress for each locale processed
this.progressManager?.tick(true, 'Fetch locale', null, PROCESS_NAMES.STACK_LOCALE);
skip += this.stackConfig.limit || 100;
const masterLocalObj = find(items, (locale: any) => {
if (locale.fallback_locale === null) {
log.debug(`Found master locale: '${locale.name}' (code: ${locale.code}).`, this.exportConfig.context);
return locale;
}
});
if (masterLocalObj) {
log.debug(`Returning master locale: '${masterLocalObj.name}'.`, this.exportConfig.context);
return masterLocalObj;
} else if (skip >= count) {
log.error(
`Locale locale not found in the stack ${this.exportConfig.apiKey}. Please ensure that the stack has a master locale.`,
this.exportConfig.context,
);
log.debug('Completed search. Master locale not found.', this.exportConfig.context);
return;
} else {
log.debug(
`Locale locale not found in current batch, continuing with skip: ${skip}`,
this.exportConfig.context,
);
return await this.getLocales(skip);
}
} else {
log.debug('No locales found to process.', this.exportConfig.context);
}
})
.catch((error: any) => {
log.debug(
`Error occurred while fetching locales for stack: ${this.exportConfig.apiKey}`,
this.exportConfig.context,
);
this.progressManager?.tick(
false,
'locale fetch',
error?.message || PROCESS_STATUS[PROCESS_NAMES.STACK_LOCALE].FAILED,
PROCESS_NAMES.STACK_LOCALE,
);
handleAndLogError(
error,
{ ...this.exportConfig.context },
`Failed to fetch locales for stack ${this.exportConfig.apiKey}`,
);
throw error;
});
}
async exportStack(): Promise<any> {
log.debug(`Starting stack export for: '${this.exportConfig.apiKey}'...`, this.exportConfig.context);
await fsUtil.makeDirectory(this.stackFolderPath);
log.debug(`Created stack directory at: '${this.stackFolderPath}'`, this.exportConfig.context);
return this.stack
.fetch()
.then((resp: any) => {
const stackFilePath = pResolve(this.stackFolderPath, this.stackConfig.fileName);
log.debug(`Writing stack data to: '${stackFilePath}'`, this.exportConfig.context);
fsUtil.writeFile(stackFilePath, resp);
// Track progress for stack export completion
this.progressManager?.tick(
true,
`stack: ${this.exportConfig.apiKey}`,
null,
PROCESS_NAMES.STACK_DETAILS,
);
log.success(
`Stack details exported successfully for stack ${this.exportConfig.apiKey}`,
this.exportConfig.context,
);
log.debug('Stack export completed successfully.', this.exportConfig.context);
return resp;
})
.catch((error: any) => {
log.debug(`Error occurred while exporting stack: ${this.exportConfig.apiKey}`, this.exportConfig.context);
this.progressManager?.tick(
false,
'stack export',
error?.message || PROCESS_STATUS[PROCESS_NAMES.STACK_DETAILS].FAILED,
PROCESS_NAMES.STACK_DETAILS,
);
handleAndLogError(error, { ...this.exportConfig.context });
});
}
async exportStackSettings(): Promise<any> {
log.info('Exporting stack settings...', this.exportConfig.context);
await fsUtil.makeDirectory(this.stackFolderPath);
return this.stack
.settings()
.then((resp: any) => {
fsUtil.writeFile(pResolve(this.stackFolderPath, PATH_CONSTANTS.FILES.SETTINGS), resp);
// Track progress for stack settings completion
this.progressManager?.tick(true, 'stack settings', null, PROCESS_NAMES.STACK_SETTINGS);
log.success('Exported stack settings successfully!', this.exportConfig.context);
return resp;
})
.catch((error: any) => {
this.progressManager?.tick(
false,
'stack settings',
error?.message || PROCESS_STATUS[PROCESS_NAMES.STACK_SETTINGS].FAILED,
PROCESS_NAMES.STACK_SETTINGS,
);
handleAndLogError(error, { ...this.exportConfig.context });
});
}
}