-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.py
67 lines (57 loc) · 1.79 KB
/
add.py
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
import os
import pathlib
import time
from zlib import crc32
import structs
from compress import Compress, CompressionTypes
from tools import mkdostime
def add(filename: str, path: pathlib.Path, compresstype: int, offset: int):
version = 46 # Bzip2
flags = 0
extra = b""
centraldirectory = []
fileinfo = os.stat(filename)
f = open(filename, "rb").read()
filename = os.path.join(path, os.path.basename(filename))
os.path.abspath(filename)
# info("Compressing " + filename + "...")
modtime, moddate = mkdostime(time.localtime(fileinfo.st_ctime))
compressed = Compress(f, compresstype)
# Create the checksum for the file
checksum = crc32(f)
# Only set compressed if lower
if len(compressed) < len(f):
data = compressed
# Otherwise just store it
else:
data = f
compresstype = CompressionTypes.STORE.value
# Create the file header
header = structs.headerStruct.pack(
b"\x50\x4b\x03\x04",
version, flags, compresstype,
modtime, moddate,
checksum,
len(data), fileinfo.st_size,
len(filename), len(extra)
)
# Create the file header for the central directory
centralheader = structs.centralHeader(
b"\x50\x4b\x01\x02", 3 << 8 | 23,
version, flags, compresstype,
modtime, moddate,
checksum,
len(data), fileinfo.st_size,
len(filename), len(extra), len("Comment"),
0, 1, 0,
offset,
)
# Create the central directory object with all metadata
centraldirectory = {
"centralheader": centralheader,
"filename": filename,
"extra": extra,
"comment": "Comment"}
# Return data
file = header + bytes(filename, 'utf-8') + extra + data
return (file, centraldirectory)