-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashbrown-cli.js
More file actions
534 lines (398 loc) · 13 KB
/
hashbrown-cli.js
File metadata and controls
534 lines (398 loc) · 13 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#!/usr/bin/env node
'use strict';
const OS = require('os');
const Util = require('util');
const FileSystem = require('fs');
const Path = require('path');
const ChildProcess = require('child_process');
const ReadLine = require('readline');
const URL = require('url');
const FileHelper = require('./FileHelper');
const RequestHelper = require('./RequestHelper');
const MAX_REQUEST_REDIRECTS = 10;
const INDENT = ' ';
const COLUMN_SPACING = ' ';
/**
* Checks arguments for validity
*/
function checkArgs(args, minAmount, usageString) {
if(!args || args.length < minAmount) {
console.log('Usage: hashbrown-cli ' + usageString);
process.exit()
}
}
/**
* Writes data to a config file
*/
async function writeConfig(filename, content) {
let baseDir = Path.join(OS.homedir(), '.config', 'hashbrown-cli');
await FileHelper.makeDirectory(baseDir);
await FileHelper.write(content, Path.join(baseDir, filename + '.json'));
}
/**
* Writes data to a cache file
*/
async function writeCache(filename, content) {
let baseDir = Path.join(OS.homedir(), '.config', 'hashbrown-cli', 'cache');
await FileHelper.makeDirectory(baseDir);
await FileHelper.write(content, Path.join(baseDir, filename + '.json'));
return Path.join(baseDir, filename + '.json');
}
/**
* Reads data from a config file
*/
async function readConfig(filename) {
let baseDir = Path.join(OS.homedir(), '.config', 'hashbrown-cli');
try {
let file = await FileHelper.read(Path.join(baseDir, filename + '.json'));
if(!file || file.length < 1) { return {}; }
return JSON.parse(file);
} catch(e) {
return {};
}
}
/**
* Gets the current session
*/
async function getSession(skipLocation = false) {
let config = await readConfig('session');
if(!config.host || !config.token) {
throw new Error('Not logged in. Please use "hashbrown-cli login" first');
}
if(!skipLocation && (!config.project || !config.environment)) {
throw new Error('Project and environment not set. Please use "hashbrown-cli use" first');
}
return config;
}
/**
* Prints strings in columns
*/
function columns(items, spacingMultiplier = 1) {
let row = '';
let spacing = '';
for(let i = 0; i < spacingMultiplier; i++) {
spacing += COLUMN_SPACING;
}
for(let i in items) {
let item = items[i];
if(item === INDENT) {
row += INDENT;
} else if(i < items.length - 1) {
if(item.length > spacing.length) {
item = item.slice(0, spacing.length - 5) + '... ';
}
row += item;
if(item.length < spacing.length) {
row += spacing.slice(0, -item.length);
}
} else {
row += item;
}
}
console.log(row);
}
/**
* Makes a resource request
*/
async function resourceRequest(method, category, id, data) {
let session = await getSession();
let url = session.host + '/api/' + session.project + '/' + session.environment + '/' + category;
if(id) {
url += '/' + id;
}
if(url.indexOf('?') > -1) {
url += '&';
} else {
url += '?';
}
url += 'token=' + session.token;
let result = await RequestHelper.request(method, url, data);
if(typeof result === 'string') {
console.log(result);
}
return result;
}
/**
* Edits a resource
*/
async function editResource(category, id) {
if(!id || id.length < 3) { throw new Error('Id should be minimum 3 characters'); }
let all = await resourceRequest('get', category);
let data = null;
for(let resource of all) {
if(resource.id.indexOf(id) === 0) {
data = resource;
id = data.id;
break;
}
}
if(!data) {
throw new Error(category[0].toUpperCase() + category.slice(1) + ' by id "' + id + '" not found');
}
let cachePath = await writeCache(id, data);
let editorName = await readConfig('settings').editor || process.env.EDITOR || 'vi';
await new Promise((resolve, reject) => {
let editor = ChildProcess.spawn(editorName, [ cachePath ], { stdio: 'inherit' });
editor.on('exit', (e, code) => {
resolve();
});
});
data = await FileHelper.read(cachePath);
data = JSON.parse(data.toString('utf8'));
await resourceRequest('post', category, id, data);
await FileHelper.remove(cachePath);
}
/**
* Gets a resource name
*/
function getResourceName(resource) {
let name = '';
if(resource.properties) {
if(typeof resource.properties.title === 'string') {
name = resource.properties.title;
} else if(typeof resource.properties.title === 'object') {
name = Object.values(resource.properties.title).join(' / ');
}
} else if(resource.title) {
name = resource.title;
} else if(resource.name) {
name = resource.name;
}
if(!name) { name = '(no name)'; }
return name;
}
/**
* Handles any resource command
*/
async function resourceCommand(category, args) {
checkArgs(args, 1, category + ' <command> [<id>]');
let session = await getSession();
switch(args[0]) {
case 'edit':
checkArgs(args, 2, category + ' edit <id>');
await editResource(category, args[1]);
break;
case 'ls':
header(session);
let all = await resourceRequest('get', category);
all = all.sort((a, b) => {
let aName = getResourceName(a);
let bName = getResourceName(b);
if(aName < bName) { return -1; }
if(bName < aName) { return 1; }
return 0;
});
for(let resource of all) {
columns([getResourceName(resource), resource.id], 3);
}
footer();
break;
case 'new':
let verb = 'new';
if(category === 'content') {
checkArgs(args, 2, category + ' new <schema>');
verb += '?schemaId=' + args[1];
}
let resource = await resourceRequest('post', category, verb);
await editResource(category, resource.id);
break;
case 'rm':
checkArgs(args, 2, category + ' rm <id>');
await resourceRequest('delete', category, args[1]);
break;
default:
throw new Error('Unknown command "' + args[0] + '"');
}
}
/**
* Prints the session header
*/
function header(session, skipLocation) {
console.log();
if(!skipLocation && session.project && session.environment) {
console.log(session.project + ':' + session.environment + '@' + URL.parse(session.host).hostname);
} else {
console.log(URL.parse(session.host).hostname);
}
console.log('--------------------');
}
/**
* Prints the session footer
*/
function footer() {
console.log();
}
class HashBrown {
/**
* Shows the help dialogue
*/
static help() {
console.log('Usage: hashbrown-cli <command> [<args>]');
console.log();
console.log('general');
columns([INDENT, 'get', 'Get a settings value, such as "editor"']);
columns([INDENT, 'help', 'Display this help dialogue']);
columns([INDENT, 'login', 'Log in to a HashBrown instance']);
columns([INDENT, 'set', 'Set a settings value, such as "editor"']);
columns([INDENT, 'use', 'Switch between projects and environments']);
console.log();
console.log('connection');
columns([INDENT, 'edit', 'Edit a connection']);
columns([INDENT, 'ls', 'List all available connections']);
columns([INDENT, 'new', 'Create a new connection']);
columns([INDENT, 'rm', 'Remove a connection']);
console.log();
console.log('content');
columns([INDENT, 'edit', 'Edit a content node']);
columns([INDENT, 'ls', 'List all available content']);
columns([INDENT, 'new', 'Create a new content node']);
columns([INDENT, 'rm', 'Remove a content node']);
console.log();
console.log('form');
columns([INDENT, 'edit', 'Edit a form']);
columns([INDENT, 'ls', 'List all available forms']);
columns([INDENT, 'new', 'Create a new form']);
columns([INDENT, 'rm', 'Remove a form']);
console.log();
console.log('schema');
columns([INDENT, 'edit', 'Edit a schema']);
columns([INDENT, 'ls', 'List all available schemas']);
columns([INDENT, 'new', 'Create a new schema']);
columns([INDENT, 'rm', 'Remove a schema']);
console.log();
console.log('project');
columns([INDENT, 'ls', 'List all projects']);
}
/**
* Logs in the user
*/
static async login(args) {
checkArgs(args, 3, 'login <host> <username> <password>');
try {
let token = await RequestHelper.request('post', args[0] + '/api/user/login?persist=false', { username: args[1], password: args[2] });
console.log('Login successful, received token', token);
let session = await readConfig('session');
session.host = args[0];
session.token = token;
delete session.project;
delete session.environment;
await writeConfig('session', session);
} catch(e) {
console.log('Login failed: ', e.message);
}
}
/**
* Handles content operations
*/
static async content(args) {
await resourceCommand('content', args);
}
/**
* Handles schema operations
*/
static async schema(args) {
await resourceCommand('schemas', args);
}
/**
* Handles connection operations
*/
static async connection(args) {
await resourceCommand('connections', args);
}
/**
* Handles form operations
*/
static async form(args) {
await resourceCommand('forms', args);
}
/**
* Switches between projects/environments
*/
static async use(args) {
checkArgs(args, 2, 'use <project> <environment>');
let session = await getSession(true);
session.project = args[0];
session.environment = args[1];
await writeConfig('session', session);
}
/**
* Gets the version fo this app
*/
static async version() {
let app = await FileHelper.read(Path.join(__dirname, 'package.json'));
app = JSON.parse(app.toString('utf8'));
console.log(app.version);
}
/**
* Handles project requests
*/
static async project(args) {
checkArgs(args, 1, 'project <command> [<id>]');
let session = await getSession(true);
switch(args[0]) {
case 'ls':
header(session, true);
let all = await RequestHelper.request('get', session.host + '/api/server/projects?token=' + session.token);
for(let i in all) {
let project = all[i];
let line = [];
if(project.settings && project.settings.info) {
line.push(project.settings.info.name);
}
line.push(project.id);
columns(line, 2);
if(project.environments) {
for(let environment of project.environments) {
columns([' ', '- ' + environment], 2);
}
} else {
columns([' ', '- live'], 2);
}
if(i < all.length - 1) {
console.log();
}
}
footer();
break;
}
}
/**
* Sets a setting parameter
*/
static async set(args) {
checkArgs(args, 2, 'set <name> <value>');
let config = await readConfig('settings');
config[args[0]] = args[1];
await writeConfig('settings', config);
}
/**
* Gets a setting parameter
*/
static async get(args) {
checkArgs(args, 1, 'get <name>');
let config = await readConfig('settings');
console.log(config[args[0]]);
}
/**
* The main method
*/
static async main() {
if(!process.argv || process.argv.length < 3) {
this.help();
process.exit(0);
}
let cmd = process.argv[2].replace('--', '');
if(typeof this[cmd] !== 'function') {
console.log('Unknown command "' + process.argv[2] + '"');
process.exit(1);
}
try {
await this[cmd](process.argv.slice(3));
process.exit(0);
} catch(e) {
console.log('ERROR:', e.message);
process.exit(1);
}
}
}
HashBrown.main();