vcs-cli-rajarshi 1.0.0__py3-none-any.whl

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.
vcs/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """
2
+ Python Version Control System - MVP Implementation
3
+ A minimal Git-like version control system with core functionality.
4
+ """
5
+
6
+ __version__ = "1.0.0"
7
+ __author__ = "VCS MVP"
vcs/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Allow the CLI to be run with ``python -m vcs``."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
vcs/cli.py ADDED
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ CLI interface for the Python Version Control System.
4
+ Provides a git-like command-line interface for version control operations.
5
+ """
6
+
7
+ import sys
8
+ import argparse
9
+ from pathlib import Path
10
+ from typing import List
11
+
12
+ from . import __version__
13
+ from .repository import Repository
14
+
15
+
16
+ class Colors:
17
+ """ANSI color codes for terminal output."""
18
+ HEADER = '\033[95m'
19
+ OKBLUE = '\033[94m'
20
+ OKCYAN = '\033[96m'
21
+ OKGREEN = '\033[92m'
22
+ WARNING = '\033[93m'
23
+ FAIL = '\033[91m'
24
+ ENDC = '\033[0m'
25
+ BOLD = '\033[1m'
26
+ UNDERLINE = '\033[4m'
27
+
28
+
29
+ class VCSCli:
30
+ """Command-line interface for VCS operations."""
31
+
32
+ def __init__(self):
33
+ self.repo = Repository()
34
+
35
+ def colorize(self, text: str, color: str) -> str:
36
+ """Add color to text if stdout is a TTY."""
37
+ if sys.stdout.isatty():
38
+ return f"{color}{text}{Colors.ENDC}"
39
+ return text
40
+
41
+ def print_success(self, message: str):
42
+ """Print success message."""
43
+ print(self.colorize(message, Colors.OKGREEN))
44
+
45
+ def print_error(self, message: str):
46
+ """Print error message."""
47
+ print(self.colorize(f"Error: {message}", Colors.FAIL), file=sys.stderr)
48
+
49
+ def print_warning(self, message: str):
50
+ """Print warning message."""
51
+ print(self.colorize(f"Warning: {message}", Colors.WARNING))
52
+
53
+ def print_info(self, message: str):
54
+ """Print info message."""
55
+ print(self.colorize(message, Colors.OKBLUE))
56
+
57
+ def cmd_init(self, args):
58
+ """Initialize a new repository."""
59
+ try:
60
+ if self.repo.init():
61
+ self.print_success("Initialized empty VCS repository")
62
+ else:
63
+ self.print_error("Repository already exists")
64
+ return 1
65
+ except Exception as e:
66
+ self.print_error(str(e))
67
+ return 1
68
+ return 0
69
+
70
+ def cmd_add(self, args):
71
+ """Add files to staging area."""
72
+ if not self.repo.is_repository():
73
+ self.print_error("Not a VCS repository")
74
+ return 1
75
+
76
+ if not args.files:
77
+ self.print_error("No files specified")
78
+ return 1
79
+
80
+ try:
81
+ results = self.repo.add(args.files)
82
+ failed = False
83
+ for file_path, status in results.items():
84
+ if status == "added":
85
+ self.print_success(f"Added: {file_path}")
86
+ else:
87
+ failed = True
88
+ self.print_error(f"{file_path}: {status}")
89
+ if failed:
90
+ return 1
91
+ except Exception as e:
92
+ self.print_error(str(e))
93
+ return 1
94
+ return 0
95
+
96
+ def cmd_commit(self, args):
97
+ """Create a new commit."""
98
+ if not self.repo.is_repository():
99
+ self.print_error("Not a VCS repository")
100
+ return 1
101
+
102
+ if not args.message:
103
+ self.print_error("Commit message required")
104
+ return 1
105
+
106
+ try:
107
+ commit_hash = self.repo.commit(args.message, args.author or "Unknown")
108
+ self.print_success(f"Committed: {commit_hash[:8]}")
109
+ except Exception as e:
110
+ self.print_error(str(e))
111
+ return 1
112
+ return 0
113
+
114
+ def cmd_status(self, args):
115
+ """Show repository status."""
116
+ if not self.repo.is_repository():
117
+ self.print_error("Not a VCS repository")
118
+ return 1
119
+
120
+ try:
121
+ status = self.repo.status()
122
+
123
+ # Print current branch
124
+ print(f"On branch {self.colorize(status['branch'], Colors.BOLD)}")
125
+ print()
126
+
127
+ # Print staged files
128
+ if status['staged']:
129
+ print(self.colorize("Changes to be committed:", Colors.OKGREEN))
130
+ for file_path in status['staged']:
131
+ print(f" {self.colorize('new file:', Colors.OKGREEN)} {file_path}")
132
+ print()
133
+
134
+ # Print modified files
135
+ if status['modified']:
136
+ print(self.colorize("Changes not staged for commit:", Colors.FAIL))
137
+ for file_path in status['modified']:
138
+ print(f" {self.colorize('modified:', Colors.FAIL)} {file_path}")
139
+ print()
140
+
141
+ # Print untracked files
142
+ if status['untracked']:
143
+ print(self.colorize("Untracked files:", Colors.WARNING))
144
+ for file_path in status['untracked']:
145
+ print(f" {file_path}")
146
+ print()
147
+
148
+ if not any([status['staged'], status['modified'], status['untracked']]):
149
+ self.print_info("Nothing to commit, working tree clean")
150
+
151
+ except Exception as e:
152
+ self.print_error(str(e))
153
+ return 1
154
+ return 0
155
+
156
+ def cmd_log(self, args):
157
+ """Show commit history."""
158
+ if not self.repo.is_repository():
159
+ self.print_error("Not a VCS repository")
160
+ return 1
161
+
162
+ try:
163
+ commits = self.repo.log(args.limit)
164
+ if not commits:
165
+ self.print_info("No commits yet")
166
+ return 0
167
+
168
+ for commit in commits:
169
+ print(self.colorize(f"commit {commit['hash']}", Colors.WARNING))
170
+ print(f"Author: {commit['author']}")
171
+ print(f"Date: {commit['timestamp']}")
172
+ print()
173
+ # Indent commit message
174
+ for line in commit['message'].split('\n'):
175
+ print(f" {line}")
176
+ print()
177
+
178
+ except Exception as e:
179
+ self.print_error(str(e))
180
+ return 1
181
+ return 0
182
+
183
+ def cmd_branch(self, args):
184
+ """Create or list branches."""
185
+ if not self.repo.is_repository():
186
+ self.print_error("Not a VCS repository")
187
+ return 1
188
+
189
+ try:
190
+ if args.name:
191
+ # Create branch
192
+ result = self.repo.branch(args.name)
193
+ self.print_success(result)
194
+ else:
195
+ # List branches
196
+ branches = self.repo.branch()
197
+ if not branches:
198
+ self.print_info("No branches found")
199
+ return 0
200
+
201
+ for branch in branches:
202
+ if branch['current']:
203
+ print(self.colorize(f"* {branch['name']}", Colors.OKGREEN))
204
+ else:
205
+ print(f" {branch['name']}")
206
+
207
+ except Exception as e:
208
+ self.print_error(str(e))
209
+ return 1
210
+ return 0
211
+
212
+ def cmd_checkout(self, args):
213
+ """Switch branches."""
214
+ if not self.repo.is_repository():
215
+ self.print_error("Not a VCS repository")
216
+ return 1
217
+
218
+ if not args.branch:
219
+ self.print_error("Branch name required")
220
+ return 1
221
+
222
+ try:
223
+ result = self.repo.checkout(args.branch)
224
+ self.print_success(result)
225
+ except Exception as e:
226
+ self.print_error(str(e))
227
+ return 1
228
+ return 0
229
+
230
+ def cmd_merge(self, args):
231
+ """Merge branches."""
232
+ if not self.repo.is_repository():
233
+ self.print_error("Not a VCS repository")
234
+ return 1
235
+
236
+ if not args.branch:
237
+ self.print_error("Branch name required")
238
+ return 1
239
+
240
+ try:
241
+ result = self.repo.merge(args.branch)
242
+ self.print_success(result)
243
+ except Exception as e:
244
+ self.print_error(str(e))
245
+ return 1
246
+ return 0
247
+
248
+
249
+ def create_parser() -> argparse.ArgumentParser:
250
+ """Create command-line argument parser."""
251
+ parser = argparse.ArgumentParser(
252
+ prog='vcs',
253
+ description='A minimal version control system',
254
+ epilog='Use "vcs <command> --help" for more information on a specific command.'
255
+ )
256
+ parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
257
+
258
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
259
+
260
+ # Init command
261
+ init_parser = subparsers.add_parser('init', help='Initialize a new repository')
262
+
263
+ # Add command
264
+ add_parser = subparsers.add_parser('add', help='Add files to staging area')
265
+ add_parser.add_argument('files', nargs='+', help='Files to add')
266
+
267
+ # Commit command
268
+ commit_parser = subparsers.add_parser('commit', help='Create a new commit')
269
+ commit_parser.add_argument('-m', '--message', required=True, help='Commit message')
270
+ commit_parser.add_argument('-a', '--author', help='Commit author')
271
+
272
+ # Status command
273
+ status_parser = subparsers.add_parser('status', help='Show repository status')
274
+
275
+ # Log command
276
+ log_parser = subparsers.add_parser('log', help='Show commit history')
277
+ log_parser.add_argument('-n', '--limit', type=int, default=10, help='Limit number of commits')
278
+
279
+ # Branch command
280
+ branch_parser = subparsers.add_parser('branch', help='Create or list branches')
281
+ branch_parser.add_argument('name', nargs='?', help='Branch name to create')
282
+
283
+ # Checkout command
284
+ checkout_parser = subparsers.add_parser('checkout', help='Switch branches')
285
+ checkout_parser.add_argument('branch', help='Branch name to switch to')
286
+
287
+ # Merge command
288
+ merge_parser = subparsers.add_parser('merge', help='Merge branches')
289
+ merge_parser.add_argument('branch', help='Branch name to merge')
290
+
291
+ return parser
292
+
293
+
294
+ def main(argv: List[str] = None) -> int:
295
+ """Main CLI entry point."""
296
+ parser = create_parser()
297
+ args = parser.parse_args(argv)
298
+
299
+ if not args.command:
300
+ parser.print_help()
301
+ return 1
302
+
303
+ cli = VCSCli()
304
+
305
+ # Route to appropriate command handler
306
+ command_handlers = {
307
+ 'init': cli.cmd_init,
308
+ 'add': cli.cmd_add,
309
+ 'commit': cli.cmd_commit,
310
+ 'status': cli.cmd_status,
311
+ 'log': cli.cmd_log,
312
+ 'branch': cli.cmd_branch,
313
+ 'checkout': cli.cmd_checkout,
314
+ 'merge': cli.cmd_merge,
315
+ }
316
+
317
+ handler = command_handlers.get(args.command)
318
+ if handler:
319
+ return handler(args)
320
+ else:
321
+ print(f"Unknown command: {args.command}", file=sys.stderr)
322
+ return 1
323
+
324
+
325
+ if __name__ == '__main__':
326
+ sys.exit(main())
vcs/repository.py ADDED
@@ -0,0 +1,474 @@
1
+ """Core storage and working-tree operations for the VCS CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import hashlib
7
+ import json
8
+ import re
9
+ from collections import deque
10
+ from datetime import datetime
11
+ from pathlib import Path, PurePosixPath
12
+ from typing import Any, Dict, List, Optional, Set
13
+
14
+
15
+ class Repository:
16
+ """A small, content-addressed local version control repository."""
17
+
18
+ def __init__(self, root_path: str = "."):
19
+ self.root_path = Path(root_path).resolve()
20
+ self.vcs_dir = self.root_path / ".vcs"
21
+ self.objects_dir = self.vcs_dir / "objects"
22
+ self.refs_dir = self.vcs_dir / "refs"
23
+ self.staging_file = self.vcs_dir / "staging.json"
24
+ self.head_file = self.vcs_dir / "HEAD"
25
+ self.config_file = self.vcs_dir / "config.json"
26
+
27
+ def init(self) -> bool:
28
+ """Initialize a new repository."""
29
+ if self.vcs_dir.exists():
30
+ return False
31
+
32
+ self.objects_dir.mkdir(parents=True)
33
+ (self.refs_dir / "heads").mkdir(parents=True)
34
+ self._write_json(self.staging_file, {})
35
+ self._write_text(self.head_file, "ref: refs/heads/main")
36
+ self._write_json(
37
+ self.config_file,
38
+ {"repository_version": "1", "created_at": datetime.now().isoformat()},
39
+ )
40
+ return True
41
+
42
+ def is_repository(self) -> bool:
43
+ return self.vcs_dir.is_dir()
44
+
45
+ def add(self, file_paths: List[str]) -> Dict[str, str]:
46
+ """Store files as binary objects and add them to the staging area."""
47
+ self._require_repository()
48
+ staging = self._read_json(self.staging_file, {})
49
+ results: Dict[str, str] = {}
50
+
51
+ for supplied_path in file_paths:
52
+ try:
53
+ relative_path, full_path = self._resolve_worktree_path(supplied_path)
54
+ except ValueError as exc:
55
+ results[supplied_path] = f"error: {exc}"
56
+ continue
57
+
58
+ if not full_path.exists():
59
+ results[supplied_path] = "error: file not found"
60
+ continue
61
+ if not full_path.is_file():
62
+ results[supplied_path] = "error: is not a regular file"
63
+ continue
64
+ if self._is_ignored(relative_path):
65
+ results[supplied_path] = "error: ignored by .vcsignore"
66
+ continue
67
+
68
+ content = full_path.read_bytes()
69
+ file_hash = self._hash_content(content)
70
+ self._store_object(file_hash, content)
71
+ staging[relative_path] = {
72
+ "hash": file_hash,
73
+ "mode": "100644",
74
+ "staged_at": datetime.now().isoformat(),
75
+ }
76
+ results[supplied_path] = "added"
77
+
78
+ self._write_json(self.staging_file, staging)
79
+ return results
80
+
81
+ def commit(self, message: str, author: str = "Unknown") -> str:
82
+ """Create a complete snapshot by applying staged files to the parent tree."""
83
+ self._require_repository()
84
+ staging = self._read_json(self.staging_file, {})
85
+ if not staging:
86
+ raise Exception("No changes staged for commit")
87
+
88
+ parent_hash = self._get_current_commit()
89
+ tree: Dict[str, Dict[str, str]] = {}
90
+ if parent_hash:
91
+ parent = self._get_commit(parent_hash)
92
+ if parent:
93
+ tree.update(parent.get("tree", {}))
94
+ tree.update(
95
+ {
96
+ path: {"hash": entry["hash"], "mode": entry.get("mode", "100644")}
97
+ for path, entry in staging.items()
98
+ }
99
+ )
100
+
101
+ commit = {
102
+ "message": message,
103
+ "author": author,
104
+ "timestamp": datetime.now().isoformat(),
105
+ "parent": parent_hash,
106
+ "tree": tree,
107
+ }
108
+ commit_hash = self._store_json_object(commit)
109
+ self._write_text(self._current_branch_file(), commit_hash)
110
+ self._write_json(self.staging_file, {})
111
+ return commit_hash
112
+
113
+ def status(self) -> Dict[str, Any]:
114
+ self._require_repository()
115
+ staging = self._read_json(self.staging_file, {})
116
+ committed_files = self._current_tree()
117
+
118
+ modified = []
119
+ for file_path, file_info in committed_files.items():
120
+ full_path = self.root_path / Path(file_path)
121
+ if not full_path.is_file():
122
+ modified.append(f"{file_path} (deleted)")
123
+ elif self._hash_content(full_path.read_bytes()) != file_info["hash"]:
124
+ modified.append(file_path)
125
+
126
+ untracked = [
127
+ path
128
+ for path in self._get_all_files()
129
+ if path not in committed_files
130
+ and path not in staging
131
+ and not self._is_ignored(path)
132
+ ]
133
+ return {
134
+ "branch": self._get_current_branch(),
135
+ "staged": sorted(staging),
136
+ "modified": sorted(modified),
137
+ "untracked": sorted(untracked),
138
+ }
139
+
140
+ def log(self, limit: int = 10) -> List[Dict[str, Any]]:
141
+ self._require_repository()
142
+ commits = []
143
+ current_hash = self._get_current_commit()
144
+ while current_hash and len(commits) < limit:
145
+ commit = self._get_commit(current_hash)
146
+ if not commit:
147
+ break
148
+ commits.append(
149
+ {
150
+ "hash": current_hash,
151
+ "message": commit["message"],
152
+ "author": commit["author"],
153
+ "timestamp": commit["timestamp"],
154
+ }
155
+ )
156
+ current_hash = commit.get("parent")
157
+ return commits
158
+
159
+ def branch(self, branch_name: Optional[str] = None) -> Any:
160
+ self._require_repository()
161
+ if branch_name is None:
162
+ current = self._get_current_branch()
163
+ return [
164
+ {"name": path.name, "current": path.name == current}
165
+ for path in sorted((self.refs_dir / "heads").iterdir())
166
+ if path.is_file()
167
+ ]
168
+
169
+ self._validate_branch_name(branch_name)
170
+ current_commit = self._get_current_commit()
171
+ if not current_commit:
172
+ raise Exception("No commits yet, cannot create branch")
173
+ branch_file = self.refs_dir / "heads" / branch_name
174
+ if branch_file.exists():
175
+ raise Exception(f"Branch '{branch_name}' already exists")
176
+ self._write_text(branch_file, current_commit)
177
+ return f"Branch '{branch_name}' created"
178
+
179
+ def checkout(self, branch_name: str) -> str:
180
+ """Switch branches only when doing so cannot discard local work."""
181
+ self._require_repository()
182
+ self._validate_branch_name(branch_name)
183
+ branch_file = self.refs_dir / "heads" / branch_name
184
+ if not branch_file.is_file():
185
+ raise Exception(f"Branch '{branch_name}' does not exist")
186
+
187
+ commit_hash = branch_file.read_text(encoding="utf-8").strip()
188
+ target_commit = self._get_commit(commit_hash) if commit_hash else None
189
+ target_tree = target_commit.get("tree", {}) if target_commit else {}
190
+ current_tree = self._current_tree()
191
+ self._assert_safe_worktree_change(current_tree, target_tree)
192
+ self._replace_worktree(current_tree, target_tree)
193
+ self._write_text(self.head_file, f"ref: refs/heads/{branch_name}")
194
+ return f"Switched to branch '{branch_name}'"
195
+
196
+ def merge(self, branch_name: str) -> str:
197
+ """Perform a three-way merge, aborting instead of choosing a conflict side."""
198
+ self._require_repository()
199
+ self._validate_branch_name(branch_name)
200
+ current_branch = self._get_current_branch()
201
+ if branch_name == current_branch:
202
+ raise Exception("Cannot merge branch into itself")
203
+
204
+ branch_file = self.refs_dir / "heads" / branch_name
205
+ if not branch_file.is_file():
206
+ raise Exception(f"Branch '{branch_name}' does not exist")
207
+
208
+ ours_hash = self._get_current_commit()
209
+ theirs_hash = branch_file.read_text(encoding="utf-8").strip()
210
+ if not theirs_hash:
211
+ return f"Branch '{branch_name}' has no commits"
212
+ if not ours_hash:
213
+ theirs = self._get_commit(theirs_hash) or {}
214
+ target_tree = theirs.get("tree", {})
215
+ self._assert_safe_worktree_change({}, target_tree)
216
+ self._replace_worktree({}, target_tree)
217
+ self._write_text(self._current_branch_file(), theirs_hash)
218
+ return f"Fast-forward merge of '{branch_name}'"
219
+
220
+ if self._is_ancestor(theirs_hash, ours_hash):
221
+ return "Already up to date"
222
+
223
+ ours = self._get_commit(ours_hash) or {}
224
+ theirs = self._get_commit(theirs_hash) or {}
225
+ ours_tree = ours.get("tree", {})
226
+ theirs_tree = theirs.get("tree", {})
227
+
228
+ if self._is_ancestor(ours_hash, theirs_hash):
229
+ self._assert_safe_worktree_change(ours_tree, theirs_tree)
230
+ self._replace_worktree(ours_tree, theirs_tree)
231
+ self._write_text(self._current_branch_file(), theirs_hash)
232
+ return f"Fast-forward merge of '{branch_name}'"
233
+
234
+ base_hash = self._find_merge_base(ours_hash, theirs_hash)
235
+ base = self._get_commit(base_hash) if base_hash else None
236
+ base_tree = base.get("tree", {}) if base else {}
237
+ merged_tree: Dict[str, Dict[str, str]] = {}
238
+ conflicts = []
239
+
240
+ for path in sorted(set(base_tree) | set(ours_tree) | set(theirs_tree)):
241
+ base_entry = base_tree.get(path)
242
+ ours_entry = ours_tree.get(path)
243
+ theirs_entry = theirs_tree.get(path)
244
+ if self._same_entry(ours_entry, theirs_entry):
245
+ chosen = ours_entry
246
+ elif self._same_entry(ours_entry, base_entry):
247
+ chosen = theirs_entry
248
+ elif self._same_entry(theirs_entry, base_entry):
249
+ chosen = ours_entry
250
+ else:
251
+ conflicts.append(path)
252
+ continue
253
+ if chosen is not None:
254
+ merged_tree[path] = chosen
255
+
256
+ if conflicts:
257
+ raise Exception("Merge conflict in: " + ", ".join(conflicts))
258
+
259
+ self._assert_safe_worktree_change(ours_tree, merged_tree)
260
+ commit = {
261
+ "message": f"Merge branch '{branch_name}'",
262
+ "author": "System",
263
+ "timestamp": datetime.now().isoformat(),
264
+ "parent": ours_hash,
265
+ "merge_parent": theirs_hash,
266
+ "tree": merged_tree,
267
+ }
268
+ new_hash = self._store_json_object(commit)
269
+ self._replace_worktree(ours_tree, merged_tree)
270
+ self._write_text(self._current_branch_file(), new_hash)
271
+ return f"Merged branch '{branch_name}'"
272
+
273
+ def _require_repository(self) -> None:
274
+ if not self.is_repository():
275
+ raise Exception("Not a VCS repository")
276
+
277
+ @staticmethod
278
+ def _hash_content(content: bytes) -> str:
279
+ return hashlib.sha1(content).hexdigest()
280
+
281
+ def _store_object(self, hash_value: str, content: bytes) -> None:
282
+ obj_file = self.objects_dir / hash_value[:2] / hash_value[2:]
283
+ if not obj_file.exists():
284
+ obj_file.parent.mkdir(parents=True, exist_ok=True)
285
+ obj_file.write_bytes(content)
286
+
287
+ def _get_object(self, hash_value: str) -> Optional[bytes]:
288
+ obj_file = self.objects_dir / hash_value[:2] / hash_value[2:]
289
+ return obj_file.read_bytes() if obj_file.is_file() else None
290
+
291
+ def _store_json_object(self, value: Dict[str, Any]) -> str:
292
+ content = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")
293
+ object_hash = self._hash_content(content)
294
+ self._store_object(object_hash, content)
295
+ return object_hash
296
+
297
+ def _get_current_branch(self) -> str:
298
+ content = self.head_file.read_text(encoding="utf-8").strip()
299
+ prefix = "ref: refs/heads/"
300
+ return content[len(prefix) :] if content.startswith(prefix) else "main"
301
+
302
+ def _current_branch_file(self) -> Path:
303
+ return self.refs_dir / "heads" / self._get_current_branch()
304
+
305
+ def _get_current_commit(self) -> Optional[str]:
306
+ branch_file = self._current_branch_file()
307
+ return branch_file.read_text(encoding="utf-8").strip() if branch_file.is_file() else None
308
+
309
+ def _get_commit(self, commit_hash: str) -> Optional[Dict[str, Any]]:
310
+ content = self._get_object(commit_hash)
311
+ if content is None:
312
+ return None
313
+ try:
314
+ return json.loads(content.decode("utf-8"))
315
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
316
+ raise Exception(f"Corrupt commit object {commit_hash}") from exc
317
+
318
+ def _current_tree(self) -> Dict[str, Dict[str, str]]:
319
+ commit_hash = self._get_current_commit()
320
+ commit = self._get_commit(commit_hash) if commit_hash else None
321
+ return commit.get("tree", {}) if commit else {}
322
+
323
+ def _assert_safe_worktree_change(
324
+ self,
325
+ current_tree: Dict[str, Dict[str, str]],
326
+ target_tree: Dict[str, Dict[str, str]],
327
+ ) -> None:
328
+ staging = self._read_json(self.staging_file, {})
329
+ if staging:
330
+ raise Exception("Staged changes would be overwritten; commit them before continuing")
331
+
332
+ changed = []
333
+ for path, info in current_tree.items():
334
+ full_path = self.root_path / Path(path)
335
+ if not full_path.is_file() or self._hash_content(full_path.read_bytes()) != info["hash"]:
336
+ changed.append(path)
337
+ if changed:
338
+ raise Exception("Local changes would be overwritten: " + ", ".join(sorted(changed)))
339
+
340
+ collisions = []
341
+ for path in target_tree:
342
+ if path not in current_tree and (self.root_path / Path(path)).exists():
343
+ collisions.append(path)
344
+ if collisions:
345
+ raise Exception("Untracked files would be overwritten: " + ", ".join(sorted(collisions)))
346
+
347
+ def _replace_worktree(
348
+ self,
349
+ current_tree: Dict[str, Dict[str, str]],
350
+ target_tree: Dict[str, Dict[str, str]],
351
+ ) -> None:
352
+ objects: Dict[str, bytes] = {}
353
+ for path, info in target_tree.items():
354
+ content = self._get_object(info["hash"])
355
+ if content is None:
356
+ raise Exception(f"Missing object {info['hash']} for {path}")
357
+ objects[path] = content
358
+
359
+ # Only remove files tracked by the current commit. Untracked files are preserved.
360
+ for path in set(current_tree) - set(target_tree):
361
+ full_path = self.root_path / Path(path)
362
+ if full_path.is_file():
363
+ full_path.unlink()
364
+
365
+ for path, info in target_tree.items():
366
+ full_path = self.root_path / Path(path)
367
+ full_path.parent.mkdir(parents=True, exist_ok=True)
368
+ full_path.write_bytes(objects[path])
369
+
370
+ def _get_all_files(self) -> Set[str]:
371
+ files = set()
372
+ for item in self.root_path.rglob("*"):
373
+ if item.is_file() and self.vcs_dir not in item.parents:
374
+ files.add(item.relative_to(self.root_path).as_posix())
375
+ return files
376
+
377
+ def _resolve_worktree_path(self, supplied_path: str) -> tuple[str, Path]:
378
+ full_path = (self.root_path / supplied_path).resolve()
379
+ try:
380
+ relative = full_path.relative_to(self.root_path)
381
+ except ValueError as exc:
382
+ raise ValueError("path is outside the repository") from exc
383
+ if relative.parts and relative.parts[0] == ".vcs":
384
+ raise ValueError("cannot add repository metadata")
385
+ return relative.as_posix(), full_path
386
+
387
+ def _ignore_patterns(self) -> List[str]:
388
+ ignore_file = self.root_path / ".vcsignore"
389
+ if not ignore_file.is_file():
390
+ return []
391
+ return [
392
+ line.strip().replace("\\", "/")
393
+ for line in ignore_file.read_text(encoding="utf-8").splitlines()
394
+ if line.strip() and not line.lstrip().startswith("#")
395
+ ]
396
+
397
+ def _is_ignored(self, path: str) -> bool:
398
+ posix_path = path.replace("\\", "/")
399
+ pure_path = PurePosixPath(posix_path)
400
+ ignored = False
401
+ for raw_pattern in self._ignore_patterns():
402
+ negate = raw_pattern.startswith("!")
403
+ pattern = raw_pattern[1:] if negate else raw_pattern
404
+ anchored = pattern.startswith("/")
405
+ pattern = pattern.lstrip("/")
406
+ if pattern.endswith("/"):
407
+ directory_pattern = pattern.rstrip("/")
408
+ parents = ["/".join(pure_path.parts[:index]) for index in range(1, len(pure_path.parts))]
409
+ matched = any(fnmatch.fnmatchcase(parent, directory_pattern) for parent in parents)
410
+ elif anchored:
411
+ matched = fnmatch.fnmatchcase(posix_path, pattern)
412
+ else:
413
+ matched = pure_path.match(pattern) or fnmatch.fnmatchcase(pure_path.name, pattern)
414
+ if matched:
415
+ ignored = not negate
416
+ return ignored
417
+
418
+ @staticmethod
419
+ def _validate_branch_name(branch_name: str) -> None:
420
+ if (
421
+ not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", branch_name)
422
+ or branch_name.endswith(".")
423
+ or ".." in branch_name
424
+ ):
425
+ raise Exception(f"Invalid branch name: '{branch_name}'")
426
+
427
+ @staticmethod
428
+ def _same_entry(left: Optional[Dict[str, str]], right: Optional[Dict[str, str]]) -> bool:
429
+ if left is None or right is None:
430
+ return left is right
431
+ return left.get("hash") == right.get("hash") and left.get("mode") == right.get("mode")
432
+
433
+ def _parents(self, commit_hash: str) -> List[str]:
434
+ commit = self._get_commit(commit_hash) or {}
435
+ return [value for value in (commit.get("parent"), commit.get("merge_parent")) if value]
436
+
437
+ def _ancestor_distances(self, start_hash: str) -> Dict[str, int]:
438
+ distances = {start_hash: 0}
439
+ queue = deque([start_hash])
440
+ while queue:
441
+ current = queue.popleft()
442
+ for parent in self._parents(current):
443
+ if parent not in distances:
444
+ distances[parent] = distances[current] + 1
445
+ queue.append(parent)
446
+ return distances
447
+
448
+ def _is_ancestor(self, possible_ancestor: str, commit_hash: str) -> bool:
449
+ return possible_ancestor in self._ancestor_distances(commit_hash)
450
+
451
+ def _find_merge_base(self, left_hash: str, right_hash: str) -> Optional[str]:
452
+ left = self._ancestor_distances(left_hash)
453
+ right = self._ancestor_distances(right_hash)
454
+ common = set(left) & set(right)
455
+ return min(common, key=lambda item: left[item] + right[item]) if common else None
456
+
457
+ @staticmethod
458
+ def _write_text(file_path: Path, content: str) -> None:
459
+ file_path.parent.mkdir(parents=True, exist_ok=True)
460
+ file_path.write_text(content, encoding="utf-8")
461
+
462
+ @staticmethod
463
+ def _read_json(file_path: Path, default: Any = None) -> Any:
464
+ if not file_path.exists():
465
+ return default
466
+ try:
467
+ return json.loads(file_path.read_text(encoding="utf-8"))
468
+ except (json.JSONDecodeError, OSError):
469
+ return default
470
+
471
+ @staticmethod
472
+ def _write_json(file_path: Path, data: Any) -> None:
473
+ file_path.parent.mkdir(parents=True, exist_ok=True)
474
+ file_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: vcs-cli-rajarshi
3
+ Version: 1.0.0
4
+ Summary: A minimal Git-like version control system
5
+ Author: Rajarshi Datta
6
+ License-Expression: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Environment :: Console
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # VCS
17
+
18
+ VCS is a small, educational, Git-like version control system written in Python.
19
+ It supports local snapshots, branches, safe checkout, and three-way merges while
20
+ keeping its on-disk format easy to inspect.
21
+
22
+ > VCS is an educational project, not a drop-in replacement for Git. The package
23
+ > is currently classified as alpha software.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install vcs-cli-rajarshi
29
+ ```
30
+
31
+ The distribution is named `vcs-cli-rajarshi`, and it installs the `vcs`
32
+ terminal command.
33
+
34
+ For local development:
35
+
36
+ ```bash
37
+ python -m pip install -e .
38
+ ```
39
+
40
+ ## Basic workflow
41
+
42
+ ```bash
43
+ mkdir my-project
44
+ cd my-project
45
+ vcs init
46
+
47
+ vcs add app.py
48
+ vcs commit -m "Initial commit" -a "Your Name"
49
+ vcs status
50
+ vcs log
51
+ ```
52
+
53
+ Branching and merging:
54
+
55
+ ```bash
56
+ vcs branch feature
57
+ vcs checkout feature
58
+ # edit and commit files
59
+ vcs checkout main
60
+ vcs merge feature
61
+ ```
62
+
63
+ Checkout and merge abort if they would overwrite staged changes, modified
64
+ tracked files, or colliding untracked files. A merge also aborts and lists the
65
+ paths when both branches changed the same file differently.
66
+
67
+ ## Ignoring files
68
+
69
+ Create a `.vcsignore` file in the repository root. It accepts common glob-style
70
+ patterns, directory patterns, comments, and `!` negation:
71
+
72
+ ```gitignore
73
+ __pycache__/
74
+ dist/
75
+ *.pyc
76
+ .env
77
+ !example.env
78
+ ```
79
+
80
+ ## Commands
81
+
82
+ - `vcs init`
83
+ - `vcs add <file> [<file> ...]`
84
+ - `vcs commit -m <message> [-a <author>]`
85
+ - `vcs status`
86
+ - `vcs log [-n <count>]`
87
+ - `vcs branch [<name>]`
88
+ - `vcs checkout <branch>`
89
+ - `vcs merge <branch>`
90
+
91
+ Run `vcs --help` or `vcs <command> --help` for command-line help.
92
+
93
+ ## Development and release
94
+
95
+ Run the tests with only the Python standard library:
96
+
97
+ ```bash
98
+ python -m unittest discover -s tests -v
99
+ ```
100
+
101
+ Build and validate a release:
102
+
103
+ ```bash
104
+ python -m pip install build twine
105
+ python -m build
106
+ python -m twine check dist/*
107
+ ```
108
+
109
+ Test the wheel in a fresh virtual environment before publishing. To publish:
110
+
111
+ ```bash
112
+ python -m twine upload dist/*
113
+ ```
114
+
115
+ ## Repository format
116
+
117
+ ```text
118
+ .vcs/
119
+ ├── objects/ # Binary-safe content-addressed objects
120
+ ├── refs/heads/ # Branch references
121
+ ├── HEAD # Current branch pointer
122
+ ├── config.json # Repository metadata
123
+ └── staging.json # Staging index
124
+ ```
125
+
126
+ VCS stores file objects byte-for-byte and hashes them with SHA-1 for educational
127
+ compatibility with the basic content-addressing idea. It does not provide Git's
128
+ network protocol, pack files, hooks, tags, rebase, or cryptographic signing.
@@ -0,0 +1,10 @@
1
+ vcs/__init__.py,sha256=Lb5u3H0iFfsYGZFgG8THPNQNhEK2GQGRa66SPSEAyT0,171
2
+ vcs/__main__.py,sha256=JOOBBMOL3dbVByKsG3UFEjYMa-DOJK-ZWMH5iO8WwyI,135
3
+ vcs/cli.py,sha256=IeZVe7M_RzCHs1vKcVIf1pjuMIw9fSwoOAoX3jn4uoU,10596
4
+ vcs/repository.py,sha256=ikx6UcRZwMHHTIRw70qj5_8w5NFPODw7lqoAIBQxyiI,19338
5
+ vcs_cli_rajarshi-1.0.0.dist-info/licenses/LICENSE,sha256=aBAzTsQ2iojTbycPe7MQWM7Cv4GNNGsJR2CuHPGDmwc,1071
6
+ vcs_cli_rajarshi-1.0.0.dist-info/METADATA,sha256=UwYYhOpxAOAomxvuSzn8KqXvhZbuWw98hqXK_IIB0dc,3050
7
+ vcs_cli_rajarshi-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ vcs_cli_rajarshi-1.0.0.dist-info/entry_points.txt,sha256=aBdYk7d4KJb6WZ1yRie6mRSXlmwQZZDMj8Khg54UxUw,37
9
+ vcs_cli_rajarshi-1.0.0.dist-info/top_level.txt,sha256=0dZ_VeWEegu9OiG5uKmX_A67QLisyqKdBzq-diyJ6a0,4
10
+ vcs_cli_rajarshi-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vcs = vcs.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Rajarshi Datta
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.
@@ -0,0 +1 @@
1
+ vcs