-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
352 lines (320 loc) · 9.24 KB
/
app.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
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
require("dotenv").config();
const _ = require("lodash");
const Promise = require("bluebird");
const path = require("path");
const fs = require("fs-extra");
const inquirer = require("inquirer");
const ui = new inquirer.ui.BottomBar();
const login = require("./api/login");
const helper = require("./api/util");
const { spawn } = require("child_process");
let session;
function prompt() {
let choices = [];
if (!_.isEmpty(session.jwt)) choices.push("Start Wizard");
choices.push(new inquirer.Separator());
choices.push("Login", new inquirer.Separator(), "Show Session Data", "Flush Repo Folders", "Exit");
inquirer
.prompt([
{
type: "list",
name: "commandType",
message: "What do you want to do?",
pageSize: 100,
choices
}
])
.then(async ({ commandType }) => {
switch (commandType) {
case "Exit":
return console.log('Goodbye.')
case "Login":
session.jwt = await login.call();
ui.log.write("You are logged in.");
write(session, prompt);
break;
case "Start Wizard":
session.cohort = await getCohort();
session.hwId = await getHomeworkId(await require("./api/getHomeworkList").call(session.cohort));
session.submissions = await require("./api/getSubmissions").call(session.cohort, session.hwId);
session.selectedSubmissions = await promptSubmissions(session.submissions);
await processSubmissions(session.selectedSubmissions);
console.log("===== Finished =====\n");
prompt();
break;
case "Show Session Data":
console.table(session);
prompt();
break;
case "Flush Repo Folders":
fs.emptyDirSync("./tmp");
fs.emptyDirSync("./repos");
console.log("Flushed the repos folder");
prompt();
break;
default:
console.log("Good Bye");
break;
}
});
}
function promptSubmissions(submissions) {
let filtered = _.filter(
submissions,
submission =>
!_.isEqual(_.get(submission, "submissionid", 0), 0) &&
!_.isNull(_.get(submission, "submissionDate"))
);
let choices = _.map(filtered, user => {
return { name: `${user.firstname} ${user.lastname}`, value: user };
});
//checkbox to pull down each user
return inquirer
.prompt([
{
type: "checkbox",
name: "selected",
message: "Students who submitted an assignment",
choices
}
])
.then(({ selected }) => {
return selected;
});
}
async function promptSubmissionUrl({
name,
submission: { UserId, AssignmentID }
}) {
let dataProcessor = require("./api/getSubmissionDataById");
const validateGitUrl = uri =>
helper.isValidGitUrl(uri) ? uri : promptRebuildUrl(uri);
let data = await dataProcessor.call(UserId, AssignmentID, true);
let githubUserName = dataProcessor.githubUserName(data);
let choices = _.map(dataProcessor.urls(data), value => ({
name: value,
value
}));
if (githubUserName)
choices.push(new inquirer.Separator());
choices.push({
name: `Pull from github.com/${githubUserName}`,
value: githubUserName
});
choices.push(new inquirer.Separator());
// choices.push({ name: "Overwrite Github Username", value: "NEXT" });
choices.push({ name: "Next Person", value: "NEXT" });
return inquirer
.prompt([
{
type: "list",
pageSize: 100,
name: "repo",
message: `Pull down a repository for ${name} (${UserId})`, //TODO: automate filtering
choices
}
])
.then(async ({ repo }) => {
switch (repo) {
case "NEXT":
return repo;
case githubUserName:
return await promptGithubRepo(githubUserName);
default:
return validateGitUrl(repo);
}
});
}
async function promptGithubRepo(githubUserName) {
let choices = await require("./api/getGithubRepoUrls").call(githubUserName);
return inquirer
.prompt([
{
type: "list",
name: "repo",
pageSize: 100,
message: `Repositories for ${githubUserName}`,
choices
}
])
.then(({ repo }) => {
return repo;
});
}
function launchTerminal(filePath, type="cmd"){
const fullPath = path.join(__dirname, filePath);
let cmd = spawn(type, ['/K', `start ${type}.exe`], { cwd: fullPath, detached: true})
cmd.unref()
return 'OK'
}
function performCommandInBackground(path, cmd, params, options = {}){
return new Promise((resolve, reject) => {
let child = spawn(cmd, params, { ...options, cwd: filePath, shell: true });
child.stdout.on("data", function(data) {
// output will be here in chunks
console.log(`stdout: ${data}`);
});
child.stderr.on("data", data => {
console.log(`stderr: ${data}`);
});
child.on("close", code => {
console.log(`child process exited with code ${code}`);
resolve();
});
child.on("error", err => {
console.log("Failed to start subprocess.", err);
reject(err);
});
});
}
function promptPostPull(filePath) {
return inquirer
.prompt([
{
type: "list",
pageSize: 100,
name: "post",
message: "Post Script",
choices: [
{ name: `Finished with ${filePath}`, value: "next" },
new inquirer.Separator(),
{ name: "Send 'npm i'", value: "npm i" },
{ name: "List files/folders", value: "ls" },
new inquirer.Separator(),
{ name: `Cmd window for ${filePath}`, value: '_new' },
{ name: `Bash window for ${filePath}`, value: '_newBash' },
]
}
])
.then(async ({ post }) => {
switch (post) {
case "next":
return "NEXT";
case "_newBash":
launchTerminal(filePath, "bash.exe")
return promptPostPull(filePath);
case "_new":
launchTerminal(filePath, "cmd.exe")
return promptPostPull(filePath);
case "npm i":
await performCommandInBackground(filePath, 'npm install')
return promptPostPull(filePath);
case "ls":
await performCommandInBackground(filePath, 'dir') //todo: account for macos
return promptPostPull(filePath);
default:
return promptPostPull(filePath);
}
});
}
function getCohort() {
return inquirer
.prompt([
{
type: "list",
name: "cohort",
pageSize: 4,
message: "Select Cohort?",
choices: [
{ name: "Mon/Wed", value: 499 },
{ name: "Tues/Thu", value: 406 }
]
}
])
.then(({ cohort }) => {
return cohort;
});
}
function getHomeworkId(list) {
let choices = _.map(list, item => {
return { name: item.Name, value: item.ID };
});
choices.push(new inquirer.Separator());
return inquirer
.prompt([
{
type: "list",
pageSize: 100,
name: "answer",
message: "Select Homework",
choices: choices
}
])
.then(({ answer }) => {
return answer;
});
}
async function processSubmissions(submissions) {
const processSubmission = async submission => {
const name = `${_.get(submission, "firstname")} ${_.get(
submission,
"lastname"
)}`;
const url = await promptSubmissionUrl({ name, submission });
if (_.isEqual(url, "NEXT")) return submission;
let localRepoPath = `./repos/${name}`;
fs.emptyDirSync(localRepoPath);
await require("./api/pullRepo").call(url, localRepoPath);
await promptPostPull(`./repos/${name}`);
return processSubmission(submission);
};
return await Promise.each(submissions, processSubmission);
}
function promptRebuildUrl(uri) {
let url = _.trimStart(uri, "http://");
url = _.trimStart(url, "https://");
let choices1 = _.split(url, ".");
let choices2 = _.split(url, "/");
let choices = choices1.concat(choices2);
let formatted = () =>
inquirer
.prompt([
{
type: "list",
pageSize: 100,
name: "userName",
message: "Choose the USERNAME for the url",
choices
},
{
type: "list",
pageSize: 100,
name: "repoName",
message: "Choose the REPOSITORY name for the url",
choices
},
{
type: "confirm",
name: "isOk",
message: ({ userName, repoName }) =>
`git clone from: https://github.com/${userName}/${repoName}?`
}
])
.then(({ userName, repoName, isOk }) => {
if (!isOk) return formatted();
return `https://github.com/${userName}/${repoName}`;
});
return formatted();
}
function start() {
fs.readJson("./cookie.json", { throws: false }, (err, jsonData) => {
if (err) console.error(err);
session = jsonData || {
homeworkList: [],
pullOptions: [],
jwt: false
};
if (session.jwt) {
ui.log.write("You are logged in.");
login.setAuth(session.jwt);
}
prompt();
});
}
function write(session = {}, cb) {
fs.writeJson("./cookie.json", session, err => {
if (err) return console.error(err);
cb();
});
}
start();