Compare commits

...

139 Commits

Author SHA1 Message Date
Lynne Megido a570b07672
release v0.7.1 🥳 2024-01-21 17:04:58 +10:00
Lynne Megido 10c6512231
REALLY update gitlab CI 2023-03-15 09:59:12 +10:00
Lynne Megido c048d21935
update gitlab CI MSRV 2023-03-15 09:17:51 +10:00
Lynne Megido 4565487149
release v0.7.0 🥳 2023-03-15 06:53:05 +10:00
Lynne Megido 5017854dd3
clippy, format 2023-03-15 06:51:29 +10:00
Lynne Megido 4469104ac1
update changelog 2023-03-15 06:46:09 +10:00
Lynne Megido 7e03dd7cf7
fix value parsing, bump MSRV 2023-03-15 06:42:44 +10:00
Lynne Megido 61196df626
update clap to 4.1 2023-03-15 06:23:59 +10:00
Lynne Megido 9e592863f1
update dependencies 2023-03-15 06:12:38 +10:00
Lynne Megido 62a630249c
update dependencies 2023-01-02 07:36:11 +10:00
Lynne Megido 57fbbc23be visual studio code 2022-09-19 01:59:48 +10:00
Lynne Megido 476209b82e
release v0.6.0 🥳 2022-09-04 13:52:37 +10:00
Lynne Megido acd33980e9
clippy cleanup 2022-09-04 13:48:54 +10:00
Lynne Megido 420bd0483c
update all dependencies, remove deprecated code 2022-09-04 13:41:41 +10:00
Lynne Megido 866a8d41d5
implement Eq where possible 2022-09-04 12:55:30 +10:00
Lynne Megido 74098ed281
update and fix dependencies 2022-09-04 12:47:17 +10:00
Lynne Megido c15d92eaa6
update deps 2022-05-20 07:18:57 +10:00
Lynne Megido b19a508020
fix changelog 2022-05-05 09:45:44 +10:00
Lynne Megido cabed845ce
release v0.5.2 🥳 2022-05-02 18:22:09 +10:00
Lynne Megido 20587fd663
clippy! 2022-05-02 18:13:06 +10:00
Lynne Megido 944360f9ab
documentation 2022-05-02 18:11:28 +10:00
Lynne Megido c9f68d8373
add reminder to use `fif --fix` 2022-05-02 18:07:14 +10:00
Lynne Megido 1b0505aad1
don't rename certain zip/exe subtypes. fixes #1 2022-05-02 18:06:51 +10:00
Lynne Megido 4b84b01adc
release v0.5.1 🥳 2022-04-12 15:09:31 +10:00
Lynne Megido 4369290cc2
cargo update 2022-04-12 15:07:49 +10:00
Lynne Megido f9c0691170
pin smartstring dep 2022-02-27 10:09:19 +10:00
Lynne Megido b464ce8c08
sort help output & group by functionality 2022-02-18 14:36:50 +10:00
Lynne Megido 2a0a74f775
update clap, replace deprecated functions 2022-02-18 14:24:17 +10:00
Lynne Megido b811f1a911
cargo update, add GPL license text 2022-02-03 15:51:20 +10:00
Lynne Megido ee6224e98c
python formatting 2022-01-24 00:16:06 +10:00
Lynne Megido e834c3e7fa
Merge branch 'master' of https://gitlab.com/Lynnesbian/fif 2022-01-24 00:13:59 +10:00
Lynne Megido 162ed80e1e
remove/rewrite some particularly verbose comments 2022-01-23 03:18:25 +10:00
Lynne Megido fc45376673
updated copyright years, fixed reuse compliance
somehow i had listed the license as LGPL 3 instead of GPL 3 in all the reuse headers, and never noticed... 0uo
2022-01-23 03:10:17 +10:00
Lynne Megido 0f9e414014
updated copyright years, fixed reuse compliance 2022-01-23 02:41:24 +10:00
Lynne Megido 66dd11397a
added attribution info to changelog 2022-01-23 02:37:07 +10:00
Lynne Megido dc9eb2fa3b
documentation improvements 2022-01-21 13:01:39 +10:00
Lynne Megido e59580b892
store screenshot with git lfs 2022-01-21 12:41:59 +10:00
Lynne Megido 330b273be6
added comments and mach-o binary support to infer 2022-01-18 18:44:46 +10:00
Lynne Megido a0396e2e1e
cargo update 2022-01-17 10:25:44 +10:00
Lynne Megido 9c404f2557 Merge branch 'infer-0.6.0' into 'master'
Update infer to 0.6.0

See merge request Lynnesbian/fif!2
2022-01-17 00:12:19 +00:00
Hannes Braun c4f0cd8d12
Update infer to 0.6.0 2022-01-15 19:36:38 +01:00
Lynne Megido 6b821f1e1e
cargo update 2022-01-05 11:36:20 +10:00
Lynne Megido 8e5ddd8e4a
minor readme changes 2022-01-01 13:35:32 +10:00
Lynne Megido c06a7a527a
release v0.5.0 🥳 2022-01-01 13:31:08 +10:00
Lynne Megido 9aef5d314c
more command line tests, more version info 2022-01-01 13:04:07 +10:00
Lynne Megido 82232a3c05
more command line tests, more version info 2022-01-01 13:02:27 +10:00
Lynne Megido 5b920665a2
cargo update, minor changes to version info 2022-01-01 11:55:49 +10:00
Lynne Megido b72ac443b1
cargo update, minor changes 2021-12-17 10:05:04 +10:00
Lynne Megido b6c2d75bdb
clippy: replace deref() with &*, remove into_iter 2021-11-25 08:45:20 +10:00
Lynne Megido 65a560d5f4
update new_mime_guess 2021-11-25 08:40:57 +10:00
Lynne Megido 313afe7cc1
test improvements
- fix tests on big endian 32 bit archs
- condense the recommend_ext test
- also test writablesln!
- general engoodening
2021-11-25 06:40:34 +10:00
Lynne Megido 33f4eb4135
replace occurrences of "mimetype" w/ "MIME type" 2021-11-25 06:29:27 +10:00
Lynne Megido ec10b58482
reorganise files.rs, use lazy Mimes in mime_type 2021-11-25 06:26:57 +10:00
Lynne Megido 667ee440e0
use parking_lot's rwlock, cargo update 2021-11-23 08:38:43 +10:00
Lynne Megido 44e14fbfba
updated formatting options 2021-11-06 02:43:08 +10:00
Lynne Megido 28aa3ad783
updated formatting options 2021-11-06 01:30:34 +10:00
Lynne Megido 855211f458
clean up windows hidden file code 2021-11-06 01:11:09 +10:00
Lynne Megido 5df8545906
cargo update, ignore sonarlint 2021-10-28 21:53:28 +10:00
Lynne Megido 672cc8da90
release v0.4.0 🥳 2021-10-14 00:04:25 +10:00
Lynne Megido c0d8105731
report files renamed/skipped/failed in --fix mode 2021-10-13 23:53:55 +10:00
Lynne Megido fcaaf283b7
ci improvements c: 2021-10-06 03:11:52 +10:00
Lynne Megido 36c0e99a92
i wonder if this is enough README badges 2021-10-06 02:54:58 +10:00
Lynne Megido 480acf515f
cleanup 2021-10-06 02:37:30 +10:00
Lynne Megido 58d5ac7e75
mostly just formatting 2021-10-06 01:41:08 +10:00
Lynne Megido b5ef95b6ef
documentation 2021-10-06 01:33:15 +10:00
Lynne Megido 6d32beedcc
cleanup 2021-10-06 00:26:04 +10:00
Lynne Megido ce79cf14ba
licensing stuff via reuse tool 2021-10-06 00:24:08 +10:00
Lynne Megido 955f0e1510
litl bit more testing 2021-10-05 04:47:33 +10:00
Lynne Megido 38ca71cc14
test smartstring::validate(), hooray 2021-10-05 02:13:32 +10:00
Lynne Megido 47c55ae61e
bumped MSRV to 1.48.0, minor improvements
- this is the rust version that debian stable (buster) currently has, so that's nice
- now we can use `const fn`s in more places, hooray
- smartstring is no longer outdated, hooray
- bitflags is no longer outdated, hooray
- mime_type in files.rs is now a bit smarter about not reading more than it has to, hooray
- removed some redundant clippy lints, hooray
- added a teensy smidgen more documentation, hooray
2021-10-05 02:12:16 +10:00
Lynne Megido c30aba35fd
fix broken multi-threaded scan_from_walkdir
i don't fully understand *why* this was broken but... it was
2021-10-05 01:45:18 +10:00
Lynne Megido 17a784732b
beeg beeg cleanup, set default prompt to error 2021-10-05 00:18:42 +10:00
Lynne Megido 556ea82a06
added --fix - fif can now rename files itself!
this alone warrants a bump to 0.4.0 imo, and now that i think about it, there's not really much keeping me from calling it 1.0...
i think i'd want to get more tests, and maybe upgrade to clap 3 stable when that happens, before calling it 1.0, though. maybe even get some sort of configuration file...
2021-10-04 23:33:48 +10:00
Lynne Megido c4fabbc0f4
refactoring, initial work on --fix feature 2021-10-04 20:22:15 +10:00
Lynne Megido 451ea3d5d9
cargo fmt, cargo update 2021-10-04 01:00:49 +10:00
Lynne Megido 3f40c61d6d
better output 0u0 2021-10-04 00:59:20 +10:00
Lynne Megido 37b9cccc9c
update gitignore 2021-10-02 19:25:35 +10:00
Lynne Megido 25d8ed64ae
capped help output to 120 chars max width 2021-09-29 23:52:20 +10:00
Lynne Megido eb3e650361
removed broken MSI support 0uo 2021-09-29 23:40:57 +10:00
Lynne Megido f1982f670e
cargo update 2021-09-29 23:33:03 +10:00
Lynne Megido 0712bf0a6b
add support for MSI files to infer backend 2021-09-29 23:31:51 +10:00
Lynne Megido 47d94cf27b
simplify InferDb custom mimetypes
using `buf.starts_with(b"\xAB\xCD")` instead of `buf[0] == 0xAB && buf[1] == 0xCD` is shorter, easier to read, removes the need for the `buf.len() > xyz` check, and actually compiles to (much) less assembly:
https://godbolt.org/z/M7GePGn1T

isn't that just lovely
2021-09-29 23:29:21 +10:00
Lynne Megido db80955f24
release v0.3.7 🥳 2021-09-25 20:09:52 +10:00
Lynne Megido 4c6163296c
flat_map_iter is 11% faster than flat_map 0uo 2021-09-25 19:55:32 +10:00
Lynne Megido 5e17e4efda
improved multithreading behaviour, & a new flag!
`-j`/`--jobs` can be used to manually set the number of threads to use for scanning files. additionally, fif won't bother with multi-threaded scanning when there are less than 32 files to scan.
2021-09-25 18:55:50 +10:00
Lynne Megido 741048839c
replace remaining OnceCells w/ Lazys, simplifying
i prefer Lazy because it simplifies initialisation by a lot, allowing for the removal of stuff like `init_db()` and the `clap_version()` functions
2021-09-25 00:54:52 +10:00
Lynne Megido 0c31277191
new screenshot, minor readme changes 2021-09-25 00:24:01 +10:00
Lynne Megido 6718f879f7
use Lazy instead of OnceCell for MIMEDB 2021-09-24 23:57:01 +10:00
Lynne Megido c2e6738f6b
use Lazy instead of OnceCell for MIMEDB 2021-09-24 23:53:02 +10:00
Lynne Megido b368be3e6b
reorder links in CHANGELOG.md 2021-09-24 22:53:33 +10:00
Lynne Megido 3e753c2a0b
replace cached dep with custom hashmap thing
i benchmarked it with hyperfine and in terms of performance it's pretty much identical, with a slight (fraction of a percent) advantage to my implementation
2021-09-24 22:08:28 +10:00
Lynne Megido 97b0a6edaa
replace cached dep with custom hashmap thing
i benchmarked it with hyperfine and in terms of performance it's pretty much identical, with a slight (fraction of a percent) advantage to my implementation
2021-09-24 22:05:12 +10:00
Lynne Megido 3d41183f1c
move license to the end of `--help` output 2021-09-24 18:12:27 +10:00
Lynne Megido 8a7cbca461
cargo fmt, rearranging use statements
by setting `group_imports = "StdExternalCrate"` in `rustfmt.toml`, cargo fmt/rustfmt rearranges your use statements into three groups:
- std/core/alloc,
- followed by external crates,
- followed by self/super/crate
2021-09-24 18:11:25 +10:00
Lynne Megido da998d019a
🚗💨 ⬆️📅
cargo update, haha get it
2021-09-24 17:58:52 +10:00
Lynne Megido 08b89d237b
disabled cleanup-msrv for now 2021-09-23 03:06:44 +10:00
Lynne Megido 3ee8745440
test.py hasn't been testing the json feature 0uo
i've had it enabled on the gitlab CI runner, but not in my test.py script that i use for local testing stuff...
2021-09-23 02:34:10 +10:00
Lynne Megido afa2bb8784
is it "an str" (ess-tee-arh) or "a str" (stir)? 2021-09-23 02:09:57 +10:00
Lynne Megido 043e0972c5
include git commit SHA in `--version` output 2021-09-23 02:07:18 +10:00
Lynne Megido a800be63f7
use SmartStrings in more places 2021-09-23 01:33:41 +10:00
Lynne Megido bddd6caeb2
format 2021-09-23 01:21:15 +10:00
Lynne Megido 74ae55ac52
AIFF support w/ infer backend 2021-09-23 01:19:56 +10:00
Lynne Megido 7c36061e03
finish the cleanup job started by #59c87a37
somehow i forgot to remove all the { unreachable!() } clutter which was one of the main reasons i did the refactor in the first place... 0uo
2021-09-23 01:03:20 +10:00
Lynne Megido 4a54511833
changelog "refactor" 2021-09-23 00:49:27 +10:00
Lynne Megido 30c7da077a
cargo update, cargo-msrv compat 2021-09-17 18:51:41 +10:00
Lynne Megido 88b5070a03
remove unneeded into() 2021-08-31 19:15:54 +10:00
Lynne Megido c2988e4f10
update changelog 2021-08-31 18:58:40 +10:00
Lynne Megido 2884f9fe4c
use SmartString properly 2021-08-28 18:21:53 +10:00
Lynne Megido fa49dd9fb5
merged inspectors module into files 2021-08-28 18:09:15 +10:00
Lynne Megido ebf2f152f0
moved string_type mod into lib.rs 2021-08-28 18:00:31 +10:00
Lynne Megido fb81f26ff5
cargo fmt 2021-08-28 17:59:04 +10:00
Lynne Megido 557f5132ff
new files module 2021-08-28 17:58:30 +10:00
Lynne Megido d625fef106
split fif into lib and bin 2021-08-28 17:54:01 +10:00
Lynne Megido 1f46bef10b
slightly nicer JSON write_all 2021-08-25 15:44:21 +10:00
Lynne Megido a2ce336fe7
use unstable sort 2021-08-25 15:26:41 +10:00
Lynne Megido 4192d37854
document version policy 2021-08-25 15:25:22 +10:00
Lynne Megido 45081efd0e
cargo update 2021-08-24 16:33:20 +10:00
Lynne Megido 6e2e788a61
oh jeez oh man v0.3.6 2021-08-18 23:42:44 +10:00
Lynne Megido e1dc2d04f1
Merge remote-tracking branch 'origin/master' 2021-08-18 23:18:28 +10:00
Lynne Megido 15b4651215
rather bland v0.3.5 release 2021-08-18 23:18:14 +10:00
Lynne Megido 0b7f9ef4a4
rather bland v0.3.5 release 2021-08-18 23:15:09 +10:00
Lynne Megido d34fa02033
update cached 2021-08-18 22:59:24 +10:00
Lynne Megido fddd479f20
more MSRV fixes, pin clap at 3.0.0-beta.2 2021-08-16 02:34:25 +10:00
Lynne Megido 2222e92080
update cargo.lock to fix MSRV compatibility 2021-08-14 22:34:05 +10:00
Lynne Megido d7e2eb9adc
cargo update 2021-08-14 22:07:37 +10:00
Lynne Megido 0404cff8b7
release v0.3.4 🥳 2021-08-07 00:42:07 +10:00
Lynne Megido ddde6acdd6
ignore_unknown_exts flag, slightly more testing 2021-08-07 00:19:30 +10:00
Lynne Megido b48b8d5a65
new-mime-guess update necessitated minor changes 2021-08-06 23:33:42 +10:00
Lynne Megido 7a7e6c9bc6 Merge branch 'herbygillot-master-patch-50502' into 'master'
README: add MacPorts install instructions

See merge request Lynnesbian/fif!1
2021-08-03 06:24:36 +00:00
Lynne Megido a071f21141
add deps.rs badge 2021-08-03 15:29:52 +10:00
Lynne Megido eed4e29e00
update dependencies 2021-08-03 15:27:03 +10:00
Lynne Megido c3adaea88c
a minor multitude of meager modifications
- clippy.sh now works if you're a weirdo with spaces in their $HOME path
- a """performance optimisation""" to utils.rs so minor that i would be surprised if it saved the world one microwatt of electricity over my entire lifespan
- cargo update
- removed useless extension_from_path function
2021-08-01 01:44:17 +10:00
Lynne Megido 8cdd0a8fc1
stricter dep vers in Cargo.toml to maintain MSRV 2021-07-30 16:52:58 +10:00
Lynne Megido 59c87a3729
minor refactoring to make formats.rs less icky 2021-07-24 16:21:20 +10:00
Lynne Megido 863954b2a2
don't optimise when testing 2021-07-21 21:18:29 +10:00
Lynne Megido 44a0351884
test on risc-v because why not 2021-07-21 21:17:10 +10:00
Lynne Megido 2f1151805f
update new_mime_guess 2021-07-21 21:16:59 +10:00
Lynne Megido 011b9eee99
add .kateproject file for project indexing 2021-07-21 21:16:32 +10:00
Herby G e66eaa66a6 README: add MacPorts install instructions 2021-06-28 12:04:10 +00:00
37 changed files with 2811 additions and 1212 deletions

View File

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
---
kind: pipeline
type: docker

4
.gitattributes vendored Normal file
View File

@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
doc/screenshot.png filter=lfs diff=lfs merge=lfs -text

11
.gitignore vendored
View File

