-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
executable file
·296 lines (275 loc) · 8.84 KB
/
index.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
#!/usr/bin/env node
const yargs = require('yargs');
const loGet = require('lodash.get');
const isEqual = require('lodash.isequal');
const pick = require('lodash.pick');
const Arena = require('are.na');
const editor = require('external-editor');
const yaml = require('js-yaml');
const arena = new Arena({ accessToken: process.env.ARENA_ACCESS_TOKEN });
const logError = err => {
if (err.response && err.response.data)
console.error(`${err.response.data.code} Error: ${err.response.data.message} (${err.response.data.description})`);
else console.error(err);
process.exit(1);
};
const selectable = {
title: { key: 'title' },
author: { key: 'user.username' },
date: { key: 'created_at' },
slug: { key: 'slug' },
link: { key: 'slug', method: x => 'https://www.are.na/channels/' + x },
id: { key: 'id' },
blockLink: { key: 'id', method: x => 'https://www.are.na/block/' + x },
userLink: { key: 'slug', method: x => 'https://www.are.na/' + x },
userAuthor: { key: 'username' }
};
const types = yargs => yargs.positional('type', {
choices: ['channel', 'channels', 'block', 'blocks']
});
const isMultiple = (argv) => {
return ((argv.type === 'channels' || argv.type === 'blocks') || argv.multiple);
};
const printOut = ({ select, multiple, type, json, join, pretty }) => (data) => {
if (json) {
return console.log(JSON.stringify(multiple ? data : data[0], undefined, pretty ? 2 : 0));
}
select = select.map(item => {
if (item === 'link' && type.match(/^block/))
item = 'blockLink';
else if (item === 'slug' && type.match(/^block/))
item = 'id';
else if (item === 'link' && type.match(/^user/))
item = 'userLink';
else if (item === 'author' && type.match(/^user/))
item = 'userAuthor';
return selectable[item];
});
data.map(d => {
if (type.match(/s$/) && d[type]) {
// d = d.channels;
d[type].map(d => {
let output = select.map(s => {
return s.method ?
s.method(loGet(d, s.key))
: loGet(d, s.key);
});
console.log(output.join(join));
});
} else {
let output = select.map(s => {
return s.method ?
s.method(loGet(d, s.key))
: loGet(d, s.key);
});
console.log(output.join(join));
}
});
};
const commands = command => argv => {
let { type, titles, status, per, page, ids, debug,
select, json, join, pretty, file, query } = argv;
let multiple = isMultiple(argv);
let method = type.replace(/s$/, '');
// let iterables = command === 'create' ? titles : ids;
let iterables = (function () {
switch (command) {
case 'create':
return titles;
case 'get':
return ids;
case 'search':
return query;
default:
return ids;
}
})();
if (!select && argv.link)
select = ['link'];
// Disable automatic stdin reading for now...
// if (!file) {
// if ((command === 'get' && !iterables.length && argv.type !== 'channels') ||
// (command === 'create' && iterables.length <= (method === 'block' ?
// 1 : 0))) {
// console.warn('Not enough arguments, reading from stdin...');
// file = '-';
// }
// }
if (file) {
if (file === '-') file = '/dev/stdin';
let content = require('fs').readFileSync(file, 'utf8').trim();
content = content.length ?
(multiple ? content.split('\n') : [content])
: [];
iterables = [...iterables, ...content];
}
let channel;
let promises = () => [];
let log;
switch (command) {
case 'get':
select = select || ['title', 'author', 'slug'];
if (!multiple && iterables.length)
iterables = [iterables.join(' ')];
if (!iterables.length && argv.type === 'channels')
iterables = [''];
promises = () => iterables.map(id => arena[method](id, { page, per, status }).get());
break;
case 'create':
select = select || ['slug'];
if (method === 'block')
channel = iterables.shift();
if (!multiple && iterables.length)
iterables = [iterables.join(' ')];
promises = () => iterables.map(item => arena[method]().create(channel || item, channel ? item : status));
break;
case 'delete':
promises = () => iterables.map(id => arena[method](id).delete())
log = () => console.log('OK.');
break;
case 'search':
select = select || ['title', 'author', 'slug'];
if (!argv.multiple)
iterables = [iterables.join(' ')];
promises = () => iterables.map(query => arena.search(query || undefined)
[type]({ per, page, status })
.then(d => ({ [type]: d })));
break;
case 'edit':
select = select || ['slug'];
let editable = ['title'];
if (method === 'block')
editable = ['content', 'title', 'description'];
else if (method === 'channel')
editable = ['title', 'status'];
promises = () => iterables.map(slug => {
return arena[method](slug).get().then(item => {
let content = {}, before = {};
if (argv.yaml) {
before = pick(item, editable);
content = yaml.safeLoad(editor.edit(yaml.safeDump(before,
{ lineWidth: 78 })));
} else {
before[editable[0]] = item[editable[0]];
content[editable[0]] = editor.edit(before[editable[0]])
.replace(/[\r\n]+$/, '');
}
if (!isEqual(content, before)) {
// Use Object.assign: currently a bug in are.na's API prevents
// updating partially without wiping out the other fields (i.e.:
// passing only "content" to be updated will wipe out title and
// description if they are not set)
return arena[method](item.id)
.update(Object.assign({}, pick(item, editable), content))
.then(result => {
// Returns new object for channels, not blocks
return Promise.resolve((result ? result.id : slug) + ': OK.');
});
} else {
return Promise.resolve(slug + ': No change, not updated.');
}
});
});
log = message => message.map(m => console.log(m));
break;
}
if (debug) {
log = () => {};
arena.requestHandler = (...req) => new Promise((resolve, reject) => {
console.log(req[0].toUpperCase(), ...req.slice(1));
resolve({});
});
}
log = log || printOut({ multiple, select, type, json, join, pretty });
Promise.all(promises())
.then(log)
.catch(logError);
};
yargs
.command(['get <type> [slugs|ids..]', '$0'], 'retrieve channels or blocks',
types, commands('get'))
.command(['create <type> [titles|urls..]', 'new', 'add'],
'create channels or blocks', types, commands('create'))
.command('delete <type> [slugs|ids..]', 'delete channels or blocks',
types, commands('delete'))
.command('search <type> [query..]', 'search channels, blocks, or users',
yargs => yargs.positional('type', {
choices: ['channels', 'blocks', 'users']
}), commands('search'))
.command('edit <type> <slugs|ids..>', 'edit a block or channel', types,
commands('edit'))
.options({
m: {
alias: 'multiple',
type: 'boolean',
describe: 'Accept multiple arguments and perform the command for each'
},
s: {
alias: 'select',
type: 'array',
choices: ['title', 'author', 'date', 'slug', 'link', 'id'],
describe: 'Fields to select and print'
},
l: {
alias: 'link',
type: 'boolean',
describe: 'Print only link[s]'
},
j: {
alias: 'join',
type: 'string',
default: ', ',
describe: 'String to join fields by'
},
p: {
alias: 'page',
type: 'number',
describe: 'Get results from the specified page'
},
x: {
alias: 'per',
type: 'number',
describe: 'Get this many results per page'
},
S: {
alias: 'status',
type: 'string',
choices: ['public', 'closed', 'private'],
describe: 'Status of new, updated, or retrieved channel[s]'
},
J: {
alias: 'json',
type: 'boolean',
describe: 'Output JSON rather than the default textual format'
},
P: {
alias: 'pretty',
type: 'boolean',
describe: 'Pretty print JSON'
},
f: {
alias: 'file',
type: 'string',
describe: 'Read arguments from this file (use - for stdin)'
},
y: {
alias: 'yaml',
type: 'boolean',
default: true,
describe: 'Edit blocks/channels using yaml'
},
D: {
alias: ['dry', 'debug'],
type: 'boolean',
describe: 'Don\'t make the requests, print them'
},
v: {
alias: 'version',
},
h: {
alias: 'help',
},
}).example('$0 channels -x5 -p2 -s slug', 'Get page 2 of a list of 5 new channels, print their slugs')
.example('$0 channel great-clothes-4295553', 'Get a channel by slug')
.example('$0 create channel Math Problems', 'Create a new channel')
.example('$0 delete channel math-problems-389752', 'Delete a channel by slug').argv;