10 logging
.basicConfig(level
=logging
.INFO
)
11 logger
= logging
.getLogger(__name__
)
15 def __init__(self
, checksum_type
='crc32'):
16 self
.checksum_type
= checksum_type
18 def pack_from_tar(self
, tar_path
, catfile_path
):
20 with tarfile
.open(tar_path
, 'r') as tar
, open(catfile_path
, 'wb') as catfile
:
21 for member
in tar
.getmembers():
23 file_data
= tar
.extractfile(member
).read()
24 packed_data
= self
._pack
_file
_data
(file_data
, member
)
25 catfile
.write(packed_data
)
27 except tarfile
.TarError
as e
:
28 logger
.error(f
"Tar file error: {e}")
31 logger
.error(f
"I/O error: {e}")
33 except Exception as e
:
34 logger
.error(f
"Unexpected error: {e}")
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
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
53 def _calculate_checksum(self
, data
):
54 if self
.checksum_type
== 'crc32':
55 checksum
= zlib
.crc32(data
).to_bytes(4, byteorder
='little')
57 checksum
= b
'\x00' * 4 # Placeholder for unsupported checksum types
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
)
71 logger
.info("Packing completed successfully.")
73 logger
.error("Packing failed.")