@ -1,5 +1,9 @@
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
/target
/imgs
/imgs.tar.zst
/fif_*
/old
/.mypy_cache
@ -7,9 +11,14 @@
*.sh
!clippy.sh
cargo-timing*.html
todo.txt
/*.txt
/pkg/*
/out
/packages
/fif
/fif.exe
.idea/workspace.xml
*.sync-conflict*
.idea/sonarlint
.directory
*.tmp

View File

@ -1,8 +1,12 @@
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
image: "rust:latest"
variables:
CARGO_HOME: $CI_PROJECT_DIR/.cargo
PACKAGE_REGISTRY_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/fif"
RUSTFLAGS: "-C debuginfo=0"
cache:
paths:
@ -34,6 +38,7 @@ stages:
script:
- cargo install cargo-sweep
- cargo sweep -i
- git -C $CI_PROJECT_DIR/.cargo/registry/index/github.com-1ecc6299db9ec823/ gc --aggressive || true
# this builds a "base" version of fif with default features enabled. this is done separately from the main build step
# for the purposes of caching - by building once *before* executing the parallel cargo-build step, we ensure that
@ -56,7 +61,7 @@ stages:
- multi-threaded infer-backend
script:
cargo build --no-default-features --locked --features="json $FEATURES"
cargo run --no-default-features --locked --features="json $FEATURES" -- --version
# test with various features on and off.
.cargo-test:
@ -81,14 +86,8 @@ clippy:
cleanup-stable:
extends: .cargo-cleanup
cleanup-msrv:
extends: cleanup-stable
image: "rust:1.43.0"
cache:
key: msrv
paths:
- target
- .cargo
# there's no point running cargo sweep on MSRV, since it's always at the same version (and therefore cargo sweep will
# never delete anything)
cleanup-nightly:
extends: cleanup-stable
@ -106,8 +105,7 @@ build-base-stable:
build-base-msrv:
extends: build-base-stable
needs: ["cleanup-msrv"]
image: "rust:1.43.0"
image: "rust:1.64.0"
cache:
key: msrv
paths:
@ -133,7 +131,7 @@ build-stable:
build-msrv:
extends: build-stable
needs: ["build-base-msrv"]
image: "rust:1.43.0"
image: "rust:1.64.0"
cache:
key: msrv
paths:
@ -158,7 +156,7 @@ test-stable:
test-msrv:
extends: test-stable
image: "rust:1.43.0"
image: "rust:1.64.0"
needs: ["build-msrv"]
cache:
key: msrv

View File

@ -4,6 +4,31 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/target" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/bitflags-23acb0a9d3874edf/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/crossbeam-epoch-bbe747f70e6c82f8/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/crossbeam-utils-9309f4d80e34d8b7/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/fif-a01af1abc82b3550/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/indexmap-f70d5e1948c750ec/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/lexical-core-3a59a0b45542312b/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/libc-21832a2a55a1017a/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/log-21f459ebfa013554/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/memchr-a5ad9a9ced7a185e/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/memoffset-1f9c809cb66f47ad/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/new_mime_guess-5a19c37b0debe30e/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/nom-f20626721c72cba3/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/proc-macro-error-97f2fc25d9b7fc89/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/proc-macro-error-attr-db3651ef459829ce/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/proc-macro2-8803fbc7990cf7aa/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/rayon-137998806e417f6b/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/rayon-core-d3b7d50c097a4664/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/ryu-84c31e8e8ee65998/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/serde-8fd409d40cb77b1e/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/serde_derive-ed28d1546b1c3ad0/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/serde_json-5bd3c27125506bb8/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/syn-311c4ed26db329d6/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/unicase-1bc56b5db838db2b/out" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/debug/build/parking_lot_core-f8d2e72482af1f8b/out" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
<excludeFolder url="file://$MODULE_DIR$/imgs" />
<excludeFolder url="file://$MODULE_DIR$/old" />

View File

@ -1,6 +1,13 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="RegExpRepeatedSpace" enabled="true" level="INFORMATION" enabled_by_default="true" />
<inspection_tool class="RsExperimentalChecks" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="RsUnusedImport" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="RsVariableMutable" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
<inspection_tool class="ShellCheck" enabled="true" level="ERROR" enabled_by_default="true">
<shellcheck_settings value="SC2016" />
</inspection_tool>
</profile>
</component>

9
.idea/markdown.xml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownSettings">
<enabledExtensions>
<entry key="MermaidLanguageExtension" value="false" />
<entry key="PlantUMLLanguageExtension" value="false" />
</enabledExtensions>
</component>
</project>

View File

@ -6,6 +6,7 @@
<option name="requiredFeatures" value="true" />
<option name="allFeatures" value="false" />
<option name="emulateTerminal" value="false" />
<option name="withSudo" value="false" />
<option name="backtrace" value="SHORT" />
<envs>
<env name="RUST_LOG" value="debug" />

3
.idea/scopes/Default.xml Normal file
View File

@ -0,0 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Default" pattern="(file[fif]:src//*||file[fif]:doc//*||file:.gitignore||file:.*.yml||file:*.sh||file:*.toml||file:Cargo.lock||file:test.py||file:*.md)&amp;&amp;!file[fif]:doc/*||file:build.rs" />
</component>

3
.kateproject Normal file
View File

@ -0,0 +1,3 @@
{
"index": true
}

12
.reuse/dep5 Normal file
View File

@ -0,0 +1,12 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: fif
Upstream-Contact: Lynnesbian <lynne@bune.city>
Source: https://gitlab.com/Lynnesbian/fif/
Files: .idea/**/* .idea/* Cargo.lock .mailmap .kateproject *.toml
Copyright: Lynnesbian
License: CC0-1.0
Files: doc/* README.md CHANGELOG.md
Copyright: Lynnesbian
License: CC-BY-SA-4.0

64
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,64 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in library 'fif'",
"cargo": {
"args": [
"test",
"--no-run",
"--lib",
"--package=fif"
],
"filter": {
"name": "fif",
"kind": "lib"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'fif'",
"cargo": {
"args": [
"build",
"--bin=fif",
"--package=fif"
],
"filter": {
"name": "fif",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'fif'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=fif",
"--package=fif"
],
"filter": {
"name": "fif",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}

View File

@ -1,83 +1,205 @@
# Changelog
Dates are given in YYYY-MM-DD format.
Dates are given in YYYY-MM-DD format - for example, the 15th of October 2021 is written as 2021-10-15.
## v0.3
### v0.3.3 (2021-07-07)
#### Features
- Added `--canonical-paths` flag for outputting canonical paths in output - for example,
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v0.7.1 - 2024-01-24
### Changed
- Updated and pinned dependencies, using the latest MSRV-compatible versions available.
## v0.7.0 - 2023-03-15
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.64.0**.
- Update [`clap`] to v4.0
- Update [`infer`] to v0.13.0, bringing support for formats such as [CPIO](https://en.wikipedia.org/wiki/Cpio) and
[OpenRaster](https://www.openraster.org/index.html)
## v0.6.0 - 2022-09-04
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.57.0**.
- Update [`clap`] to v3.2.0
- Update [`smartstring`] to v1.0 - this should (slightly) improve performance on 32-bit big endian architectures
such as PowerPC
## v0.5.2 - 2022-05-02
### Added
- Output now contains a reminder to use `fif --fix`
### Changed
- Some extensions are considered to be always valid - these are:
- "filepart", "part", "crdownload": Partially downloaded files, renaming could break download
- "bak", "backup": Backup copies are a common idiom (e.g. "game.exe.bak") and should be respected
### Fixed
- Support for many file types that are subcategories of others (e.g., fif will no longer rename apk files to zip) (#1)
## v0.5.1 - 2022-04-12
### Added
- When using the [`infer`] backend, fif is now able to detect [Mach-O](https://en.wikipedia.org/wiki/Mach-O) binaries
### Changed
- Help output is now sorted manually, and flags are grouped by functionality
### Other
- (@hannesbraun) Updated [`infer`] to v0.6.0 (!2)
- Update [`clap`] to v3.1.0, fixing deprecated code
- Pin [`smartstring`] to a version that works on our MSRV
## v0.5.0 - 2022-01-01
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.57.0**.
- Updated [`new_mime_guess`] to 4.0.0
- `--version` output now handles missing Git commit hashes, and specifies the target operating system
### Fixed
- Disabled [`smartstring`] test on unsupported architectures
### Other
- Use [`parking_lot`]'s `RwLock` instead of the built-in one for a slight performance increase
- Added more command line argument tests
## v0.4.0 - 2021-10-14
### Added
- `--fix` mode - instead of outputting a shell script or text file, fif will rename the misnamed files for you!
- By default, the user will be prompted only if fif encounters an error while renaming the file, or if renaming
the file would cause another file to be overwritten. This behaviour can be changed with the new `p`/`--prompt`
flag: `-p always` to be prompted each time, `-p error` to be prompted on errors and when a file would be
overwritten by renaming, and `-p never` to disable prompting altogether - this behaves the same as
answering "yes" to every prompt.
- The `--overwrite` flag must be specified along with `--fix` in order for fif to process renames that would cause an
existing file to be overwritten. Without it, fif will never overwrite existing files, even with `-p always`.
**Caution**: If this flag is set in combination with `--prompt never`, fif will overwrite files **without asking**!
- For a more thorough breakdown of how these flags work, see [the corresponding wiki
page](https://gitlab.com/Lynnesbian/fif/-/wikis/Fix).
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.48.0**.
- Capped help output (`-h`/`--help`) width at 120 characters max
- Output is now sorted by filename - specifically, errors will appear first, followed by files that fif is unable to
recommend an extension for, in order of filename, followed by files that fif knows how to rename, again in order
of filename.
### Other
- [Reuse](https://reuse.software) compliance
## v0.3.7 - 2021-09-25
### Added
- `-j`/`--jobs` flag for specifying the number of threads fif should use for scanning files
- AIFF (Audio Interchange File Format, a PCM audio format like WAV) detection to [`infer`] backend
- `--version` output now includes the (short) hash of the git commit fif was built from
### Changed
- fif will no longer use multithreading when scanning less than 32 files - the overhead of spawning threads isn't really
worth it
### Other
- Refactoring - split fif into `main.rs` and `lib.rs`, moved file-related functionality (directory scanning, etc.) into
files module, removed string module, etc.
- Changelog "refactoring":
- Based on the somewhat popular [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) guide, splitting the previous
"Features" heading into "Added" and "Changed" sections, renaming "Bugfixes" to "Fixed", and removing the
headings that (pointlessly?) previously divided the changelog into v0.3, v0.2, and v0.1
- A few minor grammar tweaks and reorganisations
- Replaced [`cached`] dependency with a simple HashMap-backed store
- Replace all occurrences of [`once_cell`]'s `OnceCell` with equivalent `Lazy`-based implementations
## v0.3.6 - 2021-08-16
### Other
- Fixed another major dependency issue - [`clap`] version 3 beta **2** pulls in `clap_derive` version 3 beta **4**,
causing fif to fail to build unless you use `--locked`. `Cargo.toml` now explicitly depends on `clap_derive` v3b2,
which should fix this in (hopefully) all cases...
- Added an explicit dependency on `bitflags` 1.2.1, as 1.3+ requires Rust >= 1.46
## v0.3.5 - 2021-08-16 [YANKED]
### Other
- Updated `Cargo.toml` to pin [`clap`] to version 3 beta 2 - previously, version 3 beta 4 was considered compatible and
would be used if you ran `cargo install fif` instead of `cargo install --locked fif`, however, fif does *not* work with
this version of `clap`, which caused the build to fail. Also, `clap` 3 beta 4 depends on Rust >= 1.54, breaking our MSRV
- Fixed a few other `Cargo.toml` dependency versions that were causing issues when building on MSRV
## v0.3.4 - 2021-08-07
### Added
- `-I`/`--ignore-unknown-exts` flag for ignoring files with unknown extensions - for example, if fif doesn't know
what a ".fake" file is, setting this flag will prevent it from renaming "photo.fake" to "photo.jpg". This is useful
for avoiding the case where fif incorrectly mislabels an obscure format it isn't aware of as something else.
- (@herbygillot) Added [MacPorts](https://www.macports.org/) install instructions (!1)
### Other
- Refactored `formats.rs`
- More accurate dependency versions in `Cargo.toml` to ensure that the MSRV stays supported
- Sister project (?) [`new-mime-guess`] is now v3.0.0, updated to 2018 edition Rust, and with some new file and MIME
types added
## v0.3.3 - 2021-07-07
### Added
- `--canonical-paths` flag for outputting canonical paths in output - for example,
`mv /home/lynne/file.jpg /home/lynne/file.mp3` instead of the default `mv file.jpg file.mp3`
#### Other
### Other
- The `FIF_LOG` environment variable can now be used to set log level, in addition to `RUST_LOG`
- Log output now uses abbreviated level names: For example, `[D] Message` instead of `[DEBUG] Message`
### v0.3.2 (2021-06-14)
#### Bugfixes
- Fixed PowerShell output regression introduced in v0.2.13, whoops
#### Other
## v0.3.2 - 2021-06-14
### Changed
- Nicer version output: `fif -V` reports "fif v0.3.2" (instead of just "fif 0.3.2" without the "v"), and `fif --version`
reports `fif v0.3.2 (XDG-Mime backend)`, or whatever backend you're using
- fif's trace output now includes its version, backend, operating system, and architecture
### Fixed
- Fixed PowerShell output regression introduced in v0.2.13, whoops
### Other
- Block compilation if both the `xdg-mime-backend` and `infer-backend`
[features](https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features) are enabled
### v0.3.1 (2021-06-07)
#### Features
- Added JSON output support via `-o json`
- Added plaintext output support via `-o text`
#### Other
## v0.3.1 - 2021-06-07
### Added
- JSON output support via `-o json`
- Plaintext output support via `-o text`
### Changed
- `videos` is now an alias for `video`
### Other
- More extensive README documentation
### v0.3.0 (2021-04-28)
#### Features
- Added `-x`/`--exclude` flag for excluding file extensions (overrides `-e` or `-E` - `-E images -x jpg` scans all image
## v0.3.0 - 2021-04-28
### Added
- `-x`/`--exclude` flag for excluding file extensions (overrides `-e` or `-E` - `-E images -x jpg` scans all image
files, except ".jpg" files)
- Added `-X`/`--exclude-set` flag for excluding sets of files, with the same syntax and sets as `-E`
- `-X`/`--exclude-set` flag for excluding sets of files, with the same syntax and sets as `-E`
- `-q`/`--quiet` flag for reducing output verbosity
### Changed
- The `videos` extension set has been renamed to `video`, in line with `audio`. `fif --help` has actually mistakenly
referred to the set as `video` since v0.2.12! 0uo
- In addition to supplying included extensions as a comma separated list (like `-e jpg,png`), it is now possible to
supply them through multiple uses of the `-e` flag (like `-e jpg -e png`). This also applies to `-x`
- `-e` and `-E` no longer conflict with each other, and can now be used together. For example, `-E images -e mp3`
will scan all images *and* all MP3 files
- It is now possible to specify multiple extension sets at once: `-E images,system` will scan all images and archives
- fif's output now includes the directory it was run from
- Added `-q`/`--quiet` flag for reducing output verbosity
#### Bugfixes
- Changed default verbosity to `info`
### Fixed
- Resolved some discrepancies between `application/xml` and `text/xml`
#### Other
### Other
- Published my fork of ['mime_guess'] as ['new_mime_guess'], allowing it to be used properly with
[crates.io](https://crates.io)
- The `videos` extension set has been renamed to `video`, in line with `audio`. `fif --help` has actually mistakenly
referred to the set as `video` since v0.2.12! 0uo
- CI has been vastly improved
- Changed default verbosity to `info`
## v0.2
### v0.2.13 (2021-04-26)
#### Features
- Added `-v`/`--verbose` flag for setting verbosity without using `RUST_LOG`
- Added system extension set (`.dll`, `.so`, `.exe`...)
- Output is now sorted: Files that couldn't be read, then files with no known mimetype, then files with no known
### Added
- `-v`/`--verbose` flag for setting verbosity without using `RUST_LOG`
- System extension set (`.dll`, `.so`, `.exe`...)
- [`infer`] backend now supports Ren'Py archive (`.rpa`) files
### Changed
- Output is now sorted: Files that couldn't be read, then files with no known MIME type, then files with no known
extensions, then files with the wrong extension
#### Bugfixes
- Added Apple iWork document formats to Documents extension set (`.pages`, `.key`, `.numbers`)
### Fixed
- Fixed some bad formatting in PowerShell output
- Always quote file paths in output, even when not necessary - This makes output more portable and less likely to break
in future, or if [`snailquote`] misses something
#### Other
- Added Apple iWork document formats to documents extension set
### Other
- Cleaned up and properly documented tests
- Renamed `Script` (in `formats.rs`) to `Shell`, in line with renaming in `parameters.rs`
- Added .rpa (Ren'Py archive) support to infer backend
- [`xdg-mime`] no longer uses git version
- Output `\r\n` on Windows
- Use a macro to generate `Writable` arrays, making the code a little cleaner and nicer to write
### v0.2.12 (2021-04-14)
#### Features
- Added Text extension set
### Added
- Text extension set
- Better documentation for command line arguments
#### Bugfixes
### Fixed
- Fixed a very minor output bug relating to scanning symlinked directories
- Better detection for pre-OOXML Office files
#### Other
### Other
- Much better README.md
- Added more stuff to test.py
- PKGBUILD for Arch-based distros
@ -85,113 +207,129 @@ Dates are given in YYYY-MM-DD format.
- Doubled BUF_SIZE
### v0.2.11 (2021-04-04)
#### Features
### Added
- fif can now traverse symlinks with the `-f`/`--follow-symlinks` flag
- Extensions are no longer mandatory - running fif without `-e` or `-E` will scan all files, regardless of extension
(files without extensions are still skipped unless the -S flag is used)
#### Bugfixes
- Fixed compilation on big endian 32-bit architectures (see
[here](https://github.com/bodil/smartstring/blob/v0.2.6/src/config.rs#L101-L103) for why that was a problem in the
first place)
- Fixed broken tests for the [`infer`] backend
#### Other
- Better mime type detection:
### Changed
- Better MIME type detection:
- Consider "some/x-thing" and "some/thing" to be identical
- Use a patched version of mime_guess (which took a while to make 0u0;) with many more extension/type mappings
- Extensions are no longer mandatory - running fif without `-e` or `-E` will scan all files, regardless of extension
(files without extensions are still skipped unless the -S flag is used)
### Fixed
- Fixed compilation on big endian 32-bit architectures (see
[here](https://github.com/bodil/smartstring/blob/v0.2.7/src/config.rs#L102-L104) for why that was a problem in the
first place)
- Fixed broken tests for the [`infer`] backend
### v0.2.10 (2021-03-26)
### Added
- PowerShell support!
### v0.2.9 (2021-03-17)
## v0.2.9 - 2021-03-17
### Other
- Replaced a bunch of `PathBuf`s with `Path`s, which should reduce memory usage
- Formatting improvements
### v0.2.8 (2021-03-03)
#### Features
- Added much more information - author, copyright, etc. - to `--help`/`-h` output
## v0.2.8 - 2021-03-03
### Added
- Much more information to help output: author, copyright, etc.
- Scan files without extensions with `-S` (by default, such files are ignored)
#### Bugfixes
### Fixed
- Using `-s` to skip hidden files no longer skips all files if the root directory itself is hidden
#### Other
### Other
- The `ScanError` enum now contains a `PathBuf` - Errors now return `ScanError` rather than `(ScanError, PathBuf)`
- Renamed modules in accordance with [Rust's API guidelines](https://rust-lang.github.io/api-guidelines/naming.html)
### v0.2.7 (2021-03-01)
- Default to `WARN`-level logging if `RUST_LOG` isn't set
- Added a drone CI config
- Added `test.py` for automated building and testing against Rust stable, beta, nightly, and the MSRV specified in
`Cargo.toml`
- Added a test for argument parsing
## v0.2.7 - 2021-03-01
### Added
- Documentation! And lots of it! 0u0
- Added a test for argument parsing
### Changed
- Default to `WARN`-level logging if `RUST_LOG` isn't set
### v0.2.6 (2021-02-28)
- Added tests!
### Other
- Drone CI config
- `test.py` for automated building and testing against Rust stable, beta, nightly, and the MSRV specified in
`Cargo.toml`
## v0.2.6 - 2021-02-28
### Added
- Tests!
### Changed
- Default to [`xdg-mime`] on all Unixy platforms, not just Linux - this also includes the various *BSDs (I've tested
FreeBSD), macOS (haven't tested, but I have a very old MacBook running Leopard that has `file` preinstalled, so it
*should* work fine), Redox OS (haven't tested), etc.
### v0.2.5 (2021-02-27)
## v0.2.5 - 2021-02-27
### Other
- Use [`xdg-mime`] by default on Linux, [`infer`] elsewhere
### v0.2.4 (2021-02-22)
## v0.2.4 - 2021-02-22
### Added
- Proper(ish) XML document support
- Display version in help output
### v0.2.3+hotfix (2021-02-22)
### Added
- A quick hack to fix broken/non-existent support for XML document files - `docx`, `odt`, etc.
### v0.2.3 (2021-02-22)
#### Features
## v0.2.3 - 2021-02-22
### Added
- Automatically disable [`xdg-mime`] backend on Windows
- Exit codes
- Improved error handling
- Retrieve extension sets from [`mime_guess`] rather than hardcoding them
#### Bugfixes
- Improved SVG detection
#### Other
### Changed
- Switched back from `printf` to `echo` in shell output
### Fixed
- Improved SVG detection
### Other
- More frequent and detailed comments
- Refactored `formats.rs`
- Exclude certain files and directories from the crate
### v0.2.2 (2021-02-20)
## v0.2.2 - 2021-02-20
### Added
- Windows support
### v0.2.1 (2021-02-18)
#### Features
- Added extension sets -- you can now use, for example, `-E images` to check files with known image extensions
## v0.2.1 - 2021-02-18
### Added
- Extension sets -- you can now use, for example, `-E images` to check files with known image extensions
- Shell script output now uses `printf` instead of `echo`
- Added [`infer`] backend, configurable with [Cargo features](https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features)
#### Bugfixes
- [`infer`] backend, configurable with [Cargo features](https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features)
### Fixed
- Fixed broken singlethreaded support
#### Other
### Other
- Use a global backend instance instead of passing `&db` around constantly
- Use `rustfmt` 0u0
### v0.2.0 (2021-02-15)
#### Features
## v0.2.0 - 2021-02-15
### Added
- Output a script rather than a list of misnamed files
- Parallel file scanning
- Added logging support
#### Bugfixes
- Logging support
### Fixed
- Handle filenames with invalid UTF-8
#### Other
- Added license
### Other
- Now licensed (under GPLv3)
- Replaced [`structopt`] with [`clap`] 3 (beta)
- Specify 1.43.0 as minimum supported Rust version
## v0.1
### v0.1.0 (2021-02-04)
## v0.1.0 - 2021-02-04
Initial commit!
- Only one backend - [`xdg-mime`]
- No output formats - just prints a list of files to be renamed
- Only supported flags are `-e` (specify extensions) and `-s` (scan hidden files)
<!-- links -->
[`xdg-mime`]: https://crates.io/crates/xdg-mime
[`structopt`]: https://crates.io/crates/structopt
[`cached`]: https://crates.io/crates/cached
[`clap`]: https://crates.io/crates/clap
[`infer`]: https://crates.io/crates/infer
[`mime_guess`]: https://crates.io/crates/mime_guess
[`new_mime_guess`]: https://crates.io/crates/new_mime_guess
[`once_cell`]: https://crates.io/crates/once_cell
[`parking_lot`]: https://crates.io/crates/parking_lot
[`smartstring]: https://crates.io/crates/smartstring
[`snailquote`]: https://crates.io/crates/snailquote
[`structopt`]: https://crates.io/crates/structopt
[`xdg-mime`]: https://crates.io/crates/xdg-mime

815
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,81 +1,78 @@
[package]
name = "fif"
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
version = "0.3.3"
version = "0.7.1"
authors = ["Lynnesbian <lynne@bune.city>"]
edition = "2018"
edition = "2021"
license = "GPL-3.0-or-later"
rust-version = "1.43.0" # cached breaks on 1.42.0, i think it needs https://github.com/rust-lang/rust/pull/67642/
rust-version = "1.64.0" # clap 4.1 requires >=1.64.0
repository = "https://gitlab.com/Lynnesbian/fif"
readme = "README.md"
keywords = ["mime", "mimetype", "utilities", "tools"]
categories = ["command-line-utilities"]
exclude = [".idea/", "*.toml", "!Cargo.toml", "*.sh", "*.py", "*.yml", "*.md", ".mailmap", "pkg/"]
#resolver = "2"
#license-file = "LICENSE"
[badges]
maintenance = { status = "experimental" }
[features]
default = ["multi-threaded", "json"]
multi-threaded = ["rayon"]
multi-threaded = ["rayon", "num_cpus"]
infer-backend = ["infer"]
xdg-mime-backend = ["xdg-mime"]
json = ["serde", "serde_json"]
[dependencies]
walkdir = "2.3.2"
walkdir = "2.4.0"
log = "0.4.14"
mime_guess = { package = "new_mime_guess", version = "2.1.0" }
mime = "0.3.16"
mime_guess = { package = "new_mime_guess", version = "4.0.0" }
snailquote = "0.3.0"
once_cell = "1.8.0"
rayon = { version = "1.5.0", optional = true }
exitcode = "1.1.2"
cfg-if = "1.0.0"
itertools = "0.10.0"
itertools = "0.12.0"
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
num_cpus = { version = "1.13.0", optional = true }
parking_lot = "0.12.0"
smartstring = "1"
maplit = "1.0.2"
[target.'cfg(not(unix))'.dependencies]
xdg-mime = { version = "0.3.3", optional = true }
infer = "0.5.0"
infer = "=0.13.0" # 0.14.0 uses `let else`, which requires rust 1.65
[target.'cfg(unix)'.dependencies]
xdg-mime = "0.3.3"
infer = { version = "0.5.0", optional = true }
[target.'cfg(not(all(target_endian = "big", target_pointer_width = "32")))'.dependencies]
smartstring = "0.2.6"
infer = { version = "=0.13.0", optional = true }
[dependencies.clap]
version = "3.0.0-beta.2"
version = "~4.1"
default-features = false
features = ["wrap_help", "color", "derive", "std"]
features = ["wrap_help", "color", "derive", "std", "unicode"]
[dependencies.env_logger]
version = "0.8.3"
default-features = false
features = ["termcolor", "atty"]
[dependencies.cached]
version = "0.23.0"
version = "0.10.0"
default-features = false
features = ["color"]
[dev-dependencies]
tempfile = "3.2.0"
rand = "0.8.3"
assert_cmd = "=2.0.5" # higher versions than this have dependencies that require later rust versions
regex = { version = "=1.9.5", default-features = false, features = ["std"] } # 1.9.6 requires rust 1.65
[profile.release]
lto = "thin"
# perform some simple optimisations when testing
[profile.test]
opt-level = 1
# optimise dependencies, even when producing debug and test builds
[profile.dev.package."*"]
opt-level = 3
[profile.test.package."*"]
opt-level = 3
[package.metadata]
msrv = "1.64.0"

170
LICENSES/CC-BY-SA-4.0.txt Normal file
View File

@ -0,0 +1,170 @@
Creative Commons Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. Additional offer from the Licensor Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

121
LICENSES/CC0-1.0.txt Normal file
View File

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -7,14 +7,18 @@
[![Version](https://img.shields.io/crates/v/fif.svg?logo=rust&style=flat-square)
](https://crates.io/crates/fif)
[![Minimum Supported Rust Version](https://img.shields.io/badge/msrv-1.43.0-orange?logo=rust&style=flat-square)
](https://crates.io/crates/fif)
[![Minimum Supported Rust Version](https://img.shields.io/badge/msrv-1.57.0-orange?logo=rust&style=flat-square)
](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#version-policy)
[![License](https://img.shields.io/crates/l/fif.svg?style=flat-square)
](https://gitlab.com/Lynnesbian/fif/-/blob/master/LICENSE)
[![Build status](https://img.shields.io/gitlab/pipeline/Lynnesbian/fif/master?logo=gitlab&style=flat-square)
](https://gitlab.com/Lynnesbian/fif/-/pipelines/latest)
[![Unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg?style=flat-square)
](https://github.com/rust-secure-code/safety-dance/)
[![Dependency versions](https://deps.rs/repo/gitlab/lynnesbian/fif/status.svg)
](https://deps.rs/repo/gitlab/lynnesbian/fif)
[![REUSE status](https://api.reuse.software/badge/gitlab.com/Lynnesbian/fif/)
](https://api.reuse.software/info/gitlab.com/Lynnesbian/fif/)
*A command-line tool for detecting and optionally correcting files with incorrect extensions.*
</div>
@ -55,13 +59,20 @@ cargo install --locked fif
To update, simply re-run the `install` command, or use a tool like [cargo-update
](https://github.com/nabijaczleweli/cargo-update), which can update crates installed via `cargo install`.
On macOS, `fif` can be installed through [MacPorts](https://www.macports.org):
```bash
sudo port selfupdate
sudo port install fif
```
### Cargo Features
fif supports using [`infer`] or [`xdg-mime`] as its backend for looking up file types. By default, xdg-mime will be
used on [*nix systems](https://en.wikipedia.org/wiki/Unix-like) (Linux, macOS, *BSD, etc.), and infer on all other
systems.
`xdg-mime` should work on any *nix system with the [Shared MIME Info] library installed (consult your package
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system.
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system, but it supports far
fewer file types than `xdg-mime` does, thanks to the excellent Shared MIME Info library.
You can override the default backend for your system at compile time like so:
@ -129,6 +140,25 @@ You can also manually specify an output format to use:
fif -O powershell ~/Documents > output.ps1
```
#### The `--fix` flag
If, however, you'd rather have fif fix the misnamed files itself, rather than relying on a shell script, you can use
the `--fix` flag:
```bash
# rename any misnamed .jpg files in the user's pictures directory
fif ~/Pictures --fix -e jpg
# fix any misnamed files found in the user's downloads
fif ~/Downloads --fix
```
By default, fif will avoid taking any potentially destructive actions (renaming a file to a name that already exists).
This behaviour can be disabled with the `--overwrite` flag, which will instead prompt you to overwrite the existing
file. fif will also prompt you to retry on errors.
For more information on how the `--fix` flag works, and how it behaves in conjunction with the `--overwrite` flag
and `--prompt` parameter, see [the corresponding wiki page](https://gitlab.com/Lynnesbian/fif/-/wikis/Fix).
### Logging
By default, fif will log any info, warnings, and errors encountered during execution. This can be changed with the `-v`
flag:
@ -166,7 +196,7 @@ The five logging levels are used as follows:
| Level | Description | Example |
|-|-|-|
| error | Errors that cause fif to stop running | fif was unable to open the provided directory |
| warn | Warnings that don't cause fif to stop running | fif was unable to determine the mime type of a given file |
| warn | Warnings that don't cause fif to stop running | fif was unable to determine the MIME type of a given file |
| info | Information pertaining to fif's status | The provided directory was scanned without issue, and no files are in need of renaming |
| debug | Debug information - usually not important to end users | The list of extensions fif will consider |
| trace | Trace info - usually not important to end users | "Found 15 items to check", "Scan successful", etc. |
@ -178,4 +208,46 @@ a more concise overview).
[Cargo]: https://doc.rust-lang.org/cargo/
[`xdg-mime`]: https://crates.io/crates/xdg-mime
[`infer`]: https://crates.io/crates/infer
[Shared MIME Info]: https://gitlab.freedesktop.org/xdg/shared-mime-info/
[Shared MIME Info]: https://gitlab.freedesktop.org/xdg/shared-mime-info/
## Version policy
fif adheres to the [semantic versioning](https://semver.org/) principles. While fif remains at version 0.x, the version
number will be updated as follows:
- The MAJOR version will be bumped to 1 when I believe fif to be "feature complete".
- The MINOR version will be bumped whenever I add a fairly important feature to fif (in the past, this has been bumped
when adding the ability to exclude extensions, and when fif gained the ability to output a bash script rather than a
list of invalid filenames). The MINOR version will also be bumped when increasing the MSRV.
- The PATCH version will be bumped in all other cases, including minor feature additions (in the past, this has occurred
when adding features such as more output formats and the "ignore unknown extensions" flag).
If/when fif hits version 1.0, these rules will likely remain the same as they are now.
## Code style
fif is formatted with `rustfmt` using a nightly toolchain, specifically with the command `cargo +nightly fmt`. Tabs are
used for indentation, and are assumed to be two spaces wide. Lines are 120 characters wide. Braces are placed on the
same line (["OTBS"](https://en.wikipedia.org/wiki/Indentation_style#Variant:_1TBS_(OTBS)) format), except in the case of
`where` clauses in generic parameters.
For more detailed information on the formatting rules used by this project, see the configured options in
[`rustfmt.toml`](https://gitlab.com/Lynnesbian/fif/-/blob/master/rustfmt.toml).
## Additional credits
Some of the code for correctly handling files with multiple valid extensions (particularly in the case of the
Portable Executable format) comes from [Czkawka](https://github.com/qarmin/czkawka)
## License
Copyright (C) 2021 Lynnesbian
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

View File

@ -1,3 +1,8 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
use std::process::Command;
#[allow(unreachable_code, clippy::pedantic)]
fn main() -> Result<(), String> {
#[cfg(all(feature = "infer-backend", feature = "xdg-mime-backend"))]
@ -6,5 +11,21 @@ fn main() -> Result<(), String> {
"fif cannot be compiled with multiple backends set - please enable only one, or use the default.",
));
// a more robust way of doing this would be to use vergen (https://github.com/rustyhorde/vergen), but it pulls in a
// whole bunch of extra dependencies (including chrono and git2), and also blocks compilation on the current MSRV.
// this method is less clever and robust, but it works!
let git = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output();
let hash = match git {
Ok(output) => String::from_utf8_lossy(&output.stdout).into(),
Err(_) => {
// git not being present (or failing) shouldn't block compilation
println!("cargo:warning=Failed to retrieve git commit hash");
String::from("???")
}
};
println!("cargo:rustc-env=GIT_SHA={}", hash);
println!("cargo:rustc-rerun-if-changed=.git/HEAD");
Ok(())
}

View File

@ -1,6 +1,10 @@
#!/bin/bash
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
set -e
source $HOME/.cargo/env || true
source "$HOME"/.cargo/env || true
_extra=""
_ver=""
@ -23,6 +27,7 @@ for backend in "${_backends[@]}"; do
-W clippy::pedantic \
-W clippy::complexity \
-W clippy::cargo \
-W clippy::style \
-W clippy::float_cmp_const \
-W clippy::lossy_float_literal \
-W clippy::multiple_inherent_impl \
@ -32,6 +37,9 @@ for backend in "${_backends[@]}"; do
-A clippy::shadow_unrelated \
-A clippy::option_if_let_else \
-A clippy::multiple-crate-versions \
-A clippy::must_use_candidate \
-A clippy::missing_panics_doc \
-A clippy::missing_errors_doc \
"$_extra"
done
@ -40,4 +48,7 @@ done
# redundant_closure...: the alternative is often much more verbose
# shadow_unrelated: sometimes things that seem unrelated are actually related ;)
# option_if_let_else: the suggested code is usually harder to read than the original
# multiple_crate_versions: cached uses an old version of hashbrown :c
# multiple_crate_versions: this doesn't actually trip right now, but it's not something i would want CI to fail over
# must_use_candidate: useless
# missing_panics_doc: the docs are just for me, fif isn't really intended to be used as a library, so this is unneeded
# missing_errors_doc: ditto

View File

@ -1,2 +1,3 @@
# avoid-breaking-exported-api = false # only available on nightly for now
cognitive-complexity-threshold = 15
cognitive-complexity-threshold = 15
msrv = "1.64.0"

8
doc/README.md Normal file
View File

@ -0,0 +1,8 @@
Where's the documentation?
===
If you're looking for documentation on fif, try checking...
- The built-in help documentation, by running `fif --help`
- [The usage section in the README file](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#usage), for a
brief overview of fif's functionality and how to use it
- [The wiki](https://gitlab.com/Lynnesbian/fif/-/wikis/home), for more detailed information on fif's behaviour
- [Docs.rs](https://docs.rs/fif/latest/fif/), for information pertaining to fif's internals

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 130 B

View File

@ -2,4 +2,7 @@ max_width = 120
fn_single_line = true
hard_tabs = true
tab_spaces = 2
newline_style = "Unix"
newline_style = "Unix"
group_imports = "StdExternalCrate"
array_width = 100
fn_call_width = 80

424
src/files.rs Normal file
View File

@ -0,0 +1,424 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! File handling - scanning, detecting MIME types, and so on.
use std::collections::{BTreeSet, HashMap};
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;
use std::str::FromStr;
use cfg_if::cfg_if;
use itertools::{Either, Itertools};
use log::{debug, error};
use mime::Mime;
use mime_guess::from_ext;
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use walkdir::{DirEntry, WalkDir};
use crate::findings::{Findings, ScanError};
use crate::mime_db::MimeDb;
use crate::parameters::ScanOpts;
use crate::utils::APPLICATION_ZIP;
use crate::{String, MIMEDB};
/// Cache of MIME types and their associated extensions, used by [`mime_extension_lookup()`]
static MIMEXT: Lazy<RwLock<HashMap<String, Option<Vec<String>>>>> = Lazy::new(|| RwLock::new(HashMap::new()));
/// The number of bytes to read initially when identifying a file's MIME type. Used in the [`mime_type`] function.
///
/// Rather than reading the entire file all at once into a [`BUF_SIZE`] buffer, it tends to be faster to read a small
/// chunk of the file and trying to identify that, proceeding with the larger buffer if that fails. Many file formats
/// can be identified with the first few dozen bytes, so the "happy path" will likely be taken in the majority of cases.
pub const INITIAL_BUF_SIZE: usize = 128;
/// The number of bytes to read if the file couldn't be identified from its first [`INITIAL_BUF_SIZE`] bytes. Used in
/// the [`mime_type`] function.
pub const BUF_SIZE: usize = 8192;
/// A [`Mime`] representing the "application/x-ole-storage" MIME type.
static APPLICATION_X_OLE_STORAGE: Lazy<Mime> = Lazy::new(|| Mime::from_str("application/x-ole-storage").unwrap());
cfg_if! {
if #[cfg(windows)] {
/// Determines whether or not a file is hidden by checking its win32 file attributes.
pub fn is_hidden(entry: &DirEntry) -> bool {
use std::os::windows::prelude::*;
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2; // http://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
std::fs::metadata(entry.path()) // try to get metadata for file
.map_or(
false, // if getting metadata/attributes fails, assume it's not hidden
|f| f.file_attributes() & FILE_ATTRIBUTE_HIDDEN > 0,
)
}
} else {
/// Determines whether or not a file is hidden by checking for a leading full stop.
pub fn is_hidden(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map_or(false, |f| f.starts_with('.') && f != ".")
}
}
}
/// Returns `true` if a file matches the given criteria. This means checking whether the file's extension appears in
/// `exts` (if specified), potentially skipping over hidden files, and so on.
pub fn wanted_file(
entry: &DirEntry,
exts: Option<&BTreeSet<&str>>,
exclude: Option<&BTreeSet<&str>>,
scan_opts: &ScanOpts,
) -> bool {
if entry.depth() == 0 {
// the root directory should always be scanned.
return true;
}
if !scan_opts.hidden && is_hidden(entry) {
// skip hidden files and directories. this check is performed first because it's very lightweight.
return false;
}
if entry.file_type().is_dir() {
// always allow directories - there's no point doing file extension matching on something that isn't a file.
return true;
}
if let Some(ext) = entry.path().extension() {
// file has extension - discard invalid UTF-8 and normalise it to lowercase.
let ext = ext.to_string_lossy().to_lowercase();
let ext = ext.as_str();
if scan_opts.ignore_unknown_exts && from_ext(ext).is_empty() {
// unknown extension, skip.
return false;
}
if let Some(exts) = exts {
// only scan if the file has one of the specified extensions.
exts.contains(&ext)
} else {
// no extensions specified - the file should be scanned unless its extension is on the exclude list.
exclude.map_or(true, |exclude| !exclude.contains(&ext))
}
} else {
// no file extension
scan_opts.extensionless
}
}
/// Inspects the given entry, returning a [`Findings`] on success and a [`ScanError`] on failure.
///
/// In the event of an IO error, the returned [`ScanError`] will be of type [`ScanError::File`]. Otherwise, a
/// [`ScanError::Mime`] will be returned, meaning that the file was scanned successfully, but a MIME type could not be
/// determined.
pub fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, ScanError> {
let path = entry.path();
// try to determine MIME type for this entry
let result = match mime_type(&*MIMEDB, path) {
// an error occurred while trying to read the file
Err(_) => return Err(ScanError::File(path)),
// the file was read successfully, but we were unable to determine its MIME type
Ok(None) => return Err(ScanError::Mime(path)),
// a MIME type was found!
Ok(Some(result)) => result,
};
// determine whether or not the file's current extension is valid
let valid = if let Some(entry_ext) = path.extension() {
// discard invalid UTF-8 and convert to lowercase. all extensions in both backend's databases are lowercase
// ascii, so this assumption is fine.
let entry_ext = entry_ext.to_string_lossy().to_lowercase();
// if the file has any of these extensions, it is probably either:
// - a copy of another file renamed for backup purposes (e.g. a word processor might save by renaming "my.doc" to
// "my.doc.bak", then creating "my.doc", leaving the backup for safekeeping), which shouldn't be renamed so as
// not to break the backup program
// - a partially downloaded file, which shouldn't be renamed to avoid corrupting it and blocking the downloader
// from resuming
if ["bak", "backup", "filepart", "part", "crdownload"]
.iter()
.any(|ext| ext == &entry_ext)
{
true
} else {
// otherwise, check to see whether there's a known extension for this file type
// retrieve set of known extensions for the given MIME type
let known_exts = mime_extension_lookup(result.essence_str().into());
match known_exts {
// there is a known set of extensions for this MIME type - is entry_ext in the given set?
Some(e) => e.contains(&entry_ext.into()),
// there is no known set of extensions for this MIME type :(
None => false,
}
}
} else {
// this file has no extension
false
};
let path = if canonical_paths {
match std::fs::canonicalize(path) {
Ok(path) => path,
Err(_) => return Err(ScanError::File(entry.path())),
}
} else {
path.to_path_buf() // :c
};
Ok(Findings {
file: path,
valid,
mime: result,
})
}
/// Takes a slice of [`DirEntry`]s and calls [`scan_file`] on each one, returning the results in a vector.
pub fn scan_from_walkdir(
entries: &[DirEntry],
canonical_paths: bool,
use_threads: bool,
) -> (Vec<Findings>, Vec<ScanError>) {
cfg_if! {
if #[cfg(feature = "multi-threaded")] {
use rayon::prelude::*;
const CHUNKS: usize = 32;
if use_threads && entries.len() > CHUNKS {
// split the entries into chunks of 32, and iterate over each chunk of entries in a separate thread
return entries
.par_chunks(CHUNKS)
.flat_map_iter(|chunk| {
chunk
.iter() // iter over the chunk, which is a slice of DirEntry structs
.map(|entry| scan_file(entry, canonical_paths))
.collect::<Vec<_>>()
}).partition_map(|result| match result {
Ok(f) => Either::Left(f),
Err(e) => Either::Right(e),
});
}
} else {
// should always be false when multi-threading is disabled at compile time
assert!(!use_threads)
}
}
// if we end up here, either
// - there were less than CHUNKS files to scan, or
// - the user specified that only one thread should be used, by specifying `-j 1`
// - fif was compiled without the `multi-threading` feature
entries
.iter()
.partition_map(|entry: &DirEntry| match scan_file(entry, canonical_paths) {
Ok(f) => Either::Left(f),
Err(e) => Either::Right(e),
})
}
/// Scans a given directory with [`WalkDir`], filters with [`wanted_file`], checks for errors, and returns a vector of
/// [`DirEntry`]s.
pub fn scan_directory(
dirs: &Path,
exts: Option<&BTreeSet<&str>>,
exclude: Option<&BTreeSet<&str>>,
scan_opts: &ScanOpts,
) -> Option<Vec<DirEntry>> {
let stepper = WalkDir::new(dirs).follow_links(scan_opts.follow_symlinks).into_iter();
let mut probably_fatal_error = false;
let entries: Vec<DirEntry> = stepper
.filter_entry(|e| wanted_file(e, exts, exclude, scan_opts)) // filter out unwanted files
.filter_map(|e| {
if let Err(err) = &e {
debug!("uh oh spaghettio!! {:#?}", e);
// log errors to stdout, and remove them from the iterator
let path = err.path().map_or("General error".into(), Path::to_string_lossy);
if err.depth() == 0 {
// if something goes wrong while trying to read the root directory, we're probably not going to get much done
probably_fatal_error = true;
}
// TODO: is there a way to just say `map_or(x, |y| y).thing()` instead of `map_or(x.thing(), |y| y.thing())`?
// i don't care whether i'm returning a walkdir error or an io error, i just care about whether or not it
// implements ToString (which they both do). map_or doesn't work on trait objects though :(
error!("{}: {}", path, err.io_error().map_or(err.to_string(), |e| e.to_string()));
return None;
}
e.ok()
})
// remove directories from the final list
.filter(|e| !e.file_type().is_dir())
// if fif is invoked without `-f` on a symlinked directory, it will recurse into the symlink (as desired) and ignore
// any symlinks inside the symlinked root directory. however, the root directory will still be added to `entries` as
// if it were a file to be scanned, and `scan_file` will fail to scan it, adding "Failed to read ~/whatever" to the
// output. to avoid this, we can remove all symlinks from `entries` if `-f` is not set. i know this is kind of
// confusing, but it's honestly kind of hard to explain... maybe a screenshot is better:
// https://i.imgur.com/DYG7jlB.png
// adding the symlink filter removes the line that's being pointed to in the image. 0u0
.filter(|e| scan_opts.follow_symlinks || !e.file_type().is_symlink())
.collect();
if probably_fatal_error {
None
} else {
Some(entries)
}
}
/// Tries to identify the MIME type of a file from a given path.
pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
let mut buffer = [0; INITIAL_BUF_SIZE];
let mut file = File::open(path)?;
// read a small amount to start with
let mut read = io::Result::Ok(0);
for _ in 0..3 {
// try to read the file up to 3 times, retrying if interrupted, bailing otherwise
file.seek(SeekFrom::Start(0))?;
read = file.read(&mut buffer);
match read {
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) | Ok(_) => break,
}
}
let read = read?;
let r = db.get_type(&buffer);
if read < INITIAL_BUF_SIZE {
// the file is smaller than INITIAL_BUF_SIZE - there's no point reading it again
return Ok(r);
}
let r = r.filter(|mime|
// some MIME types should be investigated further, reading up to BUF_SIZE even if they've been determined already
// one such type is XML - there's many more specific types that can be determined by reading further (such as SVG)
mime != &mime::TEXT_XML
// another is ZIP - many file formats (DOCX, ODT, JAR...) are just ZIP files with particular data structures.
// determining that a file is in one of the MS office formats in particular requires looking quite far into the
// file.
&& mime != &*APPLICATION_ZIP
// doc/ppt/xls files are a subset of what's known as an "OLE2 compound document storage", at least according to
// shared-mime-info. if a pre-OOXML era MS office file is scanned and identified as x-ole-storage, reading further
// will allow it to be detected correctly as the appropriate filetype.
&& mime != &*APPLICATION_X_OLE_STORAGE);
if r.is_some() {
return Ok(r);
}
// attempt to read up to BUF_SIZE bytes of the file.
let mut buffer = [0; BUF_SIZE];
file.seek(SeekFrom::Start(0))?;
_ = file.read(&mut buffer)?;
Ok(db.get_type(&buffer))
}
/// Returns a list of known extensions for this MIME type, if any.
/// This function uses the [`Mime`]'s "essence" rather than the [`Mime`] itself - [`mime_guess::get_mime_extensions`]
/// ignores the type suffix, treating "image/svg+xml" as "image/svg", and thus fails to find any extensions. Passing the
/// `essence_str` (which includes the suffix) fixes this.
pub fn mime_extension_lookup(essence: String) -> Option<Vec<String>> {
if let Some(exts) = MIMEXT.read().get(&essence) {
return exts.clone();
}
let mut exts = mime_guess::get_mime_extensions_str(essence.as_str());
if exts.is_none() {
// no matches :c
// mime_guess' database isn't exactly perfect... there are a lot of times where the db will return "some/x-thing"
// but mime_guess only understands "some/thing", or vice-versa.
// so, if there appear to be no extensions, try replacing "some/x-thing" with "some/thing", or "some/thing" with
// "some/x-thing".
if essence.contains("/x-") {
// replace e.g. "application/x-gzip" with "application/gzip"
exts = mime_guess::get_mime_extensions_str(&essence.replace("/x-", "/"));
} else {
// replace e.g. "video/mp2t" with "video/x-mp2t"
exts = mime_guess::get_mime_extensions_str(&essence.replace('/', "/x-"));
}
}
let exts = match exts {
Some(exts) => {
let possible_exts: Vec<String> = exts.iter().map(|e| String::from(*e)).collect();
Some(if essence == mime::IMAGE_JPEG.essence_str() {
// possible_exts starts with "jpe", because it's alphabetically before "jpeg" and "jpg". however, jpg/jpeg are
// far more common than jpe, so it makes sense to suggest one of those rather than jpe. to do this, we can
// add "jpg" to the start of the possible_exts list, ensuring that it will be the extension suggested by fif.
[vec![String::from("jpg")], possible_exts].concat()
} else if essence == mime::TEXT_XML.essence_str() || essence == "application/xml" {
// a somewhat similar case arises with XML files - the first suggested extension is "asa", when it should
// (in my opinion) be "xml".
// there's also another problem: SVG files can easily be misidentified as XML files, because they usually
// *are* valid XML - the more whitespace and comments an SVG file begins with, the more bytes must be read
// before it's possible to determine that it's an SVG rather than an XML file. to "fix" this, we can add "svg"
// as a valid extension for XML files, ensuring that SVG files misidentified as XML will still be considered
// to have valid extensions.
// TODO: if a file is detected as application/xml, but it has an extension like "xht" which corresponds to
// "application/xhtml+xml", let it through - in other words, if it's identified as application/xml, but its
// extension is classed as application/*+xml, consider it OK
[vec![String::from("xml"), String::from("svg")], possible_exts].concat()
} else if essence == "application/msword" {
// classic office files considered harmful
vec![String::from("doc"), String::from("xls"), String::from("ppt")]
} else if essence == "application/zip" {
// both backends seem to be unable to consistently detect OOXML files, so they should be considered valid
// extensions for zip files to prevent them being erroneously renamed.
// additionally, there are various popular formats that are just renamed zip files, such as android's apk
// format, that also shouldn't be renamed.
[
vec![
String::from("zip"),
String::from("docx"),
String::from("xlsx"),
String::from("pptx"),
String::from("apk"),
String::from("ipa"),
String::from("docbook"),
String::from("kdenlive"),
String::from("vcpkg"),
String::from("nupkg"),
String::from("whl"),
String::from("xpi"),
],
possible_exts,
]
.concat()
} else if essence == "application/x-ms-dos-executable" {
// .dll, .exe, .scr, etc. files are given the same MIME type, and aren't really distinguishable from each other
// ... but you definitely don't want to rename one to the other!
[
vec![
String::from("exe"),
String::from("dll"),
String::from("scr"),
String::from("com"),
String::from("dll16"),
String::from("drv"),
String::from("drv16"),
String::from("cpl"),
String::from("msstyles"),
String::from("sys"),
],
possible_exts,
]
.concat()
} else {
possible_exts
})
}
None => None,
};
MIMEXT.write().insert(essence, exts.clone());
exts
}

View File

@ -1,25 +1,61 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! The [`Findings`] and [`ScanError`] structs, used for conveying whether a given file was able to be scanned, whether
//! its MIME type could be inferred, and whether the file should be renamed.
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
use mime_guess::Mime;
use crate::inspectors::mime_extension_lookup;
use crate::string_type::String;
use mime::Mime;
#[cfg(feature = "json")]
use serde::{ser::SerializeStruct, Serializer};
use std::fmt::{Display, Formatter};
/// Information about a scanned file.
#[derive(Ord, PartialOrd, Eq, PartialEq)]
use crate::files::mime_extension_lookup;
use crate::String;
/// Information about a successfully scanned file.
#[derive(Eq, PartialEq, Debug)]
pub struct Findings {
/// The location of the scanned file.
pub file: PathBuf,
/// Whether or not the file's extension is valid for its mimetype.
/// Whether or not the file's extension is valid for its MIME type.
pub valid: bool,
/// The file's mimetype.
/// The file's MIME type.
pub mime: Mime,
}
impl Findings {
/// Returns the recommended extension for this file, if known.
pub fn recommended_extension(&self) -> Option<String> {
mime_extension_lookup(self.mime.essence_str().into()).map(|extensions| extensions[0].clone())
}
/// Returns the recommended path for this file - i.e. what it should be renamed to - if known.
pub fn recommended_path(&self) -> Option<PathBuf> {
self
.recommended_extension()
.map(|ext| self.file.with_extension(ext.as_str()))
}
}
impl PartialOrd<Self> for Findings {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for Findings {
fn cmp(&self, other: &Self) -> Ordering {
// files with no recommended extension should appear first, so that fif outputs the "no known extension for x"
// comments before the "mv x y" instructions
match (self.recommended_extension(), other.recommended_extension()) {
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
_ => self.file.cmp(&other.file),
}
}
}
#[cfg(feature = "json")]
impl serde::Serialize for Findings {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
@ -36,19 +72,14 @@ impl serde::Serialize for Findings {
}
}
impl Findings {
pub fn recommended_extension(&self) -> Option<String> {
mime_extension_lookup(self.mime.essence_str().into()).map(|extensions| extensions[0].clone())
}
}
/// Errors that can occur while scanning a file with [`scan_file`](crate::files::scan_file).
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq)]
#[cfg_attr(feature = "json", derive(serde::Serialize))]
#[cfg_attr(feature = "json", serde(tag = "type", content = "path"))]
pub enum ScanError<'a> {
/// Something went wrong while trying to read the given file.
File(&'a Path),
/// Failed to determine the mimetype of the given file.
/// Failed to determine the MIME type of the given file.
Mime(&'a Path),
}
@ -59,7 +90,7 @@ impl<'a> Display for ScanError<'a> {
"Couldn't {} file: {}",
match self {
Self::File(_) => "read",
Self::Mime(_) => "determine mime type of",
Self::Mime(_) => "determine MIME type of",
},
match self {
Self::File(f) | Self::Mime(f) => f.to_string_lossy(),

View File

@ -1,4 +1,9 @@
//! The various formats that [fif](crate) can output to.
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Logic for handling the various output formats that fif can output to.
#![allow(missing_copy_implementations)]
use std::ffi::OsStr;
use std::io::{self, Write};
@ -10,18 +15,21 @@ use cfg_if::cfg_if;
use snailquote::escape;
use crate::findings::ScanError;
use crate::utils::clap_long_version;
use crate::utils::CLAP_LONG_VERSION;
use crate::Findings;
use itertools::Itertools;
use crate::String;
/// A macro for creating an array of `Writable`s without needing to pepper your code with `into()`s.
/// A macro for creating an array of [`Writable`]s without needing to pepper your code with `into()`s.
/// # Usage
/// ```
/// let f = std::io::stdout();
/// use crate::fif::writables;
/// use crate::fif::formats::{Writable, smart_write};
/// let mut f = std::io::stdout();
///
/// // Instead of...
/// smart_write(f, &["hello".into(), Writable::Newline]);
/// smart_write(&mut f, &["hello".into(), Writable::Newline]);
/// // ...just use:
/// smart_write(f, writables!["hello", Newline]);
/// smart_write(&mut f, writables!["hello", Newline]);
/// ```
#[macro_export]
macro_rules! writables {
@ -33,31 +41,23 @@ macro_rules! writables {
$crate::formats::Writable::Newline
};
(@do Space) => {
$crate::formats::Writable::Space
};
(@do $arg:expr) => {
$arg.into()
}
}
#[macro_export]
/// Does the same thing as [writables], but adds a Newline to the end.
/// Does the same thing as [`writables`], but adds a Newline to the end.
macro_rules! writablesln {
[$($args:tt),+] => {
&[$(writables!(@do $args),)* writables!(@do Newline)]
};
}
#[doc(hidden)]
type Entries<'a> = [Result<Findings, ScanError<'a>>];
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
pub enum Writable<'a> {
String(&'a str),
Path(&'a Path),
Space,
Newline,
}
@ -74,13 +74,12 @@ impl<'a> From<&'a OsStr> for Writable<'a> {
fn from(p: &'a OsStr) -> Writable<'a> { Writable::Path(p.as_ref()) }
}
fn generated_by() -> String { format!("Generated by fif {}", clap_long_version()) }
fn generated_by() -> String { format!("Generated by fif {}", CLAP_LONG_VERSION.as_str()).into() }
fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
// ehhhh
for writeable in writeables {
match writeable {
Writable::Space => write!(f, " ")?,
Writable::Newline => {
cfg_if! {
if #[cfg(windows)] {
@ -90,7 +89,7 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
}
}
}
Writable::String(s) => write!(f, "{}", s)?,
Writable::String(s) => write!(f, "{s}")?,
Writable::Path(path) => {
if let Some(path_str) = path.to_str() {
let escaped = escape(path_str);
@ -98,9 +97,9 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
// the escaped string is the same as the input - this will occur for inputs like "file.txt" which don't
// need to be escaped. however, it's Best Practice™ to escape such strings anyway, so we prefix/suffix the
// escaped string with single quotes.
write!(f, "'{}'", escaped)?;
write!(f, "'{escaped}'")?;
} else {
write!(f, "{}", escaped)?;
write!(f, "{escaped}")?;
}
} else {
write!(f, "'")?;
@ -111,7 +110,7 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
// f.write_all(&*path.as_os_str().encode_wide().collect::<Vec<u16>>())?;
write!(f, "{}", path.as_os_str().to_string_lossy())?;
} else {
f.write_all(&*path.as_os_str().as_bytes())?;
f.write_all(path.as_os_str().as_bytes())?;
}
}
write!(f, "'")?;
@ -122,90 +121,64 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
Ok(())
}
// TODO: this might need a restructure.
// it would be nice if i didn't have to write a case for every OutputFormat variant that looked like
// OutputFormat::PowerShell => PowerShell::new().write_all(...)
// also, JSON's implementation differs vastly from PowerShell and Shell's implementations. Maybe they shouldn't be
// treated as implementing the same trait, since in that case, the format trait is more of a concept rather than an
// actual definition of behaviour.
// structuring code is *hard*
pub trait Format {
fn new() -> Self;
fn rename<W: Write>(&self, _f: &mut W, _from: &Path, _to: &Path) -> io::Result<()> { unreachable!() }
fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn unreadable<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn header<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() }
fn footer<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() }
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
// TODO: clean this up - it's kinda messy
self.header(f, entries)?;
// output will be generated in the order:
// - files that couldn't be read
// - files with no known mime type
// - files with no known extension
// - files with a known extension
// files that already have a correct extension won't be represented in the output.
// sort errors so unreadable files appear before files with unknown mimetypes - ScanError impls Ord such that
// ScanError::File > ScanError::Mime
let errors = entries.iter().filter_map(|e| e.as_ref().err()).sorted();
// sort files so that files with no known extension come before those with known extensions - None > Some("jpg")
let findings = entries
.iter()
.filter_map(|e| e.as_ref().ok())
.sorted_by(|a, b| b.recommended_extension().cmp(&a.recommended_extension()).reverse());
pub trait FormatSteps {
fn rename<W: Write>(&self, _f: &mut W, _from: &Path, _to: &Path) -> io::Result<()>;
fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn unreadable<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn header<W: Write>(&self, _f: &mut W) -> io::Result<()>;
fn footer<W: Write>(&self, _f: &mut W) -> io::Result<()>;
fn write_steps<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.header(f)?;
for error in errors {
match error {
// failed to read the file
ScanError::File(path) => self.unreadable(f, path)?,
// file was read successfully, but we couldn't determine a mimetype
// file was read successfully, but we couldn't determine a MIME type
ScanError::Mime(path) => self.unknown_type(f, path)?,
}
}
if findings.len() != entries.len() {
// if these lengths aren't the same, there was at least one error
if !errors.is_empty() {
// add a blank line between the errors and commands
smart_write(f, writables![Newline])?;
}
for finding in findings {
if let Some(ext) = finding.recommended_extension() {
self.rename(f, finding.file.as_path(), &finding.file.with_extension(ext.as_str()))?;
if let Some(name) = finding.recommended_path() {
self.rename(f, finding.file.as_path(), &name)?;
} else {
self.no_known_extension(f, finding.file.as_path())?;
}
}
self.footer(f, entries)
self.footer(f)
}
}
pub trait Format {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()>;
}
/// Bourne-Shell compatible script.
pub struct Shell {}
pub struct Shell;
impl Format for Shell {
fn new() -> Self { Self {} }
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for Shell {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln!("mv -v -i -- ", from, Space, to))
smart_write(f, writablesln!("mv -v -i -- ", from, "\t", to))
}
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(
f,
writablesln![
"cat <<- '???'",
Newline,
"No known extension for ",
path,
Newline,
"???"
],
writablesln!["cat <<- '???'", Newline, "No known extension for ", path, Newline, "???"],
)
}
@ -214,61 +187,49 @@ impl Format for Shell {
}
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["# Failed to detect mime type for ", path])
smart_write(f, writablesln!["# Failed to detect MIME type for ", path])
}
fn header<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
smart_write(
f,
writablesln!["#!/usr/bin/env sh", Newline, "# ", (generated_by().as_str())],
)?;
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(f, writablesln!["#!/usr/bin/env sh", Newline, "# ", (generated_by().as_str())])?;
if let Ok(working_directory) = std::env::current_dir() {
smart_write(f, writablesln!["# Run from ", (working_directory.as_path())])?;
}
write!(f, "# Happy with these changes? Run `fif --fix` from the same directory!")?;
smart_write(f, writablesln![Newline, "set -e", Newline])
}
fn footer<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
smart_write(f, writablesln![Newline, "echo 'Done.'"])
}
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> { smart_write(f, writablesln![Newline, "echo 'Done.'"]) }
}
// PowerShell is a noun, not a type
#[allow(clippy::doc_markdown)]
/// PowerShell script.
pub struct PowerShell {}
pub struct PowerShell;
impl Format for PowerShell {
fn new() -> Self { Self {} }
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for PowerShell {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
// unfortunately there doesn't seem to be an equivalent of sh's `mv -i` -- passing the '-Confirm' flag will prompt
// the user to confirm every single rename, and using Move-Item -Force will always overwrite without prompting.
// there doesn't seem to be a way to rename the file, prompting only if the target already exists.
smart_write(
f,
writablesln![
"Rename-Item -Verbose -Path ",
from,
" -NewName ",
(to.file_name().unwrap())
],
writablesln!["Rename-Item -Verbose -Path ", from, " -NewName ", (to.file_name().unwrap())],
)
}
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(
f,
writablesln![
"Write-Output @'",
Newline,
"No known extension for ",
path,
Newline,
"'@"
],
writablesln!["Write-Output @'", Newline, "No known extension for ", path, Newline, "'@"],
)
}
@ -280,10 +241,10 @@ impl Format for PowerShell {
}
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["<# Failed to detect mime type for ", path, " #>"])
smart_write(f, writablesln!["<# Failed to detect MIME type for ", path, " #>"])
}
fn header<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(
f,
writablesln!["#!/usr/bin/env pwsh", Newline, "<# ", (generated_by().as_str()), " #>"],
@ -292,18 +253,24 @@ impl Format for PowerShell {
if let Ok(working_directory) = std::env::current_dir() {
smart_write(f, writablesln!["<# Run from ", (working_directory.as_path()), " #>"])?;
}
write!(f, "<# Happy with these changes? Run `fif --fix` from the same directory! #>")?;
smart_write(f, writables![Newline])
}
fn footer<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(f, writablesln![Newline, "Write-Output 'Done!'"])
}
}
pub struct Text;
impl Format for Text {
fn new() -> Self { Self {} }
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for Text {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln![from, " should be renamed to ", to])
}
@ -320,14 +287,19 @@ impl Format for Text {
smart_write(f, writablesln!["Couldn't determine type for ", path])
}
fn header<W: Write>(&self, f: &mut W, _entries: &Entries) -> io::Result<()> {
smart_write(f, writablesln![(generated_by().as_str()), Newline])
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(f, writablesln![(generated_by().as_str()), Newline])?;
if let Ok(working_directory) = std::env::current_dir() {
smart_write(f, writablesln!["Run from ", (working_directory.as_path())])?;
}
write!(f, "Happy with these changes? Run `fif --fix` from the same directory!")
}
fn footer<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(
f,
writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
// writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
&[Writable::Newline],
)
}
}
@ -337,22 +309,14 @@ pub struct Json;
#[cfg(feature = "json")]
impl Format for Json {
fn new() -> Self { Self {} }
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
#[derive(serde::Serialize)]
struct SerdeEntries<'a> {
errors: &'a Vec<&'a ScanError<'a>>,
findings: &'a Vec<&'a Findings>,
errors: &'a [ScanError<'a>],
findings: &'a [Findings],
}
let result = serde_json::to_writer_pretty(
f,
&SerdeEntries {
errors: &entries.iter().filter_map(|e| e.as_ref().err()).sorted().collect(),
findings: &entries.iter().filter_map(|f| f.as_ref().ok()).sorted().collect(),
},
);
let result = serde_json::to_writer_pretty(f, &SerdeEntries { errors, findings });
if let Err(err) = result {
log::error!("Error while serialising: {}", err);

View File

@ -1,133 +0,0 @@
//! Functions for getting the mime type and extension of a file.
use std::fs::File;
use std::io;
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
use std::str::FromStr;
use cached::cached;
use mime_guess::Mime;
use crate::mime_db::MimeDb;
use crate::string_type::String;
/// The number of bytes to read initially.
///
/// Rather than reading the entire file all at once into a [`BUF_SIZE`] buffer, it tends to be faster to read a small
/// chunk of the file and trying to identify that, proceeding with the larger buffer if that fails. Many file formats
/// can be identified with the first few dozen bytes, so the "happy path" will likely be taken in the majority of cases.
pub const INITIAL_BUF_SIZE: usize = 128;
/// The number of bytes to read if the file couldn't be identified from its first [`INITIAL_BUF_SIZE`] bytes.
pub const BUF_SIZE: usize = 8192;
/// Tries to identify the mimetype of a file from a given path.
pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
let mut buffer = [0; INITIAL_BUF_SIZE];
let mut file = File::open(path)?;
// read a small amount to start with
file.read(&mut buffer)?;
let r = db.get_type(&buffer).filter(|mime|
// some mime types should be investigated further, reading up to BUF_SIZE even if they've been determined already
// one such type is XML - there's many more specific types that can be determined by reading further (such as SVG)
mime != &mime_guess::mime::TEXT_XML
// another is ZIP - many file formats (DOCX, ODT, JAR...) are just ZIP files with particular data structures.
// determining that a file is in one of the MS office formats in particular requires looking quite far into the
// file.
&& mime != &Mime::from_str("application/zip").unwrap()
// doc/ppt/xls files are a subset of what's known as an "OLE2 compound document storage", at least according to
// shared-mime-info. if a pre-OOXML era MS office file is scanned and identified as x-ole-storage, reading further
// will allow it to be detected correctly as the appropriate filetype.
&& mime != &Mime::from_str("application/x-ole-storage").unwrap());
if r.is_some() {
return Ok(r);
}
// attempt to read up to the BUF_SIZE bytes of the file.
// we've already read the first 128 bytes into a buffer, but i can't see an obvious way to reuse them in a way that's
// faster than simply moving the seek position back to the start of the file and re-reading the whole BUF_SIZE bytes.
// for example, reading (BUF_SIZE - INITIAL_BUF_SIZE) bytes, then concatenating the original INITIAL_BUF_SIZE buffer
// with this new one would presumably be faster - but it's not. i think it's more expensive to create the iterator,
// collect the contents, etc. i'll have to look into this more. i don't at all doubt that there IS a way to do this
// efficiently, and i can think of a way in principle, but i'm not sure how to express it in a way that is both
// idiomatic/safe and fast.
let mut buffer = [0; BUF_SIZE];
file.seek(SeekFrom::Start(0))?;
file.read(&mut buffer)?;
Ok(db.get_type(&buffer))
}
cached! {
MIMEXT;
fn mime_extension_lookup(essence: String) -> Option<Vec<String>> = {
// Returns a list of known extensions for this mime type, if any.
// This function uses the [Mime]'s "essence" rather than the [Mime] itself - mime_guess::get_mime_extensions ignores
// the type suffix, treating "image/svg+xml" as "image/svg", and thus fails to find any extensions. Passing the
// essence_str (which includes the suffix) fixes this.
// ↑ this is supposed to be a doc comment, but the cached! macro doesn't support that... i would switch to the
// proc_macro version of cached, but it has a huge number of deps :c
let essence = essence.as_str();
let mut exts = mime_guess::get_mime_extensions_str(essence);
if exts.is_none() {
// no matches :c
// mime_guess' database isn't exactly perfect... there are a lot of times where the db will return "some/x-thing"
// but mime_guess only understands "some/thing", or vice-versa.
// so, if there appear to be no extensions, try replacing "some/x-thing" with "some/thing", or "some/thing" with
// "some/x-thing".
if essence.contains("/x-") {
// replace e.g. "application/x-gzip" with "application/gzip"
exts = mime_guess::get_mime_extensions_str(&essence.replace("/x-", "/"));
} else {
// replace e.g. "video/mp2t" with "video/x-mp2t"
exts = mime_guess::get_mime_extensions_str(&essence.replace("/", "/x-"));
}
}
match exts {
Some(exts) => {
let possible_exts: Vec<String> = exts.iter().map(|e| String::from(*e)).collect();
Some(if essence == mime_guess::mime::IMAGE_JPEG.essence_str() {
// possible_exts starts with "jpe", because it's alphabetically before "jpeg" and "jpg". however, jpg/jpeg are
// far more common than jpe, so it makes sense to suggest one of those rather than jpe. to do this, we can
// add "jpg" to the start of the possible_exts list, ensuring that it will be the extension suggested by fif.
[vec![String::from("jpg")], possible_exts].concat()
} else if essence == mime_guess::mime::TEXT_XML.essence_str() || essence == "application/xml" {
// a somewhat similar case arises with XML files - the first suggested extension is "asa", when it should
// (in my opinion) be "xml".
// there's also another problem: SVG files can easily be misidentified as XML files, because they usually
// *are* valid XML - the more whitespace and comments an SVG file begins with, the more bytes must be read
// before it's possible to determine that it's an SVG rather than an XML file. to "fix" this, we can add "svg"
// as a valid extension for XML files, ensuring that SVG files misidentified as XML will still be considered
// to have valid extensions.
// TODO: if a file is detected as application/xml, but it has an extension like "xht" which corresponds to
// "application/xhtml+xml", let it through - in other words, if it's identified as application/xml, but its
// extension is classed as application/*+xml, consider it OK
[vec![String::from("xml"), String::from("svg")], possible_exts].concat()
} else if essence == "application/msword" {
// classic office files considered harmful
vec![String::from("doc"), String::from("xls"), String::from("ppt")]
} else if essence == "application/zip" {
// neither xdg-mime nor infer seem to be able to detect office XML files properly...
[vec![String::from("zip"), String::from("docx"), String::from("xlsx"), String::from("pptx")], possible_exts].concat()
} else if essence == "application/x-ms-dos-executable" {
// both .dll and .exe files are given the same mime type... but you definitely don't want to rename one to the
// other!
[vec![String::from("dll"), String::from("exe")], possible_exts].concat()
} else {
possible_exts
})
},
None => None
}
}
}

56
src/lib.rs Normal file
View File

@ -0,0 +1,56 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! This library consists of all of the things fif needs to run. It only exists as a library to separate code, and to
//! make documentation and testing a bit easier. I don't recommend using this as a library for your crate, as it may
//! have breaking changes without incrementing the major version - it's really only meant to be a place for fif's
//! internals to live.
//!
//! You can view [fif's README](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#fif) to learn more.
#![forbid(unsafe_code)]
#![warn(
trivial_casts,
unused_lifetimes,
unused_qualifications,
missing_copy_implementations,
unused_allocation
)]
pub mod files;
pub mod findings;
pub mod formats;
pub mod mime_db;
pub mod parameters;
pub mod utils;
use cfg_if::cfg_if;
use once_cell::sync::Lazy;
use crate::findings::Findings;
use crate::mime_db::MimeDb;
cfg_if! {
if #[cfg(not(all(target_endian = "big", target_pointer_width = "32")))] {
/// On most architectures, this is a type alias for [`SmartString`](crate). However, on [architectures
/// unsupported by `smartstring`](https://github.com/bodil/smartstring/blob/v0.2.9/src/config.rs#L91-L93), this
/// is simply an alias to [`std::string::String`].
pub use smartstring::alias::String;
} else {
/// On most architectures, this is a type alias for [`SmartString`](crate). However, on [architectures
/// unsupported by `smartstring`](https://github.com/bodil/smartstring/blob/v0.2.9/src/config.rs#L91-L93), this
/// is simply an alias to [`std::string::String`].
// one particular arch that this needs to be turned off for is powerpc (the 32 bit variant that the pre-G5
// powerpc macs used)
pub use std::string::String;
}
}
cfg_if! {
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
/// A [`Lazy`] holding an instance of [`mime_db::MimeDb`]. Initialised at program startup.
pub static MIMEDB: Lazy<mime_db::InferDb> = Lazy::new(crate::mime_db::InferDb::init);
} else {
/// A [`Lazy`] holding an instance of [`mime_db::MimeDb`]. Initialised at program startup.
pub static MIMEDB: Lazy<mime_db::XdgDb> = Lazy::new(crate::mime_db::XdgDb::init);
}
}

View File

@ -1,70 +1,40 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
// fif - a command-line tool for detecting and optionally correcting files with incorrect extensions.
// Copyright (C) 2021 Lynnesbian
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![forbid(unsafe_code)]
#![warn(trivial_casts, unused_lifetimes, unused_qualifications)]
#![warn(
trivial_casts,
unused_lifetimes,
unused_qualifications,
missing_copy_implementations,
unused_allocation
)]
use std::ffi::OsStr;
use std::io::{stdout, BufWriter, Write};
use std::path::Path;
use std::io::{stdin, stdout, BufWriter, Write};
use std::process::exit;
use cfg_if::cfg_if;
use clap::Clap;
use clap::Parser;
use fif::files::{scan_directory, scan_from_walkdir};
use fif::formats::{self, Format};
use fif::parameters::{self, OutputFormat, Prompt};
use fif::utils::{os_name, CLAP_LONG_VERSION};
use itertools::Itertools;
use log::{debug, error, info, trace, warn, Level};
use once_cell::sync::OnceCell;
use walkdir::{DirEntry, WalkDir};
use crate::findings::Findings;
use crate::findings::ScanError;
use crate::formats::{Format, PowerShell, Shell};
use crate::mime_db::MimeDb;
use crate::parameters::{OutputFormat, ScanOpts};
use crate::utils::{clap_long_version, os_name};
use std::collections::BTreeSet;
mod findings;
mod formats;
mod inspectors;
mod mime_db;
mod parameters;
pub(crate) mod string_type;
#[cfg(test)]
mod tests;
mod utils;
cfg_if! {
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
/// A [OnceCell] holding an instance of [mime_db::MimeDb].
static MIMEDB: OnceCell<mime_db::InferDb> = OnceCell::new();
} else {
/// A [OnceCell] holding an instance of [mime_db::MimeDb].
static MIMEDB: OnceCell<mime_db::XdgDb> = OnceCell::new();
}
}
#[doc(hidden)]
#[allow(clippy::cognitive_complexity)]
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
fn main() {
let args: parameters::Parameters = parameters::Parameters::parse();
let mut builder = env_logger::Builder::new();
builder
.filter_level(args.default_verbosity()) // set default log level
.filter_level(args.get_verbosity()) // set default log level
.parse_default_env() // set log level from RUST_LOG
.parse_env("FIF_LOG") // set log level from FIF_LOG
.format(|buf, r| {
@ -80,12 +50,10 @@ fn main() {
trace!(
"fif {}, running on {} {}",
clap_long_version(),
CLAP_LONG_VERSION.as_str(),
std::env::consts::ARCH,
os_name()
);
trace!("Initialising mimetype database");
init_db();
debug!("Iterating directory: {:?}", args.dir);
@ -115,259 +83,157 @@ fn main() {
trace!("Found {} items to check", entries.len());
let results: Vec<_> = scan_from_walkdir(&entries, args.canonical_paths)
.into_iter()
.filter(
|result| result.is_err() || !result.as_ref().unwrap().valid,
// TODO: find a way to trace! the valid files without doing ↓
// || if result.as_ref().unwrap().valid { trace!("{:?} ok", result.as_ref().unwrap().file); false } else { true }
)
.collect();
cfg_if! {
if #[cfg(feature = "multi-threaded")] {
let use_threads = args.jobs != 1;
trace!("Scanning complete");
if use_threads {
// 0 is a special case - it should be understood to mean "all available host CPUs"
let jobs = if args.jobs == 0 { num_cpus::get() } else { args.jobs };
for result in &results {
match result {
Ok(r) => {
debug!(
"{:?} is of type {}, should have extension \"{}\"",
r.file,
r.mime,
r.recommended_extension().unwrap_or_else(|| "???".into())
);
// set up the global thread pool with the requested number of threads
rayon::ThreadPoolBuilder::new().num_threads(jobs).build_global().unwrap();
trace!("Multithreading enabled, using {} threads", jobs);
} else {
trace!("Multithreading disabled at runtime");
}
Err(f) => warn!("{}", f),
} else { // `multi-threading` feature disabled
let use_threads = false;
trace!("Multithreading disabled at compile time");
}
}
if results.is_empty() {
let (findings, errors) = scan_from_walkdir(&entries, args.canonical_paths, use_threads);
trace!("Scanning complete");
if findings.is_empty() && errors.is_empty() {
info!("All files have valid extensions!");
exit(0);
exit(exitcode::OK);
}
let mut buffered_stdout = BufWriter::new(stdout());
// remove files that already have the correct extension, then sort - first by whether or not they have a
// recommended_extension() (with None before Some(ext)), then by filename
let findings = findings
.into_iter()
.filter(|f| !f.valid)
.sorted_unstable()
.collect_vec();
// sort errors (File errors before Mime errors), then log a warning for each error
let errors = errors
.into_iter()
.sorted_unstable()
.map(|e| {
warn!("{}", &e);
e
})
.collect_vec();
let result = match args.output_format {
OutputFormat::Sh => Shell::new().write_all(&mut buffered_stdout, &results),
OutputFormat::PowerShell => PowerShell::new().write_all(&mut buffered_stdout, &results),
#[cfg(feature = "json")]
OutputFormat::Json => formats::Json::new().write_all(&mut buffered_stdout, &results),
OutputFormat::Text => formats::Text::new().write_all(&mut buffered_stdout, &results),
};
if args.fix {
fn ask(message: &str) -> bool {
let mut buf = String::with_capacity(1);
print!("{message} [y/N] ");
if result.is_err() {
error!("Failed to write to stdout.");
exit(exitcode::IOERR);
}
// flush stdout to ensure message is displayed
stdout().flush().expect("Failed to flush stdout");
if buffered_stdout.flush().is_err() {
error!("Failed to flush stdout.");
exit(exitcode::IOERR);
if let Err(e) = stdin().read_line(&mut buf) {
// something went wrong while reading input - just exit
error!("{}", e);
exit(exitcode::IOERR)
}
buf.starts_with('y') || buf.starts_with('Y')
}
let prompt = args.prompt.unwrap_or(Prompt::Error);
let mut renamed = 0_u32; // files that were successfully renamed
let mut skipped = 0_u32; // files that were skipped over without trying to rename
let mut failed = 0_u32; // files that fif failed to rename - e.g. files that are exclusively locked
for f in findings {
if let Some(rename_to) = f.recommended_path() {
let will_rename = {
if !args.overwrite && rename_to.exists() {
// handles: --prompt never, --prompt error, --prompt always
// user didn't specify --overwrite, and the destination exists
info!("Not renaming {:#?}: Target {:#?} exists", f.file, rename_to);
false
} else if prompt == Prompt::Never {
// handles: --prompt never --overwrite
// user specified --prompt never in conjunction with --overwrite, so always rename
true
} else if prompt == Prompt::Error || ask(&format!("Rename {:#?} to {:#?}?", &f.file, &rename_to)) {
// handles: --prompt error --overwrite, --prompt always --overwrite [y]
// if the target exists, prompt before renaming; otherwise, just rename
!rename_to.exists() || ask(&format!("Destination {rename_to:#?} already exists, overwrite?"))
} else {
// handles: --prompt always --overwrite [n]
// user was prompted and replied "no"
false
}
};
if !will_rename {
skipped += 1;
continue;
}
loop {
// until file is renamed successfully
match std::fs::rename(&f.file, &rename_to) {
Ok(()) => {
info!("Renamed {:#?} -> {:#?}", f.file, rename_to);
renamed += 1;
break;
}
Err(e) => {
warn!("Couldn't rename {:#?} to {:#?}: {:#?}", f.file, rename_to, e);
// if the user passed --prompt never, continue to the next file
// otherwise, prompt user to retry move, retrying until the rename succeeds or they respond "N"
if prompt == Prompt::Never || !ask(&format!("Error while renaming file: {e:#?}. Try again?")) {
failed += 1;
break;
}
}
}
}
} else {
// no recommended name :c
info!("No known extension for file {:#?} of type {}", f.file, f.mime);
skipped += 1;
}
}
info!(
"Processed {} files: Renamed {}, skipped {}, failed to rename {}",
renamed + skipped + failed,
renamed,
skipped,
failed
);
} else {
let mut buffered_stdout = BufWriter::new(stdout());
if match args.output_format {
// TODO: simplify this to something like formats::write_all(args.output_format, ...)
OutputFormat::Sh => formats::Shell.write_all(&mut buffered_stdout, &findings, &errors),
OutputFormat::PowerShell => formats::PowerShell.write_all(&mut buffered_stdout, &findings, &errors),
#[cfg(feature = "json")]
OutputFormat::Json => formats::Json.write_all(&mut buffered_stdout, &findings, &errors),
OutputFormat::Text => formats::Text.write_all(&mut buffered_stdout, &findings, &errors),
}
.is_err()
{
error!("Failed to write to stdout.");
exit(exitcode::IOERR);
}
if buffered_stdout.flush().is_err() {
error!("Failed to flush stdout.");
exit(exitcode::IOERR);
}
}
debug!("Done");
}
cfg_if! {
if #[cfg(windows)] {
/// Determines whether or not a file is hidden by checking its win32 file attributes.
fn is_hidden(entry: &DirEntry) -> bool {
use std::os::windows::prelude::*;
std::fs::metadata(entry.path()) // try to get metadata for file
.map_or(
false, // if getting metadata/attributes fails, assume it's not hidden
|f| f.file_attributes() & 0x2 > 0, // flag for hidden - https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
)
}
} else {
/// Determines whether or not a file is hidden by checking for a leading full stop.
fn is_hidden(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map_or(false, |f| f.starts_with('.') && f != ".")
}
}
}
/// Returns `true` if a file matches the given criteria. This means checking whether the file's extension appears in
/// `exts` (if specified), potentially skipping over hidden files, and so on.
fn wanted_file(
entry: &DirEntry,
exts: Option<&BTreeSet<&str>>,
exclude: Option<&BTreeSet<&str>>,
scan_opts: &ScanOpts,
) -> bool {
if entry.depth() == 0 {
// the root directory should always be scanned.
return true;
}
if !scan_opts.hidden && is_hidden(entry) {
// skip hidden files and directories. this check is performed first because it's very lightweight.
return false;
}
if entry.file_type().is_dir() {
// always allow directories - there's no point doing file extension matching on something that isn't a file.
return true;
}
if let Some(ext) = extension_from_path(entry.path()) {
// file has extension - discard invalid UTF-8 and normalise it to lowercase.
let ext = ext.to_string_lossy().to_lowercase();
let ext = ext.as_str();
if let Some(exts) = exts {
// only scan if the file has one of the specified extensions.
exts.contains(&ext)
} else {
// no extensions specified - the file should be scanned unless its extension is on the exclude list.
exclude.map_or(true, |exclude| !exclude.contains(&ext))
}
} else {
// no file extension
scan_opts.extensionless
}
}
/// Given a file path, returns its extension, using [`std::path::Path::extension`].
fn extension_from_path(path: &Path) -> Option<&OsStr> { path.extension() }
/// Inspects the given entry, returning a [`Findings`] on success and a [`ScanError`] on failure.
///
/// In the event of an IO error, the returned [`ScanError`] will be of type [`ScanError::File`]. Otherwise, a
/// [`ScanError::Mime`] will be returned, meaning that the file was scanned successfully, but a mimetype could not be
/// determined.
fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, ScanError> {
let path = entry.path();
// try to determine mimetype for this entry
let result = match inspectors::mime_type(MIMEDB.get().unwrap(), path) {
// an error occurred while trying to read the file
Err(_) => return Err(ScanError::File(path)),
// the file was read successfully, but we were unable to determine its mimetype
Ok(None) => return Err(ScanError::Mime(path)),
// a mimetype was found!
Ok(Some(result)) => result,
};
// set of known extensions for the given mimetype
let known_exts = inspectors::mime_extension_lookup(result.essence_str().into());
// file extension for this particular file
let entry_ext = extension_from_path(path);
let valid = match known_exts {
// there is a known set of extensions for this mimetype, and the file has an extension
Some(e) if entry_ext.is_some() => e.contains(&entry_ext.unwrap().to_string_lossy().to_lowercase().into()),
// either this file has no extension, or there is no known set of extensions for this mimetype :(
Some(_) | None => false,
};
let path = if canonical_paths {
match std::fs::canonicalize(path) {
Ok(path) => path,
Err(_) => return Err(ScanError::File(entry.path())),
}
} else {
path.to_path_buf() // :c
};
Ok(Findings {
file: path,
valid,
mime: result,
})
}
/// Takes a slice of [`DirEntry`]s and calls [`scan_file`] on each one, returning the results in a vector.
fn scan_from_walkdir(entries: &[DirEntry], canonical_paths: bool) -> Vec<Result<Findings, ScanError>> {
cfg_if! {
if #[cfg(feature = "multi-threaded")] {
use rayon::prelude::*;
// split the entries into chunks of 32, and iterate over each chunk of entries in a separate thread
entries
.par_chunks(32)
.flat_map(|chunk| {
chunk
.iter() // iter over the chunk, which is a slice of DirEntry structs
.map(|entry| scan_file(entry, canonical_paths))
.collect::<Vec<_>>()
})
.collect()
} else {
entries.iter().map(|entry: &DirEntry| scan_file(entry, canonical_paths)).collect()
}
}
}
/// Scans a given directory with [`WalkDir`], filters with [`wanted_file`], checks for errors, and returns a vector of
/// [DirEntry]s.
fn scan_directory(
dirs: &Path,
exts: Option<&BTreeSet<&str>>,
exclude: Option<&BTreeSet<&str>>,
scan_opts: &ScanOpts,
) -> Option<Vec<DirEntry>> {
let stepper = WalkDir::new(dirs).follow_links(scan_opts.follow_symlinks).into_iter();
let mut probably_fatal_error = false;
let entries: Vec<DirEntry> = stepper
.filter_entry(|e| wanted_file(e, exts, exclude, scan_opts)) // filter out unwanted files
.filter_map(|e| {
if let Err(err) = &e {
debug!("uh oh spaghettio!! {:#?}", e);
// log errors to stdout, and remove them from the iterator
let path = err.path().map_or("General error".into(), Path::to_string_lossy);
if err.depth() == 0 {
// if something goes wrong while trying to read the root directory, we're probably not going to get much done
probably_fatal_error = true;
}
// TODO: is there a way to just say `map_or(x, |y| y).thing()` instead of `map_or(x.thing(), |y| y.thing())`?
// i don't care whether i'm returning a walkdir error or an io error, i just care about whether or not it
// implements ToString (which they both do). map_or doesn't work on trait objects though :(
error!(
"{}: {}",
path,
err.io_error().map_or(err.to_string(), |e| e.to_string())
);
return None;
}
e.ok()
})
// remove directories from the final list
.filter(|e| !e.file_type().is_dir())
// if fif is invoked without `-f` on a symlinked directory, it will recurse into the symlink (as desired) and ignore
// any symlinks inside the symlinked root directory. however, the root directory will still be added to `entries` as
// if it were a file to be scanned, and `scan_file` will fail to scan it, adding "Failed to read ~/whatever" to the
// output. to avoid this, we can remove all symlinks from `entries` if `-f` is not set. i know this is kind of
// confusing, but it's honestly kind of hard to explain... maybe a screenshot is better:
// https://i.imgur.com/DYG7jlB.png
// adding the symlink filter removes the line that's being pointed to in the image. 0u0
.filter(|e| scan_opts.follow_symlinks || !e.file_type().is_symlink())
.collect();
if probably_fatal_error {
None
} else {
Some(entries)
}
}
/// Initialises [`MIMEDB`] with a value dependent on the current backend.
fn init_db() {
cfg_if! {
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
MIMEDB
.set(mime_db::InferDb::init())
.or(Err("Failed to initialise Infer backend!"))
.unwrap();
} else {
MIMEDB
.set(mime_db::XdgDb::init())
.or(Err("Failed to initialise XDG Mime backend!"))
.unwrap();
}
}
}

View File

@ -1,10 +1,24 @@
//! Backend-neutral Mime database implementation.
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Backend-neutral Mime database abstraction.
use cfg_if::cfg_if;
use mime_guess::Mime;
use mime::Mime;
/// A thin wrapper around either [`Infer`] or [`xdg-mime::SharedMimeInfo`], depending on which [cargo features]
/// fif was compiled with. By default, fif uses an [`Infer`]-based implementation on Windows, and an
/// [`xdg-mime`]-based one everywhere else. This behaviour can be changed at compile time by using the aforementioned
/// [cargo features].
///
/// [cargo features]: https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features
/// [`Infer`]: https://docs.rs/infer/
/// [`xdg-mime::SharedMimeInfo`]: https://docs.rs/xdg-mime/0/xdg_mime/struct.SharedMimeInfo.html
/// [`xdg-mime`]: https://docs.rs/xdg-mime/
pub trait MimeDb {
/// Initialise the database.
fn init() -> Self;
/// Given a slice of bytes, returns the inferred MIME type, if any.
fn get_type(&self, data: &[u8]) -> Option<Mime>;
}
@ -12,12 +26,13 @@ cfg_if! {
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
use std::str::FromStr;
/// The [`Infer`](https://docs.rs/infer/)-based implementation of [`MimeDb`].
pub struct InferDb {
db: infer::Infer,
}
fn open_document_check(buf: &[u8], kind: &str) -> bool {
let mime = format!("application/vnd.oasis.opendocument.{}", kind);
let mime = format!("application/vnd.oasis.opendocument.{kind}");
let mime = mime.as_bytes();
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
@ -27,26 +42,56 @@ cfg_if! {
fn init() -> Self {
let mut info = infer::Infer::new();
// In addition to the file inferences provided by Infer, I've also added a few of my own below. Some of them
// replace Infer's existing ones, some of them are less than perfect, and still others are for relatively
// obscure formats, so I'm not really sure whether or not they should be contributed upstream.
// OpenDocument Text (used by e.g. LibreOffice Writer)
info.add("application/vnd.oasis.opendocument.text", "odt", |buf| {
open_document_check(buf, "text")
});
// OpenDocument Spreadsheet (LibreOffice Calc)
info.add("application/vnd.oasis.opendocument.spreadsheet", "ods", |buf| {
open_document_check(buf, "spreadsheet")
});
// OpenOffice Presentation (LibreOffice Impress)
info.add("application/vnd.oasis.opendocument.presentation", "odp", |buf| {
open_document_check(buf, "presentation")
});
// Ren'Py Archive (Ren'Py: https://www.renpy.org/)
info.add("application/x-rpa", "rpa", |buf| {
buf.len() >= 34 && buf.starts_with(b"RPA-") && buf[7] == b' ' && buf[24] ==b' '
});
// Mach-O Binaries (The executable format used by macOS)
// my source for most of this info is this article: https://h3adsh0tzz.com/2020/01/macho-file-format/
info.add("application/x-mach-binary", "macho", |buf| {
// a 32-bit mach-o header occupies 28 bits of space, so any input smaller than that cannot be a mach-o
// binary, even if it starts with the magic numbers.
// java class files also start with 0xCAFEBABE. since infer doesn't support detecting these files,
// collisions are not an issue. if, however, infer does gain support for identifying java class files, the
// 0xCAFEBABE check should be removed, as java bytecode files are far more prevalent than 32-bit universal
// mach-o binaries [citation needed].
// check for magic numbers (0xFEEDCACF, 0xFEEDFACE, 0xCAFEBABE) in both big and little endian forms
buf.len() >= 28 && [b"\xFE\xED\xFA\xCF", b"\xFE\xED\xFA\xCE", b"\xCA\xFE\xBA\xBE", b"\xCF\xFA\xED\xFE",
b"\xCE\xFA\xED\xFE", b"\xBE\xBA\xFE\xCA"].iter().any(|magic_numbers| buf.starts_with(&magic_numbers[..]))
});
// info.add("application/x-msi", "msi", |buf| {
// TODO: find a way to detect MSI files properly - this just detects those weird windows OLE files and therefore
// also picks up on .doc files
// buf.starts_with(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1")
// });
// Scalable Vector Graphics
info.add("image/svg+xml", "svg", |buf| {
// before doing the moderately expensive SVG check, we should make sure that the input is actually SGML-ish
// by "SGML-ish", i mean starts with anywhere from zero to ∞-1 whitespace characters, and then a less than sign,
// and then there's some other stuff we don't care about right now
// before doing the moderately expensive SVG check, we should make sure that the input is actually SGML-ish,
// by which i mean, starts with the pattern "\s*<".
// so, here comes our fancy pants """""SGML-ish validator"""""
for c in buf {
@ -62,8 +107,8 @@ cfg_if! {
// - split the buffer up into chunks separated by the less than sign
// - check to see if this chunk starts with any of these identifiers:
let identifiers: Vec<&[u8]> = vec![b"svg", b"SVG", b"!DOCTYPE svg", b"!DOCTYPE SVG"];
// - if it does, the nested `any` will short circuit and immediately return true, causing the parent `any` to do
// the same
// - if it does, the nested `any` will short circuit and immediately return true, causing the parent `any` to
// do the same
// - and finally, if none of the chunks match, we'll return false
// TODO: this is kind of messy, i'd like to clean it up somehow :(
@ -72,17 +117,20 @@ cfg_if! {
.any(|buf| identifiers.iter().any(|id| buf.starts_with(id)))
});
// unmut
let info = info;
Self { db: info }
}
fn get_type(&self, data: &[u8]) -> Option<Mime> {
self.db.get(data).map(|f| Mime::from_str(f.mime_type()).unwrap())
if let Some(mime) = self.db.get(data) {
match Mime::from_str(mime.mime_type()) {
Err(_) => None,
Ok(m) => Some(m),
}
} else { None }
}
}
} else {
/// The [`xdg-mime`](https://docs.rs/xdg-mime/)-based implementation of [`MimeDb`].
pub struct XdgDb {
db: xdg_mime::SharedMimeInfo,
}

View File

@ -1,21 +1,30 @@
//! [Clap] struct used to parse command line arguments.
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Command line argument parsing logic and associated functions.
use crate::string_type::String as StringType;
use crate::utils::{clap_long_version, clap_version};
use cfg_if::cfg_if;
use clap::{AppSettings, Clap};
use std::collections::BTreeSet;
use std::path::PathBuf;
use cfg_if::cfg_if;
use clap::{ArgAction, Parser, ValueEnum};
use crate::utils::{CLAP_LONG_VERSION, CLAP_VERSION};
use crate::String as StringType;
cfg_if! {
if #[cfg(windows)] {
/// The default [`OutputFormat`] to use.
const DEFAULT_FORMAT: &str = "powershell";
} else {
/// The default [`OutputFormat`] to use.
const DEFAULT_FORMAT: &str = "sh";
}
}
#[derive(Clap, PartialEq, Debug)]
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
/// The format to use when running fif without the `--fix` flag. Specified at runtime with the `-o`/`--output-format`
/// flag.
pub enum OutputFormat {
/// A Bourne shell compatible script.
#[clap(alias = "shell", alias = "bash")]
@ -30,31 +39,54 @@ pub enum OutputFormat {
Json,
}
// TODO: convert this to macro style?: https://docs.rs/clap/3.0.0-beta.2/clap/index.html#using-macros
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
/// Specifies under what conditions the user should be prompted when running fif in `--fix` mode. Defaults to `Error`.
/// Specified at runtime with the `-p`/`--prompt` flag.
pub enum Prompt {
/// Never prompt.
Never,
/// Prompt only on errors, and on overwrites, if `--overwrite` is set.
Error,
/// Prompt for every rename.
Always,
}
#[derive(Clap, Debug)]
#[derive(Parser, Debug)]
#[allow(clippy::struct_excessive_bools)]
#[clap(
version = clap_version(),
long_version = clap_long_version(),
version = CLAP_VERSION.as_str(),
long_version = CLAP_LONG_VERSION.as_str(),
author = option_env!("CARGO_PKG_AUTHORS").unwrap_or("Lynnesbian"),
about = option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("File Info Fixer"),
before_help = "Copyright © 2021 Lynnesbian under the GPL3 (or later) License.",
before_long_help = "Copyright © 2021 Lynnesbian\n\
before_help = "Copyright © 2021-2022 Lynnesbian under the GPL3 (or later) License.",
after_long_help = "Copyright © 2021-2022 Lynnesbian\n\
This program is free software: you can redistribute it and/or modify \
it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 \
of the License, or (at your option) any later version.",
setting(AppSettings::ColoredHelp)
max_term_width = 120
)]
/// [`Clap`]-derived struct used to parse command line arguments.
pub struct Parameters {
// NOTE: clap's comma-separated argument parser makes it impossible to specify extensions with commas in their name -
// `-e sil\,ly` is treated as ["sil", "ly"] rather than as ["silly"], no matter how i escape the comma (in bash,
// anyway). is this really an issue? it does technically exclude some perfectly valid extensions, but i've never seen
// a file extension with a comma in its name before.
/// Automatically rename files to use the correct extension, prompting the user for every rename.
#[clap(long, help_heading = "RENAMING")]
pub fix: bool,
/// Requires --fix. Should fif prompt you `Never`, only on `Error`s and overwrites, or `Always`?
#[clap(short = 'p', long, value_enum, requires = "fix", help_heading = "RENAMING")]
pub prompt: Option<Prompt>,
/// Requires --fix. Allow overwriting files. Warning: When used in combination with `--prompt never`, fif will
/// overwrite files without prompting!
#[clap(long, requires = "fix", help_heading = "RENAMING")]
pub overwrite: bool,
// NOTE: it is impossible (as far as i can tell) to accept extensions with commas in their name. i don't know why
// you would ever want a file named something like "example.xy,z", though... fif's -e and -x flags don't support this.
/// Only examine files with these extensions.
/// Multiple extensions can be specified by either using the flag multiple times (`-e jpg -e png -e gif`), or by
/// separating them with commas (`-e jpg,png,gif`).
#[clap(short, long, use_delimiter = true, require_delimiter = true, value_name = "ext", validator = lowercase_exts)]
#[clap(short, long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", num_args(1),
value_parser = validate_exts, help_heading = "FILTERING")]
pub exts: Option<Vec<StringType>>,
/// Use these preset lists of extensions as the search filter (comma-separated list).
@ -63,16 +95,18 @@ pub struct Parameters {
#[clap(
short = 'E',
long,
arg_enum,
use_delimiter = true,
require_delimiter = true,
value_name = "set"
value_enum,
use_value_delimiter = true,
value_delimiter = ',',
value_name = "set",
help_heading = "FILTERING"
)]
pub ext_set: Vec<ExtensionSet>,
/// Don't scan files with these extensions.
/// This option takes precedence over extensions specified with `-e` or `-E`.
#[clap(short = 'x', long, use_delimiter = true, require_delimiter = true, value_name = "ext", validator = lowercase_exts)]
#[clap(short = 'x', long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", value_parser =
validate_exts, help_heading = "FILTERING")]
pub exclude: Option<Vec<StringType>>,
/// Exclude files using a preset list of extensions.
@ -80,66 +114,88 @@ pub struct Parameters {
#[clap(
short = 'X',
long,
arg_enum,
use_delimiter = true,
require_delimiter = true,
value_name = "set"
value_enum,
use_value_delimiter = true,
value_delimiter = ',',
value_name = "set",
help_heading = "FILTERING"
)]
pub exclude_set: Vec<ExtensionSet>,
/// Don't skip hidden files and directories.
/// Even if this flag is not present, fif will still recurse into a hidden root directory - for example, `fif
/// ~/.hidden` will recurse into `~/.hidden` regardless of whether or not -s was passed as an argument.
#[clap(short, long)]
#[clap(short, long, help_heading = "FILTERING")]
pub scan_hidden: bool,
/// Scan files without extensions.
/// By default, fif will ignore files without extensions - for example, a jpeg file named `photo` won't be considered
/// misnamed. Supplying the -S flag will cause fif to recommend renaming this file to `photo.jpg`.
#[clap(short = 'S', long)]
#[clap(short = 'S', long, help_heading = "FILTERING")]
pub scan_extensionless: bool,
/// Follow symlinks.
#[clap(short, long, help_heading = "FILTERING")]
pub follow_symlinks: bool,
/// Don't rename files with extensions unknown to fif.
/// For example, with this option, fif will not rename "image.unknown" to "image.jpg"
#[clap(short = 'I', long, help_heading = "FILTERING")]
pub ignore_unknown_exts: bool,
/// Output format to use.
/// By default, fif will output a PowerShell script on Windows, and a Bourne Shell script on other platforms.
#[clap(short, long, default_value = DEFAULT_FORMAT, arg_enum, value_name = "format")]
#[clap(short, long, default_value = DEFAULT_FORMAT, value_enum, value_name = "format", help_heading = "OUTPUT")]
pub output_format: OutputFormat,
/// Follow symlinks.
#[clap(short, long)]
pub follow_symlinks: bool,
/// Output verbosity. Each additional `-v` increases verbosity.
/// Can be overridden by FIF_LOG or RUST_LOG.
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
pub verbose: u8,
/// Output quietness. Each additional `-q` decreases verbosity.
/// Can be overridden by FIF_LOG or RUST_LOG.
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
pub quiet: u8,
/// Use canonical (absolute) paths in output.
/// A canonical path is the "one true path" to a given file, and is always an absolute path. While a file may have
/// many absolute paths (for example, on Windows, '\\?\C:\file.txt' and 'C:\file.txt' are both absolute paths to the
/// same file), but only one canonical path. This does not effect logged output.
#[clap(long)]
#[clap(long, help_heading = "OUTPUT")]
pub canonical_paths: bool,
/// The directory to process.
#[clap(name = "DIR", default_value = ".", parse(from_os_str))]
#[clap(name = "DIR", default_value = ".", value_parser)]
pub dir: PathBuf,
#[cfg(feature = "multi-threaded")]
/// Number of jobs (threads) to use when scanning results.
/// The default behaviour is to use one thread per CPU thread. This behaviour can be manually requested by setting
/// `-j 0`. Using `-j 1` will disable multi-threading behaviour, as if you had compiled fif with the multi-threading
/// feature disabled. Setting more jobs than you have CPU threads is not recommended.
#[clap(short = 'j', long, default_value = "0", help_heading = "MISC")]
pub jobs: usize,
}
fn lowercase_exts(exts: &str) -> Result<(), String> {
/// Validation function for argument parsing that ensures passed-in extensions are lowercase, and that the user
/// didn't supply an empty list.
fn validate_exts(exts: &str) -> Result<StringType, String> {
// TODO: i would much rather accept uppercase exts and convert them to lowercase than just rejecting lowercase exts...
if exts.is_empty() {
return Err(String::from("Cannot specify empty extensions"));
}
if exts.to_lowercase() != exts {
return Err(String::from("Supplied extensions must be lowercase"));
}
Ok(())
Ok(exts.into())
}
/// Further options relating to scanning.
#[derive(PartialEq, Debug)]
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ScanOpts {
/// Whether hidden files and directories should be scanned.
pub hidden: bool,
@ -147,6 +203,8 @@ pub struct ScanOpts {
pub extensionless: bool,
/// Should symlinks be followed?
pub follow_symlinks: bool,
/// Whether to rename files with unknown extensions.
pub ignore_unknown_exts: bool,
}
impl Parameters {
@ -209,18 +267,18 @@ impl Parameters {
}
}
/// Populates a [`ScanOpts`] struct with values from [`self`].
pub const fn get_scan_opts(&self) -> ScanOpts {
ScanOpts {
hidden: self.scan_hidden,
extensionless: self.scan_extensionless,
follow_symlinks: self.follow_symlinks,
ignore_unknown_exts: self.ignore_unknown_exts,
}
}
pub fn default_verbosity(&self) -> log::LevelFilter {
#![allow(clippy::missing_const_for_fn)]
// match was not permitted inside const functions until 1.46
/// Gets the verbosity set by the user via the `-v` and `-q` flags.
pub const fn get_verbosity(&self) -> log::LevelFilter {
use log::LevelFilter;
match self.quiet {
@ -239,7 +297,7 @@ impl Parameters {
}
/// Sets of extensions for use with [Parameter](crate::parameters::Parameters)'s `-E` flag.
#[derive(Clap, PartialEq, Debug)]
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
pub enum ExtensionSet {
/// Extensions used for image file formats, such as `png`, `jpeg`, `webp`, etc.
Images,
@ -249,7 +307,7 @@ pub enum ExtensionSet {
#[clap(alias = "videos")]
Video,
/// Extensions used for media file formats. This acts as a combination of the [Images](ExtensionSet::Images),
/// [Audio](ExtensionSet::Audio) and [Videos](ExtensionSet::Videos) variants.
/// [Audio](ExtensionSet::Audio) and [Video](ExtensionSet::Video) variants.
Media,
/// Extensions used for document file formats, such as `pdf`, `odt`, `docx`, etc.
Documents,
@ -268,12 +326,7 @@ impl ExtensionSet {
Self::Images => mime_guess::get_mime_extensions_str("image/*").unwrap().to_vec(),
Self::Audio => mime_guess::get_mime_extensions_str("audio/*").unwrap().to_vec(),
Self::Video => mime_guess::get_mime_extensions_str("video/*").unwrap().to_vec(),
Self::Media => [
Self::Images.extensions(),
Self::Audio.extensions(),
Self::Video.extensions(),
]
.concat(),
Self::Media => [Self::Images.extensions(), Self::Audio.extensions(), Self::Video.extensions()].concat(),
Self::Documents => vec![
"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "tsv", "odt", "ods", "odp", "oda", "rtf", "ps",
"pages", "key", "numbers",

View File

@ -1,11 +0,0 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(not(all(target_endian = "big", target_pointer_width = "32")))] {
// most architectures
pub use smartstring::alias::String;
} else {
// powerpc and other big endian 32-bit archs
pub use std::string::String;
}
}

View File

@ -1,116 +1,112 @@
use crate::findings::Findings;
use crate::formats::{Format, PowerShell, Shell};
use crate::inspectors::{mime_extension_lookup, BUF_SIZE};
use crate::mime_db::MimeDb;
use crate::string_type::String;
use crate::{extension_from_path, scan_directory, scan_from_walkdir};
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
use crate::parameters::Parameters;
use clap::Clap;
use mime_guess::mime::{APPLICATION_OCTET_STREAM, APPLICATION_PDF, IMAGE_JPEG, IMAGE_PNG};
use mime_guess::Mime;
use crate::parameters::ExtensionSet;
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use clap::Parser;
use fif::files::{mime_extension_lookup, scan_directory, scan_from_walkdir, BUF_SIZE};
use fif::findings::Findings;
use fif::formats::{Format, PowerShell, Shell};
use fif::mime_db::MimeDb;
use fif::utils::APPLICATION_ZIP;
use fif::{String, MIMEDB};
use itertools::Itertools;
use maplit::{btreeset, hashmap};
use mime::{Mime, APPLICATION_OCTET_STREAM, APPLICATION_PDF, IMAGE_JPEG, IMAGE_PNG};
use crate::parameters::ExtensionSet;
use crate::parameters::Parameters;
const JPEG_BYTES: &[u8] = b"\xFF\xD8\xFF";
const PNG_BYTES: &[u8] = b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
const PDF_BYTES: &[u8] = b"%PDF-";
const ZIP_BYTES: &[u8] = b"PK\x03\x04";
cfg_if::cfg_if! {
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
fn get_mime_db() -> crate::mime_db::InferDb {
crate::mime_db::InferDb::init()
}
} else {
fn get_mime_db() -> crate::mime_db::XdgDb {
crate::mime_db::XdgDb::init()
}
}
}
fn application_zip() -> Mime {
use std::str::FromStr;
Mime::from_str("application/zip").unwrap()
}
#[test]
/// Ensure that `extension_from_path` successfully returns the extension from a set of paths.
fn get_ext() {
let mut ext_checks: HashMap<_, Option<&OsStr>> = HashMap::new();
ext_checks.insert(Path::new("test.txt"), Some(OsStr::new("txt")));
ext_checks.insert(Path::new("test.zip"), Some(OsStr::new("zip")));
ext_checks.insert(Path::new("test.tar.gz"), Some(OsStr::new("gz")));
ext_checks.insert(Path::new("test."), Some(OsStr::new("")));
ext_checks.insert(Path::new("test"), None);
ext_checks.insert(Path::new(".hidden"), None);
let ext_checks: HashMap<_, Option<&OsStr>> = hashmap![
Path::new("test.txt") => Some(OsStr::new("txt")),
Path::new("test.zip") => Some(OsStr::new("zip")),
Path::new("test.tar.gz") => Some(OsStr::new("gz")),
Path::new("test.") => Some(OsStr::new("")),
Path::new("test") => None,
Path::new(".hidden") => None,
];
for (path, ext) in ext_checks {
assert_eq!(extension_from_path(path), ext);
assert_eq!(path.extension(), ext);
}
}
#[test]
/// Ensure that the mime types for JPEG, PNG, PDF, and ZIP are detected from their magic numbers.
/// Ensure that the MIME types for JPEG, PNG, PDF, and ZIP are detected from their magic numbers.
fn detect_type() {
let db = get_mime_db();
assert_eq!(db.get_type(JPEG_BYTES), Some(IMAGE_JPEG));
assert_eq!(db.get_type(PNG_BYTES), Some(IMAGE_PNG));
assert_eq!(db.get_type(PDF_BYTES), Some(APPLICATION_PDF));
assert_eq!(db.get_type(ZIP_BYTES), Some(application_zip()));
assert_eq!(MIMEDB.get_type(JPEG_BYTES), Some(IMAGE_JPEG));
assert_eq!(MIMEDB.get_type(PNG_BYTES), Some(IMAGE_PNG));
assert_eq!(MIMEDB.get_type(PDF_BYTES), Some(APPLICATION_PDF));
assert_eq!(MIMEDB.get_type(ZIP_BYTES), Some(APPLICATION_ZIP.clone()));
}
#[test]
/// Ensure that `mime_extension_lookup` works as expected, and that the set of extensions for JPEG, PNG, PDF, and ZIP
/// contain "jpg", "png", "pdf", and "zip", respectively.
fn recommend_ext() {
assert!(mime_extension_lookup(IMAGE_JPEG.essence_str().into())
.unwrap()
.contains(&String::from("jpg")));
assert!(mime_extension_lookup(IMAGE_PNG.essence_str().into())
.unwrap()
.contains(&String::from("png")));
assert!(mime_extension_lookup(APPLICATION_PDF.essence_str().into())
.unwrap()
.contains(&String::from("pdf")));
assert!(mime_extension_lookup(application_zip().essence_str().into())
.unwrap()
.contains(&String::from("zip")));
let tests = hashmap![
&IMAGE_JPEG => "jpg",
&IMAGE_PNG => "png",
&APPLICATION_PDF => "pdf",
&*APPLICATION_ZIP => "zip",
];
for (mime, ext) in tests {
assert!(
mime_extension_lookup(mime.essence_str().into())
.unwrap()
.contains(&String::from(ext)),
"mime_extension_lookup for {} didn't contain {}!",
mime.essence_str(),
ext
);
}
}
#[test]
/// Create a simple directory with some files, run `scan_directory` on it, and ensure that the files have their
/// associated mime types correctly deduced.
/// associated MIME types correctly deduced.
fn simple_directory() {
use crate::parameters::ScanOpts;
use std::borrow::Borrow;
use std::env::set_current_dir;
use std::fs::{canonicalize, File};
use std::io::Write;
use tempfile::tempdir;
use crate::parameters::ScanOpts;
// set of files to scan. all but the last files have magic numbers corresponding to their extension, except for
// "wrong.jpg", which is actually a png.
let mut files = HashMap::new();
files.insert("test.jpg", JPEG_BYTES);
files.insert("test.jpeg", JPEG_BYTES);
files.insert("test.png", PNG_BYTES);
files.insert("test.pdf", PDF_BYTES);
files.insert("test.zip", ZIP_BYTES);
files.insert("wrong.jpg", PNG_BYTES);
let files = hashmap![
"test.jpg" => JPEG_BYTES,
"test.jpeg" => JPEG_BYTES,
"test.png" => PNG_BYTES,
"test.pdf" => PDF_BYTES,
"test.zip" => ZIP_BYTES,
"wrong.jpg" => PNG_BYTES,
"ignore.fake_ext" => ZIP_BYTES,
];
let dir = tempdir().expect("Failed to create temporary directory.");
set_current_dir(dir.path()).expect("Failed to change directory.");
for (name, bytes) in &files {
let mut file = File::create(dir.path().join(name)).expect(&*format!("Failed to create file: {}", name));
let mut file = File::create(dir.path().join(name)).unwrap_or_else(|_| panic!("Failed to create file: {name}"));
file
.write_all(bytes)
.expect(&*format!("Failed to write to file: {}", name));
.unwrap_or_else(|_| panic!("Failed to write to file: {name}"));
drop(file);
}
@ -118,23 +114,22 @@ fn simple_directory() {
hidden: true,
extensionless: false,
follow_symlinks: false,
ignore_unknown_exts: true,
};
let entries = scan_directory(dir.path(), None, None, &scan_opts).expect("Directory scan failed.");
assert_eq!(entries.len(), files.len());
// there should be one file missing: "ignore.fake_ext"
assert_eq!(entries.len(), files.len() - 1);
// initialise global mime DB - this is needed because `scan_from_walkdir` expects it to be present.
crate::init_db();
let use_threads = cfg!(feature = "multi-threaded");
let results = scan_from_walkdir(&entries, false);
let canonical_results = scan_from_walkdir(&entries, true);
let results = scan_from_walkdir(&entries, false, use_threads).0;
let canonical_results = scan_from_walkdir(&entries, true, use_threads).0;
assert_eq!(results.len(), canonical_results.len());
for (result, canonical_result) in results.iter().zip(canonical_results.iter()) {
// there should be no IO errors during this test. any IO errors encountered are outside the scope of this test.
let result = result.as_ref().expect("Error while scanning file");
let canonical_result = canonical_result.as_ref().expect("Error while scanning file");
// paths should be canonical
assert_eq!(canonicalize(&result.file).unwrap(), canonical_result.file);
@ -142,38 +137,48 @@ fn simple_directory() {
if !result.valid {
// the only invalid file detected should be "wrong.jpg", which is a misnamed png file
// 1. ensure detected extension is "jpg"
assert_eq!(extension_from_path(result.file.as_path()).unwrap(), OsStr::new("jpg"));
// 2. ensure detected mime type is IMAGE_PNG
assert_eq!(result.file.as_path().extension().unwrap(), OsStr::new("jpg"));
// 2. ensure detected MIME type is IMAGE_PNG
assert_eq!(result.mime, IMAGE_PNG);
// 3. ensure the recommended extension for "wrong.jpg" is "png"
assert_eq!(&result.recommended_extension().unwrap(), &String::from("png"));
// 4. ensure the recommended filename for "wrong.jpg" is "wrong.png"
assert_eq!(result.recommended_path().unwrap().file_name(), Some(OsStr::new("wrong.png")));
continue;
}
// check if the recommended extension for this file is in the list of known extensions for its mimetype - for
// check if the recommended extension for this file is in the list of known extensions for its MIME type - for
// example, if the file is determined to be an IMAGE_PNG, its recommended extension should be one of the extensions
// returned by `mime_extension_lookup(IMAGE_PNG)`.
assert!(mime_extension_lookup(result.mime.essence_str().into())
.unwrap()
.contains(&result.recommended_extension().unwrap()));
// make sure the guessed mimetype is correct based on the extension of the scanned file
// because we already know that the extensions match the mimetype (as we created these files ourselves earlier in
// ensure that the recommended_name function outputs something beginning with "test"
assert!(result
.recommended_path()
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("test"));
// make sure the guessed MIME type is correct based on the extension of the scanned file
// because we already know that the extensions match the MIME type (as we created these files ourselves earlier in
// the test), all files with the "jpg" extension should be IMAGE_JPEGs, etc.
let ext = extension_from_path(result.file.as_path());
assert!(ext.is_some());
let ext = result.file.as_path().extension().unwrap();
assert_eq!(
result.mime,
match ext.unwrap().to_string_lossy().borrow() {
match ext.to_string_lossy().borrow() {
"jpg" | "jpeg" => IMAGE_JPEG,
"png" => IMAGE_PNG,
"pdf" => APPLICATION_PDF,
"zip" => application_zip(),
"zip" => APPLICATION_ZIP.clone(),
_ => APPLICATION_OCTET_STREAM, // general "fallback" type
},
"Incorrect MIME type detected - got {:?} for a {:?} file",
result.mime,
ext.unwrap()
ext
);
}
}
@ -211,6 +216,7 @@ fn argument_parsing() {
hidden: false,
extensionless: false,
follow_symlinks: true,
ignore_unknown_exts: false,
},
"ScanOpts are incorrect"
);
@ -219,7 +225,7 @@ fn argument_parsing() {
#[test]
/// Ensure that `fif -e jpg dir` is interpreted as "scan for jpg files in dir" and not "scan for jpg and dir files"
fn positional_args() {
for flag in &["-x", "-e", "-X", "-E"] {
for flag in ["-x", "-e", "-X", "-E"] {
assert_eq!(
Parameters::parse_from(vec!["fif", flag, "images", "directory"]).dir,
PathBuf::from("directory")
@ -245,12 +251,7 @@ fn exclude_overrides() {
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "abc,def,ghi,jkl", "-x", "abc,def"]);
let extensions = args.extensions();
assert!(extensions.is_some(), "Extensions should be set!");
let extensions = extensions.unwrap();
assert!(!extensions.contains(&"abc"));
assert!(!extensions.contains(&"def"));
assert!(extensions.contains(&"ghi"));
assert!(extensions.contains(&"jkl"));
assert_eq!(extensions, Some(btreeset!["ghi", "jkl"]));
}
#[test]
@ -260,10 +261,7 @@ fn exclude_set_overrides_includes() {
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "jpg,flac", "-X", "images"]);
let extensions = args.extensions();
assert!(extensions.is_some(), "Extensions should be set!");
let mut extensions = extensions.unwrap().into_iter();
assert_eq!(extensions.next(), Some("flac"), "Extensions should contain flac!");
assert_eq!(extensions.next(), None, "Too many extensions!");
assert_eq!(extensions, Some(btreeset!["flac"]));
}
#[test]
@ -281,18 +279,19 @@ fn exclude_set_overrides_include_set() {
.iter()
.chain(ExtensionSet::Video.extensions().iter())
{
assert!(extensions.contains(&ext), "Extensions should contain {}!", ext);
assert!(extensions.contains(&ext), "Extensions should contain {ext}!");
}
// ensure all of images' extensions are excluded
for ext in ExtensionSet::Images.extensions() {
assert!(!extensions.contains(&ext), "Extensions should not contain {}!", ext);
assert!(!extensions.contains(&ext), "Extensions should not contain {ext}!");
}
}
#[test]
/// Ensure that badly formed command line arguments are rejected.
fn rejects_bad_args() {
use assert_cmd::Command;
let tests = [
// Non-existent flags:
vec!["fif", "-abcdefghijklmnopqrstuvwxyz"],
@ -304,34 +303,97 @@ fn rejects_bad_args() {
vec!["fif", "-X", "pebis"],
// `-e` with nothing but commas:
vec!["fif", "-e", ",,,,,"],
// `-x` with nothing but commas:
vec!["fif", "-x", ",,,,,"],
// `-j` with a negative value:
vec!["fif", "-j", "-1"],
// `--prompt` without `--fix`:
vec!["fif", "--prompt", "always"],
// `--overwrite` without `--fix`:
vec!["fif", "--overwrite"],
];
for test in &tests {
assert!(Parameters::try_parse_from(test).is_err(), "Failed to reject {:?}", test);
// first, try testing the flags against the Parameters struct...
assert!(Parameters::try_parse_from(test).is_err(), "Failed to reject {test:?}");
// ...then, make sure it actually works against the binary
let mut cmd = Command::cargo_bin("fif").unwrap();
cmd.args(test).assert().failure();
}
}
#[test]
/// Ensure that a few simple, well-formed command line argument cases pass
fn accepts_good_args() {
use assert_cmd::Command;
// all of these commands pass either the version or help flag, ensuring that they won't fail for reasons relating
// to filesystem access
let tests = [
vec!["-V"],
vec!["--version"],
vec!["-E", "images", "--version"],
vec!["-h"],
vec!["--help"],
vec!["dir_name", "--version"],
];
for test in &tests {
let mut cmd = Command::cargo_bin("fif").unwrap();
cmd.args(test).assert().success();
}
}
#[test]
/// Ensures that output from the `-V` and `--version` flags is formatted properly.
fn check_version_output() {
use std::string::String;
use assert_cmd::Command;
use regex::Regex;
// test `-V` matches the format of "fif x.y.z"
let mut cmd = Command::cargo_bin("fif").unwrap();
let output = cmd.arg("-V").ok().unwrap().stdout;
let output = String::from_utf8(output).unwrap();
assert!(
Regex::new(r"fif v([0-9]\.){2}[0-9]").unwrap().is_match(output.trim()),
"\"{output}\" does not match the expected `-v` format!"
);
// test `--version` matches the format of "fif x.y.z (OS, example backend, commit #1234abc)"
let mut cmd = Command::cargo_bin("fif").unwrap();
let output = cmd.arg("--version").ok().unwrap().stdout;
let output = String::from_utf8(output).unwrap();
assert!(
Regex::new(r"fif v([0-9]\.){2}[0-9] \(.+, .+ backend, (unknown commit|commit #[[:xdigit:]]{7})\)")
.unwrap()
.is_match(output.trim()),
"\"{}\" does not match the expected `--version` format!",
output.trim()
);
}
#[test]
/// Generate random series of bytes and try to identify them. This test makes no assertions and can only fail if the
/// mime database somehow panics or hangs.
fn identify_random_bytes() {
use rand::RngCore;
let db = get_mime_db();
let mut rng = rand::thread_rng();
let mut bytes: [u8; BUF_SIZE * 2] = [0; BUF_SIZE * 2];
let mut results: HashMap<Mime, i32> = HashMap::new();
let mut results: BTreeMap<Mime, i32> = BTreeMap::new();
for _ in 1..1000 {
rng.fill_bytes(&mut bytes);
if let Some(detected_type) = db.get_type(&bytes) {
if let Some(detected_type) = MIMEDB.get_type(&bytes) {
*results.entry(detected_type).or_insert(0) += 1;
}
}
for (mime, count) in &results {
println!("{}:\t{} counts", mime, count);
println!("{mime}:\t{count} counts");
}
println!("No type found:\t{} counts", 500 - results.values().sum::<i32>());
println!("No type found:\t{} counts", 1000 - results.values().sum::<i32>());
}
#[test]
@ -341,19 +403,19 @@ fn outputs_move_commands() {
use std::io::Read;
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
let entries = vec![Ok(Findings {
let findings = vec![Findings {
file: Path::new("misnamed_file.png").to_path_buf(),
valid: false,
mime: IMAGE_JPEG,
})];
}];
for format in &["Shell", "PowerShell"] {
let mut cursor = std::io::Cursor::new(Vec::new());
let mut contents = std::string::String::new();
match *format {
"Shell" => Shell::new().write_all(&mut cursor, &entries),
"PowerShell" => PowerShell::new().write_all(&mut cursor, &entries),
"Shell" => Shell.write_all(&mut cursor, &findings, &[]),
"PowerShell" => PowerShell.write_all(&mut cursor, &findings, &[]),
_ => unreachable!(),
}
.expect("Failed to write to cursor");
@ -365,10 +427,8 @@ fn outputs_move_commands() {
// the output should contain a command like "mv -i misnamed_file.png misnamed_file.jpg"
assert!(
contents.contains("misnamed_file.jpg"),
"{} output doesn't contain move command!\n===\n{}",
format,
contents
contents.contains("misnamed_file.jpg") && contents.contains("misnamed_file.png"),
"{format} output doesn't contain move command!\n===\n{contents}"
);
}
}
@ -377,20 +437,21 @@ fn outputs_move_commands() {
#[cfg(feature = "json")]
/// Ensure JSON output is valid.
fn test_json() {
use crate::formats::Json;
use std::io::Read;
use crate::formats::Json;
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
let entries = vec![Ok(Findings {
let findings = vec![Findings {
file: Path::new("misnamed_file.png").to_path_buf(),
valid: false,
mime: IMAGE_JPEG,
})];
}];
let mut cursor = std::io::Cursor::new(Vec::new());
let mut contents = std::string::String::new();
Json::new()
.write_all(&mut cursor, &entries)
Json
.write_all(&mut cursor, &findings, &[])
.expect("Failed to write to cursor");
cursor.set_position(0);
@ -398,11 +459,10 @@ fn test_json() {
.read_to_string(&mut contents)
.expect("Failed to read from cursor to string");
// the output should contain the file's mime type
// the output should contain the file's MIME type
assert!(
contents.contains(IMAGE_JPEG.essence_str()),
"JSON output doesn't contain move command!\n===\n{}",
contents
"JSON output doesn't contain move command!\n===\n{contents}"
);
}
@ -419,25 +479,25 @@ fn media_contains_audio_video_images() {
.for_each(|ext| assert!(media_exts.contains(&ext)));
assert_eq!(
Parameters::parse_from(&["fif", "-E", "media"]).extensions(),
Parameters::parse_from(&["fif", "-E", "audio,video,images"]).extensions()
Parameters::parse_from(["fif", "-E", "media"]).extensions(),
Parameters::parse_from(["fif", "-E", "audio,video,images"]).extensions()
);
}
#[test]
/// Ensure that the `writables!` macro produces the output it should.
/// Ensure that the `writables!` and `writablesln!` macros produce the output they should.
fn writables_is_correct() {
use crate::formats::Writable;
use crate::writables;
use fif::formats::Writable;
use fif::{writables, writablesln};
assert_eq!(
&[
"henlo".into(),
Path::new("henlo").into(),
Writable::Newline,
Writable::Space
],
writables!["henlo", (Path::new("henlo")), Newline, Space]
&["henlo".into(), Path::new("henlo").into(), Writable::Newline,],
writables!["henlo", (Path::new("henlo")), Newline]
);
assert_eq!(
&["henlo".into(), Path::new("henlo").into(), Writable::Newline, Writable::Newline],
writablesln!["henlo", (Path::new("henlo")), Newline]
);
}
@ -446,22 +506,57 @@ fn writables_is_correct() {
fn verbosity() {
use log::LevelFilter;
assert!(
Parameters::try_parse_from(&["fif", "-q", "-v"]).is_err(),
Parameters::try_parse_from(["fif", "-q", "-v"]).is_err(),
"Failed to reject usage of both -q and -v!"
);
let mut expected_results = HashMap::new();
expected_results.insert("-qqqqqqqq", LevelFilter::Off);
expected_results.insert("-qqq", LevelFilter::Off);
expected_results.insert("-qq", LevelFilter::Error);
expected_results.insert("-q", LevelFilter::Warn);
expected_results.insert("-s", LevelFilter::Info);
expected_results.insert("-v", LevelFilter::Debug);
expected_results.insert("-vv", LevelFilter::Trace);
expected_results.insert("-vvv", LevelFilter::Trace);
expected_results.insert("-vvvvvvvv", LevelFilter::Trace);
let expected_results = hashmap![
"-qqqqqqqq" => LevelFilter::Off,
"-qqq" => LevelFilter::Off,
"-qq" => LevelFilter::Error,
"-q" => LevelFilter::Warn,
"-s" => LevelFilter::Info,
"-v" => LevelFilter::Debug,
"-vv" => LevelFilter::Trace,
"-vvv" => LevelFilter::Trace,
"-vvvvvvvv" => LevelFilter::Trace,
];
for (flags, level) in expected_results {
assert_eq!(Parameters::parse_from(&["fif", flags]).default_verbosity(), level);
assert_eq!(Parameters::parse_from(["fif", flags]).get_verbosity(), level);
}
}
#[test]
/// Ensures `os_name()`'s output is the same as [`std::env::consts::OS`], capitalisation notwithstanding
fn validate_os_name() {
assert_eq!(fif::utils::os_name().to_lowercase(), std::env::consts::OS.to_lowercase());
}
#[test]
/// Ensures that [`Findings`] are sorted properly.
fn sort_findings() {
let findings = vec![
Findings {
file: Path::new("ccc").to_path_buf(),
valid: false,
mime: IMAGE_JPEG,
},
Findings {
file: Path::new("bbb.xyz").to_path_buf(),
valid: true,
mime: IMAGE_PNG,
},
Findings {
file: Path::new("aaa").to_path_buf(),
valid: true,
mime: APPLICATION_PDF,
},
];
let mut findings = findings.iter().sorted_unstable();
assert_eq!(findings.next().unwrap().file, Path::new("aaa"));
assert_eq!(findings.next().unwrap().file, Path::new("bbb.xyz"));
assert_eq!(findings.next().unwrap().file, Path::new("ccc"));
assert_eq!(findings.next(), None);
}

View File

@ -1,5 +1,15 @@
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Various minor utilities.
use std::str::FromStr;
use cfg_if::cfg_if;
use once_cell::sync::OnceCell;
use mime::Mime;
use once_cell::sync::Lazy;
use crate::String;
/// The current version of fif, as defined in Cargo.toml.
pub const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
@ -14,37 +24,38 @@ cfg_if! {
}
}
// the version and long_version given to clap need to be a &str, but we want to use format!, which returns a String.
// we can't just do something like `version = format!(...).as_str()`, because clap needs to know that the version will
// live for a given lifetime, which we need to satisfy by making our String static. of course, you can't use format!
// statically, so we need to use a OnceCell or similar to get around this.
static CLAP_VERSION: OnceCell<String> = OnceCell::new();
static CLAP_LONG_VERSION: OnceCell<String> = OnceCell::new();
/// The version defined in Cargo.toml, prefixed with a v (e.g. "v0.4.0")
pub(crate) static CLAP_VERSION: Lazy<String> = Lazy::new(|| String::from("v") + VERSION.unwrap_or("???"));
/// Sets [`CLAP_VERSION`] to be the version defined in Cargo.toml, prefixed with a v (e.g. "v0.3.1"), then returns it as
/// a String.
pub fn clap_version() -> &'static str { CLAP_VERSION.get_or_init(|| format!("v{}", VERSION.unwrap_or("???"))) }
/// The version defined in Cargo.toml, prefixed with a v (e.g. "v0.4.0"), followed by the chosen backend and
/// abbreviated git commit hash in parentheses - For example, "v0.4.0 (XDG-Mime backend, commit #043e097)"
pub static CLAP_LONG_VERSION: Lazy<String> = Lazy::new(|| {
// handle cases where GIT_SHA is set to an empty string
let commit = match option_env!("GIT_SHA") {
Some(hash) if !hash.trim().is_empty() => String::from("commit #") + hash,
_ => String::from("unknown commit"),
};
/// Sets [`CLAP_LONG_VERSION`] to be similar to [`CLAP_VERSION`], followed by the chosen backend in parentheses (e.g.
/// "v0.3.1 (XDG-Mime backend)"), then returns it as a String.
pub fn clap_long_version() -> &'static str {
CLAP_LONG_VERSION.get_or_init(|| format!("v{} ({} backend)", VERSION.unwrap_or("???"), BACKEND))
}
format!("v{} ({}, {} backend, {})", VERSION.unwrap_or("???"), os_name(), BACKEND, commit).into()
});
/// A [`Mime`] representing the "application/zip" MIME type.
pub static APPLICATION_ZIP: Lazy<Mime> = Lazy::new(|| Mime::from_str("application/zip").unwrap());
/// Returns the name of the target operating system with proper casing, like "Windows" or "macOS".
#[allow(clippy::option_map_unit_fn)]
pub fn os_name() -> String {
use std::env::consts::OS;
match OS {
match std::env::consts::OS {
// special cases: "ios" should not be capitalised into "Ios", for example
"ios" => "iOS".into(),
"macos" => "macOS".into(),
"freebsd" => "FreeBSD".into(),
"openbsd" => "OpenBSD".into(),
"netbsd" => "NetBSD".into(),
"vxworks" => "VxWorks".into(),
_ => {
os => {
// generic case: return consts::OS with the first letter in uppercase ("linux" -> "Linux")
let mut os_upper = String::from(OS);
let mut os_upper = String::from(os);
os_upper.get_mut(0..1).map(|first| first.make_ascii_uppercase());
os_upper
}

20
test.py
View File

@ -1,19 +1,26 @@
#!/usr/bin/env python
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: GPL-3.0-or-later
import re
import subprocess
import sys
def test_archs():
archs = ["aarch64", "powerpc"]
archs = ["aarch64", "powerpc", "riscv64gc"]
upto = 1
target = len(archs)
for arch in archs:
print(f"Testing {arch} ({upto} of {target})")
subprocess.run(f"cross test --features=infer-backend --target {arch}-unknown-linux-gnu".split(" ")).check_returncode()
subprocess\
.run(f"cross test --features=json,infer-backend --target {arch}-unknown-linux-gnu".split(" "))\
.check_returncode()
upto += 1
def test_versions():
match = re.search(
r'rust-version ?= ?"([\d.]+)"',
@ -33,13 +40,16 @@ def test_versions():
for version in versions:
for backend in backends:
print(f"[{version}, {backend}] Tests ({upto} of {target})")
subprocess.run(f"cargo +{version} test --features={backend}-backend".split(" ")).check_returncode()
subprocess.run(f"cargo +{version} test --features=json,{backend}-backend".split(" ")).check_returncode()
upto += 1
print(f"[{version}, {backend}] Scanning imgs ({upto} of {target})")
subprocess.run(f"cargo +{version} run --release --features={backend}-backend -- imgs".split(" ")).check_returncode()
subprocess\
.run(f"cargo +{version} run --release --features=json,{backend}-backend -- imgs".split(" "))\
.check_returncode()
upto += 1
def main():
done_something = False
if "versions" in sys.argv:
@ -54,6 +64,8 @@ def main():
sys.exit(2)
print("Done! You might want to run cargo clean...")
subprocess.run(["du", "-sh", "target"])
if __name__ == "__main__":
main()