git-tm 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 vHackBots
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ <div align="center">
2
+ <img src="./src/public/images/logo.svg" width="100" height="100">
3
+
4
+ <h1>Git Time Machine</h1>
5
+
6
+ <br/>
7
+ </div>
8
+
9
+ An elegant visual Git history explorer with real-time commit comparison capabilities.
10
+
11
+ Built for [FOSS Hack 2025](https://fossunited.org/fosshack/2025), Git Time Machine empowers developers to travel through their codebase history, debug with ease, and collaborate seamlessly. Whether you're auditing changes, resolving conflicts, or understanding project growth, this tool has you covered—all while staying true to the spirit of free and open-source software.
12
+
13
+ ---
14
+ ## Features
15
+
16
+ ### Core Functionality
17
+
18
+ - **Interactive Branch Navigation**:
19
+ - Visual branch list with color coding
20
+ - Support for both local and remote branches
21
+ - Easy branch switching and tracking
22
+
23
+ - **Rich Commit History**:
24
+ - Beautiful commit timeline visualization
25
+ - Emoji support for conventional commit messages
26
+ - Author avatars with GitHub profile integration
27
+ - Detailed commit metadata (author, date, hash)
28
+
29
+ - **Advanced Diff Viewer**:
30
+ - Side-by-side commit comparison
31
+ - Syntax-highlighted code diffs
32
+ - File status indicators (Added, Modified, Deleted)
33
+ - Collapsible diff sections by file
34
+ - Line number tracking for both versions
35
+ - Binary file detection
36
+
37
+ - **User Interface**:
38
+ - Modern glass-morphism design
39
+ - Responsive layout for all screen sizes
40
+ - Smooth animations and transitions
41
+ - Toast notifications for user feedback
42
+ - Collapsible comparison panel
43
+
44
+ ### Technical Features
45
+
46
+ - **Git Integration**:
47
+ - Full Git repository support
48
+ - Remote repository synchronization
49
+ - Branch checkout capabilities
50
+ - Comprehensive commit history
51
+
52
+ - **Performance**:
53
+ - Lazy loading of commit data
54
+ - Efficient diff parsing and rendering
55
+ - Optimized avatar loading with fallbacks
56
+ - Minimal memory footprint
57
+
58
+ ### Installation
59
+
60
+ <!-- to be done -->
61
+
62
+ ## Usage
63
+
64
+ 1. **Open a Project**:
65
+ - Clone a Git repository or open an existing project directory
66
+ - Ensure that the project has a valid Git history
67
+
68
+ 2. **Run the cli command**:
69
+ - Run the following command in the terminal:
70
+ ```bash
71
+ git-tm .
72
+ ```
73
+ - This will start the Git Time Machine server and open the web interface in your default browser
74
+
75
+ 3. **Explore the History**:
76
+ - Navigate through the commit history using the timeline
77
+ - Compare commits by selecting two different versions
78
+ - View detailed commit metadata and file changes
79
+ - Switch branches and track changes in real-time
80
+ - Enjoy the seamless Git experience!
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "git-tm",
3
+ "version": "0.1.0",
4
+ "description": "An elegant visual Git history explorer with real-time commit comparison capabilities",
5
+ "main": "src/cli.js",
6
+ "bin": {
7
+ "git-tm": "./src/cli.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node src/cli.js"
11
+ },
12
+ "type": "module",
13
+ "dependencies": {
14
+ "boxen": "^8.0.1",
15
+ "center-align": "^1.0.1",
16
+ "chalk": "^4.1.2",
17
+ "commander": "^11.1.0",
18
+ "express": "^4.18.2",
19
+ "figlet": "^1.6.0",
20
+ "gradient-string": "^3.0.0",
21
+ "open": "^10.0.3",
22
+ "ora": "^7.0.1",
23
+ "simple-git": "^3.22.0"
24
+ }
25
+ }
package/src/cli.js ADDED
@@ -0,0 +1,234 @@
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
+ await displayBanner();
66
+ console.log(chalk.yellow(`⚠️ Error: ${errorMessage}\n`));
67
+ console.log(await getHelpText() + "\n");
68
+ console.log(chalk.red("Exiting...\n"));
69
+ process.exit(exitCode);
70
+ }
71
+
72
+ async function validateGitRepo(repoPath) {
73
+ const spinner = createSpinner("Validating repository...");
74
+ spinner.start();
75
+
76
+ const fullPath = path.resolve(process.cwd(), repoPath);
77
+ const gitPath = path.join(fullPath, ".git");
78
+
79
+ if (!fs.existsSync(fullPath)) {
80
+ spinner.fail(chalk.red("Repository validation failed"));
81
+ await showErrorAndHelp(
82
+ `Directory does not exist: ${chalk.yellow(fullPath)}`
83
+ );
84
+ }
85
+
86
+ if (!fs.existsSync(gitPath)) {
87
+ spinner.fail(chalk.red("Repository validation failed"));
88
+ await showErrorAndHelp(
89
+ `Not a git repository: ${chalk.blue(
90
+ fullPath
91
+ )}\nMake sure the directory contains a .git folder`
92
+ );
93
+ }
94
+
95
+ spinner.succeed(chalk.green("Repository validated successfully"));
96
+ return fullPath;
97
+ }
98
+
99
+ async function getHelpText() {
100
+ return [
101
+ await displayBanner(),
102
+ chalk.bold("Usage:"),
103
+ ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ${chalk.cyan(
104
+ "<repository-path>"
105
+ )} [options]`,
106
+ "",
107
+ chalk.bold("Examples:"),
108
+ ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} . ${chalk.dim(
109
+ "Start with current directory"
110
+ )}`,
111
+ ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ./my-project ${chalk.dim(
112
+ "Start with specific repository"
113
+ )}`,
114
+ ` $ ${chalk.hex(GIT_ORANGE)("git-tm")} ${chalk.cyan("-p")} 8000 ./repo ${chalk.dim(
115
+ "Start with custom port"
116
+ )}`,
117
+ "",
118
+ chalk.bold("Options:"),
119
+ ` ${chalk.cyan("-p, --port")} <number> ${chalk.dim(
120
+ "Port to run the server (default: " + DEFAULT_PORT + ")"
121
+ )}`,
122
+ ` ${chalk.cyan("-h, --help")} ${chalk.dim(
123
+ "Display this help message"
124
+ )}`,
125
+ ` ${chalk.cyan("-V, --version")} ${chalk.dim(
126
+ "Output the version number"
127
+ )}`,
128
+ "",
129
+ chalk.bold("More Info:"),
130
+ ` ${chalk.blue("https://github.com/vHackBots/Git-Time-Machine")}`,
131
+ ].join("\n");
132
+ }
133
+
134
+ function createBox(content, options = {}) {
135
+ const terminalWidth = process.stdout.columns || 80;
136
+ const boxWidth = Math.min(70, terminalWidth - 4);
137
+
138
+ return boxen(content, {
139
+ padding: 1,
140
+ margin: {
141
+ top: 1,
142
+ bottom: 1,
143
+ left: 2,
144
+ right: 0,
145
+ },
146
+ borderStyle: "round",
147
+ borderColor: "cyan",
148
+ width: boxWidth,
149
+ textAlignment: "left",
150
+ float: "left",
151
+ ...options,
152
+ });
153
+ }
154
+
155
+ if (process.argv.includes('-v') || process.argv.includes('--version')) {
156
+ console.log("\n"+chalk.hex("#e84d31")("git-tm") + ` version: ${chalk.cyan(VERSION)}`);
157
+ process.exit(0);
158
+ }
159
+
160
+ program
161
+ .name("git-tm")
162
+ .description("Interactive Git repository visualization tool")
163
+ .version(VERSION, '-v, --version', 'Output the current version')
164
+ .argument("[repo-path]", "path to git repository")
165
+ .option(
166
+ "-p, --port <number>",
167
+ "port to run the server on",
168
+ DEFAULT_PORT.toString()
169
+ )
170
+ .helpOption(false)
171
+ .addOption(new program.Option("-h, --help", "display help").hideHelp())
172
+ .action(async (repoPath, options) => {
173
+ if (options.help) {
174
+ console.log(await getHelpText() + "\n");
175
+ process.exit(0);
176
+ }
177
+ if (!repoPath) {
178
+ console.log(await getHelpText() + '\n');
179
+ process.exit(0);
180
+ }
181
+
182
+ await displayBanner();
183
+ console.log();
184
+
185
+ const fullPath = await validateGitRepo(repoPath);
186
+ process.chdir(fullPath);
187
+
188
+ const startingSpinner = createSpinner("Starting server...");
189
+ startingSpinner.start();
190
+
191
+ try {
192
+ const port = await startServer(parseInt(options.port));
193
+ startingSpinner.succeed(chalk.green("Server started successfully"));
194
+
195
+ console.log(
196
+ createBox(
197
+ [
198
+ chalk.cyan.bold("📂 Repository Information"),
199
+ `${chalk.white("Path:")} ${chalk.yellow(fullPath)}`,
200
+ "",
201
+ chalk.cyan.bold("🚀 Server Information"),
202
+ `${chalk.white("URL:")} ${chalk.green(
203
+ `http://localhost:${port}`
204
+ )}`,
205
+ `${chalk.white("Port:")} ${chalk.cyan(port)}`,
206
+ "",
207
+ chalk.dim("Press Ctrl+C to stop the server"),
208
+ ].join("\n")
209
+ )
210
+ );
211
+
212
+ await sleep(5000);
213
+
214
+ process.on("SIGINT", async () => {
215
+ console.log(
216
+ centerAlign(chalk.cyan("\nThanks for using Git Time Machine! 👋\n"))
217
+ );
218
+ process.exit(0);
219
+ });
220
+ } catch (error) {
221
+ startingSpinner.fail(chalk.red("Failed to start server"));
222
+ console.log(chalk.red(`Error: ${error.message}\n`));
223
+ process.exit(1);
224
+ }
225
+ })
226
+ .exitOverride(async (err) => {
227
+ if (err.code === "commander.missingArgument") {
228
+ console.log(await getHelpText() + "\n");
229
+ process.exit(1);
230
+ }
231
+ throw err;
232
+ });
233
+
234
+ program.parse(process.argv);
package/src/git.js ADDED
@@ -0,0 +1,213 @@
1
+ import simpleGit from 'simple-git';
2
+
3
+ async function getRepoData() {
4
+ const git = simpleGit();
5
+ let isOffline = false;
6
+
7
+ const localData = await Promise.all([
8
+ git.branch(),
9
+ git.log(["--all"]),
10
+ git.tags(),
11
+ git.raw(["remote"]),
12
+ ]).catch((err) => {
13
+ console.error("Failed to get local repo data:", err);
14
+ return [null, null, null, ""];
15
+ });
16
+
17
+ try {
18
+ await git.fetch(["--all"]);
19
+ isOffline = false;
20
+ } catch (error) {
21
+ console.warn("Working in offline mode - using local data only");
22
+ isOffline = true;
23
+ }
24
+
25
+ const [localBranches, log, tags, remotes] = localData;
26
+
27
+ if (!localBranches || !log) {
28
+ throw new Error("Failed to read local repository data");
29
+ }
30
+
31
+ const localBranchList = localBranches.all.filter(
32
+ (branch) => !branch.includes("remotes/")
33
+ );
34
+
35
+ let remoteBranchList = [];
36
+ if (!isOffline && remotes) {
37
+ try {
38
+ const remoteBranches = await git.raw([
39
+ "for-each-ref",
40
+ "refs/remotes",
41
+ "--format=%(refname:short)",
42
+ ]);
43
+
44
+ remoteBranchList = remoteBranches
45
+ .split("\n")
46
+ .filter(
47
+ (branch) =>
48
+ branch &&
49
+ !branch.endsWith("/HEAD") &&
50
+ branch.split("/").length > 1 &&
51
+ !localBranchList.some((localBranch) =>
52
+ branch.endsWith("/" + localBranch)
53
+ )
54
+ )
55
+ .map((branch) => ({
56
+ name: branch.trim(),
57
+ fullName: "remotes/" + branch.trim(),
58
+ remote: branch.split("/")[0],
59
+ shortName: branch.split("/").slice(1).join("/"),
60
+ }));
61
+ } catch (error) {
62
+ console.error("Failed to get remote branches:", error);
63
+ }
64
+ }
65
+
66
+ const commits = log.all.map((commit) => ({
67
+ ...commit,
68
+ fullRefs: commit.refs
69
+ .split(",")
70
+ .map((ref) => ref.trim())
71
+ .filter(Boolean),
72
+ refs: commit.refs
73
+ .split(",")
74
+ .map((ref) => ref.trim())
75
+ .filter((ref) => ref && !ref.includes("tag:")),
76
+ }));
77
+
78
+ return {
79
+ commits,
80
+ branches: localBranchList,
81
+ remoteBranches: remoteBranchList,
82
+ current: localBranches.current,
83
+ tags: tags?.all || [],
84
+ isOffline,
85
+ };
86
+ }
87
+
88
+ async function getBranchCommits(branchName) {
89
+ const git = simpleGit();
90
+ try {
91
+
92
+ const { current: currentBranch } = await git.branch();
93
+ let baseBranch = currentBranch;
94
+
95
+ if (currentBranch !== 'main' && currentBranch !== 'master') {
96
+ try {
97
+ await git.show(["main"]);
98
+ baseBranch = "main";
99
+ } catch {
100
+ try {
101
+ await git.show(["master"]);
102
+ baseBranch = "master";
103
+ } catch {
104
+ baseBranch = currentBranch;
105
+ }
106
+ }
107
+ }
108
+
109
+ let targetBranch = branchName;
110
+ if (branchName.startsWith("remotes/")) {
111
+ if (branchName === "remotes/origin" || !branchName.includes("/")) {
112
+ return [];
113
+ }
114
+ targetBranch = branchName.replace("remotes/", "refs/remotes/");
115
+ }
116
+
117
+ if (targetBranch === baseBranch) {
118
+ const log = await git.log(["--first-parent", targetBranch]);
119
+ return log.all;
120
+ }
121
+
122
+ const revList = await git.raw([
123
+ "rev-list",
124
+ "--first-parent",
125
+ targetBranch,
126
+ "^" + baseBranch,
127
+ "--not",
128
+ "--all",
129
+ ]);
130
+
131
+ if (!revList.trim()) {
132
+ const log = await git.log(["--first-parent", targetBranch]);
133
+ return log.all;
134
+ }
135
+
136
+ const commits = [];
137
+ const commitHashes = revList.split("\n").filter((hash) => hash.trim());
138
+
139
+ for (const hash of commitHashes) {
140
+ if (!hash) continue;
141
+
142
+ const commitInfo = await git.show([
143
+ "--format=%H%n%an%n%ae%n%at%n%s%n%D",
144
+ "--no-patch",
145
+ hash,
146
+ ]);
147
+
148
+ const [
149
+ commitHash,
150
+ authorName,
151
+ authorEmail,
152
+ timestamp,
153
+ subject,
154
+ refs = "",
155
+ ] = commitInfo.split("\n");
156
+
157
+ commits.push({
158
+ hash: commitHash,
159
+ author_name: authorName,
160
+ author_email: authorEmail,
161
+ date: new Date(parseInt(timestamp) * 1000).toISOString(),
162
+ message: subject,
163
+ refs: refs,
164
+ });
165
+ }
166
+
167
+ return commits;
168
+ } catch (error) {
169
+ console.error("Failed to get branch commits:", error);
170
+ throw error;
171
+ }
172
+ }
173
+
174
+ async function compareCommits(commit1, commit2) {
175
+ const git = simpleGit();
176
+ try {
177
+ const diff = await git.raw([
178
+ "diff",
179
+ "--binary",
180
+ "-p",
181
+ "--no-color",
182
+ commit1,
183
+ commit2,
184
+ ]);
185
+ return diff;
186
+ } catch (error) {
187
+ console.error("Failed to compare commits:", error);
188
+ throw new Error(`Failed to compare commits: ${error.message}`);
189
+ }
190
+ }
191
+
192
+ async function checkoutRemoteBranch(branchName) {
193
+ const git = simpleGit();
194
+ try {
195
+ await git.checkout([
196
+ "-b",
197
+ branchName.split("/").slice(2).join("/"),
198
+ "--track",
199
+ branchName,
200
+ ]);
201
+ return true;
202
+ } catch (error) {
203
+ console.error("Failed to checkout branch:", error.message);
204
+ return false;
205
+ }
206
+ }
207
+
208
+ export {
209
+ getRepoData,
210
+ getBranchCommits,
211
+ compareCommits,
212
+ checkoutRemoteBranch,
213
+ };