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
|
use log::*;
use std::fs::read_dir;
use std::fs::read_link;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use walkdir::DirEntry;
use once_cell::sync::Lazy; // 1.3.1
use regex::Regex;
use std::borrow::Cow;
use std::fs::File;
use std::io;
use std::process::Command;
use std::sync::atomic::Ordering;
use zip::result::ZipResult;
use std::fs;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckType {
Tds,
Package,
}
pub struct Utils {
kind: CheckType,
}
impl Utils {
pub fn new(kind: CheckType) -> Utils {
Utils { kind }
}
pub fn check_filesize(&self, fsize: u64, dir_entry_str: &str) -> bool {
// if it is an empty file we don't need
// to check further
if fsize == 0 {
e0005!(dir_entry_str);
return false;
}
if fsize > 40 * 1024 * 1024 {
if self.kind == CheckType::Package {
w0005!(dir_entry_str, fsize / 1024 / 1024);
} else {
w0006!(dir_entry_str, fsize / 1024 / 1024);
}
return false;
}
true
}
// we check for the "good" characters, all other characters yield an
// error message
pub fn filename_has_bad_chars(&self, entry: &DirEntry, dir_entry_str: &str) {
let s = entry.file_name().to_str().unwrap();
for (i, c) in s.char_indices() {
match c {
'A'..='Z'
| '0'..='9'
| 'a'..='z'
| '+'
| ','
| '-'
| '.'
| '/'
| ':'
| '='
| '@'
| '_' => (),
_ => {
e0001!(c, dir_entry_str, i);
}
}
}
}
pub fn is_unwanted_directory(&self, entry: &str, dir_entry_str: &str) {
let names = ["__MACOSX"];
for n in &names {
if *n == entry {
e0018!(dir_entry_str);
};
}
}
pub fn check_for_hidden_file(&self, entry: &str, dir_entry_str: &str) {
if entry.starts_with('.') {
match self.kind {
CheckType::Package => {
e0007!(dir_entry_str);
}
CheckType::Tds => {
e0007t!(dir_entry_str);
}
}
}
}
// fname is the base name without the directory part
pub fn check_for_hidden_directory(&self, fname: &str, dir_entry_str: &str) {
// We have to single out '.' and './' as they denote just the current directory
// That case may happen if pkgcheck gets called like: `pkgcheck -d .` or `pkgcheck -d ./`
if fname == "." || fname == "./" {
return;
};
//if fname.map(|s| s.starts_with('.')).unwrap_or(false) {
if fname.starts_with('.') {
match self.kind {
CheckType::Package => {
e0006!(dir_entry_str);
}
CheckType::Tds => {
e0006t!(dir_entry_str);
}
}
}
}
pub fn check_for_temporary_file(&self, dir_entry_str: &str) {
static RE: Lazy<Regex> = Lazy::new(regex_temporary_file_endings);
if RE.is_match(dir_entry_str) {
match self.kind {
CheckType::Package => {
e0008!(dir_entry_str);
}
CheckType::Tds => {
e0008t!(dir_entry_str);
}
}
}
}
pub fn check_for_empty_directory(&self, dir_entry_str: &str, dir_entry_display: &str) {
match read_dir(dir_entry_str) {
// try to read the directory specified
Ok(contents) => {
if contents.count() == 0 {
match self.kind {
CheckType::Package => {
e0004!(dir_entry_display);
}
CheckType::Tds => {
// Note: Karl Berry recommended to issue a warning only
// as an empty directory in a TDS zip archive
// - is automatically deleted before including
// it in texlive
w0007!(dir_entry_display);
}
}
}
}
Err(e) => {
e0027!(dir_entry_display, e);
}
}
}
// just copied from zip-extensions-rs
pub fn zip_extract(archive_file: &Path, target_dir: &Path) -> ZipResult<()> {
let file = File::open(archive_file)?;
let mut archive = zip::ZipArchive::new(file)?;
archive.extract(target_dir)
}
pub fn unzip(&self, zip_archive: &str, out_dir: &str) -> ZipResult<()> {
let archive_file = PathBuf::from(zip_archive);
let target_dir = PathBuf::from(out_dir);
Utils::zip_extract(&archive_file, &target_dir)
}
}
pub fn temp_file_endings() -> Vec<(String, String)> {
// https://github.com/github/gitignore/blob/master/TeX.gitignore
// http://hopf.math.purdue.edu/doc/html/suffixes.html
let v = vec![
("-blx.aux", "bibliography auxiliary file"),
("-blx.bib", "bibliography auxiliary file"),
(".4ct", "htlatex related"),
(".4tc", "htlatex related"),
(".DS_Store", "Mac OS custom attribute file"),
(".acn", "glossaries related"),
(".acr", "glossaries related"),
(".alg", ""),
(".aux", "core latex auxiliary file"),
(".backup", "backup file"),
(".bak", "backup file"),
(".bbl", "bibliography auxiliary file"),
(".bcf", "bibliography auxiliary file"),
(".blg", "bibliography log file"),
(".brf", "hyperref related"),
(".cb", "core latex auxiliary file"),
(".cb2", "core latex auxiliary file"),
(".cpt", "cprotect related"),
(".dvi", "intermediate document"),
(".ent", ""),
(".fdb_latexmk", "latexmk related"),
(".fff", "endfloat related"),
(".fls", ""),
(".fmt", "core latex auxiliary file"),
(".fot", "core latex auxiliary file"),
(".gaux", "generated by gregoriotex"),
(".glg", "glossary related"),
(".glo", "glossary related"),
(".glog", "generated by gregoriotex"),
(".gls", "glossary related"),
(".glsdefs", "glossaries related"),
(".gtex", "generated by gregoriotex"),
(".hd", ""),
(".idv", "htlatex related"),
(".idx", "makeidx related"),
(".ilg", "makeidx related"),
(".ind", "makeidx related"),
(".lg", "htlatex related"),
(".loa", "core latex auxiliary file (list of algorithms)"),
(".lod", "generated by easy-todo"),
(".lof", "core latex auxiliary file (list of figures)"),
(".log", "a log file for any flavor of TeX"),
(".lol", "core latex auxiliary file (list of listings)"),
(".los", "list of slides"),
(".lot", "core latex auxiliary file"),
(".lox", ""),
(".lyx#", "LyX related autosave file"),
(".maf", "generated by minitoc"),
(".mlc", "generated by minitoc"),
(".mlf", "generated by minitoc"),
(".mlt", "generated by minitoc"),
(".nav", "beamer related"),
(".nlg", ""),
(".nlo", ""),
(".nls", ""),
(".o", "C object file"),
(".out", "Core latex auxiliary file"),
(".pdfsync", "pdfsync related"),
(".pre", "beamer related"),
(".pyg", ""),
(".run.xml", ""),
(".sav", "used for saved data"),
(".snm", "beamer related"),
(".soc", ""),
(".spl", "elsarticle related"),
(".sta", "generated by standalone package"),
(".swp", "vim swap file"),
(".synctex", "synctex related"),
(".synctex(busy)", "synctex related"),
(".synctex.gz", "synctex related"),
(".synctex.gz(busy)", "synctex related"),
(".tpt", ""),
(".tdo", "generated by todonotes (list of todos)"),
(".thm", "amsthm related"),
(".tmb", "generated by thumbs package"),
(".tmp", "indicates a temporary file"),
(".toc", "core latex auxiliary file (table of contents)"),
(".trc", "htlatex related"),
(".ttt", "endfloat related"),
(".tuc", ""),
(".upa", "generated by the soulpos package"),
(".upb", "generated by the soulpos package"),
(".url", "generated by jurabib"),
(".vrb", "beamer related"),
(".w18", "temporary file for the ifplatform package"),
(".xdv", "intermediate document"),
(".xref", "htlatex related"),
(".xray", "dump of \\show output"),
("~", "a file name ending with ~ (tilde) is temporary anyway"),
("Thumbs.db", "thumbnails file in Windows"),
];
v.into_iter()
.map(|(i, j)| (i.to_string(), j.to_string()))
.collect()
}
pub fn regex_temporary_file_endings() -> Regex {
let mut rv = String::new();
let mut first_time = true;
for (p, _) in temp_file_endings() {
if first_time {
rv.push('(');
first_time = false;
} else {
rv.push('|');
}
let px = str::replace(&p, ".", "\\.");
rv.push_str(&px);
}
rv.push_str(")$");
Regex::new(&rv).unwrap()
}
pub fn get_symlink(entry: &DirEntry) -> Result<Option<PathBuf>, io::Error> {
let r = entry.path().to_str().unwrap();
match read_link(r) {
Ok(o) => {
let full_path = if o.is_absolute() {
o
} else {
// make the relative path absolute
let p = entry.path().parent().unwrap();
p.join(&o)
};
if full_path.exists() {
Ok(Some(full_path))
} else {
Ok(None)
}
}
Err(e) => Err(e),
}
}
pub fn _is_symlink_broken(entry: &DirEntry) -> Result<bool, io::Error> {
let r = entry.path().to_str().unwrap();
match read_link(r) {
Ok(o) => {
let full_path = if o.is_absolute() {
o
} else {
// make the relative path absolute
let p = entry.path().parent().unwrap();
p.join(&o)
};
Ok(!full_path.exists())
}
Err(e) => Err(e),
}
}
// Runs `pdfinfo` to check a PDF document. If `pdfinfo`
// returns non zero we assume that the PDF document is
// corrupted.
pub fn is_pdf_ok(fname: &str) -> CmdReturn {
run_cmd("pdfinfo", &[fname])
}
pub fn get_perms(path: &Path) -> u32 {
match path.metadata() {
Ok(p) => p.permissions().mode(),
Err(_e) => 0,
}
}
pub fn others_match(p: u32, m: u32) -> bool {
p == m
}
#[test]
fn test_others_have() {
assert_eq!(others_have(0o600, 4), false);
assert_eq!(others_have(0o601, 4), false);
assert_eq!(others_have(0o602, 4), false);
assert_eq!(others_have(0o603, 4), false);
assert_eq!(others_have(0o604, 4), true);
assert_eq!(others_have(0o605, 4), true);
assert_eq!(others_have(0o606, 4), true);
assert_eq!(others_have(0o607, 4), true);
}
// It checks if a permission `p` has the bits
// given in `m` set for others
pub fn others_have(p: u32, m: u32) -> bool {
let p1 = p & 0o0007;
p1 & m == m
}
#[test]
fn test_owner_has() {
assert_eq!(owner_has(0o000, 4), false);
assert_eq!(owner_has(0o100, 4), false);
assert_eq!(owner_has(0o200, 4), false);
assert_eq!(owner_has(0o300, 4), false);
assert_eq!(owner_has(0o400, 4), true);
assert_eq!(owner_has(0o505, 4), true);
assert_eq!(owner_has(0o605, 4), true);
assert_eq!(owner_has(0o705, 4), true);
}
// It checks if a permission `p` has the bits
// given in `m` set for the owner.
pub fn owner_has(p: u32, m: u32) -> bool {
let p1 = p & 0o7777;
let m1 = m << 6;
p1 & m1 == m1
}
#[allow(dead_code)]
fn owner_match(p: u32, m: u32) -> bool {
let p1 = p & 0o0700;
let m1 = m << 6;
p1 == m1
}
// Formats a permission value to octal for output
pub fn perms_to_string(p: u32) -> Cow<'static, str> {
format!("{:04o}", p & 0o7777).into()
}
pub struct CmdReturn {
pub status: bool,
pub output: Option<String>,
}
// Runs a command in a shell
// If the command returns 0 stdout gets captured. Otherwise
// stderr gets captured and returned.
pub fn run_cmd(cmd: &str, argument: &[&str]) -> CmdReturn {
let output = Command::new(cmd)
.args(argument.iter())
.output()
.unwrap_or_else(|_| panic!("Failed to execute process `{}`", cmd));
if output.status.success() {
CmdReturn {
status: true,
output: Some(String::from_utf8_lossy(&output.stdout).to_string()),
}
} else {
CmdReturn {
status: false,
output: Some(String::from_utf8_lossy(&output.stderr).to_string()),
}
}
}
// returns true if file is a directory and does exist
// returns false otherwise
pub fn exists_dir(file: &str) -> bool {
match fs::metadata(file) {
Ok(attr) => attr.is_dir(),
Err(_) => false,
}
}
// returns true if file is a regular file and does exist
// returns false otherwise
pub fn exists_file(file: &str) -> bool {
match fs::metadata(file) {
Ok(attr) => attr.is_file(),
Err(_) => false,
}
}
#[test]
fn test_dirname() {
assert!(dirname("/etc/fstab") == Some("/etc"));
assert!(dirname("/etc/") == Some("/etc"));
assert!(dirname("/") == Some("/"));
}
#[allow(dead_code)]
pub fn dirname(entry: &str) -> Option<&str> {
if let Some(stripped) = entry.strip_suffix('/') {
if entry.len() == 1 {
return Some(entry);
}
return Some(stripped);
}
let pos = entry.rfind('/');
match pos {
None => None,
Some(pos) => Some(&entry[..pos]),
}
}
#[test]
fn test_format_duration() {
assert!(format_duration(&Duration::new(5, 0)) == String::from("5sec"));
assert!(format_duration(&Duration::new(105, 0)) == String::from("1min 45sec"));
assert!(format_duration(&Duration::new(3801, 0)) == String::from("1h 3min 21sec"));
assert!(format_duration(&Duration::new(25449, 0)) == String::from("7h 4min 9sec"));
assert!(format_duration(&Duration::new(108245, 0)) == String::from("1d 6h 4min 5sec"));
assert!(format_duration(&Duration::new(0, 0)) == String::from("0sec"));
}
#[test]
fn test_filename() {
assert!(filename("/etc/fstab") == Some("fstab"));
assert!(filename("fstab") == Some("fstab"));
assert!(filename("../pkgcheck.rs/testdirs/fira.tds.zip") == Some("fira.tds.zip"));
assert!(filename("/etc/") == None);
assert!(filename("/") == None);
}
// We return the right part of a path name if it does not end with a `/`
pub fn filename(entry: &str) -> Option<&str> {
if entry.ends_with('/') {
return None;
}
let pos = entry.rfind('/');
match pos {
None => Some(entry),
Some(pos) => Some(&entry[pos + 1..]),
}
}
// Found here: https://codereview.stackexchange.com/questions/98536/extracting-the-last-component-basename-of-a-filesystem-path
pub fn basename(path: &str) -> Cow<str> {
let mut pieces = path.rsplitn(2, |c| c == '/' || c == '\\');
match pieces.next() {
Some(p) => p.into(),
None => path.into(),
}
}
pub fn format_duration(duration: &Duration) -> String {
let seconds = duration.as_secs();
let days = seconds / 86400;
let hours = (seconds % 86400) / 3600;
let minutes = (seconds % 3600) / 60;
let seconds = seconds % 60;
let mut result = String::new();
if days > 0 {
result.push_str(&format!("{}d ", days));
}
if hours > 0 {
result.push_str(&format!("{}h ", hours));
}
if minutes > 0 {
result.push_str(&format!("{}min ", minutes));
}
if seconds > 0 || result.is_empty() {
result.push_str(&format!("{}sec", seconds));
}
return result.trim().to_string();
}
|