forked from mixn/carbon-now-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·297 lines (268 loc) · 7.03 KB
/
cli.js
File metadata and controls
executable file
·297 lines (268 loc) · 7.03 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
#!/usr/bin/env node
// Native
const {promisify} = require('util');
const {basename, extname} = require('path');
const asyncRename = promisify(require('fs').rename);
// Packages
const meow = require('meow');
const {bold, red, green} = require('chalk');
const opn = require('opn');
const queryString = require('query-string');
const terminalImage = require('terminal-image');
const generate = require('nanoid/generate');
const tempy = require('tempy');
const updateNotifier = require('update-notifier');
const Listr = require('listr');
// Source
const pkg = require('./package.json');
const getInputFromSource = require('./src/get-input');
const processContent = require('./src/process-content');
const getLanguage = require('./src/get-language');
const headlessVisit = require('./src/headless-visit');
const interactiveMode = require('./src/interactive-mode');
const presetHandler = require('./src/preset');
const imgToClipboard = require('./src/util/img-to-clipboard');
// Helpers
const {CARBON_URL, LATEST_PRESET} = require('./src/helpers/globals');
let settings = require('./src/helpers/default-settings');
const cli = meow(`
${bold('Usage')}
$ carbon-now <file>
$ pbpaste | carbon-now
$ carbon-now --from-clipboard
${bold('Options')}
-s, --start Starting line of <file>
-e, --end Ending line of <file>
-i, --interactive Interactive mode
-l, --location Image save location, default: cwd
-t, --target Image name, default: original-hash.{png|svg}
-o, --open Open in browser instead of saving
-c, --copy Copy image to clipboard
-p, --preset Use a saved preset
-h, --headless Use only non-experimental Puppeteer features
--config Use a different, local config (read-only)
--from-clipboard Read input from clipboard instead of file
${bold('Examples')}
See: https://github.com/mixn/carbon-now-cli#examples
`,
{
flags: {
start: {
type: 'number',
alias: 's',
default: 1
},
end: {
type: 'number',
alias: 'e',
default: 1000
},
open: {
type: 'boolean',
alias: 'o',
default: false
},
location: {
type: 'string',
alias: 'l',
default: process.cwd()
},
target: {
type: 'string',
alias: 't',
default: null
},
interactive: {
type: 'boolean',
alias: 'i',
default: false
},
preset: {
type: 'string',
alias: 'p',
default: LATEST_PRESET
},
copy: {
type: 'boolean',
alias: 'c',
default: false
},
config: {
type: 'string',
default: undefined // So that default params trigger
},
fromClipboard: {
type: 'boolean',
default: false
},
headless: {
type: 'boolean',
alias: 'h',
default: false
}
}
});
const [FILE] = cli.input;
const {
start: START_LINE,
end: END_LINE,
open: OPEN,
location: LOCATION,
target: TARGET,
copy: COPY,
interactive: INTERACTIVE,
preset: PRESET,
config: CONFIG,
fromClipboard: FROM_CLIPBOARD,
headless: HEADLESS
} = cli.flags;
let url = CARBON_URL;
let input;
// Run main CLI programm
(async () => {
try {
input = await getInputFromSource(FILE, FROM_CLIPBOARD);
} catch (error) {
console.error(`
${red(error)}
${bold('Usage')}
$ carbon-now <file>
$ pbpaste | carbon-now
$ carbon-now --from-clipboard
`);
process.exit(1);
}
// If --preset given, take that particular preset
if (PRESET) {
settings = {
...settings,
...(await presetHandler.get(PRESET, CONFIG))
};
}
// If --interactive, enter interactive mode and adopt settings
// This unfortunately can’t be inside of Listr since it leads to rendering problems
if (INTERACTIVE) {
settings = {
...settings,
...(await interactiveMode())
};
}
// Prepare tasks
const tasks = new Listr([
// Task 1: Process and encode file
{
title: `Processing ${FILE || 'stdin'}`,
task: async ctx => {
const processedContent = await processContent(input, START_LINE, END_LINE);
ctx.urlEncodedContent = encodeURIComponent(processedContent);
}
},
// Task 2: Merge all given settings (default, preset, interactive), prepare URL
{
title: 'Preparing connection',
task: async ({urlEncodedContent}) => {
// Save the current settings as 'latest-preset' to global config
// Don’t do so for local configs passed via --config
// The `save` method takes care of whether something should
// also be saved as a preset, or just as 'latest-preset'
if (!CONFIG) {
await presetHandler.save(settings.preset, settings);
}
// Add code and language, irrelevant for storage and always different
settings = {
...settings,
code: urlEncodedContent,
l: FILE ? getLanguage(FILE) : 'auto'
};
// Prepare the querystring that we’ll send to Carbon
url = `${url}?${queryString.stringify(settings)}`;
}
},
// Task 3: Only open the browser if --open
{
title: 'Opening in browser',
skip: () => !OPEN,
task: () => {
opn(url);
}
},
// Task 4: Download image to --location if not --open
{
title: 'Fetching beautiful image',
skip: () => OPEN,
task: async ctx => {
const {type: IMG_TYPE} = settings;
const SAVE_DIRECTORY = COPY ? tempy.directory() : LOCATION;
const FULL_DOWNLOADED_PATH = `${SAVE_DIRECTORY}/carbon.${IMG_TYPE}`;
const ORIGINAL_FILE_NAME = FILE ? basename(FILE, extname(FILE)) : 'stdin';
const NEW_FILE_NAME = TARGET || `${ORIGINAL_FILE_NAME}-${generate('123456abcdef', 10)}`;
const FULL_SAVE_PATH = `${SAVE_DIRECTORY}/${NEW_FILE_NAME}.${IMG_TYPE}`;
// Fetch image
await headlessVisit({
url,
location: SAVE_DIRECTORY,
type: IMG_TYPE,
headless: HEADLESS
});
// Don’t rename file if --copy
if (COPY) {
ctx.downloadedAs = FULL_DOWNLOADED_PATH;
} else {
await asyncRename(FULL_DOWNLOADED_PATH, FULL_SAVE_PATH);
ctx.downloadedAs = FULL_SAVE_PATH;
}
}
},
// Task 5: Copy image to clipboard if --copy
{
title: 'Copying image to clipboard',
skip: () => !COPY || OPEN,
task: async ({downloadedAs}) => {
await imgToClipboard(downloadedAs);
}
}
]);
try {
const {downloadedAs} = await tasks.run();
console.log(`
${green('Done!')}`
);
switch (true) {
case OPEN: {
console.log(`
Browser opened — finish your image there! 😌`
);
break;
}
case COPY: {
console.log(`
Image copied to clipboard! 😌`
);
break;
}
default: {
console.log(`
The file can be found here: ${downloadedAs} 😌`
);
if (process.env.TERM_PROGRAM && process.env.TERM_PROGRAM.match('iTerm')) {
console.log(`
iTerm2 should display the image below. 😊
${await terminalImage.file(downloadedAs)}`
);
}
}
}
updateNotifier({pkg}).notify();
process.exit();
} catch (error) {
console.error(`
${red('Error: Sending code to https://carbon.now.sh went wrong.')}
This is mostly due to:
– Insensical input like \`--start 10 --end 2\`
– Carbon being down or taking too long to respond
– Your internet connection not working or being too slow
Additional info:
${error}`);
process.exit(1);
}
})();