Update pycatfile.py
[PyCatFile.git] / pycatfilealt.py
blobd87993c0c7ff2c11136155fa4cf2042eca563d1c
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__)
14 class CatFilePacker:
15 def __init__(self, checksum_type='crc32'):
16 self.checksum_type = checksum_type
18 def pack_from_tar(self, tar_path, catfile_path):
19 try:
20 with tarfile.open(tar_path, 'r') as tar, open(catfile_path, 'wb') as catfile:
21 for member in tar.getmembers():
22 if member.isfile():
23 file_data = tar.extractfile(member).read()
24 packed_data = self._pack_file_data(file_data, member)
25 catfile.write(packed_data)
26 return True
27 except tarfile.TarError as e:
28 logger.error(f"Tar file error: {e}")
29 return False
30 except IOError as e:
31 logger.error(f"I/O error: {e}")
32 return False
33 except Exception as e:
34 logger.error(f"Unexpected error: {e}")
35 return False
37 def _pack_file_data(self, data, member):
38 metadata = self._create_metadata(member)
39 checksum = self._calculate_checksum(data)
40 metadata_length = len(metadata).to_bytes(4, byteorder='little')
41 data_length = len(data).to_bytes(4, byteorder='little')
42 packed_data = metadata_length + metadata + data_length + data + checksum
43 return packed_data
45 def _create_metadata(self, member):
46 name = member.name.encode('utf-8')
47 size = member.size.to_bytes(8, byteorder='little')
48 mtime = member.mtime.to_bytes(8, byteorder='little')
49 mode = member.mode.to_bytes(4, byteorder='little')
50 metadata = name + size + mtime + mode
51 return metadata
53 def _calculate_checksum(self, data):
54 if self.checksum_type == 'crc32':
55 checksum = zlib.crc32(data).to_bytes(4, byteorder='little')
56 else:
57 checksum = b'\x00' * 4 # Placeholder for unsupported checksum types
58 return checksum
61 if __name__ == "__main__":
62 parser = argparse.ArgumentParser(
63 description='Pack files from a TAR archive into a CAT file.')
64 parser.add_argument('tar_path', help='Path to the TAR file to pack')
65 parser.add_argument('catfile_path', help='Path to the CAT file to create')
66 args = parser.parse_args()
68 packer = CatFilePacker(checksum_type='crc32')
69 success = packer.pack_from_tar(args.tar_path, args.catfile_path)
70 if success:
71 logger.info("Packing completed successfully.")
72 else:
73 logger.error("Packing failed.")