-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
now-alias
executable file
·274 lines (222 loc) · 7.52 KB
/
now-alias
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
#!/usr/bin/env node
import chalk from 'chalk';
import minimist from 'minimist';
import table from 'text-table';
import ms from 'ms';
import NowAlias from '../lib/alias';
import login from '../lib/login';
import * as cfg from '../lib/cfg';
import { error } from '../lib/error';
import toHost from '../lib/to-host';
const argv = minimist(process.argv.slice(2), {
string: ['config', 'token'],
boolean: ['help', 'debug'],
alias: {
help: 'h',
config: 'c',
debug: 'd',
token: 't'
}
});
const subcommand = argv._[0];
// options
const help = () => {
console.log(`
${chalk.bold('𝚫 now alias')} <ls | set | rm> <deployment> <alias>
${chalk.dim('Options:')}
-h, --help output usage information
-c ${chalk.bold.underline('FILE')}, --config=${chalk.bold.underline('FILE')} config file
-d, --debug debug mode [off]
-t ${chalk.bold.underline('TOKEN')}, --token=${chalk.bold.underline('TOKEN')} login token
${chalk.dim('Examples:')}
${chalk.gray('–')} Lists all your aliases:
${chalk.cyan('$ now alias ls')}
${chalk.gray('–')} Adds a new alias to ${chalk.underline('my-api.now.sh')}:
${chalk.cyan(`$ now alias set ${chalk.underline('api-ownv3nc9f8.now.sh')} ${chalk.underline('my-api.now.sh')}`)}
The ${chalk.dim('`.now.sh`')} suffix can be ommited:
${chalk.cyan('$ now alias set api-ownv3nc9f8 my-api')}
The deployment id can be used as the source:
${chalk.cyan('$ now alias set deploymentId my-alias')}
Custom domains work as alias targets:
${chalk.cyan(`$ now alias set ${chalk.underline('api-ownv3nc9f8.now.sh')} ${chalk.underline('my-api.com')}`)}
${chalk.dim('–')} The subcommand ${chalk.dim('`set`')} is the default and can be skipped.
${chalk.dim('–')} ${chalk.dim('`http(s)://`')} in the URLs is unneeded / ignored.
${chalk.gray('–')} Removing an alias:
${chalk.cyan('$ now alias rm aliasId')}
To get the list of alias ids, use ${chalk.dim('`now alias ls`')}.
${chalk.dim('Alias:')} ln
`);
};
// options
const debug = argv.debug;
const apiUrl = argv.url || 'https://api.zeit.co';
if (argv.config) cfg.setConfigFile(argv.config);
const exit = (code) => {
// we give stdout some time to flush out
// because there's a node bug where
// stdout writes are asynchronous
// https://github.com/nodejs/node/issues/6456
setTimeout(() => process.exit(code || 0), 100);
};
if (argv.help || !subcommand) {
help();
exit(0);
} else {
const config = cfg.read();
Promise.resolve(argv.token || config.token || login(apiUrl))
.then(async (token) => {
try {
await run(token);
} catch (err) {
if (err.userError) {
error(err.message);
} else {
error(`Unknown error: ${err.stack}`);
}
exit(1);
}
})
.catch((e) => {
error(`Authentication error – ${e.message}`);
exit(1);
});
}
async function run (token) {
const alias = new NowAlias(apiUrl, token, { debug });
const args = argv._.slice(1);
switch (subcommand) {
case 'list':
case 'ls':
if (0 !== args.length) {
error('Invalid number of arguments');
return exit(1);
}
const start_ = new Date();
const list = await alias.list();
const urls = new Map(list.map(l => [l.uid, l.url]));
const aliases = await alias.ls();
aliases.sort((a, b) => new Date(b.created) - new Date(a.created));
const current = new Date();
const text = table(aliases.map((_alias) => {
const _url = chalk.underline(`https://${_alias.alias}`);
const target = _alias.deploymentId;
const _sourceUrl = urls.get(target)
? chalk.underline(`https://${urls.get(target)}`)
: chalk.gray('<null>');
const time = chalk.gray(ms(current - new Date(_alias.created)) + ' ago');
return [
'',
// we default to `''` because some early aliases didn't
// have an uid associated
null == _alias.uid ? '' : _alias.uid,
_sourceUrl,
_url,
time
];
}), { align: ['l', 'r', 'l'], hsep: ' '.repeat(2) });
const elapsed_ = ms(new Date() - start_);
console.log(`> ${list.length} alias${list.length > 1 ? 'es' : ''} found ${chalk.gray(`[${elapsed_}]`)}`);
if (text) console.log('\n' + text + '\n');
break;
case 'remove':
case 'rm':
const _target = String(args[0]);
if (!_target) {
const err = new Error('No alias id specified');
err.userError = true;
throw err;
}
if (1 !== args.length) {
error('Invalid number of arguments');
return exit(1);
}
const _aliases = await alias.ls();
const _alias = findAlias(_target, _aliases);
if (!_alias) {
const err = new Error(`Alias not found by "${_target}". Run ${chalk.dim('`now alias ls`')} to see your aliases.`);
err.userError = true;
throw err;
}
try {
const confirmation = (await readConfirmation(alias, _alias, _aliases)).toLowerCase();
if ('y' !== confirmation && 'yes' !== confirmation) {
console.log('\n> Aborted');
process.exit(0);
}
const start = new Date();
await alias.rm(_alias);
const elapsed = ms(new Date() - start);
console.log(`${chalk.cyan('> Success!')} Alias ${chalk.bold(_alias.uid)} removed [${elapsed}]`);
} catch (err) {
error(err);
exit(1);
}
break;
case 'add':
case 'set':
if (2 !== args.length) {
error('Invalid number of arguments');
return exit(1);
}
await alias.set(String(args[0]), String(args[1]));
break;
default:
if (2 === argv._.length) {
await alias.set(String(argv._[0]), String(argv._[1]));
} else if (argv._.length >= 3) {
error('Invalid number of arguments');
help();
exit(1);
} else {
error('Please specify a valid subcommand: ls | set | rm');
help();
exit(1);
}
}
alias.close();
}
function indent (text, n) {
return text.split('\n').map((l) => ' '.repeat(n) + l).join('\n');
}
async function readConfirmation (alias, _alias, list) {
const deploymentsList = await alias.list();
const urls = new Map(deploymentsList.map(l => [l.uid, l.url]));
return new Promise((resolve, reject) => {
const time = chalk.gray(ms(new Date() - new Date(_alias.created)) + ' ago');
const _sourceUrl = chalk.underline(`https://${urls.get(_alias.deploymentId)}`);
const tbl = table(
[[_alias.uid, _sourceUrl, chalk.underline(`https://${_alias.alias}`), time]],
{ align: ['l', 'r', 'l'], hsep: ' '.repeat(6) }
);
process.stdout.write('> The following alias will be removed permanently\n');
process.stdout.write(' ' + tbl + '\n');
process.stdout.write(` ${chalk.bold.red('> Are you sure?')} ${chalk.gray('[yN] ')}`);
process.stdin.on('data', (d) => {
process.stdin.pause();
resolve(d.toString().trim());
}).resume();
});
}
function findAlias (alias, list) {
let key, val;
if (/\./.test(alias)) {
val = toHost(alias);
key = 'alias';
} else {
val = alias;
key = 'uid';
}
const _alias = list.find((d) => {
if (d[key] === val) {
if (debug) console.log(`> [debug] matched alias ${d.uid} by ${key} ${val}`);
return true;
}
// match prefix
if (`${val}.now.sh` === d.alias) {
if (debug) console.log(`> [debug] matched alias ${d.uid} by url ${d.host}`);
return true;
}
return false;
});
return _alias;
}