forked from mcadonline/canvas-jenzabar-integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·187 lines (162 loc) · 5.36 KB
/
cli.js
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
#!/usr/bin/env node
/* eslint-disable no-console */
import meow from 'meow';
import inquirer from 'inquirer';
import { DateTime } from 'luxon';
import main from './main.js';
import writeToFile from './utils/writeToFile.js';
import generators from './generators/index.js';
import services from './services/index.js';
import settings from './settings.js';
const logger = {
log: (msg) => console.log(msg),
info: (msg) => console.warn(`\n ℹ️ Info: ${msg}`),
warn: (msg) => console.warn(`\n⚠️ Warning: ${msg}\n`),
error: (msg) => console.error(`\n❌ Error: ${msg}\n`),
};
const generatorDict = {
users: generators.users,
'enrollment-adds': generators.enrollAdds,
'enrollment-drops': generators.enrollDrops,
'enrollment-faculty': generators.enrollFaculty,
'enrollment-faculty-senate': generators.enrollFacultySenate,
'enrollment-sandboxes': generators.enrollSandbox,
'course-shells': generators.courseShells,
'course-sandboxes': generators.courseSandboxes,
'course-updates': generators.courseUpdates,
'courses-to-publish': generators.coursesToPublish,
sections: generators.sections,
};
const isValidGenerator = (str) => Object.keys(generatorDict).includes(str);
const listGeneratorsInCLI = ({ indentSize = 8, indentFirst = true }) =>
Object.keys(generatorDict)
// should the first generator be indented?
// this is helpful if this function generates a list
// in another string template
.map((str, i) => (!indentFirst && i === 0 ? str : ' '.repeat(indentSize) + str))
.join('\n');
async function promptUser() {
const { generatorKey, destinations } = await inquirer.prompt([
{
type: 'list',
name: 'generatorKey',
message: 'What do you want to generate?',
choices: Object.keys(generatorDict),
},
{
type: 'checkbox',
name: 'destinations',
message: 'Destinations? (in addition to stdout)',
choices: ['file', 'upload'],
},
]);
const userChoices = {
generatorKey,
destinations: {
file: destinations.includes('file'),
upload: destinations.includes('upload'),
},
};
if (!userChoices.destinations.upload) return userChoices;
const followups = await inquirer.prompt([
{
type: 'checkbox',
name: 'uploadOptions',
message: 'Upload Options?',
choices: ['override_sis_stickiness'],
},
]);
return {
...userChoices,
uploadOptions: {
override_sis_stickiness: followups.uploadOptions.includes('override_sis_stickiness'),
},
};
}
async function cli() {
const { flags, input } = meow(
`
Usage
$ canvas-jenzabar <generator> <options>
Generators
${listGeneratorsInCLI({ indentSize: 8, indentFirst: false })}
Options
--help help and options
--file save csv to a file in \`./tmp\` folder
--upload upload csv to Canvas via SIS Imports
--override-sis-stickiness on csv upload, override any sis stickiness
--current-date-time [dt] use given iso datetime for current datetime
Example
$ canvas-jenzabar users --upload
`,
{
flags: {
file: { type: 'boolean' },
upload: { type: 'boolean' },
overrideSisStickiness: { type: 'boolean' },
currentDateTime: {
type: 'string',
default: DateTime.local().toISO(),
},
},
}
);
if (flags.overrideSisStickiness && !flags.upload) {
logger.error(`option '--override-sis-stickiness' can only be used with '--upload`);
process.exit();
}
let destinations = {
file: flags.file,
upload: flags.upload,
};
let uploadOptions = {
override_sis_stickiness: flags.overrideSisStickiness,
};
// if input is given and invalid, error
let generatorKey = input ? input[0] : null;
if (generatorKey && !isValidGenerator(generatorKey)) {
logger.error(
`${generatorKey} is not a valid generator. Use --help option to see valid generators.`
);
}
logger.log(`
🌕 CANVAS HOST:\t${settings.canvas.hostname}
🔵 JENZABAR HOST:\t${settings.jex.server}
🕐 DATETIME:\t\t${flags.currentDateTime}
`);
// if no generator given as cli input
// prompt user for generator and destination
if (!generatorKey) {
const answers = await promptUser();
({ generatorKey, destinations, uploadOptions } = answers);
}
try {
const generatorFn = generatorDict[generatorKey];
const generatorFnBoundToFlags = generatorFn.bind(null, flags);
const csv = await main(generatorFnBoundToFlags);
logger.log(csv);
logger.info(JSON.stringify(destinations));
if (csv.length === 0) {
logger.log('🤓 No data generated. Done!');
return;
}
if (destinations.file) {
// save to file
const fileDest = await writeToFile(csv, { filenamePrefix: generatorKey });
logger.log(`👍 Saving to file: ${fileDest}`);
}
if (destinations.upload) {
// upload to canvas
logger.log(`⤴️ Uploading Data to: ${settings.canvas.hostname}`);
const uploadUrl = [
`/accounts/1/sis_imports?extensions=csv`,
uploadOptions.override_sis_stickiness ? `&override_sis_stickiness=true` : '',
].join('');
const res = await services.canvas.post(uploadUrl, csv);
logger.info(`Response: ${JSON.stringify(res)}`);
}
} catch (err) {
console.error(err.message);
}
}
cli();