@recoder.xyz/rithub 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/rithub.mjs +67 -4
- package/package.json +5 -5
- package/src/auth.mjs +72 -0
- package/src/cli.mjs +112 -20
- package/src/config.mjs +55 -0
- package/src/init.mjs +11 -5
- package/src/repo.mjs +151 -0
package/bin/rithub.mjs
CHANGED
|
@@ -1,26 +1,89 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
4
|
-
import { dirname } from "node:path";
|
|
3
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { homedir } from "node:os";
|
|
5
7
|
|
|
6
8
|
import { main } from "../src/cli.mjs";
|
|
7
9
|
|
|
10
|
+
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
|
|
11
|
+
|
|
12
|
+
/** Reads a token from the terminal with the input hidden -- used by `rit
|
|
13
|
+
* login` when no `--token`/`RITHUB_TOKEN` was given. Piped/non-interactive
|
|
14
|
+
* stdin (CI, another process) is read whole instead of char-by-char, so
|
|
15
|
+
* `echo $TOKEN | rit login` works without a TTY. Never echoes what was
|
|
16
|
+
* typed, not even as `*` (simplest correct thing; avoids cursor-position
|
|
17
|
+
* bugs entirely). */
|
|
18
|
+
function promptHidden(message) {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
if (!process.stdin.isTTY) {
|
|
21
|
+
let data = "";
|
|
22
|
+
process.stdin.setEncoding("utf8");
|
|
23
|
+
process.stdin.on("data", (chunk) => (data += chunk));
|
|
24
|
+
process.stdin.on("end", () => resolve(data));
|
|
25
|
+
process.stdin.on("error", () => resolve(data));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
process.stdout.write(message);
|
|
29
|
+
const { stdin } = process;
|
|
30
|
+
stdin.resume();
|
|
31
|
+
stdin.setRawMode(true);
|
|
32
|
+
stdin.setEncoding("utf8");
|
|
33
|
+
let value = "";
|
|
34
|
+
const finish = (result) => {
|
|
35
|
+
stdin.setRawMode(false);
|
|
36
|
+
stdin.pause();
|
|
37
|
+
stdin.removeListener("data", onData);
|
|
38
|
+
process.stdout.write("\n");
|
|
39
|
+
resolve(result);
|
|
40
|
+
};
|
|
41
|
+
function onData(char) {
|
|
42
|
+
if (char === "\n" || char === "\r" || char === "\u0004") {
|
|
43
|
+
finish(value);
|
|
44
|
+
} else if (char === "\u0003") {
|
|
45
|
+
finish(value); // Ctrl+C: stop reading, let the caller fail on an empty token
|
|
46
|
+
} else if (char === "\u007f" || char === "\b") {
|
|
47
|
+
value = value.slice(0, -1);
|
|
48
|
+
} else {
|
|
49
|
+
value += char;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
stdin.on("data", onData);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
8
56
|
const code = await main(process.argv.slice(2), {
|
|
9
57
|
env: process.env,
|
|
10
58
|
cwd: process.cwd(),
|
|
59
|
+
homeDir: homedir(),
|
|
60
|
+
version: pkg.version,
|
|
11
61
|
out: (s) => process.stdout.write(`${s}\n`),
|
|
12
62
|
err: (s) => process.stderr.write(`${s}\n`),
|
|
13
63
|
now: () => Date.now(),
|
|
14
64
|
fetchImpl: fetch,
|
|
65
|
+
promptHidden,
|
|
15
66
|
exists: (path) => existsSync(path),
|
|
16
67
|
readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : null),
|
|
17
|
-
writeFile: (path, contents) => {
|
|
68
|
+
writeFile: (path, contents, opts) => {
|
|
18
69
|
mkdirSync(dirname(path), { recursive: true });
|
|
19
70
|
writeFileSync(path, contents);
|
|
71
|
+
if (opts?.mode !== undefined) chmodSync(path, opts.mode);
|
|
72
|
+
},
|
|
73
|
+
unlink: (path) => {
|
|
74
|
+
try {
|
|
75
|
+
rmSync(path, { force: true });
|
|
76
|
+
} catch {
|
|
77
|
+
// best-effort: logout must not crash if the file is already gone or unreadable
|
|
78
|
+
}
|
|
20
79
|
},
|
|
21
80
|
run: (command, args, cwd) => {
|
|
22
81
|
try {
|
|
23
|
-
|
|
82
|
+
// GIT_TERMINAL_PROMPT=0: a credential prompt in a non-interactive CLI
|
|
83
|
+
// (an agent, CI) would otherwise hang forever instead of failing with
|
|
84
|
+
// a message we can print. Interactive logins go through `rit login`,
|
|
85
|
+
// not a git credential prompt.
|
|
86
|
+
const output = execFileSync(command, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
24
87
|
return { ok: true, output };
|
|
25
88
|
} catch (err) {
|
|
26
89
|
return { ok: false, output: `${err.stdout ?? ""}${err.stderr ?? err.message ?? ""}` };
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@recoder.xyz/rithub",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "A gh-style CLI for Rithub: `rit login`, `rit clone`, `rit repo create`, `rit push`, plus `rit init`'s no-human agent signup. One command, zero deps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
|
-
"engines": { "node": ">=
|
|
8
|
-
"bin": { "rithub": "bin/rithub.mjs" },
|
|
7
|
+
"engines": { "node": ">=18" },
|
|
8
|
+
"bin": { "rithub": "bin/rithub.mjs", "rit": "bin/rithub.mjs" },
|
|
9
9
|
"files": ["bin", "src", "README.md"],
|
|
10
10
|
"homepage": "https://rithub.dev",
|
|
11
|
-
"keywords": ["rithub", "git", "agent", "agent-native", "ci", "cli"],
|
|
11
|
+
"keywords": ["rithub", "git", "agent", "agent-native", "ci", "cli", "gh"],
|
|
12
12
|
"scripts": {
|
|
13
13
|
"test": "node --test test/*.test.mjs"
|
|
14
14
|
}
|
package/src/auth.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `rit login` / `rit logout` / `rit whoami`. Rithub (Gitea underneath) has
|
|
2
|
+
// no OAuth2 device-code flow -- confirmed live, 2026-11-30:
|
|
3
|
+
// `https://rithub.dev/login/device/code` answers a plain 404 -- so this is
|
|
4
|
+
// the token-paste flow the task spec calls for as the fallback: open the
|
|
5
|
+
// applications settings page, paste a personal access token, we validate it
|
|
6
|
+
// against the real account before saving anything.
|
|
7
|
+
import { CliError, DEFAULT_API_URL } from "./init.mjs";
|
|
8
|
+
import { loadConfig, saveConfig, clearConfig, resolveSession } from "./config.mjs";
|
|
9
|
+
|
|
10
|
+
async function fetchUser(io, apiUrl, token) {
|
|
11
|
+
const res = await io.fetchImpl(`${apiUrl}/api/v1/user`, {
|
|
12
|
+
headers: { accept: "application/json", authorization: `token ${token}`, "user-agent": "rithub-cli" },
|
|
13
|
+
});
|
|
14
|
+
const text = await res.text();
|
|
15
|
+
let body = null;
|
|
16
|
+
try {
|
|
17
|
+
body = text ? JSON.parse(text) : null;
|
|
18
|
+
} catch {
|
|
19
|
+
body = null;
|
|
20
|
+
}
|
|
21
|
+
return { status: res.status, body };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `rit login [--token <token>] [--api-url <url>]`: validates a token against
|
|
25
|
+
* the real account (GET /api/v1/user) before saving it, so a typo or a
|
|
26
|
+
* token missing `read:user` scope fails loudly here instead of surfacing
|
|
27
|
+
* later as a confusing 401/403 from `rit clone`. */
|
|
28
|
+
export async function runLogin(options, io) {
|
|
29
|
+
const apiUrl = (options.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
30
|
+
let token = options.token ?? io.env.RITHUB_TOKEN;
|
|
31
|
+
if (!token) {
|
|
32
|
+
// write:user is not a typo for write:repository: Gitea's own
|
|
33
|
+
// POST /api/v1/user/repos (used by `rit repo create` and `rit push`'s
|
|
34
|
+
// auto-create) is gated on write:user, not write:repository -- confirmed
|
|
35
|
+
// live, 2026-11-30, from the server's own 403 scope error. A token
|
|
36
|
+
// missing it still works for `rit clone`/`rit push` to an existing repo.
|
|
37
|
+
io.out(`Open ${apiUrl}/user/settings/applications, generate a token (needs "read:user" and "write:repository" to clone/push; add "write:user" too if you want \`rit repo create\`/\`rit push\` to create repos), then paste it below.`);
|
|
38
|
+
token = (await io.promptHidden("Token: ")).trim();
|
|
39
|
+
}
|
|
40
|
+
token = token.trim();
|
|
41
|
+
if (!token) throw new CliError("no token given", { code: "invalid_argument" });
|
|
42
|
+
|
|
43
|
+
const { status, body } = await fetchUser(io, apiUrl, token);
|
|
44
|
+
if (status !== 200 || !body?.login) {
|
|
45
|
+
const reason = body?.message ?? (status === 0 ? "could not reach the server" : `HTTP ${status}`);
|
|
46
|
+
throw new CliError(`that token did not work against ${apiUrl} (${reason})`, { code: "auth_failed" });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
saveConfig(io, { token, username: body.login, apiUrl });
|
|
50
|
+
return { username: body.login, apiUrl };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** `rit logout`: deletes the saved config. Does not revoke the token on the
|
|
54
|
+
* server (Rithub has no "revoke this specific token" self-service route
|
|
55
|
+
* surfaced here) -- revoke it at `/user/settings/applications` if needed. */
|
|
56
|
+
export async function runLogout(_options, io) {
|
|
57
|
+
const existing = loadConfig(io);
|
|
58
|
+
clearConfig(io);
|
|
59
|
+
return { loggedOut: true, username: existing?.username };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `rit whoami`: re-checks the saved/env token is still live, rather than
|
|
63
|
+
* just echoing the cached username. */
|
|
64
|
+
export async function runWhoami(_options, io) {
|
|
65
|
+
const session = resolveSession(io);
|
|
66
|
+
if (!session) throw new CliError("not logged in -- run `rit login`", { code: "not_logged_in" });
|
|
67
|
+
const { status, body } = await fetchUser(io, session.apiUrl, session.token);
|
|
68
|
+
if (status !== 200 || !body?.login) {
|
|
69
|
+
throw new CliError(`the ${session.source === "env" ? "RITHUB_TOKEN" : "saved"} token is invalid or revoked (HTTP ${status})`, { code: "auth_failed" });
|
|
70
|
+
}
|
|
71
|
+
return { username: body.login, apiUrl: session.apiUrl };
|
|
72
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -1,25 +1,51 @@
|
|
|
1
1
|
import { runInit, runClaim, CliError, DEFAULT_API_URL } from "./init.mjs";
|
|
2
|
+
import { runLogin, runLogout, runWhoami } from "./auth.mjs";
|
|
3
|
+
import { runClone, runRepoCreate, runPush } from "./repo.mjs";
|
|
2
4
|
|
|
3
|
-
const USAGE = `
|
|
4
|
-
rithub claim --email <you@example.com> [--json]
|
|
5
|
+
const USAGE = `rit <command> [options] (alias: rithub)
|
|
5
6
|
|
|
6
|
-
init
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
init no account needed -- provisions a Rithub
|
|
8
|
+
account, token and first repo, points
|
|
9
|
+
this directory's git remote at it
|
|
10
|
+
claim --email <you@example.com> hands a human ownership of the account
|
|
11
|
+
\`init\` created in this directory
|
|
12
|
+
login [--token <token>] sign in: paste a token from
|
|
13
|
+
${DEFAULT_API_URL}/user/settings/applications
|
|
14
|
+
(or pass --token / set RITHUB_TOKEN)
|
|
15
|
+
logout forget the saved token
|
|
16
|
+
whoami print the account the saved/env token belongs to
|
|
17
|
+
clone <owner/repo|repo> [dir] clone a repo (bare name = your own account)
|
|
18
|
+
repo create <name> [--private] create a repo on Rithub (needs a token
|
|
19
|
+
[--description <text>] with the "write:user" scope)
|
|
20
|
+
push [--private] [--name <name>] create the repo if missing (needs
|
|
21
|
+
"write:user" for that), add a \`rithub\`
|
|
22
|
+
remote, push the current branch
|
|
23
|
+
help, --help, -h show this
|
|
24
|
+
--version, -v print the CLI version
|
|
13
25
|
|
|
14
|
-
|
|
15
|
-
|
|
26
|
+
Flags on any command: --json (machine-readable output), --api-url <url>
|
|
27
|
+
(or RITHUB_API_URL env, default ${DEFAULT_API_URL}).`;
|
|
28
|
+
|
|
29
|
+
function toKey(flag) {
|
|
30
|
+
return flag.replace(/^--/, "").replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** One small generic parser for every command: declare which flags take a
|
|
34
|
+
* value and which are booleans, everything else positional goes in `_`.
|
|
35
|
+
* Keeps each command's own code free of argv-walking boilerplate. */
|
|
36
|
+
function parseFlags(argv, { valueFlags = [], boolFlags = [] } = {}) {
|
|
37
|
+
const out = { _: [] };
|
|
16
38
|
for (let i = 0; i < argv.length; i++) {
|
|
17
39
|
const arg = argv[i];
|
|
18
|
-
if (arg
|
|
19
|
-
|
|
20
|
-
else if (arg
|
|
21
|
-
|
|
22
|
-
else
|
|
40
|
+
if (boolFlags.includes(arg)) {
|
|
41
|
+
out[toKey(arg)] = true;
|
|
42
|
+
} else if (valueFlags.includes(arg)) {
|
|
43
|
+
out[toKey(arg)] = argv[++i];
|
|
44
|
+
} else if (arg.startsWith("--")) {
|
|
45
|
+
throw new CliError(`unknown option ${arg}`, { code: "invalid_argument" });
|
|
46
|
+
} else {
|
|
47
|
+
out._.push(arg);
|
|
48
|
+
}
|
|
23
49
|
}
|
|
24
50
|
return out;
|
|
25
51
|
}
|
|
@@ -27,8 +53,17 @@ function parseArgs(argv) {
|
|
|
27
53
|
export async function main(argv, io) {
|
|
28
54
|
const [command, ...rest] = argv;
|
|
29
55
|
try {
|
|
56
|
+
if (command === "--version" || command === "-v") {
|
|
57
|
+
io.out(io.version ?? "unknown");
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
if (command === "help" || command === "--help" || command === "-h") {
|
|
61
|
+
io.out(USAGE);
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
30
65
|
if (command === "init") {
|
|
31
|
-
const args =
|
|
66
|
+
const args = parseFlags(rest, { valueFlags: ["--repo", "--api-url"], boolFlags: ["--json"] });
|
|
32
67
|
const result = await runInit({ repoName: args.repo, apiUrl: args.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL, cwd: io.cwd }, io);
|
|
33
68
|
if (args.json) {
|
|
34
69
|
io.out(JSON.stringify(result));
|
|
@@ -41,20 +76,77 @@ export async function main(argv, io) {
|
|
|
41
76
|
}
|
|
42
77
|
return 0;
|
|
43
78
|
}
|
|
79
|
+
|
|
44
80
|
if (command === "claim") {
|
|
45
|
-
const args =
|
|
81
|
+
const args = parseFlags(rest, { valueFlags: ["--email", "--api-url"], boolFlags: ["--json"] });
|
|
46
82
|
const result = await runClaim({ email: args.email, cwd: io.cwd }, io);
|
|
47
83
|
io.out(args.json ? JSON.stringify(result) : `Claimed ${result.username} as ${result.email}. ${result.next}`);
|
|
48
84
|
return 0;
|
|
49
85
|
}
|
|
86
|
+
|
|
87
|
+
if (command === "login") {
|
|
88
|
+
const args = parseFlags(rest, { valueFlags: ["--token", "--api-url"], boolFlags: ["--json"] });
|
|
89
|
+
const result = await runLogin({ token: args.token, apiUrl: args.apiUrl }, io);
|
|
90
|
+
io.out(args.json ? JSON.stringify(result) : `Logged in as ${result.username} on ${result.apiUrl}.`);
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (command === "logout") {
|
|
95
|
+
const args = parseFlags(rest, { boolFlags: ["--json"] });
|
|
96
|
+
const result = await runLogout({}, io);
|
|
97
|
+
io.out(args.json ? JSON.stringify(result) : result.username ? `Logged out ${result.username}.` : "Already logged out.");
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (command === "whoami") {
|
|
102
|
+
const args = parseFlags(rest, { boolFlags: ["--json"] });
|
|
103
|
+
const result = await runWhoami({}, io);
|
|
104
|
+
io.out(args.json ? JSON.stringify(result) : `${result.username} (${result.apiUrl})`);
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (command === "clone") {
|
|
109
|
+
const args = parseFlags(rest, { valueFlags: ["--api-url"], boolFlags: ["--json"] });
|
|
110
|
+
const [target, dir] = args._;
|
|
111
|
+
if (!target) throw new CliError("`rit clone` needs a repo: `rit clone <owner/repo|repo> [dir]`", { code: "invalid_argument" });
|
|
112
|
+
const result = await runClone({ target, dir, apiUrl: args.apiUrl }, io);
|
|
113
|
+
io.out(args.json ? JSON.stringify(result) : `Cloned ${result.owner}/${result.repo} into ${result.dir}.`);
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (command === "repo") {
|
|
118
|
+
const [subcommand, ...repoRest] = rest;
|
|
119
|
+
if (subcommand !== "create") {
|
|
120
|
+
throw new CliError(subcommand ? `unknown \`rit repo\` subcommand "${subcommand}" (only "create" exists)` : "`rit repo create <name>` needs a subcommand", { code: "invalid_argument" });
|
|
121
|
+
}
|
|
122
|
+
const args = parseFlags(repoRest, { valueFlags: ["--description", "--api-url"], boolFlags: ["--private", "--json"] });
|
|
123
|
+
const [name] = args._;
|
|
124
|
+
if (!name) throw new CliError("`rit repo create` needs a name: `rit repo create <name>`", { code: "invalid_argument" });
|
|
125
|
+
const result = await runRepoCreate({ name, private: args.private, description: args.description, apiUrl: args.apiUrl }, io);
|
|
126
|
+
io.out(args.json ? JSON.stringify(result) : `Created ${result.owner}/${result.repo} -> ${result.html_url}\nClone: ${result.clone_url}`);
|
|
127
|
+
return 0;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (command === "push") {
|
|
131
|
+
const args = parseFlags(rest, { valueFlags: ["--name", "--api-url"], boolFlags: ["--private", "--json"] });
|
|
132
|
+
const result = await runPush({ name: args.name, private: args.private, apiUrl: args.apiUrl, cwd: io.cwd }, io);
|
|
133
|
+
if (args.json) {
|
|
134
|
+
io.out(JSON.stringify(result));
|
|
135
|
+
} else {
|
|
136
|
+
if (result.created) io.out(`Created ${result.owner}/${result.repo} on Rithub.`);
|
|
137
|
+
io.out(`Pushed ${result.branch} -> ${result.html_url}`);
|
|
138
|
+
}
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
50
142
|
io.err(USAGE);
|
|
51
143
|
return command ? 1 : 0;
|
|
52
144
|
} catch (err) {
|
|
53
145
|
if (err instanceof CliError) {
|
|
54
|
-
io.err(`
|
|
146
|
+
io.err(`rit ${command ?? ""}: ${err.message}`);
|
|
55
147
|
return 1;
|
|
56
148
|
}
|
|
57
|
-
io.err(`
|
|
149
|
+
io.err(`rit: unexpected error: ${err.message}`);
|
|
58
150
|
return 1;
|
|
59
151
|
}
|
|
60
152
|
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// `rit login` / `rit logout` / `rit whoami` and everything that needs a
|
|
2
|
+
// standing credential (`rit clone`, `rit repo create`, `rit push`) share one
|
|
3
|
+
// small config file instead of each re-deriving a token: ~/.config/rithub/
|
|
4
|
+
// config.json, written with 0600 perms (same spirit as `gh`'s own hosts.yml
|
|
5
|
+
// and npm's ~/.npmrc -- a plain JSON file under $HOME, not the OS keychain,
|
|
6
|
+
// since this has to work identically on a headless box with no keychain).
|
|
7
|
+
//
|
|
8
|
+
// `RITHUB_TOKEN` always overrides the saved file for the *token* (handy for
|
|
9
|
+
// CI/agents that export it rather than run `rit login` interactively), but
|
|
10
|
+
// never replaces the *username* unless it's the same token `rit login` saved
|
|
11
|
+
// -- otherwise an unrelated env token would silently resolve `rit clone
|
|
12
|
+
// <bare-name>` against the wrong account.
|
|
13
|
+
import { DEFAULT_API_URL } from "./init.mjs";
|
|
14
|
+
|
|
15
|
+
const CONFIG_FILE_RELATIVE = ".config/rithub/config.json";
|
|
16
|
+
|
|
17
|
+
export function configPath(io) {
|
|
18
|
+
return `${io.homeDir.replace(/\/+$/, "")}/${CONFIG_FILE_RELATIVE}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function loadConfig(io) {
|
|
22
|
+
const text = io.readFile(configPath(io));
|
|
23
|
+
if (!text) return null;
|
|
24
|
+
try {
|
|
25
|
+
const value = JSON.parse(text);
|
|
26
|
+
return value && typeof value.token === "string" && typeof value.username === "string" ? value : null;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Saves `{ token, username, apiUrl }`, 0600 (owner read/write only -- this file holds a live access token). */
|
|
33
|
+
export function saveConfig(io, config) {
|
|
34
|
+
io.writeFile(configPath(io), `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function clearConfig(io) {
|
|
38
|
+
io.unlink(configPath(io));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The active session for any command that calls the Rithub API or needs to
|
|
42
|
+
* know who's logged in: `null` when there's neither a `RITHUB_TOKEN` nor a
|
|
43
|
+
* saved config (the caller decides whether that's fatal). */
|
|
44
|
+
export function resolveSession(io, { apiUrl: overrideApiUrl } = {}) {
|
|
45
|
+
const saved = loadConfig(io);
|
|
46
|
+
const apiUrl = (overrideApiUrl ?? io.env.RITHUB_API_URL ?? saved?.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
47
|
+
const envToken = io.env.RITHUB_TOKEN;
|
|
48
|
+
if (envToken) {
|
|
49
|
+
return { token: envToken, apiUrl, username: saved?.token === envToken ? saved.username : undefined, source: "env" };
|
|
50
|
+
}
|
|
51
|
+
if (saved) {
|
|
52
|
+
return { token: saved.token, apiUrl, username: saved.username, source: "config" };
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
package/src/init.mjs
CHANGED
|
@@ -55,7 +55,12 @@ function ensureGitignored(io, cwd) {
|
|
|
55
55
|
io.writeFile(path, next);
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
/** Points `cwd`'s git remote named `remoteName` (default `origin`, overridden
|
|
59
|
+
* by `rit push` to `rithub` so it doesn't collide with a GitHub `origin`
|
|
60
|
+
* already set in the same checkout) at `gitRemote`, git-init'ing first if
|
|
61
|
+
* `cwd` isn't a repo yet. Exported for `src/repo.mjs` (`rit push`) to reuse
|
|
62
|
+
* rather than re-implement. */
|
|
63
|
+
export function setGitRemote(io, cwd, gitRemote, remoteName = "origin") {
|
|
59
64
|
const inGitRepo = io.run("git", ["rev-parse", "--is-inside-work-tree"], cwd).ok;
|
|
60
65
|
if (!inGitRepo) {
|
|
61
66
|
const init = io.run("git", ["init"], cwd);
|
|
@@ -67,16 +72,17 @@ function setGitRemote(io, cwd, gitRemote) {
|
|
|
67
72
|
io.run("git", ["symbolic-ref", "HEAD", "refs/heads/main"], cwd);
|
|
68
73
|
}
|
|
69
74
|
const remotes = io.run("git", ["remote"], cwd);
|
|
70
|
-
const
|
|
71
|
-
const result =
|
|
75
|
+
const hasRemote = remotes.ok && remotes.output.split("\n").map((l) => l.trim()).includes(remoteName);
|
|
76
|
+
const result = hasRemote ? io.run("git", ["remote", "set-url", remoteName, gitRemote], cwd) : io.run("git", ["remote", "add", remoteName, gitRemote], cwd);
|
|
72
77
|
if (!result.ok) throw new CliError(`could not set the git remote: ${result.output.slice(-400)}`, { code: "git_failed" });
|
|
73
78
|
}
|
|
74
79
|
|
|
75
80
|
/** The real current branch name, so printed instructions never claim `main`
|
|
76
81
|
* when this directory's git (pre-existing or just-initialized on an old git
|
|
77
82
|
* that ignored symbolic-ref) is actually on something else. Falls back to
|
|
78
|
-
* `main` only if git itself can't answer (e.g. no git on PATH).
|
|
79
|
-
|
|
83
|
+
* `main` only if git itself can't answer (e.g. no git on PATH). Exported for
|
|
84
|
+
* `src/repo.mjs` (`rit push`). */
|
|
85
|
+
export function currentBranch(io, cwd) {
|
|
80
86
|
const result = io.run("git", ["branch", "--show-current"], cwd);
|
|
81
87
|
const name = result.ok ? result.output.trim() : "";
|
|
82
88
|
return name || "main";
|
package/src/repo.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// `rit clone`, `rit repo create`, `rit push` -- the gh-style commands the
|
|
2
|
+
// task was filed over (`rit clone homeplan` had no CLI to run at all).
|
|
3
|
+
// Shares `setGitRemote`/`currentBranch` with `src/init.mjs`'s `rit init`
|
|
4
|
+
// rather than re-implementing them.
|
|
5
|
+
import { CliError, setGitRemote, currentBranch } from "./init.mjs";
|
|
6
|
+
import { resolveSession } from "./config.mjs";
|
|
7
|
+
|
|
8
|
+
const NAME_RE = /^[A-Za-z0-9._-]{1,100}$/;
|
|
9
|
+
|
|
10
|
+
function basename(path) {
|
|
11
|
+
return path.replace(/\/+$/, "").split("/").pop() || "repo";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function sanitizeRepoName(name) {
|
|
15
|
+
return typeof name === "string" && NAME_RE.test(name) ? name : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function apiCall(io, apiUrl, path, init, token) {
|
|
19
|
+
const headers = {
|
|
20
|
+
accept: "application/json",
|
|
21
|
+
"user-agent": "rithub-cli",
|
|
22
|
+
...(init?.body ? { "content-type": "application/json" } : {}),
|
|
23
|
+
...(token ? { authorization: `token ${token}` } : {}),
|
|
24
|
+
};
|
|
25
|
+
const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
|
|
26
|
+
const text = await res.text();
|
|
27
|
+
let body = null;
|
|
28
|
+
try {
|
|
29
|
+
body = text ? JSON.parse(text) : null;
|
|
30
|
+
} catch {
|
|
31
|
+
body = { message: text.slice(0, 200) };
|
|
32
|
+
}
|
|
33
|
+
return { status: res.status, body };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Git args for an authenticated one-shot call: the token rides on
|
|
37
|
+
* `http.extraHeader`, passed via `-c` on this single invocation only -- it
|
|
38
|
+
* is never written to `.git/config` (verified live, 2026-11-30: cloning a
|
|
39
|
+
* private repo this way leaves no token/header in the resulting repo's
|
|
40
|
+
* config). `credential.helper=` (empty) is set alongside it so a cached OS
|
|
41
|
+
* credential (osxkeychain etc.) never silently substitutes a different
|
|
42
|
+
* identity than the one `rit login` chose. */
|
|
43
|
+
function gitAuthedArgs(token, args) {
|
|
44
|
+
return token ? ["-c", "credential.helper=", "-c", `http.extraHeader=Authorization: token ${token}`, ...args] : args;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Splits `owner/repo` or a bare `repo` (resolved against the logged-in
|
|
48
|
+
* user) into `{ owner, repo }`. Returns `null` if it can't be resolved
|
|
49
|
+
* (bare name with nobody logged in, or a malformed target). */
|
|
50
|
+
export function parseTarget(target, fallbackOwner) {
|
|
51
|
+
if (typeof target !== "string" || target.length === 0) return null;
|
|
52
|
+
const parts = target.split("/").filter(Boolean);
|
|
53
|
+
if (parts.length === 2 && NAME_RE.test(parts[0]) && NAME_RE.test(parts[1])) return { owner: parts[0], repo: parts[1] };
|
|
54
|
+
if (parts.length === 1 && NAME_RE.test(parts[0])) return fallbackOwner ? { owner: fallbackOwner, repo: parts[0] } : null;
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `rit clone <owner/repo|repo> [dir]`: looks the repo up first (so a 404 or
|
|
59
|
+
* a private repo this token can't see gets a clear message, not git's own
|
|
60
|
+
* cryptic "could not read Username" prompt-timeout), then does the real
|
|
61
|
+
* `git clone` with the token on `http.extraHeader` only if one is set --
|
|
62
|
+
* an anonymous clone of a public repo works with no login at all, same as
|
|
63
|
+
* plain `git clone` always did. */
|
|
64
|
+
export async function runClone(options, io) {
|
|
65
|
+
const session = resolveSession(io, { apiUrl: options.apiUrl });
|
|
66
|
+
const apiUrl = session?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
|
|
67
|
+
const target = parseTarget(options.target, session?.username);
|
|
68
|
+
if (!target) {
|
|
69
|
+
throw new CliError(
|
|
70
|
+
session
|
|
71
|
+
? `"${options.target}" doesn't look like a repo -- use a bare name or owner/repo`
|
|
72
|
+
: `"${options.target}" has no owner -- run \`rit login\` first, or pass owner/repo`,
|
|
73
|
+
{ code: "invalid_argument" }
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const { status, body } = await apiCall(io, apiUrl, `/api/v1/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}`, { method: "GET" }, session?.token);
|
|
78
|
+
if (status === 404) throw new CliError(`${target.owner}/${target.repo} was not found (or this token can't see it)`, { code: "not_found" });
|
|
79
|
+
if (status !== 200) throw new CliError(`could not look up ${target.owner}/${target.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
|
|
80
|
+
|
|
81
|
+
const cloneUrl = body.clone_url ?? `${apiUrl}/${target.owner}/${target.repo}.git`;
|
|
82
|
+
const dir = options.dir ?? target.repo;
|
|
83
|
+
const args = gitAuthedArgs(session?.token, ["clone", cloneUrl, dir]);
|
|
84
|
+
const result = io.run("git", args, io.cwd);
|
|
85
|
+
if (!result.ok) throw new CliError(`git clone failed: ${result.output.slice(-500)}`, { code: "git_failed" });
|
|
86
|
+
|
|
87
|
+
return { owner: target.owner, repo: target.repo, dir, html_url: body.html_url, private: !!body.private };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `rit repo create <name> [--private] [--description <text>]`. */
|
|
91
|
+
export async function runRepoCreate(options, io) {
|
|
92
|
+
const session = resolveSession(io, { apiUrl: options.apiUrl });
|
|
93
|
+
if (!session) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
|
|
94
|
+
const name = sanitizeRepoName(options.name);
|
|
95
|
+
if (!name) throw new CliError("give a repo name using only letters, numbers, dots, dashes and underscores", { code: "invalid_argument" });
|
|
96
|
+
|
|
97
|
+
const { status, body } = await apiCall(
|
|
98
|
+
io,
|
|
99
|
+
session.apiUrl,
|
|
100
|
+
"/api/v1/user/repos",
|
|
101
|
+
{ method: "POST", body: JSON.stringify({ name, private: !!options.private, description: options.description ?? "", auto_init: false }) },
|
|
102
|
+
session.token
|
|
103
|
+
);
|
|
104
|
+
if (status === 409) throw new CliError(`a repo named ${name} already exists`, { code: "already_exists" });
|
|
105
|
+
if (status !== 201) throw new CliError(`could not create ${name} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
|
|
106
|
+
|
|
107
|
+
return { owner: session.username ?? body.owner?.login, repo: name, clone_url: body.clone_url, html_url: body.html_url };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `rit push`: creates the repo on Rithub if it doesn't exist yet (name =
|
|
111
|
+
* the current directory's name), points a `rithub` remote at it (a
|
|
112
|
+
* separate remote from `origin` on purpose -- a checkout that already has
|
|
113
|
+
* a GitHub `origin` must not lose it), and pushes the current branch with
|
|
114
|
+
* `-u`. */
|
|
115
|
+
export async function runPush(options, io) {
|
|
116
|
+
const cwd = options.cwd ?? io.cwd;
|
|
117
|
+
const session = resolveSession(io, { apiUrl: options.apiUrl });
|
|
118
|
+
if (!session) throw new CliError("not logged in -- run `rit login` first", { code: "not_logged_in" });
|
|
119
|
+
|
|
120
|
+
const inRepo = io.run("git", ["rev-parse", "--is-inside-work-tree"], cwd).ok;
|
|
121
|
+
if (!inRepo) throw new CliError("not a git repository -- run this inside one (or `git init` first)", { code: "not_a_repo" });
|
|
122
|
+
|
|
123
|
+
const name = sanitizeRepoName(options.name ?? basename(cwd));
|
|
124
|
+
if (!name) throw new CliError("could not derive a repo name from this directory -- pass one explicitly with --name", { code: "invalid_argument" });
|
|
125
|
+
|
|
126
|
+
const lookup = await apiCall(io, session.apiUrl, `/api/v1/repos/${encodeURIComponent(session.username)}/${encodeURIComponent(name)}`, { method: "GET" }, session.token);
|
|
127
|
+
let repoInfo = lookup.body;
|
|
128
|
+
if (lookup.status === 404) {
|
|
129
|
+
const created = await apiCall(
|
|
130
|
+
io,
|
|
131
|
+
session.apiUrl,
|
|
132
|
+
"/api/v1/user/repos",
|
|
133
|
+
{ method: "POST", body: JSON.stringify({ name, private: !!options.private, auto_init: false }) },
|
|
134
|
+
session.token
|
|
135
|
+
);
|
|
136
|
+
if (created.status !== 201) throw new CliError(`could not create ${name} on Rithub (HTTP ${created.status}): ${created.body?.message ?? "unknown error"}`, { code: "create_failed" });
|
|
137
|
+
repoInfo = created.body;
|
|
138
|
+
} else if (lookup.status !== 200) {
|
|
139
|
+
throw new CliError(`could not reach Rithub (HTTP ${lookup.status}): ${lookup.body?.message ?? "unknown error"}`, { code: "network_error" });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
setGitRemote(io, cwd, repoInfo.clone_url, "rithub");
|
|
143
|
+
const branch = currentBranch(io, cwd);
|
|
144
|
+
if (!branch) throw new CliError("no commits yet -- commit something first", { code: "no_commits" });
|
|
145
|
+
|
|
146
|
+
const pushArgs = gitAuthedArgs(session.token, ["push", "-u", "rithub", branch]);
|
|
147
|
+
const result = io.run("git", pushArgs, cwd);
|
|
148
|
+
if (!result.ok) throw new CliError(`git push failed: ${result.output.slice(-500)}`, { code: "git_failed" });
|
|
149
|
+
|
|
150
|
+
return { owner: session.username, repo: name, branch, created: lookup.status === 404, html_url: repoInfo.html_url };
|
|
151
|
+
}
|