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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use crate::error::{GzippyError, GzippyResult};
use crate::format::CompressionFormat;
use std::env;
#[derive(Debug, Clone)]
pub struct GzippyArgs {
pub files: Vec<String>,
pub compression_level: u8,
pub block_size: usize,
pub processes: usize,
pub decompress: bool,
pub test: bool,
pub list: bool,
pub stdout: bool,
pub keep: bool,
pub force: bool,
pub quiet: bool,
pub verbose: bool,
pub verbosity: u8,
pub recursive: bool,
pub independent: bool,
pub suffix: String,
pub format: CompressionFormat,
pub help: bool,
pub version: bool,
pub license: bool,
pub rsyncable: bool,
pub no_name: bool,
pub no_time: bool,
pub name: bool,
pub time: bool,
pub comment: Option<String>,
pub alias: Option<String>,
pub huffman: bool,
pub rle: bool,
pub synchronous: bool,
pub best: bool,
pub fast: bool,
pub analyze: bool,
pub analyze_full: bool,
pub build_index: bool,
pub seek: Option<u64>,
pub index_file: Option<String>,
pub index_interval: usize,
pub zopfli_iterations: Option<u32>,
pub zopfli_no_split: bool,
pub zopfli_split_max: Option<u32>,
}
impl Default for GzippyArgs {
fn default() -> Self {
GzippyArgs {
files: Vec::new(),
compression_level: 6,
block_size: 128 * 1024, // 128KB
processes: num_cpus::get().max(1),
decompress: false,
test: false,
list: false,
stdout: false,
keep: false,
force: false,
quiet: false,
verbose: false,
verbosity: 0,
recursive: false,
independent: false,
suffix: ".gz".to_string(),
format: CompressionFormat::Gzip,
help: false,
version: false,
license: false,
rsyncable: false,
no_name: false,
no_time: false,
name: true,
time: true,
comment: None,
alias: None,
huffman: false,
rle: false,
synchronous: false,
best: false,
fast: false,
analyze: false,
analyze_full: false,
build_index: false,
seek: None,
index_file: None,
index_interval: 4 * 1024 * 1024, // 4 MB default
zopfli_iterations: None,
zopfli_no_split: false,
zopfli_split_max: None,
}
}
}
impl GzippyArgs {
pub fn parse() -> GzippyResult<Self> {
let mut args = GzippyArgs::default();
let mut argv: Vec<String> = env::args().collect();
argv.remove(0); // Remove program name
// Check for environment variables first
if let Ok(gzip_env) = env::var("GZIP") {
let gzip_args = parse_env_args(&gzip_env);
argv.splice(0..0, gzip_args);
}
if let Ok(pigz_env) = env::var("PIGZ") {
let pigz_args = parse_env_args(&pigz_env);
argv.splice(0..0, pigz_args);
}
let mut i = 0;
let mut in_options = true;
while i < argv.len() {
let arg = &argv[i];
if !in_options || !arg.starts_with('-') {
args.files.push(arg.clone());
i += 1;
continue;
}
if arg == "--" {
in_options = false;
i += 1;
continue;
}
if arg == "-" {
args.files.push(arg.clone());
i += 1;
continue;
}
// Parse long options
if arg.starts_with("--") {
match arg.as_str() {
"--help" => args.help = true,
"--version" => args.version = true,
"--license" => args.license = true,
"--decompress" | "--uncompress" => args.decompress = true,
"--test" => args.test = true,
"--list" => args.list = true,
"--stdout" | "--to-stdout" => args.stdout = true,
"--keep" => args.keep = true,
"--force" => args.force = true,
"--quiet" | "--silent" => {
args.quiet = true;
args.verbosity = 0;
}
"--verbose" => {
args.verbose = true;
args.verbosity = 2;
}
"--recursive" => args.recursive = true,
"--independent" => args.independent = true,
"--zlib" => {
args.format = CompressionFormat::Zlib;
args.suffix = ".zz".to_string();
}
"--zip" => {
args.format = CompressionFormat::Zip;
args.suffix = ".zip".to_string();
}
"--rsyncable" => args.rsyncable = true,
"--no-name" => {
args.no_name = true;
args.name = false;
args.no_time = true;
args.time = false;
}
"--no-time" => {
args.no_time = true;
args.time = false;
}
"--name" => {
args.name = true;
args.no_name = false;
args.time = true;
args.no_time = false;
}
"--time" => {
args.time = true;
args.no_time = false;
}
"--huffman" => args.huffman = true,
"--rle" => args.rle = true,
"--synchronous" => args.synchronous = true,
"--best" => {
args.best = true;
args.compression_level = 9;
}
"--fast" => {
args.fast = true;
args.compression_level = 1;
}
// Ultra compression: true zopfli (very slow)
"--ultra" => {
args.compression_level = 11;
}
// Maximum compression: libdeflate L12 (near-zopfli at reasonable speed)
"--max" => {
args.compression_level = 12;
}
"--no-block-split" => args.zopfli_no_split = true,
"--analyze" => args.analyze = true,
"--full" => args.analyze_full = true,
"--index" => args.build_index = true,
_ => {
// Handle options with values
if let Some(value) = arg.strip_prefix("--level=") {
args.compression_level = parse_compression_level(value)?;
} else if let Some(value) = arg.strip_prefix("--blocksize=") {
args.block_size = parse_block_size(value)?;
} else if let Some(value) = arg.strip_prefix("--processes=") {
args.processes = value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid processes: {}",
value
))
})?;
} else if let Some(value) = arg.strip_prefix("--suffix=") {
args.suffix = value.to_string();
} else if let Some(value) = arg.strip_prefix("--comment=") {
args.comment = Some(value.to_string());
} else if let Some(value) = arg.strip_prefix("--alias=") {
args.alias = Some(value.to_string());
} else if let Some(value) = arg.strip_prefix("--seek=") {
args.seek = Some(value.parse::<u64>().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid seek offset: {}",
value
))
})?);
} else if let Some(value) = arg.strip_prefix("--index-file=") {
args.index_file = Some(value.to_string());
} else if let Some(value) = arg.strip_prefix("--index-interval=") {
args.index_interval = value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid index interval: {}",
value
))
})?;
} else if let Some(value) = arg.strip_prefix("--zopfli-iterations=") {
args.zopfli_iterations = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid zopfli iterations: {}",
value
))
})?);
} else if let Some(value) = arg.strip_prefix("--block-split-max=") {
args.zopfli_split_max = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid block split max: {}",
value
))
})?);
} else if arg == "--level"
|| arg == "--blocksize"
|| arg == "--processes"
|| arg == "--suffix"
|| arg == "--comment"
|| arg == "--alias"
|| arg == "--zopfli-iterations"
|| arg == "--block-split-max"
{
// These require the next argument
if i + 1 >= argv.len() {
return Err(GzippyError::invalid_argument(format!(
"{} requires an argument",
arg
)));
}
i += 1;
let value = &argv[i];
match arg.as_str() {
"--level" => {
args.compression_level = parse_compression_level(value)?
}
"--blocksize" => args.block_size = parse_block_size(value)?,
"--processes" => {
args.processes = value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid processes: {}",
value
))
})?
}
"--suffix" => args.suffix = value.to_string(),
"--comment" => args.comment = Some(value.to_string()),
"--alias" => args.alias = Some(value.to_string()),
"--zopfli-iterations" => {
args.zopfli_iterations = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid zopfli iterations: {}",
value
))
})?)
}
"--block-split-max" => {
args.zopfli_split_max = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid block split max: {}",
value
))
})?)
}
_ => unreachable!(),
}
} else {
return Err(GzippyError::invalid_argument(format!(
"Unknown option: {}",
arg
)));
}
}
}
} else {
// Parse short options
let chars: Vec<char> = arg.chars().collect();
let mut j = 1; // Skip the initial '-'
while j < chars.len() {
match chars[j] {
'h' => args.help = true,
'V' => args.version = true,
'L' => args.license = true,
'd' => args.decompress = true,
't' => args.test = true,
'l' => args.list = true,
'c' => args.stdout = true,
'k' => args.keep = true,
'f' => args.force = true,
'q' => {
args.quiet = true;
args.verbosity = 0;
}
'v' => {
args.verbose = true;
args.verbosity += 1;
}
'r' => args.recursive = true,
'i' => args.independent = true,
'z' => {
args.format = CompressionFormat::Zlib;
args.suffix = ".zz".to_string();
}
'K' => {
args.format = CompressionFormat::Zip;
args.suffix = ".zip".to_string();
}
'R' => args.rsyncable = true,
'n' => {
args.no_name = true;
args.name = false;
args.no_time = true;
args.time = false;
}
'N' => {
args.name = true;
args.no_name = false;
args.time = true;
args.no_time = false;
}
'H' => args.huffman = true,
'U' => args.rle = true,
'Y' => args.synchronous = true,
'm' => {
args.no_time = true;
args.time = false;
}
'M' => {
args.time = true;
args.no_time = false;
}
'0'..='9' => {
let level = chars[j] as u8 - b'0';
args.compression_level = level;
}
'I' => args.zopfli_no_split = true,
'b' | 'p' | 'S' | 'C' | 'A' | 'F' | 'J' => {
// Save the option character before potentially modifying j
let opt_char = chars[j];
// These require values
let value = if j + 1 < chars.len() {
// Value is attached to the option
let value_str: String = chars[j + 1..].iter().collect();
j = chars.len(); // Skip the rest of the characters
value_str
} else {
// Value is the next argument
if i + 1 >= argv.len() {
return Err(GzippyError::invalid_argument(format!(
"-{} requires an argument",
opt_char
)));
}
i += 1;
argv[i].clone()
};
match opt_char {
'b' => args.block_size = parse_block_size(&value)?,
'p' => {
args.processes = value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid processes: {}",
value
))
})?
}
'S' => args.suffix = value,
'C' => args.comment = Some(value),
'A' => args.alias = Some(value),
'F' => {
args.zopfli_iterations = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid iterations: {}",
value
))
})?)
}
'J' => {
args.zopfli_split_max = Some(value.parse().map_err(|_| {
GzippyError::invalid_argument(format!(
"Invalid block split max: {}",
value
))
})?)
}
_ => unreachable!(),
}
}
_ => {
return Err(GzippyError::invalid_argument(format!(
"Unknown option: -{}",
chars[j]
)))
}
}
j += 1;
}
}
i += 1;
}
// Validate and adjust settings
if args.processes == 0 {
args.processes = 1;
}
// Level 0: no compression (store)
// Levels 1-9: gzip compatible
// Levels 10-12: ultra compression (libdeflate high levels)
if args.compression_level > 12 {
return Err(GzippyError::InvalidLevel(args.compression_level));
}
if args.block_size < 1024 {
return Err(GzippyError::InvalidBlockSize(
"Block size must be at least 1K".to_string(),
));
}
Ok(args)
}
pub fn use_zopfli(&self) -> bool {
self.compression_level == 11
|| self.zopfli_iterations.is_some()
|| self.zopfli_no_split
|| self.zopfli_split_max.is_some()
}
}
fn parse_env_args(env_str: &str) -> Vec<String> {
let mut args = Vec::new();
let mut current_arg = String::new();
let mut in_quotes = false;
for ch in env_str.chars() {
match ch {
'"' => in_quotes = !in_quotes,
' ' | '\t' if !in_quotes => {
if !current_arg.is_empty() {
args.push(current_arg.clone());
current_arg.clear();
}
}
_ => current_arg.push(ch),
}
}
if !current_arg.is_empty() {
args.push(current_arg);
}
args
}
fn parse_compression_level(value: &str) -> GzippyResult<u8> {
let level: u8 = value.parse().map_err(|_| {
GzippyError::invalid_argument(format!("Invalid compression level: {}", value))
})?;
if level > 12 {
return Err(GzippyError::InvalidLevel(level));
}
Ok(level)
}
fn parse_block_size(value: &str) -> GzippyResult<usize> {
let value = value.to_lowercase();
if value.is_empty() {
return Err(GzippyError::InvalidBlockSize(
"Empty block size".to_string(),
));
}
let (num_str, multiplier) = if value.ends_with('k') {
(&value[..value.len() - 1], 1024)
} else if value.ends_with('m') {
(&value[..value.len() - 1], 1024 * 1024)
} else if value.ends_with('g') {
(&value[..value.len() - 1], 1024 * 1024 * 1024)
} else {
(value.as_str(), 1)
};
let num: usize = num_str
.parse()
.map_err(|_| GzippyError::InvalidBlockSize(format!("Invalid block size: {}", value)))?;
Ok(num * multiplier)
}