Add files via upload
[PyCatFile.git] / pycatfilealt.py
blobcc2e564a973ce2eda3f078dd8f304860fdd4302b
1 import os
2 import sys
3 import logging
4 import tarfile
5 import zlib
6 import argparse
7 from io import BytesIO
9 # Configure logging
10 logging.basicConfig(level=logging.INFO)
11 logger = logging.getLogger(__name__)
13 class CatFilePacker:
14 def __init__(self, checksum_type='crc32'):
15 self.checksum_type = checksum_type
17 def pack_from_tar(self, tar_path, catfile_path):
18 try:
19 with tarfile.open(tar_path, 'r') as tar, open(catfile_path, 'wb') as catfile:
20 for member in tar.getmembers():
21 if member.isfile():
22 file_data = tar.extractfile(member).read()
23 packed_data = self._pack_file_data(file_data, member)
24 catfile.write(packed_data)
25 return True
26 except tarfile.TarError as e:
27 logger.error(f"Tar file error: {e}")
28 return False
29 except IOError as e:
30 logger.error(f"I/O error: {e}")
31 return False
32 except Exception as e:
33 logger.error(f"Unexpected error: {e}")
34 return False
36 def _pack_file_data(self, data, member):
37 metadata = self._create_metadata(member)
38 checksum = self._calculate_checksum(data)
39 metadata_length = len(metadata).to_bytes(4, byteorder='little')
40 data_length = len(data).to_bytes(4, byteorder='little')
41 packed_data = metadata_length + metadata + data_length + data + checksum
42 return packed_data
44 def _create_metadata(self, member):
45 name = member.name.encode('utf-8')
46 size = member.size.to_bytes(8, byteorder='little')
47 mtime = member.mtime.to_bytes(8, byteorder='little')
48 mode = member.mode.to_bytes(4, byteorder='little')
49 metadata = name + size + mtime + mode
50 return metadata
52 def _calculate_checksum(self, data):
53 if self.checksum_type == 'crc32':
54 checksum = zlib.crc32(data).to_bytes(4, byteorder='little')
55 else:
56 checksum = b'\x00' * 4 # Placeholder for unsupported checksum types
57 return checksum
59 if __name__ == "__main__":
60 parser = argparse.ArgumentParser(description='Pack files from a TAR archive into a CAT file.')
61 parser.add_argument('tar_path', help='Path to the TAR file to pack')
62 parser.add_argument('catfile_path', help='Path to the CAT file to create')
63 args = parser.parse_args()
65 packer = CatFilePacker(checksum_type='crc32')
66 success = packer.pack_from_tar(args.tar_path, args.catfile_path)
67 if success:
68 logger.info("Packing completed successfully.")
69 else:
70 logger.error("Packing failed.")