git-tm 0.4.1 → 1.0.1

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/src/cli.js CHANGED
@@ -1,235 +1,147 @@
1
- #!/usr/bin/env node
2
-
3
- import { program } from "commander";
4
- import path from "path";
5
- import fs from "fs";
6
- import chalk from "chalk";
7
- import boxen from "boxen";
8
- import centerAlign from "center-align";
9
- import { fileURLToPath } from "url";
10
- import { dirname } from "path";
11
- import { startServer } from "./server.js";
12
- import ora from "ora";
13
- import figlet from "figlet";
14
- import gradient from "gradient-string";
15
- import { readFile } from 'fs/promises';
16
-
17
- const __filename = fileURLToPath(import.meta.url);
18
- const __dirname = dirname(__filename);
19
-
20
- const packageJson = JSON.parse(
21
- await readFile(
22
- new URL('../package.json', import.meta.url)
23
- )
24
- );
25
-
26
- const VERSION = packageJson.version;
27
- const DEFAULT_PORT = 7890;
28
- const GIT_ORANGE = "#e84d31";
29
- const WHITE = "#ffffff";
30
-
31
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
-
33
- async function displayBanner() {
34
- const banner = await new Promise((resolve, reject) => {
35
- figlet("Git Time Machine", {
36
- font: "Standard",
37
- horizontalLayout: "default",
38
- verticalLayout: "default",
39
- width: 80,
40
- whitespaceBreak: true,
41
- }, (err, data) => {
42
- if (err) {
43
- reject(err);
44
- return;
45
- }
46
- resolve(data);
47
- });
48
- });
49
-
50
- const bannerGradient = gradient(GIT_ORANGE, WHITE);
51
- console.log(bannerGradient(banner));
52
- }
53
-
54
- function createSpinner(text) {
55
- return ora({
56
- text,
57
- color: "cyan",
58
- spinner: {
59
- frames: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
60
- },
61
- });
62
- }
63
-
64
- async function showErrorAndHelp(errorMessage, exitCode = 1) {
65
- console.log(chalk.yellow(`⚠️ Error: ${errorMessage}\n`));
66
- console.log(await getHelpText() + "\n");
67
- process.exit(exitCode);
68
- }
69
-
70
- async function validateGitRepo(repoPath) {
71
- const spinner = createSpinner("Validating repository...");
72
- spinner.start();
73
-
74
- const fullPath = path.resolve(process.cwd(), repoPath);
75
- const gitPath = path.join(fullPath, ".git");
76
-
77
- if (!fs.existsSync(fullPath)) {
78
- spinner.fail(chalk.red("Repository validation failed"));
79
- await showErrorAndHelp(
80
- `Directory does not exist: ${chalk.yellow(fullPath)}`
81
- );
82
- }
83
-
84
- if (!fs.existsSync(gitPath)) {
85
- spinner.fail(chalk.red("Repository validation failed"));
86
- await showErrorAndHelp(
87
- `Not a git repository: ${chalk.white(
88
- fullPath
89
- )}\nMake sure the directory contains a .git folder`
90
- );
91
- }
92
-
93
- spinner.succeed(chalk.green("Repository validated successfully"));
94
- return fullPath;
95
- }
96
-
97
- async function getHelpText() {
98
- return [
99
- "",
100
- chalk.bold("Git Time Machine"),
101
- chalk.dim("Interactive Git repository visualization tool"),
102
- "",
103
- chalk.bold("Usage:"),
104
- ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ${chalk.cyan(
105
- "<repository-path>"
106
- )} [options]`,
107
- "",
108
- chalk.bold("Examples:"),
109
- ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} . ${chalk.dim(
110
- "Start with current directory"
111
- )}`,
112
- ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ./my-project ${chalk.dim(
113
- "Start with specific repository"
114
- )}`,
115
- ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ${chalk.cyan(
116
- "-p"
117
- )} 8000 ./repo ${chalk.dim("Start with custom port")}`,
118
- "",
119
- chalk.bold("Options:"),
120
- ` ${chalk.cyan("-p, --port")} <number> ${chalk.dim(
121
- "Port to run the server (default: " + DEFAULT_PORT + ")"
122
- )}`,
123
- ` ${chalk.cyan("-h, --help")} ${chalk.dim(
124
- "Display this help message"
125
- )}`,
126
- ` ${chalk.cyan("-V, --version")} ${chalk.dim(
127
- "Output the version number"
128
- )}`,
129
- "",
130
- chalk.bold("More Info:"),
131
- ` ${chalk.yellow("https://gitlab.com/nandhu-44/Git-Time-Machine")}`,
132
- ].join("\n");
133
- }
134
-
135
- function createBox(content, options = {}) {
136
- const terminalWidth = process.stdout.columns || 80;
137
- const boxWidth = Math.min(70, terminalWidth - 4);
138
-
139
- return boxen(content, {
140
- padding: 1,
141
- margin: {
142
- top: 1,
143
- bottom: 1,
144
- left: 2,
145
- right: 0,
146
- },
147
- borderStyle: "round",
148
- borderColor: "cyan",
149
- width: boxWidth,
150
- textAlignment: "left",
151
- float: "left",
152
- ...options,
153
- });
154
- }
155
-
156
- if (process.argv.includes('-v') || process.argv.includes('--version')) {
157
- console.log("\n"+chalk.hex("#e84d31")("git-tm") + ` version: ${chalk.cyan(VERSION)}`);
158
- process.exit(0);
159
- }
160
-
161
- program
162
- .name("git-tm")
163
- .description("Interactive Git repository visualization tool")
164
- .version(VERSION, '-v, --version', 'Output the current version')
165
- .argument("[repo-path]", "path to git repository")
166
- .option(
167
- "-p, --port <number>",
168
- "port to run the server on",
169
- DEFAULT_PORT.toString()
170
- )
171
- .helpOption(false)
172
- .addOption(new program.Option("-h, --help", "display help").hideHelp())
173
- .action(async (repoPath, options) => {
174
- if (options.help) {
175
- console.log(await getHelpText() + "\n");
176
- process.exit(0);
177
- }
178
- if (!repoPath) {
179
- console.log(await getHelpText() + '\n');
180
- process.exit(0);
181
- }
182
-
183
- await displayBanner();
184
- console.log();
185
-
186
- const fullPath = await validateGitRepo(repoPath);
187
- process.chdir(fullPath);
188
-
189
- const startingSpinner = createSpinner("Starting server...");
190
- startingSpinner.start();
191
-
192
- try {
193
- const port = await startServer(parseInt(options.port));
194
- startingSpinner.succeed(chalk.green("Server started successfully"));
195
-
196
- console.log(
197
- createBox(
198
- [
199
- chalk.cyan.bold("📂 Repository Information"),
200
- `${chalk.white("Path:")} ${chalk.yellow(fullPath)}`,
201
- "",
202
- chalk.cyan.bold("🚀 Server Information"),
203
- `${chalk.white("URL:")} ${chalk.green(
204
- `http://localhost:${port}`
205
- )}`,
206
- `${chalk.white("Port:")} ${chalk.cyan(port)}`,
207
- "",
208
- chalk.dim("Press Ctrl+C to stop the server"),
209
- ].join("\n")
210
- )
211
- );
212
-
213
- await sleep(5000);
214
-
215
- process.on("SIGINT", async () => {
216
- console.log(
217
- centerAlign(chalk.cyan("\nThanks for using Git Time Machine! 👋\n"))
218
- );
219
- process.exit(0);
220
- });
221
- } catch (error) {
222
- startingSpinner.fail(chalk.red("Failed to start server"));
223
- console.log(chalk.red(`Error: ${error.message}\n`));
224
- process.exit(1);
225
- }
226
- })
227
- .exitOverride(async (err) => {
228
- if (err.code === "commander.missingArgument") {
229
- console.log(await getHelpText() + "\n");
230
- process.exit(1);
231
- }
232
- throw err;
233
- });
234
-
235
- program.parse(process.argv);
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { parseArgs } from "node:util";
7
+ import { openRepo } from "./git.js";
8
+ import { createServer, listen } from "./server.js";
9
+
10
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
11
+
12
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== "dumb";
13
+ const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
14
+ const c = {
15
+ bold: paint("1"),
16
+ dim: paint("2"),
17
+ red: paint("31"),
18
+ green: paint("32"),
19
+ cyan: paint("36"),
20
+ accent: (s) => (useColor ? `\x1b[38;2;240;81;51m${s}\x1b[0m` : String(s)),
21
+ };
22
+
23
+ const HELP = `
24
+ ${c.accent(c.bold("git-tm"))} ${c.dim(`v${pkg.version}`)} Explore a repository's history in your browser
25
+
26
+ ${c.bold("Usage")}
27
+ git-tm [path] [options]
28
+ git tm [path] [options] ${c.dim("same thing, as a Git subcommand (use -h for help)")}
29
+
30
+ ${c.bold("Options")}
31
+ -p, --port <number> Port to listen on ${c.dim("(default 7890, next free port is used if busy)")}
32
+ --host <address> Interface to bind ${c.dim("(default 127.0.0.1)")}
33
+ -o, --open Open the browser once the server is running
34
+ --no-avatars Do not load author avatars from GitHub / Gravatar
35
+ -v, --version Print the version
36
+ -h, --help Print this help
37
+
38
+ ${c.bold("Examples")}
39
+ git-tm ${c.dim("current directory")}
40
+ git-tm ../other-repo ${c.dim("another repository")}
41
+ git-tm -p 8080 --open
42
+
43
+ ${c.dim(pkg.homepage)}
44
+ `;
45
+
46
+ function fail(message) {
47
+ console.error(`${c.red("error")} ${message}`);
48
+ console.error(c.dim("Run git-tm --help for usage."));
49
+ process.exit(1);
50
+ }
51
+
52
+ function parse() {
53
+ try {
54
+ return parseArgs({
55
+ allowPositionals: true,
56
+ options: {
57
+ port: { type: "string", short: "p", default: "7890" },
58
+ host: { type: "string", default: "127.0.0.1" },
59
+ open: { type: "boolean", short: "o", default: false },
60
+ "no-open": { type: "boolean", default: false }, // accepted for compatibility; opening is now opt-in
61
+ "no-avatars": { type: "boolean", default: false },
62
+ version: { type: "boolean", short: "v", default: false },
63
+ help: { type: "boolean", short: "h", default: false },
64
+ },
65
+ });
66
+ } catch (err) {
67
+ fail(err.message);
68
+ }
69
+ }
70
+
71
+ function openBrowser(url) {
72
+ const [cmd, args] =
73
+ process.platform === "darwin"
74
+ ? ["open", [url]]
75
+ : process.platform === "win32"
76
+ ? ["cmd", ["/c", "start", "", url]]
77
+ : ["xdg-open", [url]];
78
+ try {
79
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
80
+ child.on("error", () => {});
81
+ child.unref();
82
+ } catch {
83
+ /* no browser available; the URL is printed anyway */
84
+ }
85
+ }
86
+
87
+ function tildify(p) {
88
+ const home = os.homedir();
89
+ return p === home || p.startsWith(home + path.sep) ? "~" + p.slice(home.length) : p;
90
+ }
91
+
92
+ async function main() {
93
+ const { values, positionals } = parse();
94
+ if (values.help) return console.log(HELP);
95
+ if (values.version) return console.log(pkg.version);
96
+ if (positionals.length > 1) fail("Only one repository path can be given");
97
+
98
+ const port = Number(values.port);
99
+ if (!Number.isInteger(port) || port < 0 || port > 65535) fail(`Invalid port: ${values.port}`);
100
+
101
+ const target = path.resolve(positionals[0] ?? ".");
102
+ let repo;
103
+ try {
104
+ repo = await openRepo(target);
105
+ } catch (err) {
106
+ fail(err.message);
107
+ }
108
+
109
+ const server = createServer(repo, { avatars: !values["no-avatars"], host: values.host });
110
+ let actual;
111
+ try {
112
+ actual = await listen(server, port, values.host);
113
+ } catch (err) {
114
+ fail(`Could not start server: ${err.message}`);
115
+ }
116
+
117
+ const shownHost = ["127.0.0.1", "::1", "0.0.0.0", "::"].includes(values.host) ? "localhost" : values.host;
118
+ const url = `http://${shownHost}:${actual}`;
119
+ const info = await repo.info().catch(() => ({}));
120
+ const where = info.branch ?? (info.head ? info.head.slice(0, 7) : "no commits yet");
121
+
122
+ console.log();
123
+ console.log(` ${c.accent(c.bold("git-tm"))} ${c.dim(`v${pkg.version}`)}`);
124
+ console.log();
125
+ console.log(` ${c.dim("repo")} ${tildify(repo.root)} ${c.dim(`(${where})`)}`);
126
+ console.log(` ${c.dim("url ")} ${c.cyan(url)}`);
127
+ if (actual !== port && port !== 0) console.log(` ${c.dim(`port ${port} was busy, using ${actual}`)}`);
128
+ console.log();
129
+ console.log(c.dim(" Press Ctrl+C to stop"));
130
+ console.log();
131
+
132
+ if (values.open) openBrowser(url);
133
+
134
+ // Keep serving if something unexpected goes wrong; say what happened instead of dying silently.
135
+ const report = (err) => console.error(`${c.red("error")} ${err?.stack || err}`);
136
+ process.on("uncaughtException", report);
137
+ process.on("unhandledRejection", report);
138
+
139
+ const stop = () => {
140
+ server.close();
141
+ process.exit(0);
142
+ };
143
+ process.on("SIGINT", stop);
144
+ process.on("SIGTERM", stop);
145
+ }
146
+
147
+ main();