-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit.py
More file actions
2094 lines (1663 loc) · 71.2 KB
/
git.py
File metadata and controls
2094 lines (1663 loc) · 71.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import getpass
import hashlib
import logging
import os
import re
import stat
import struct
import time
import urllib.error
import urllib.request
import zlib
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
# Set up basic logging configuration
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
def object_exists(hash_sha1: str, repo_path: Path) -> bool:
"""
Checks if a Git object with the given hash exists in the repository.
Args:
hash_sha1 (str): The SHA-1 hash of the Git object to check.
repo_path (Path): Path to the repository root directory.
Returns:
bool: True if the object exists, False otherwise.
"""
object_dir = repo_path / ".git" / "objects" / hash_sha1[:2]
object_path = object_dir / hash_sha1[2:]
return object_path.is_file()
def write_git_object(sha1: str, content_compressed: bytes, repo_path: Path) -> Path:
"""
Writes compressed Git object content to the .git/objects directory.
Args:
sha1 (str): The SHA-1 hash of the object.
content_compressed (bytes): The compressed object content.
repo_path (Path): Path to the repository root directory.
Returns:
Path: Path to the written object file.
"""
object_dir = repo_path / ".git" / "objects"
object_dir.mkdir(parents=True, mode=0o775, exist_ok=True)
subdir = object_dir / sha1[:2]
subdir.mkdir(mode=0o775, exist_ok=True)
object_path = subdir / sha1[2:]
# Check if the file already exists before trying to open it
if object_path.is_file():
logger.info(f"Object {sha1} already exists. Skipping write.")
return object_path
with open(object_path, "wb") as f:
f.write(content_compressed)
object_path.chmod(0o444)
return object_path
def hash_object(
file_path: Union[str, Path], repo_path: Path, write_flag: bool = False
) -> Tuple[Optional[str], Optional[bytes], Optional[bytes]]:
"""
Computes the SHA-1 hash of a file and optionally writes it as a blob object.
Args:
file_path (str): Path to the file to hash.
repo_path (Path): Path to the repository root directory.
write_flag (bool): If True, writes the object to the Git database.
Returns:
tuple: (sha1_hash, file_content, full_content) or (None, None, None) on error.
"""
try:
with open(file_path, "rb") as f:
content = f.read()
except FileNotFoundError:
logger.error(f"Error: File '{file_path}' not found.")
return None, None, None
header = f"blob {len(content)}\x00".encode("utf-8")
full_content = header + content
sha1 = hashlib.sha1(full_content).hexdigest()
if write_flag:
compressed_content = zlib.compress(full_content)
write_git_object(sha1, compressed_content, repo_path)
return sha1, content, full_content
def initialize_git_repository() -> None:
"""
Initializes a new empty Git repository in the current directory.
Creates the .git directory structure with objects, refs, and HEAD file.
"""
logger.info("Initializing empty Git repository...")
git_dir = Path(".git")
git_dir.mkdir()
# Create standard Git directories
(git_dir / "objects").mkdir()
(git_dir / "refs").mkdir()
(git_dir / "refs" / "heads").mkdir()
# Create the HEAD file, which points to 'refs/heads/master'
with open(git_dir / "HEAD", "w") as f:
f.write("ref: refs/heads/master\n")
logger.info(f"Initialized empty Git repository in {Path.cwd() / '.git'}")
def ls_tree(args: argparse.Namespace, repo_path: Path) -> None:
"""
Lists the contents of a Git tree object.
Args:
args: Parsed command line arguments containing object_hash, r (recursive), and name_only flags.
repo_path (Path): Path to the repository root directory.
"""
object_hash = args.object_hash
recursive = args.r
name_only = args.name_only
# Read the Git object and its type
data, object_type, _ = read_git_object(object_hash, repo_path)
if data is None:
logger.error(f"Error: Object '{object_hash}' not found.")
return
# Check if the object is actually a tree
if object_type != b"tree":
logger.error(f"Error: Object '{object_hash}' is not a tree object.")
return
offset = 0
while offset < len(data):
# Find the end of the mode and name part (before the null byte)
null_byte_index = data.find(b"\x00", offset)
if null_byte_index == -1:
# Should not happen in a well-formed tree object
break
# Decode the mode and name part
mode_and_name_part = data[offset:null_byte_index].decode("utf-8")
mode, name = mode_and_name_part.split(" ", 1)
# The SHA-1 hash is 20 bytes long and follows the null byte
sha1_bytes_start = null_byte_index + 1
sha1_bytes_end = sha1_bytes_start + 20
sha1_bytes = data[sha1_bytes_start:sha1_bytes_end]
# Convert binary SHA-1 hash to its hexadecimal string representation
sha1_hex = sha1_bytes.hex()
# Check if the entry is a directory (mode 40000)
is_tree = mode == "40000"
# Print the output
if not name_only:
mode_formatted = f"0{mode}"
if is_tree:
logger.info(f"{mode_formatted} {object_type.decode()} {sha1_hex}\t{name}")
else:
logger.info(f"{mode_formatted} blob {sha1_hex}\t{name}")
else:
logger.info(name)
# If the recursive flag is set and the entry is a directory, call ls_tree recursively
if recursive and is_tree:
logger.info(f"\n{name}/")
ls_tree(argparse.Namespace(object_hash=sha1_hex, r=True, name_only=name_only), repo_path)
# Update the offset for the next entry
offset = sha1_bytes_end
def cat_file(option: str, object_hash: str, repo_path: Path) -> None:
"""
Displays content or type information for a Git object.
Args:
option (str): 'p' to print content, 't' to print type.
object_hash (str): The SHA-1 hash of the Git object.
repo_path (Path): Path to the repository root directory.
"""
data, object_type, _ = read_git_object(object_hash, repo_path)
if data:
if option == "p":
print(data.decode("utf-8"), end="")
elif option == "t":
logger.info(object_type.decode("utf-8") if object_type else "unknown")
else:
logger.error(f"Error: Object '{object_hash}' not found.")
def read_git_object(sha1: str, repo_path: Path) -> Tuple[Optional[bytes], Optional[bytes], Optional[int]]:
"""
Reads a Git object from disk and decompresses it.
Args:
sha1 (str): The SHA-1 hash of the Git object.
repo_path (Path): Path to the repository root directory.
Returns:
tuple: (content, object_type, size) or (None, None, None) on error.
"""
object_path = repo_path / ".git" / "objects" / sha1[:2] / sha1[2:]
if not object_path.is_file():
return None, None, None
try:
with open(object_path, "rb") as f:
compressed_content = f.read()
decompressed_content = zlib.decompress(compressed_content)
header, content = decompressed_content.split(b"\x00", 1)
obj_type, size_str = header.decode().split()
size = int(size_str)
return content, obj_type.encode(), size
except zlib.error as e:
return None, None, None
except Exception as e:
return None, None, None
def read_index(index_path: Path) -> List[Dict[str, Any]]:
"""
Reads the Git index file and parses its entries.
Args:
index_path (Path): Path to the Git index file.
Returns:
list: List of dictionaries containing index entry information.
"""
if not index_path.exists():
return []
entries = []
with open(index_path, "rb") as f:
data = f.read()
idx = 0
# Read header
magic, version, num_entries = struct.unpack(">4sLL", data[idx : idx + 12])
idx += 12
if magic != b"DIRC" or version != 2:
logger.error("Invalid index file header.")
return []
# Read entries
for _ in range(num_entries):
entry_data = data[idx : idx + 62]
ctime_s, ctime_n, mtime_s, mtime_n, dev, ino, mode, uid, gid, size, sha1_bytes, flags = struct.unpack(
">LLLLLLLLLL20sH", entry_data
)
idx += 62
path_end = data.find(b"\x00", idx)
path = data[idx:path_end].decode("utf-8", errors="surrogateescape")
idx = path_end + 1
# Adjust index for padding
padding = (8 - ((62 + len(path) + 1) % 8)) % 8
idx += padding
entries.append(
{
"ctime_s": ctime_s,
"ctime_n": ctime_n,
"mtime_s": mtime_s,
"mtime_n": mtime_n,
"dev": dev,
"ino": ino,
"mode": mode,
"uid": uid,
"gid": gid,
"size": size,
"sha1": sha1_bytes.hex(),
"flags": flags,
"path": path,
}
)
return entries
def write_index(index_path: Path, entries: List[Dict[str, Any]]) -> None:
"""
Writes index entries to the Git index file in binary format.
Args:
index_path (Path): Path to the Git index file.
entries (list): List of dictionaries containing index entry information.
"""
with open(index_path, mode="wb+") as f:
# Header
f.write(struct.pack(">4sLL", b"DIRC", 2, len(entries)))
# Entries
for entry in entries:
path_bytes = entry["path"].encode("utf-8")
flags = entry["flags"] | len(path_bytes)
f.write(
struct.pack(
">LLLLLLLLLL20sH",
entry["ctime_s"],
entry["ctime_n"],
entry["mtime_s"],
entry["mtime_n"],
entry["dev"],
entry["ino"],
entry["mode"],
entry["uid"],
entry["gid"],
entry["size"],
bytes.fromhex(entry["sha1"]),
flags,
)
)
f.write(path_bytes)
f.write(b"\x00")
# Padding
padding_len = (8 - ((62 + len(path_bytes) + 1) % 8)) % 8
f.write(b"\x00" * padding_len)
# SHA-1 checksum
f.seek(0)
checksum = hashlib.sha1(f.read()).digest()
f.write(checksum)
def set_object_permissions(repo_path: Path) -> None:
"""
Sets file permissions to 444 (read-only) for all Git object files.
Prevents 'badFilemode' errors by ensuring correct file permissions.
Args:
repo_path (Path): Path to the repository root directory.
"""
objects_path = repo_path / ".git" / "objects"
if not objects_path.is_dir():
logger.error("Error: .git/objects directory not found.")
return
logger.info("Setting object file permissions to 444...")
for root, dirs, files in os.walk(objects_path):
for file_name in files:
file_path = Path(root) / file_name
# Check if the file is an object file (e.g., not a packfile index)
if len(file_name) == 38 and len(Path(root).name) == 2:
try:
os.chmod(file_path, 0o444)
except OSError as e:
logger.error(f"Error changing permissions for {file_path}: {e}")
logger.info("Permissions updated successfully.")
def ls_files(repo_path: Path) -> None:
"""
Lists all files currently staged in the Git index.
Args:
repo_path (Path): Path to the repository root directory.
"""
index_path = repo_path / ".git" / "index"
entries = read_index(index_path)
for entry in entries:
logger.info(entry["path"])
def add(file_path: Union[str, Path], repo_path: Path) -> None:
"""
Adds a file to the Git index (staging area).
Args:
file_path (str): Path to the file to add.
repo_path (Path): Path to the repository root directory.
"""
file_path = Path(file_path)
if not file_path.is_file():
logger.error(f"Error: File '{file_path}' not found.")
return
# Hash the file content
content = file_path.read_bytes()
header = f"blob {len(content)}\x00".encode()
sha1 = hashlib.sha1(header + content).hexdigest()
# Write object to disk
object_exists_flag = object_exists(sha1, repo_path)
if not object_exists_flag:
write_git_object(sha1, zlib.compress(header + content), repo_path)
else:
logger.info(f"Object {sha1} already exists. Skipping write.")
# Read existing index entries
index_path = repo_path / ".git" / "index"
entries = read_index(index_path)
# Create new index entry
st = os.stat(file_path)
# CORRECTION: This section ensures the file mode is correct for Git.
# The original approach of using `st.st_mode` directly could lead to
# the 'badFilemode' warning because `os.stat` returns platform-specific
# bits that Git does not recognize or support.
# By explicitly setting the mode to either 100644 (regular file)
# or 100755 (executable file), we ensure the mode is always valid
# for Git's index format.
mode = st.st_mode
if stat.S_ISREG(mode):
if (mode & stat.S_IXUSR) or (mode & stat.S_IXGRP) or (mode & stat.S_IXOTH):
mode = 0o100755
else:
mode = 0o100644
elif stat.S_ISLNK(mode):
mode = 0o120000
else:
logger.error(f"Unsupported file type for '{file_path}'. Skipping.")
return
new_entry = {
"ctime_s": int(st.st_ctime),
"ctime_n": 0,
"mtime_s": int(st.st_mtime),
"mtime_n": 0,
"dev": st.st_dev,
"ino": st.st_ino,
"mode": mode, # Use the corrected mode
"uid": st.st_uid,
"gid": st.st_gid,
"size": st.st_size,
"sha1": sha1,
"flags": 0,
"path": str(file_path),
}
# Add or update the entry
new_entries = {entry["path"]: entry for entry in entries}
new_entries[str(file_path)] = new_entry
sorted_entries = sorted(new_entries.values(), key=lambda x: x["path"])
# Write the new index file
write_index(index_path, sorted_entries)
logger.info(f"Files to add to the index: - {file_path}")
def write_tree_command(repo_path: Path) -> str:
"""
Creates a tree object from the current index entries.
Args:
repo_path (Path): Path to the repository root directory.
Returns:
str: SHA-1 hash of the created tree object.
"""
entries = read_index(repo_path)
tree_hash = write_tree(entries, repo_path)
logger.info(tree_hash)
return tree_hash
def write_tree(entries: List[Dict[str, Any]], repo_path: Path) -> str:
"""
Recursively creates tree objects from index entries.
Args:
entries (list): List of index entries to create tree from.
repo_path (Path): Path to the repository root directory.
Returns:
str: SHA-1 hash of the created tree object.
"""
if not entries:
return ""
# Sort entries by path
entries.sort(key=lambda x: x["path"])
# Group entries into subtrees based on the directory
tree_entries = {}
for entry in entries:
parts = entry["path"].split("/", 1)
if len(parts) == 1:
# File at the current tree level
tree_entries[parts[0]] = {"mode": entry["mode"], "sha1": entry["sha1"], "path": entry["path"]}
else:
dirname, rest = parts
if dirname not in tree_entries:
tree_entries[dirname] = {"mode": 0o40000, "path": dirname, "children": []} # Directory mode
tree_entries[dirname]["children"].append({"path": rest, "sha1": entry["sha1"], "mode": entry["mode"]})
# Create tree content
tree_content = b""
for name, data in tree_entries.items():
mode = data["mode"]
if "children" in data:
# The entry is a subtree, call recursively
subtree_sha1 = write_tree(data["children"], repo_path)
sha1_bytes = bytes.fromhex(subtree_sha1)
else:
# The entry is a file, use the hash from the index
sha1_bytes = bytes.fromhex(data["sha1"])
mode_str = f"{mode:o}".encode("ascii")
tree_content += mode_str + b" " + name.encode("utf-8") + b"\x00" + sha1_bytes
header = f"tree {len(tree_content)}\x00".encode("utf-8")
full_content = header + tree_content
sha1 = hashlib.sha1(full_content).hexdigest()
# Write the tree object
compressed_content = zlib.compress(full_content)
write_git_object(sha1, compressed_content, repo_path)
return sha1
def get_author_info(repo_path: Path) -> Tuple[str, str]:
"""
Retrieves author information following Git's configuration hierarchy.
Checks environment variables, local config, then global config.
Args:
repo_path (Path): Path to the repository root directory.
Returns:
tuple: (author_name, author_email)
"""
# 1. Check environment variables
author_name = os.getenv("GIT_AUTHOR_NAME")
author_email = os.getenv("GIT_AUTHOR_EMAIL")
# If not found in environment variables, check your Git configuration
if not author_name or not author_email:
config_local_path = repo_path / ".git" / "config"
config_global_path = Path.home() / ".gitconfig"
config = ConfigParser()
# 2. Check the local configuration file
if config_local_path.is_file():
config.read(config_local_path)
if "user" in config and "name" in config["user"]:
author_name = config["user"]["name"]
if "user" in config and "email" in config["user"]:
author_email = config["user"]["email"]
# 3. Check the global configuration file if the local configuration is not sufficient
if (not author_name or not author_email) and config_global_path.is_file():
config.read(config_global_path)
if "user" in config and "name" in config["user"]:
author_name = config["user"]["name"]
if "user" in config and "email" in config["user"]:
author_email = config["user"]["email"]
# 4. Use default value if nothing found
if not author_name:
author_name = "Unknown User"
if not author_email:
author_email = "unknown.email@example.com"
return author_name, author_email
def commit_tree(tree_hash: str, parent_hash: Optional[str], message: str, repo_path: Path) -> str:
"""
Creates a new commit object with the specified tree and parent.
Args:
tree_hash (str): SHA-1 hash of the tree object.
parent_hash (str): SHA-1 hash of the parent commit (can be None).
message (str): Commit message.
repo_path (Path): Path to the repository root directory.
Returns:
str: SHA-1 hash of the created commit object.
"""
lines = [f"tree {tree_hash}"]
if parent_hash:
lines.append(f"parent {parent_hash}")
# Data for the commit creation
timestamp = int(time.time())
timezone_offset = time.strftime("%z", time.localtime())
author_name, author_email = get_author_info(repo_path)
author = f"{author_name} <{author_email}> {timestamp} {timezone_offset}"
committer = f"{author_name} <{author_email}> {timestamp} {timezone_offset}"
lines.append(f"author {author}")
lines.append(f"committer {committer}")
lines.append("")
lines.append(message + "\n")
content = "\n".join(lines).encode("utf-8")
header = f"commit {len(content)}\x00".encode("utf-8")
full_content = header + content
sha1 = hashlib.sha1(full_content).hexdigest()
# Write the commit object
compressed_content = zlib.compress(full_content)
write_git_object(sha1, compressed_content, repo_path)
logger.info(sha1)
return sha1
def commit(args: argparse.Namespace, repo_path: Path) -> None:
"""
Creates a new commit from staged changes in the index.
Args:
args: Parsed command line arguments containing the commit message.
repo_path (Path): Path to the repository root directory.
"""
if not (repo_path / ".git" / "index").is_file():
logger.error("Error: No staged changes. Use 'git add' to stage files first.")
return
tree_hash = write_tree_command(repo_path)
head_path = repo_path / ".git" / "HEAD"
if head_path.is_file():
with open(head_path, "r") as f:
head_ref = f.read().strip()
if head_ref.startswith("ref: "):
branch_name = head_ref.split(": ")[1]
branch_path = repo_path / ".git" / branch_name
if branch_path.is_file():
with open(branch_path, "r") as f:
parent_hash = f.read().strip()
else:
parent_hash = None
else:
parent_hash = None
commit_hash = commit_tree(tree_hash, parent_hash, args.message, repo_path)
if parent_hash is None:
logger.info(f"[{branch_name.split('/')[-1]} (root-commit) {commit_hash[:7]}] {args.message}")
else:
logger.info(f"[{branch_name.split('/')[-1]} {commit_hash[:7]}] {args.message}")
# Update the branch reference file
with open(branch_path, "w") as f:
f.write(commit_hash)
# Add the fix: Reset the index to the state of the new tree.
# This ensures `git status` correctly shows no pending changes.
create_index_file(tree_hash, repo_path)
# def clone_repository(repo_url, directory=None):
# """
# Clones a remote Git repository.
# """
# # 1. Parse repository URL
# match = re.match(r'https://github.com/([^/]+)/([^/]+)\.git', repo_url)
# if not match:
# logger.error("Error: Invalid GitHub repository URL.")
# return
# owner, repo_name = match.groups()
# if directory is None:
# directory = repo_name
# logger.info(f"Starting to clone repository from {repo_url}...")
# # 2. Get initial refs from the server
# git_service_url = f"https://github.com/{owner}/{repo_name}.git/info/refs?service=git-upload-pack"
# try:
# response = requests.get(git_service_url)
# response.raise_for_status()
# except requests.exceptions.RequestException as e:
# logger.error(f"Error while fetching refs from the server: {e}")
# return
# # 3. Find HEAD commit hash from server response
# head_hash = None
# head_ref = None
# data_str = response.text
# # Show data from the server (like in your log)
# logger.info("--- Data from server ---")
# logger.info(data_str)
# logger.info("------------------------")
# # Look for the symbolic HEAD reference, e.g., "symref=HEAD:refs/heads/master"
# symref_match = re.search(r'symref=HEAD:(\S+)', data_str)
# if symref_match:
# head_ref = symref_match.group(1)
# logger.info(f"Found symbolic HEAD reference pointing to: '{head_ref}'")
# else:
# # If there's no symref, try to find "HEAD" directly
# head_match = re.search(r'([0-9a-f]{40})\s+HEAD', data_str)
# if head_match:
# head_hash = head_match.group(1)
# logger.info(f"Found HEAD commit hash: {head_hash}")
# # If a symbolic reference was found, find its hash
# if head_ref:
# ref_match = re.search(fr'([0-9a-f]{{40}})\s+{re.escape(head_ref)}', data_str)
# if ref_match:
# head_hash = ref_match.group(1)
# logger.info(f"Found commit hash for '{head_ref}': {head_hash}")
# else:
# logger.error(f"Error: Could not find commit hash for branch '{head_ref}'.")
# return
# if not head_hash:
# logger.error("Error: Could not find HEAD commit hash.")
# return
# # 4. Create the new directory and initialize a Git repository
# if Path(directory).exists():
# logger.error(f"Error: Directory '{directory}' already exists.")
# return
# logger.info(f"Creating directory '{directory}'...")
# os.makedirs(directory)
# os.chdir(directory)
# logger.info("Initializing local repository...")
# initialize_git_repository()
# # 5. Update the .git/HEAD file
# head_file_path = Path('.git/HEAD')
# with open(head_file_path, 'w') as f:
# f.write(f"ref: {head_ref}\n")
# logger.info(f"Set local HEAD file to: {head_ref}")
# # 6. The rest of the cloning logic, e.g., fetching objects from the server, goes here
# logger.info(f"Fetching objects, starting from commit: {head_hash}")
# # Logic for fetching the commit and its tree is omitted here,
# # as it was not part of your original problem.
# logger.info("Cloning completed successfully!")
def setup_git_config(
repo_path: Path, remote_url: str, branch_name: str = "master", remote_name: str = "origin"
) -> None:
"""
Creates or updates the Git configuration file with repository settings.
Args:
repo_path (Path): Path to the repository root directory.
remote_url (str): URL of the remote repository.
branch_name (str): Name of the default branch (default: 'master').
remote_name (str): Name of the remote (default: 'origin').
"""
config = ConfigParser()
config_path = repo_path / ".git" / "config"
# Read the existing file if it exists
if config_path.is_file():
config.read(config_path)
# Set up the [core] section
if "core" not in config:
config["core"] = {
"repositoryformatversion": "0",
"filemode": "true",
"bare": "false",
"logallrefupdates": "true",
}
# Set up the [remote "origin"] section
remote_section = f'remote "{remote_name}"'
if not config.has_section(remote_section):
config[remote_section] = {"url": remote_url, "fetch": "+refs/heads/*:refs/remotes/origin/*"}
# Set up the [branch "master"] section
branch_section = f'branch "{branch_name}"'
if not config.has_section(branch_section):
config[branch_section] = {"remote": remote_name, "merge": f"refs/heads/{branch_name}"}
# Write the changes to the file
with open(config_path, "w") as configfile:
config.write(configfile)
def clone(repo_url: str, directory: Optional[str] = None) -> None:
"""
Clones a remote Git repository using the Smart HTTP protocol.
Args:
repo_url (str): URL of the repository to clone.
directory (str, optional): Directory name for the cloned repository.
"""
repo_url = repo_url if ".git" in repo_url else repo_url + ".git"
repo_name = directory if directory else repo_url.split("/")[-1].split(".git")[0]
logger.info(f"Cloning into '{repo_name}'...")
# 1. Discover refs (get the latest commit hash for the main branch)
logger.info("Fetching references...")
try:
request = urllib.request.Request(
url=f"{repo_url}/info/refs?service=git-upload-pack",
method="GET",
)
refs_response = urllib.request.urlopen(request)
if refs_response.getcode() >= 400:
raise urllib.error.HTTPError(
f"{repo_url}/info/refs?service=git-upload-pack",
refs_response.getcode(),
"HTTP Error",
refs_response.headers,
None,
)
except urllib.error.URLError as e:
logger.error(f"Error while fetching references: {e.reason}")
return
except urllib.error.HTTPError as e:
logger.error(f"HTTP Error while fetching references: {e.code} - {e.reason}")
return
logger.info("Full response from info/refs:")
data = refs_response.read().decode("utf-8")
head_commit_hash = find_head_commit(data)
if not head_commit_hash:
logger.error("Could not find HEAD commit hash. Exiting.")
return
logger.info(f"Fetched HEAD commit hash: {head_commit_hash}")
# 2. Request the packfile
logger.info("Sending request for packfile...")
want_line = f"want {head_commit_hash}\n"
want_payload = f"{len(want_line) + 4:04x}{want_line}".encode("utf-8")
flush_packet = b"0000"
done_line = "done\n"
done_payload = f"{len(done_line) + 4:04x}{done_line}".encode("utf-8")
full_payload = want_payload + flush_packet + done_payload
logger.debug(f"Constructed data sent in POST request: {full_payload!r}")
headers = {"Content-Type": "application/x-git-upload-pack-request"}
try:
req = urllib.request.Request(f"{repo_url}/git-upload-pack", data=full_payload, headers=headers, method="POST")
with urllib.request.urlopen(req) as response:
packfile_data = parse_packfile_response(response)
logger.info(f"Received response from server: {response.getcode()} {response.reason}")
if response.getcode() >= 400:
raise urllib.error.HTTPError(
f"HTTP Error: {response.getcode()}", response.getcode(), response.reason, response.headers, None
)
except urllib.error.HTTPError as e:
logger.error(f"HTTP Error: {e.code} {e.reason}")
return
except urllib.error.URLError as e:
logger.error(f"URL Error while requesting packfile: {e.reason}")
return
if not packfile_data:
logger.error("No packfile data found in the response.")
return
# 3. Unpack the packfile
logger.info("Unpacking the packfile...")
repo_path = Path(repo_name)
repo_path.mkdir(parents=True, mode=0o775, exist_ok=True)
git_dir = repo_path / ".git"
git_objests = git_dir / "objects"
git_pack = git_objests / "pack"
git_pack.mkdir(parents=True, mode=0o775, exist_ok=True)
git_info = git_objests / "info"
git_info.mkdir(parents=True, mode=0o775, exist_ok=True)
pack_path = git_pack / "pack-temp.pack"
with open(pack_path, "wb") as f:
f.write(packfile_data)
unpack_packfile(pack_path, repo_path)
set_object_permissions(repo_path)
# 4. Checkout the commit
logger.info(f"Checking out commit {head_commit_hash}...")
with open(git_dir / "HEAD", "w") as f:
f.write(f"ref: refs/heads/master\n")
refs_path = git_dir / "refs" / "heads"
refs_path.mkdir(parents=True, mode=0o775, exist_ok=True)
with open(refs_path / "master", "w") as f:
f.write(head_commit_hash + "\n")
remotes_dir = git_dir / "refs" / "remotes"
remotes_dir.mkdir(parents=True, mode=0o775, exist_ok=True)
origin_dir = remotes_dir / "origin"
origin_dir.mkdir(parents=True, mode=0o775, exist_ok=True)
with open(origin_dir / "master", "w") as f:
f.write(head_commit_hash + "\n")
checkout(head_commit_hash, repo_path)
setup_git_config(repo_path, repo_url)
logger.info("Cloning completed successfully!")
def find_head_commit(refs_text: str) -> Optional[str]:
"""
Parses Git references to find the HEAD commit hash.
Args:
refs_text (str): Raw text containing Git references.
Returns:
str: SHA-1 hash of the HEAD commit, or None if not found.
"""
lines = refs_text.strip().split("\n")
for line in lines:
parts = line.split()
if len(parts) == 2 and parts[1] == "refs/heads/main":
return parts[0][-40:]
for line in lines:
parts = line.split()
if len(parts) == 2 and parts[1] == "refs/heads/master":
return parts[0][-40:]
return None
def parse_packfile_response(response: Any) -> bytes:
"""
Extracts packfile data from a Git upload-pack response stream.
Args:
response: HTTP response object from git-upload-pack request.
Returns:
bytes: Raw packfile data, or empty bytes on error.
"""
packfile_data = b""
while response.readable() is True:
try:
chunk = response.read(8192)
if not chunk:
break # End of stream
# Check for the PACK header to find the start of the packfile
pack_header_start = chunk.find(b"PACK")
if pack_header_start != -1:
packfile_data += chunk[pack_header_start:]
# Once we find the header, the rest of the stream is the packfile
# so we can break the loop
while response.readable():
try:
remaining_chunk = response.read(8192)
if not remaining_chunk:
break # End of stream
packfile_data += remaining_chunk
except Exception as e:
logger.error(f"Error while reading the response stream: {e}")
return b"" # Return empty stream on error
break