-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcli.js
executable file
·80 lines (73 loc) · 1.89 KB
/
cli.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
#!/usr/bin/env node
'use strict'
const meow = require('meow')
const getStdin = require('get-stdin')
const logSymbols = require('log-symbols')
const cli = meow(`
Usage
~ ❯❯❯ url [string]
~ ❯❯❯ echo [string] | url
Options
-d, --decode Decode URL encoded string
-p, --plain Display output without log symbols
Examples
~ ❯❯❯ url "just 4n0ther URL enc0d3d $tr1ng"
${logSymbols.success} just%204n0ther%20URL%20enc0d3d
~ ❯❯❯ url -d url%E2%80%93encoded%20string
${logSymbols.success} url–encoded string
`, {
flags: {
decode: {
type: 'boolean',
alias: 'd',
default: false
},
plain: {
type: 'boolean',
alias: 'p',
default: false
}
}
});
const input = cli.input[0]
function URLEncode (text) {
return encodeURIComponent(text)
}
function URLEncodedRegex (ciphertext) {
const re = '(?:[^%]|%[0-9A-Fa-f]{2})+'
if ((ciphertext ? new RegExp('(?:^' + re + '$)') : new RegExp(re, 'g')).test(ciphertext)) return true
else return false
}
function URLDecode (text) {
if (URLEncodedRegex(text)) return decodeURIComponent(text)
else return 'Ciphertext doesn\'t seem to be URL-encoded'
}
function display (plaintext) {
if (plaintext != 'Ciphertext doesn\'t seem to be URL-encoded') {
const leading = (cli.flags["plain"]) ? `` : `${logSymbols.success} `
console.log(leading + plaintext)
} else {
const leading = (cli.flags["plain"]) ? `` : `${logSymbols.error} `
console.log(leading + `Ciphertext doesn\'t seem to be URL-encoded`)
process.exit(1);
}
}
if (!input && process.stdin.isTTY) {
console.log('Enter string to URL encode/decode')
process.exit(1)
}
if (input) {
if (cli.flags["decode"]) {
display(URLDecode(input.trim()))
} else {
display(URLEncode(input.trim()))
}
} else {
getStdin().then(stdin => {
if (cli.flags["decode"]) {
display(URLDecode(stdin.trim()))
} else {
display(URLEncode(stdin.trim()))
}
})
}