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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::{fs::{File, self}, io::{self, Read, BufReader, BufWriter, Seek, Write}, error::Error, fmt, thread, path::{PathBuf, Path}};
use indicatif::ProgressBar;
use zip::{ZipArchive, write::FileOptions, ZipWriter};
use crossbeam_channel::{bounded, Sender, Receiver};
use crate::{minify::{only_recompress, MinifyType}, blacklist, fop::{FileOp, pack_file}, errors::ErrorCollector};
pub fn optimize_archive(
in_path: PathBuf,
out_path: PathBuf,
pb: ProgressBar,
errors: &mut dyn ErrorCollector,
file_opts: &FileOptions,
use_blacklist: bool
) -> io::Result<i64> {
let (tx, rx) = bounded(2);
let t1 = thread::spawn(move || {
let fin = File::open(in_path)?;
read_archive_entries(fin, tx, use_blacklist)
});
let fout = File::create(out_path)?;
let rsum = save_archive_entries(fout, rx, file_opts, errors, pb);
t1.join().unwrap()?;
rsum
}
pub fn optimize_fs_copy(
in_path: PathBuf,
out_path: PathBuf,
pb: ProgressBar,
errors: &mut dyn ErrorCollector,
use_blacklist: bool
) -> io::Result<i64> {
if in_path == out_path {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "The paths are the same"))
}
let (tx, rx) = bounded(2);
let t1 = thread::spawn(move || {
read_fs_entries(&in_path, tx, use_blacklist)
});
let rsum = save_fs_entries(&out_path, rx, errors, pb);
t1.join().unwrap()?;
rsum
}
pub fn save_archive_entries<W: Write + Seek>(
w: W,
rx: Receiver<EntryType>,
file_opts: &FileOptions,
ev: &mut dyn ErrorCollector,
pb: ProgressBar
) -> io::Result<i64> {
let mut dsum = 0;
let mut zw = ZipWriter::new(BufWriter::new(w));
let mut cnt = 0;
let mut cv = Vec::new();
for et in rx {
match et {
EntryType::Count(u) => {
pb.set_length(u);
}
EntryType::Directory(d) => {
if d != ".cache/" {
zw.add_directory(d, file_opts.clone())?;
}
}
EntryType::File(fname, buf, fop) => {
use FileOp::*;
cnt += 1;
pb.set_position(cnt);
pb.set_message(fname.clone());
match fop {
Recompress(cmin) => {
pack_file(
&mut zw,
&fname,
file_opts,
&buf,
cmin
)?;
}
Minify(m) => {
let fsz = buf.len() as i64;
let buf = match m.minify(&buf, &mut cv) {
Ok(()) => &cv,
Err(e) => {
ev.collect(fname.to_string(), e);
&buf
}
};
dsum -= (buf.len() as i64) - fsz;
pack_file(&mut zw, &fname, file_opts, &buf, m.compress_min())?;
cv.clear();
}
Ignore => {
ev.collect(fname.to_string(), Box::new(blacklist::BlacklistedFile));
}
Warn(x) => {
ev.collect(fname.to_string(), Box::new(StrError(x)));
pack_file(&mut zw, &fname, file_opts, &buf, 0)?;
}
Signfile => {
ev.collect(fname.to_string(), Box::new(StrError(ERR_SIGNFILE.to_string())));
}
}
}
}
}
pb.finish_with_message("Saving...");
zw.finish()?;
Ok(dsum)
}
fn check_file_by_name(fname: &str, use_blacklist: bool) -> FileOp {
use FileOp::*;
if fname.starts_with(".cache/") { return Ignore }
if fname.starts_with("META-INF/") {
let sub = &fname[9..];
match sub {
"MANIFEST.MF" => {return Recompress(64) }
"SIGNFILE.SF" | "SIGNFILE.DSA" => { return Signfile }
x if x.starts_with("SIG-") || [".DSA", ".RSA", ".SF"].into_iter().any(|e| x.ends_with(e)) => {
return Signfile
}
x if x.starts_with("services/") => { return Recompress(64) }
_ => {}
}
}
let ftype = fname.rsplit_once('.').unzip().1.unwrap_or("");
if ftype == "class" {
return Recompress(64)
}
if only_recompress(ftype) {
return Recompress(4)
}
if let Some(x) = MinifyType::by_extension(ftype) {
return Minify(x)
}
if use_blacklist && blacklist::can_ignore_type(ftype) { Ignore } else { Recompress(2) }
}
pub fn read_archive_entries<R: Read + Seek>(
r: R,
tx: Sender<EntryType>,
use_blacklist: bool
) -> io::Result<()> {
let mut za = ZipArchive::new(BufReader::new(r))?;
let jfc = za.len() as u64;
tx.send(EntryType::Count(jfc)).unwrap();
for i in 0..jfc {
let mut jf = za.by_index(i as usize)?;
let fname = jf.name().to_string();
tx.send(if fname.ends_with('/') {
EntryType::Directory(fname)
} else {
let fop = check_file_by_name(&fname, use_blacklist);
let mut obuf = Vec::new();
match fop {
FileOp::Ignore => {}
_ => {
obuf.reserve_exact(jf.size() as usize);
jf.read_to_end(&mut obuf)?;
}
}
EntryType::File(fname, obuf, fop)
}).unwrap();
}
Ok(())
}
pub fn save_fs_entries(
dest_dir: &Path,
rx: Receiver<EntryType>,
ev: &mut dyn ErrorCollector,
pb: ProgressBar
) -> io::Result<i64> {
let mut dsum = 0;
let mut cnt = 0;
let mut cv = Vec::new();
for et in rx {
match et {
EntryType::Count(u) => {
pb.set_length(u);
}
EntryType::Directory(dir) => {
let mut dp = PathBuf::from(dest_dir);
dp.push(dir);
fs::create_dir(dp)?;
}
EntryType::File(fname, buf, fop) => {
use FileOp::*;
cnt += 1;
pb.set_position(cnt);
pb.set_message(fname.clone());
let mut fp = PathBuf::from(dest_dir);
fp.push(fname.clone());
match fop {
Recompress(_) => {
fs::write(fp, buf)?;
}
Minify(m) => {
let fsz = buf.len() as i64;
let buf = match m.minify(&buf, &mut cv) {
Ok(()) => &cv,
Err(e) => {
ev.collect(fname.to_string(), e);
&buf
}
};
dsum -= (buf.len() as i64) - fsz;
fs::write(fp, buf)?;
cv.clear();
}
Ignore => {
ev.collect(fname, Box::new(blacklist::BlacklistedFile));
}
Warn(x) => {
ev.collect(fname, Box::new(StrError(x)));
fs::write(fp, buf)?;
}
Signfile => {
ev.collect(fname, Box::new(StrError(ERR_SIGNFILE.to_string())));
}
}
}
}
}
Ok(dsum)
}
pub fn read_fs_entries(
src_dir: &Path,
tx: Sender<EntryType>,
use_blacklist: bool
) -> io::Result<()> {
let mut vdir = Vec::new();
vdir.push(src_dir.to_owned());
while let Some(px) = vdir.pop() {
let rd = fs::read_dir(px)?.collect::<Result<Vec<_>, _>>()?;
tx.send(EntryType::Count(rd.len() as u64)).unwrap();
for de in rd {
let meta = de.metadata()?;
if meta.is_dir() {
let dp = de.path();
let dname = dp.strip_prefix(src_dir).expect("Subdir not in source dir")
.to_string_lossy().to_string();
vdir.push(dp);
tx.send(EntryType::Directory(dname)).unwrap();
} else if meta.is_file() {
let fp = de.path();
let fname = fp.strip_prefix(src_dir).expect("File not in source dir")
.to_string_lossy().to_string();
let fop = check_file_by_name(&fname, use_blacklist);
let ff = fs::read(fp)?;
tx.send(EntryType::File(fname, ff, fop)).unwrap();
}
}
}
Ok(())
}
pub enum EntryType {
Count(u64),
Directory(String),
File(String, Vec<u8>, FileOp)
}
#[derive(Debug)]
pub(crate) struct StrError(pub String);
impl Error for StrError {}
impl fmt::Display for StrError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
const ERR_SIGNFILE: &str = "This file cannot be repacked since it contains SHA-256 digests for zipped entries";