This repository was archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.js
More file actions
468 lines (399 loc) · 11.4 KB
/
Copy pathcli.js
File metadata and controls
468 lines (399 loc) · 11.4 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
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
const { pick } = require('underscore');
const { rnKeys: renameKeys, is, touch, load } = require('ak-tools');
const dayjs = require('dayjs');
const dateFormat = `YYYY-MM-DD`;
const types = require('./types.js');
const path = require('path');
// https://www.npmjs.com/package/inquirer
const inquirer = require('inquirer');
exports.cli = async function () {
/** @type {types.Source} */
let source = {};
/** @type {types.Target} */
let target = {};
/** @type {types.Options} */
let options = {};
const userConfig = await checkForCliConfig(process.argv.slice().pop());
if (userConfig) {
try {
({ source, target, options } = userConfig);
return { source, target, options };
}
catch (e) {
console.log('invalid configuration file... quitting!');
process.exit();
}
}
const ask = inquirer.createPromptModule();
console.log(welcome);
const whatIsYourPurpose = await ask(firstQuestions());
if (!whatIsYourPurpose.intent) {
console.log('\tthose are the only things i know how to do! sorry!\n');
console.log(whomp);
process.exit(0);
}
console.log(`\tcool... we can definitely do that... ${cool}\n`);
console.log('checking for .env credentials...');
({ envCredsSource: source, envCredsTarget: target } = exports.getEnvCreds());
if (isValid(source) && isValid(target)) {
console.log(`\t👍 yep... i see your credentials... ${letsgo}`);
}
//credentials
else {
console.log(`\t👎 didn't find a complete .env file... so...\n`);
const howAuth = await ask(authQuestions());
console.log('\n');
if (howAuth.auth === "service") {
const authSrc = await ask([
...authQuestions("service", "SOURCE", source),
...standardQuestions("SOURCE", source)
]);
console.log('\n');
source.acct = authSrc.acct;
source.pass = authSrc.pass;
source.project = authSrc.project;
source.region = authSrc.region;
if (whatIsYourPurpose.intent === 'copy') {
//need a target
const authDest = await ask([
...authQuestions("service", "TARGET", target),
...standardQuestions("TARGET", target)
]);
target.acct = authDest.acct;
target.pass = authDest.pass;
target.project = authDest.project;
target.region = authDest.region;
}
}
if (howAuth.auth === "bearer") {
const authSrc = await ask([
...authQuestions("bearer", "SOURCE", source),
...standardQuestions("SOURCE", source)
]);
source.bearer = authSrc.bearer;
source.project = authSrc.project;
source.region = authSrc.region;
console.log('\n');
if (whatIsYourPurpose.intent === 'copy') {
//need a target
const authDest = await ask([
...authQuestions("bearer", "TARGET", target),
...standardQuestions("TARGET", target)
]);
target.bearer = authDest.bearer;
target.project = authDest.project;
target.region = authDest.region;
}
}
}
console.log('\n');
// options
if (whatIsYourPurpose.intent === 'copy') {
const optConfig = await ask(optionsQuestions(source.project, target.project));
options.shouldGenerateSummary = optConfig.shouldGenerateSummary;
options.shouldCopyEvents = optConfig.shouldCopyEvents;
options.shouldCopyProfiles = optConfig.shouldCopyProfiles;
options.shouldCopySchema = optConfig.shouldCopySchema;
options.shouldCopyEntities = true;
source.dash_id = optConfig.dash_id
?.split(",")
?.map(s => s.trim())
?.filter(a => a)
?.map(Number) || [];
if (optConfig.shouldCopyEvents) {
console.log('\n');
const dates = await ask(dateQuestions(source.project));
source.start = dayjs(dates.start).format(dateFormat);
source.end = dayjs(dates.end).format(dateFormat);
options.timeOffset = Number(dates.timeOffset);
}
}
else {
options = {
transformEventsFunc: x => x,
transformProfilesFunc: x => x,
shouldGenerateSummary: true,
shouldCopyEvents: false,
shouldCopyProfiles: false,
shouldCopyEntities: false,
shouldCopySchema: false,
silent: false,
skipPrompt: false,
timeOffset: 0
};
}
console.log("\n");
const shouldSave = await ask(saveConfig());
if (shouldSave.saveConfig) {
const saved = await touch(`./mpMigrate-${source.project}-to-${target.project}.json`, { source, target, options }, true);
console.log(`configuration saved to ${saved}`);
console.log("\n");
}
return {
source, target, options
};
};
exports.getEnvCreds = function () {
//sweep .env to pickup creds
require('dotenv').config({ override: true });
/** @type {types.Source} */
let envCredsSource = {
acct: "",
pass: "",
bearer: "",
project: "",
start: "",
end: "",
region: "",
dash_id: []
};
/** @type {types.Target} */
let envCredsTarget = {
acct: "",
pass: "",
bearer: "",
project: "",
region: "US"
};
const envVarsSource = pick(process.env, `SOURCE_ACCT`, `SOURCE_PASS`, `SOURCE_PROJECT`, `SOURCE_DATE_START`, `SOURCE_DATE_END`, `SOURCE_REGION`, `SOURCE_DASH_ID`, `SOURCE_BEARER`);
const envVarsTarget = pick(process.env, `TARGET_ACCT`, `TARGET_PASS`, `TARGET_PROJECT`, `TARGET_REGION`, `TARGET_BEARER`);
const sourceKeyNames = { SOURCE_ACCT: "acct", SOURCE_PASS: "pass", SOURCE_PROJECT: "project", SOURCE_DATE_START: "start", SOURCE_DATE_END: "end", SOURCE_REGION: "region", SOURCE_DASH_ID: "dash_id", SOURCE_BEARER: "bearer" };
const targetKeyNames = { TARGET_ACCT: "acct", TARGET_PASS: "pass", TARGET_PROJECT: "project", TARGET_REGION: "region", TARGET_BEARER: "bearer" };
// @ts-ignore
envCredsSource = renameKeys(envVarsSource, sourceKeyNames);
// @ts-ignore
envCredsTarget = renameKeys(envVarsTarget, targetKeyNames);
if (dayjs(envCredsSource.start).isValid()) {
envCredsSource.start = dayjs(envCredsSource.start).format(dateFormat);
}
else {
envCredsSource.start = dayjs().format(dateFormat);
}
if (dayjs(envCredsSource.end).isValid()) {
envCredsSource.end = dayjs(envCredsSource.end).format(dateFormat);
}
else {
envCredsSource.end = dayjs().format(dateFormat);
}
// region defaults
if (!envCredsSource.region) envCredsSource.region = `US`;
if (!envCredsTarget.region) envCredsTarget.region = `US`;
// dash_ids
if (envCredsSource.dash_id) {
// @ts-ignore
envCredsSource.dash_id = envCredsSource.dash_id.split(",").map(a => Number(a.trim()));
// @ts-ignore
let dashIdsValid = envCredsSource.dash_id.every((dashId) => is(Number, dashId) && !isNaN(dashId));
if (!dashIdsValid) {
console.log(`ERROR: your source_dash_id needs to be a number (or a comma separated list of numbers) got:`);
console.log(envCredsSource.dash_id.join('\t\n'));
console.log('\ndouble check your .env and try again');
process.exit(1);
}
}
// else {
// envCredsSource.dash_id = [];
// }
return {
envCredsSource,
envCredsTarget
};
};
function notEmpty(str) {
if (!str) return "your answer can't be empty...";
return true;
}
function isValid(p) {
if (!(p.acct && p.pass) && !p.bearer) {
return false;
}
if (!p.project) {
return false;
}
return true;
}
function dashCopyValidate(answer) {
try {
if (answer === "") return true;
const parsed = answer.split(",")
.map(s => s.trim())
.filter(a => a)
.map(Number);
if (parsed.every((dashId) => is(Number, dashId) && !isNaN(dashId))) {
return true;
}
else {
return "board ids are numbers only";
}
}
catch (e) {
return "hmmm... i couldn't understand that... try again";
}
}
// QUESTIONS
function firstQuestions() {
return [
{
type: "list",
message: "what are you trying to do?",
name: "intent",
choices: [
{ name: "enumerate saved reports", value: "report" },
{ name: "copy between projects", value: "copy" },
{ name: "something else...", value: false }
]
}];
}
function standardQuestions(label = `SOURCE`, config = {}) {
return [{
type: "input",
message: `${label} PROJECT: what is your project's ID?`,
name: "project",
validate: notEmpty,
default: config.project || ""
},
{
type: "input",
message: `${label} PROJECT: what is your project's region?`,
name: "region",
default: "US"
}];
}
function authQuestions(type, label, config = {}) {
if (type === "service") {
return [
{
type: "input",
message: `${label} PROJECT: what is your service account user name?`,
name: "acct",
validate: notEmpty,
default: config.acct || ""
},
{
type: "input",
message: `${label} PROJECT: what is your service account secret?`,
name: "pass",
validate: notEmpty,
default: config.pass || ""
}];
}
if (type === "bearer") {
return [
{
type: "input",
message: `${label} PROJECT: what is your bearer token?`,
name: "bearer",
validate: notEmpty,
default: config.bearer || ""
}
];
}
//first question
else {
return [
{
type: "list",
message: "how do you want to authenticate?",
name: "auth",
choices: [
{ name: "service account", value: "service" },
{ name: "bearer token", value: "bearer" }
]
}
];
}
}
function optionsQuestions(srcPid, destPid) {
return [
{
type: "input",
message: `copy specific boards(s) from project ${srcPid} to project ${destPid}?`,
suffix: `\n\tenter comma separated list of board ids in project ${srcPid} (or leave blank to copy all boards)\n`,
name: "dash_id",
validate: dashCopyValidate
},
{
type: "confirm",
message: `do you want to copy all EVENTS from project ${srcPid} to project ${destPid}?`,
name: "shouldCopyEvents",
default: false
},
{
type: "confirm",
message: `do you want to copy all PROFILES from project ${srcPid} to project ${destPid}?`,
name: "shouldCopyProfiles",
default: false
},
{
type: "confirm",
message: `do you want to copy the SCHEMA (lexicon) from project ${srcPid} to project ${destPid}?`,
name: "shouldCopySchema",
default: false
},
{
type: "confirm",
message: `do you want to generate a log of everything that was done?`,
name: "shouldGenerateSummary",
default: true
}
];
}
function dateQuestions(srcPid) {
return [
{
type: "input",
message: `what is the start date for project ${srcPid}'s event export?`,
suffix: "\nYYYY-MM-DD\n",
name: "start",
validate: notEmpty,
default: dayjs().subtract(30, 'd').format(dateFormat)
},
{
type: "input",
message: `what is the end date for project ${srcPid}'s event export?`,
suffix: "\nYYYY-MM-DD\n",
name: "end",
default: dayjs().format(dateFormat)
},
{
type: "input",
message: `(if project ${srcPid} was created before Feb 2023): what is the UTC timezone offset for for project ${srcPid}?`,
suffix: "\n# of hours\n",
name: "timeOffset",
default: 0
},
];
}
function saveConfig() {
return [
{
type: "confirm",
message: `would you like to save your configuration file for re-use?`,
name: "saveConfig",
default: true
},
];
}
async function checkForCliConfig(maybeJson) {
let file = null;
try {
file = await load(path.resolve(maybeJson), true, 'utf-8', true);
return file;
}
catch (e) {
return file;
}
}
const hero = String.raw`
┌┬┐┌─┐ ┌┬┐┬┌─┐┬─┐┌─┐┌┬┐┌─┐
│││├─┘ │││││ ┬├┬┘├─┤ │ ├┤
┴ ┴┴ ┴ ┴┴└─┘┴└─┴ ┴ ┴ └─┘
`;
const banner = `\n\t(by AK) v${require('./package.json').version}
this script can COPY data (events + users) as well as saved entities (boards, reports, cohorts, custom event/props)\n\t ...from one project to another\n\n`;
const welcome = hero.concat(banner);
const whomp = String.raw`
¯\_(ツ)_/¯
`;
const letsgo = String.raw`ᕕ( ಠ‿ಠ)ᕗ`;
const cool = String.raw`( ͡° ͜ʖ ͡°)`;