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