/
init.ts
99 lines (90 loc) · 2.94 KB
/
init.ts
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
import { Command, flags } from "@oclif/command";
import chalk from "chalk";
import { isEmpty } from "lodash";
import open from "open";
import { createAuthenticationServer } from "../api";
import { getConfiguration } from "../config";
export default class InitCommand extends Command {
static description = "initializes RedGit with Reddit authentication tokens";
static flags = {
force: flags.boolean({
description:
"forces reinitialization even if RedGit has already been initialized",
default: false,
hidden: true,
}),
"no-open": flags.boolean({
description:
"do not automatically open the authorization URL in browser",
default: false,
hidden: true,
}),
"no-write": flags.boolean({
description:
"do not write authorization tokens into the configuration file",
default: false,
hidden: true,
}),
};
async run() {
const config = getConfiguration();
const accessToken = config.get("accessToken");
const refreshToken = config.get("refreshToken");
const { flags } = this.parse(InitCommand);
const onStart = (authenticationURL: string) => {
this.log(
"Open URL %s in the browser to authorize RedGit to use the Reddit API.",
authenticationURL
);
if (!flags["no-open"]) {
open(authenticationURL);
}
};
const onReject = (authenticationURL: string) => {
this.warn(
'In order to obtain a token, you will need to click "allow" at the Reddit authentication screen.'
);
this.log(
"You can try again by opening following URL in the browser: %s",
authenticationURL
);
};
const onError = () => {
this.warn("An error occurred while obtaining the authorization tokens.");
};
if (!isEmpty(accessToken) && !isEmpty(refreshToken) && !flags.force) {
this.error(
`RedGit has already been initialized. Use ${chalk.yellow(
"--force"
)} to reinitialize.`
);
}
return createAuthenticationServer(onStart, onReject, onError).then(
([accessToken, refreshToken]) => {
const config = getConfiguration();
process.stdout.write(
"Your Reddit tokens have been successfully retrieved.\n\n"
);
if (!flags["no-write"]) {
config.set("accessToken", accessToken);
config.set("refreshToken", refreshToken);
process.stdout.write(`\
These tokens have been written into your RedGit configuration file located at:
${chalk.yellow(config.path)}
You can now start using ${chalk.yellow("redgit")}.
`);
} else {
process.stdout.write(`\
In order to use RedGit, you need to store these tokens into your RedGit configuration file located at:
${chalk.yellow(config.path)}
Insert following lines into the file:
${chalk.yellow(`{
"accessToken": "${accessToken}",
"refreshToken": "${refreshToken}"
}`)}
`);
}
}
);
}
}