Compare commits
282 commits
v0.2.3+hot
...
master
Author | SHA1 | Date | |
---|---|---|---|
484a27b044 | |||
274f6a44c1 | |||
74e14fca78 | |||
72256ae8d2 | |||
a570b07672 | |||
10c6512231 | |||
c048d21935 | |||
4565487149 | |||
5017854dd3 | |||
4469104ac1 | |||
7e03dd7cf7 | |||
61196df626 | |||
9e592863f1 | |||
62a630249c | |||
57fbbc23be | |||
476209b82e | |||
acd33980e9 | |||
420bd0483c | |||
866a8d41d5 | |||
74098ed281 | |||
c15d92eaa6 | |||
b19a508020 | |||
cabed845ce | |||
20587fd663 | |||
944360f9ab | |||
c9f68d8373 | |||
1b0505aad1 | |||
4b84b01adc | |||
4369290cc2 | |||
f9c0691170 | |||
b464ce8c08 | |||
2a0a74f775 | |||
b811f1a911 | |||
ee6224e98c | |||
e834c3e7fa | |||
162ed80e1e | |||
fc45376673 | |||
0f9e414014 | |||
66dd11397a | |||
dc9eb2fa3b | |||
e59580b892 | |||
330b273be6 | |||
a0396e2e1e | |||
9c404f2557 | |||
|
c4f0cd8d12 | ||
6b821f1e1e | |||
8e5ddd8e4a | |||
c06a7a527a | |||
9aef5d314c | |||
82232a3c05 | |||
5b920665a2 | |||
b72ac443b1 | |||
b6c2d75bdb | |||
65a560d5f4 | |||
313afe7cc1 | |||
33f4eb4135 | |||
ec10b58482 | |||
667ee440e0 | |||
44e14fbfba | |||
28aa3ad783 | |||
855211f458 | |||
5df8545906 | |||
672cc8da90 | |||
c0d8105731 | |||
fcaaf283b7 | |||
36c0e99a92 | |||
480acf515f | |||
58d5ac7e75 | |||
b5ef95b6ef | |||
6d32beedcc | |||
ce79cf14ba | |||
955f0e1510 | |||
38ca71cc14 | |||
47c55ae61e | |||
c30aba35fd | |||
17a784732b | |||
556ea82a06 | |||
c4fabbc0f4 | |||
451ea3d5d9 | |||
3f40c61d6d | |||
37b9cccc9c | |||
25d8ed64ae | |||
eb3e650361 | |||
f1982f670e | |||
0712bf0a6b | |||
47d94cf27b | |||
db80955f24 | |||
4c6163296c | |||
5e17e4efda | |||
741048839c | |||
0c31277191 | |||
6718f879f7 | |||
c2e6738f6b | |||
b368be3e6b | |||
3e753c2a0b | |||
97b0a6edaa | |||
3d41183f1c | |||
8a7cbca461 | |||
da998d019a | |||
08b89d237b | |||
3ee8745440 | |||
afa2bb8784 | |||
043e0972c5 | |||
a800be63f7 | |||
bddd6caeb2 | |||
74ae55ac52 | |||
7c36061e03 | |||
4a54511833 | |||
30c7da077a | |||
88b5070a03 | |||
c2988e4f10 | |||
2884f9fe4c | |||
fa49dd9fb5 | |||
ebf2f152f0 | |||
fb81f26ff5 | |||
557f5132ff | |||
d625fef106 | |||
1f46bef10b | |||
a2ce336fe7 | |||
4192d37854 | |||
45081efd0e | |||
6e2e788a61 | |||
e1dc2d04f1 | |||
15b4651215 | |||
0b7f9ef4a4 | |||
d34fa02033 | |||
fddd479f20 | |||
2222e92080 | |||
d7e2eb9adc | |||
0404cff8b7 | |||
ddde6acdd6 | |||
b48b8d5a65 | |||
7a7e6c9bc6 | |||
a071f21141 | |||
eed4e29e00 | |||
c3adaea88c | |||
8cdd0a8fc1 | |||
59c87a3729 | |||
863954b2a2 | |||
44a0351884 | |||
2f1151805f | |||
011b9eee99 | |||
a941040948 | |||
f243cbba76 | |||
0d034a5c4b | |||
|
e66eaa66a6 | ||
10bf85ba0f | |||
e511d215be | |||
4f78d93975 | |||
3b731a7c61 | |||
3b7a26961b | |||
8a91ca3ef4 | |||
60eb781132 | |||
02f377cbb2 | |||
d0a6e918cc | |||
ec4ad77136 | |||
8b2b26d44f | |||
bd1a2a3e3a | |||
0278fe252e | |||
6934dd0b5e | |||
1ecc6e6c6e | |||
f8dcdf8a3c | |||
95956f8e30 | |||
df9c033b38 | |||
0c8c58366f | |||
c66a639eed | |||
8dac4127e9 | |||
5720c53735 | |||
2d5d41b162 | |||
04574e5932 | |||
ca5773c167 | |||
a50350a15e | |||
8341c4aaf7 | |||
c3b5dbea35 | |||
81347a7658 | |||
3b3a64c9ea | |||
394bcf1897 | |||
0b1abcd659 | |||
a1b16bd8e0 | |||
64efb0de27 | |||
417893cae0 | |||
0c0d3f12ea | |||
b93e111357 | |||
774e72423f | |||
beebbbbb3b | |||
a60a19191a | |||
80f14085cf | |||
6d6897a86e | |||
32edcc0c92 | |||
48c9475b4e | |||
26521e3fae | |||
952e157873 | |||
090e4adafe | |||
4acbcaaa9b | |||
9fb647f214 | |||
8cca5097d4 | |||
a05af12352 | |||
84ce0fc0ce | |||
534101db8b | |||
cb6e111f16 | |||
4f5914ed75 | |||
d5d58e1830 | |||
af3d51fcda | |||
d578efa7a4 | |||
22f1f280d7 | |||
b3ce5d3d46 | |||
b12c42adbb | |||
fc51f8128a | |||
7e3efbed5c | |||
aad70ee13b | |||
af9968947c | |||
b864b4b388 | |||
40bdac274f | |||
889b2e2316 | |||
2ceafb7acf | |||
7a315e9cf6 | |||
475998fd22 | |||
0753c7c948 | |||
b80c510d48 | |||
d6974b4959 | |||
6a7577d874 | |||
e9acdd7751 | |||
4e37e184ec | |||
430a4b9ab4 | |||
6837a73672 | |||
bbe1d25681 | |||
4d553587aa | |||
255665cae0 | |||
b877d7d65e | |||
dc2ac7b002 | |||
83091c754d | |||
2713083a82 | |||
48632a471a | |||
59a3042ebc | |||
7f87f59670 | |||
e7637013eb | |||
9c8be183d9 | |||
383f6a30f2 | |||
21dfe93a05 | |||
d54cc8d6da | |||
0f2f408c09 | |||
e83ac778d6 | |||
be37b24705 | |||
cb2a30f455 | |||
fb67c11eb6 | |||
12d9001bb8 | |||
55f73d8a9a | |||
25c9efa2f1 | |||
7115692f9d | |||
129aa83ade | |||
40a90308a5 | |||
62562a0b69 | |||
67cffcff91 | |||
c68a88c6b0 | |||
87dab7284f | |||
e3af10cf5b | |||
6d55b3c309 | |||
b09b871b3d | |||
8a152d4118 | |||
4412161193 | |||
5907309689 | |||
32da919f81 | |||
c270383e6f | |||
1aa355e753 | |||
58f3b323cc | |||
ecee74eb29 | |||
31aaa80701 | |||
e294f56ecf | |||
67fb03821d | |||
d04fc22d46 | |||
dcbf3e8b3c | |||
bcd77d9ed6 | |||
809df5bc0e | |||
601481130f | |||
b89e71a6ab | |||
d76ed2585d | |||
967592b22a | |||
fb204d9c9a | |||
52a0709097 | |||
ebc2bcfb41 | |||
b141b85ea7 | |||
db94465bb7 |
46 changed files with 4686 additions and 991 deletions
17
.drone.yml
Normal file
17
.drone.yml
Normal file
|
@ -0,0 +1,17 @@
|
|||
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: default
|
||||
|
||||
steps:
|
||||
- name: linux-gnu
|
||||
image: rust:latest
|
||||
commands:
|
||||
- cargo test --locked -j3
|
||||
#- name: linux-musl
|
||||
# image: rust:alpine
|
||||
# commands:
|
||||
# - cargo test -j3
|
4
.gitattributes
vendored
Normal file
4
.gitattributes
vendored
Normal 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
|
19
.gitignore
vendored
19
.gitignore
vendored
|
@ -1,7 +1,24 @@
|
|||
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
/target
|
||||
/imgs
|
||||
fif_*
|
||||
/imgs.tar.zst
|
||||
/fif_*
|
||||
/old
|
||||
/.mypy_cache
|
||||
/__pycache__
|
||||
*.sh
|
||||
!clippy.sh
|
||||
cargo-timing*.html
|
||||
/*.txt
|
||||
/pkg/*
|
||||
/out
|
||||
/packages
|
||||
/fif
|
||||
/fif.exe
|
||||
.idea/workspace.xml
|
||||
*.sync-conflict*
|
||||
.idea/sonarlint
|
||||
.directory
|
||||
*.tmp
|
||||
|
|
223
.gitlab-ci.yml
Normal file
223
.gitlab-ci.yml
Normal file
|
@ -0,0 +1,223 @@
|
|||
# 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:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
default:
|
||||
before_script:
|
||||
- rustc --version
|
||||
- cargo version
|
||||
|
||||
stages:
|
||||
- lint # KNEE-DEEP IN THE DEBUG
|
||||
- cache-cleanup # THE CACHES OF HELL
|
||||
- build-base # INFERNAL build times
|
||||
- build # THY CREDITS CONSUMED
|
||||
- test # SIGKILL
|
||||
# - release
|
||||
|
||||
# TEMPLATES
|
||||
|
||||
# this step uses cargo-sweep to clean up unneeded cruft that accumulates over time in the target dir. cargo clean is
|
||||
# not used because it simply rm -rf's the entire target directory (and thus prevents build caching). i would really like
|
||||
# to either replace this with a bash script, or to install cargo-sweep as a binary instead of building it from source
|
||||
# like this. i'd also like to add a step that checks to see whether the target dir exists, and exits early if not.
|
||||
.cargo-cleanup:
|
||||
stage: cache-cleanup
|
||||
allow_failure: true
|
||||
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
|
||||
# cargo-build can reuse some cached stuff, rather than building from scratch every time.
|
||||
.cargo-build-base:
|
||||
stage: build-base
|
||||
script:
|
||||
cargo build --locked
|
||||
|
||||
# build with various features on and off.
|
||||
.cargo-build:
|
||||
extends: .cargo-build-base
|
||||
stage: build
|
||||
parallel:
|
||||
matrix:
|
||||
- FEATURES:
|
||||
- xdg-mime-backend
|
||||
- infer-backend
|
||||
- multi-threaded xdg-mime-backend
|
||||
- multi-threaded infer-backend
|
||||
|
||||
script:
|
||||
cargo run --no-default-features --locked --features="json $FEATURES" -- --version
|
||||
|
||||
# test with various features on and off.
|
||||
.cargo-test:
|
||||
extends: .cargo-build
|
||||
stage: test
|
||||
script:
|
||||
cargo test --no-default-features --locked --verbose --features="json $FEATURES"
|
||||
|
||||
# LINT
|
||||
|
||||
# run the included clippy.sh with "ci" mode on - clippy will exit with code 1 if anything at all is amiss. this is just
|
||||
# here to make sure i remember to run clippy.sh locally myself and fix/ignore all the warnings before committing, as i
|
||||
# should be.
|
||||
clippy:
|
||||
stage: lint
|
||||
script:
|
||||
- rustup component add clippy
|
||||
- cargo clippy --version
|
||||
- ./clippy.sh ci
|
||||
|
||||
# CACHE CLEANUP
|
||||
cleanup-stable:
|
||||
extends: .cargo-cleanup
|
||||
|
||||
# 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
|
||||
image: "rustlang/rust:nightly"
|
||||
cache:
|
||||
key: nightly
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
# BUILD BASE
|
||||
build-base-stable:
|
||||
extends: .cargo-build-base
|
||||
needs: ["cleanup-stable"]
|
||||
|
||||
build-base-msrv:
|
||||
extends: build-base-stable
|
||||
image: "rust:1.64.0"
|
||||
cache:
|
||||
key: msrv
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
build-base-nightly:
|
||||
extends: build-base-stable
|
||||
needs: ["cleanup-nightly"]
|
||||
image: "rustlang/rust:nightly"
|
||||
cache:
|
||||
key: nightly
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
# BUILD
|
||||
|
||||
build-stable:
|
||||
extends: .cargo-build
|
||||
needs: ["build-base-stable"]
|
||||
|
||||
build-msrv:
|
||||
extends: build-stable
|
||||
needs: ["build-base-msrv"]
|
||||
image: "rust:1.64.0"
|
||||
cache:
|
||||
key: msrv
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
build-nightly:
|
||||
extends: build-stable
|
||||
needs: ["build-base-nightly"]
|
||||
image: "rustlang/rust:nightly"
|
||||
cache:
|
||||
key: nightly
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
# TEST
|
||||
|
||||
test-stable:
|
||||
extends: .cargo-test
|
||||
needs: ["build-stable"]
|
||||
|
||||
test-msrv:
|
||||
extends: test-stable
|
||||
image: "rust:1.64.0"
|
||||
needs: ["build-msrv"]
|
||||
cache:
|
||||
key: msrv
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
test-nightly:
|
||||
extends: test-stable
|
||||
image: "rustlang/rust:nightly"
|
||||
needs: ["build-nightly"]
|
||||
cache:
|
||||
key: nightly
|
||||
paths:
|
||||
- target
|
||||
- .cargo
|
||||
|
||||
# RELEASE
|
||||
# this is currently all disabled because
|
||||
# a) it's gross
|
||||
# b) it probably won't work and i really don't want to partake in CI tomfoolery right now, or ever
|
||||
|
||||
#build-release:
|
||||
# stage: release
|
||||
# cache: { }
|
||||
# rules:
|
||||
# - if: $CI_COMMIT_TAG
|
||||
# needs: ["test-stable"]
|
||||
# script:
|
||||
# - ./package.sh
|
||||
# artifacts:
|
||||
# paths:
|
||||
# - out/
|
||||
|
||||
#upload-release:
|
||||
# stage: release
|
||||
# cache: { }
|
||||
# rules:
|
||||
# - if: $CI_COMMIT_TAG
|
||||
# image: curlimages/curl:latest
|
||||
# script:
|
||||
# - git describe --tags --abbrev=0 | cut -c 2- > tmp
|
||||
# - |
|
||||
# cd out
|
||||
# for _bin in *.{zip,xz} do; curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file "$_bin" "${PACKAGE_REGISTRY_URL}/$(cat ../tmp)/${_bin}"; done
|
||||
# - rm ../tmp
|
||||
|
||||
#create-release:
|
||||
# stage: release
|
||||
# cache: {}
|
||||
# image: registry.gitlab.com/gitlab-org/release-cli:latest
|
||||
# rules:
|
||||
# - if: $CI_COMMIT_TAG
|
||||
# script:
|
||||
# - |
|
||||
# cd out
|
||||
# echo -n "release-cli create --name \"Release $CI_COMMIT_TAG\" --tag-name=\"$CI_COMMIT_TAG\" " > tmp.sh
|
||||
# git describe --tags --abbrev=0 | cut -c 2- > tmp
|
||||
# for _bin in *.{zip,xz}; do echo -n --assets-link \"\{\"name\":\"${_bin}\",\"url\":\"${PACKAGE_REGISTRY_URL}/$(cat tmp)/${_bin}\"\}\" >> tmp.sh; echo -n " " >> tmp.sh; done
|
||||
# - cat tmp.sh
|
||||
# - bash tmp.sh
|
||||
# - |
|
||||
# rm tmp.sh
|
||||
# rm tmp
|
23
.idea/csv-plugin.xml
generated
23
.idea/csv-plugin.xml
generated
|
@ -1,23 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CsvFileAttributes">
|
||||
<option name="attributeMap">
|
||||
<map>
|
||||
<entry key="/src/main.rs">
|
||||
<value>
|
||||
<Attribute>
|
||||
<option name="separator" value="	" />
|
||||
</Attribute>
|
||||
</value>
|
||||
</entry>
|
||||
<entry key="/src/parameters.rs">
|
||||
<value>
|
||||
<Attribute>
|
||||
<option name="separator" value="," />
|
||||
</Attribute>
|
||||
</value>
|
||||
</entry>
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
29
.idea/fif.iml
generated
29
.idea/fif.iml
generated
|
@ -3,10 +3,39 @@
|
|||
<component name="NewModuleRootManager">
|
||||
<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" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/awful" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.mypy_cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/pkg" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/out" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
|
|
31
.idea/inspectionProfiles/Project_Default.xml
generated
31
.idea/inspectionProfiles/Project_Default.xml
generated
|
@ -1,30 +1,13 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="PyAugmentAssignmentInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="PyComparisonWithNoneInspection" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="PyInconsistentIndentationInspection" enabled="true" level="ERROR" enabled_by_default="true" />
|
||||
<inspection_tool class="PyMissingTypeHintsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="E302" />
|
||||
<option value="E305" />
|
||||
<option value="E261" />
|
||||
<option value="E128" />
|
||||
<option value="E124" />
|
||||
<option value="W191" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredIdentifiers">
|
||||
<list>
|
||||
<option value="mutagen.id3._frames.APIC.*" />
|
||||
<option value="music_tools.note.Note" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<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
generated
Normal file
9
.idea/markdown.xml
generated
Normal 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>
|
19
.idea/runConfigurations/Coverage.xml
generated
Normal file
19
.idea/runConfigurations/Coverage.xml
generated
Normal file
|
@ -0,0 +1,19 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Coverage" type="CargoCommandRunConfiguration" factoryName="Cargo Command">
|
||||
<option name="command" value="test" />
|
||||
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
|
||||
<option name="channel" value="NIGHTLY" />
|
||||
<option name="requiredFeatures" value="true" />
|
||||
<option name="allFeatures" value="false" />
|
||||
<option name="emulateTerminal" value="false" />
|
||||
<option name="backtrace" value="SHORT" />
|
||||
<envs>
|
||||
<env name="RUST_LOG" value="debug" />
|
||||
</envs>
|
||||
<option name="isRedirectInput" value="false" />
|
||||
<option name="redirectInputPath" value="" />
|
||||
<method v="2">
|
||||
<option name="CARGO.BUILD_TASK_PROVIDER" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
20
.idea/runConfigurations/Run.xml
generated
Normal file
20
.idea/runConfigurations/Run.xml
generated
Normal file
|
@ -0,0 +1,20 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Run" type="CargoCommandRunConfiguration" factoryName="Cargo Command" nameIsGenerated="true">
|
||||
<option name="command" value="run -- imgs" />
|
||||
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
|
||||
<option name="channel" value="DEFAULT" />
|
||||
<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" />
|
||||
</envs>
|
||||
<option name="isRedirectInput" value="false" />
|
||||
<option name="redirectInputPath" value="" />
|
||||
<method v="2">
|
||||
<option name="CARGO.BUILD_TASK_PROVIDER" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
19
.idea/runConfigurations/Test.xml
generated
Normal file
19
.idea/runConfigurations/Test.xml
generated
Normal file
|
@ -0,0 +1,19 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Test" type="CargoCommandRunConfiguration" factoryName="Cargo Command">
|
||||
<option name="command" value="test" />
|
||||
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
|
||||
<option name="channel" value="DEFAULT" />
|
||||
<option name="requiredFeatures" value="true" />
|
||||
<option name="allFeatures" value="false" />
|
||||
<option name="emulateTerminal" value="false" />
|
||||
<option name="backtrace" value="SHORT" />
|
||||
<envs>
|
||||
<env name="RUST_LOG" value="debug" />
|
||||
</envs>
|
||||
<option name="isRedirectInput" value="false" />
|
||||
<option name="redirectInputPath" value="" />
|
||||
<method v="2">
|
||||
<option name="CARGO.BUILD_TASK_PROVIDER" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
19
.idea/runConfigurations/Test__infer_.xml
generated
Normal file
19
.idea/runConfigurations/Test__infer_.xml
generated
Normal file
|
@ -0,0 +1,19 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Test (infer)" type="CargoCommandRunConfiguration" factoryName="Cargo Command">
|
||||
<option name="command" value="test --features=infer-backend" />
|
||||
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
|
||||
<option name="channel" value="DEFAULT" />
|
||||
<option name="requiredFeatures" value="true" />
|
||||
<option name="allFeatures" value="false" />
|
||||
<option name="emulateTerminal" value="false" />
|
||||
<option name="backtrace" value="SHORT" />
|
||||
<envs>
|
||||
<env name="RUST_LOG" value="debug" />
|
||||
</envs>
|
||||
<option name="isRedirectInput" value="false" />
|
||||
<option name="redirectInputPath" value="" />
|
||||
<method v="2">
|
||||
<option name="CARGO.BUILD_TASK_PROVIDER" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
3
.idea/scopes/Default.xml
generated
Normal file
3
.idea/scopes/Default.xml
generated
Normal 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)&&!file[fif]:doc/*||file:build.rs" />
|
||||
</component>
|
3
.kateproject
Normal file
3
.kateproject
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"index": true
|
||||
}
|
1
.mailmap
Normal file
1
.mailmap
Normal file
|
@ -0,0 +1 @@
|
|||
Lynne <lynne@bune.city> Lynnesbian <lynne@bune.city>
|
12
.reuse/dep5
Normal file
12
.reuse/dep5
Normal 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
64
.vscode/launch.json
vendored
Normal 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}"
|
||||
}
|
||||
]
|
||||
}
|
340
CHANGELOG.md
Normal file
340
CHANGELOG.md
Normal file
|
@ -0,0 +1,340 @@
|
|||
# Changelog
|
||||
Dates are given in YYYY-MM-DD format - for example, the 15th of October 2021 is written as 2021-10-15.
|
||||
|
||||
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.2 - 2024-08-07
|
||||
### Changed
|
||||
- Updated and pinned dependencies, using the latest MSRV-compatible versions available.
|
||||
- Implement clippy suggestions
|
||||
|
||||
## 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
|
||||
- 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
|
||||
### 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
|
||||
### 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
|
||||
### Added
|
||||
- `-x`/`--exclude` flag for excluding file extensions (overrides `-e` or `-E` - `-E images -x jpg` scans all image
|
||||
files, except ".jpg" files)
|
||||
- `-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
|
||||
- Changed default verbosity to `info`
|
||||
### Fixed
|
||||
- Resolved some discrepancies between `application/xml` and `text/xml`
|
||||
### Other
|
||||
- Published my fork of ['mime_guess'] as ['new_mime_guess'], allowing it to be used properly with
|
||||
[crates.io](https://crates.io)
|
||||
- CI has been vastly improved
|
||||
|
||||
## v0.2
|
||||
### v0.2.13 (2021-04-26)
|
||||
### 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
|
||||
- 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
|
||||
- Cleaned up and properly documented tests
|
||||
- Renamed `Script` (in `formats.rs`) to `Shell`, in line with renaming in `parameters.rs`
|
||||
- [`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)
|
||||
### Added
|
||||
- Text extension set
|
||||
- Better documentation for command line arguments
|
||||
### Fixed
|
||||
- Fixed a very minor output bug relating to scanning symlinked directories
|
||||
- Better detection for pre-OOXML Office files
|
||||
### Other
|
||||
- Much better README.md
|
||||
- Added more stuff to test.py
|
||||
- PKGBUILD for Arch-based distros
|
||||
- More test coverage
|
||||
- Doubled BUF_SIZE
|
||||
|
||||
### v0.2.11 (2021-04-04)
|
||||
### Added
|
||||
- fif can now traverse symlinks with the `-f`/`--follow-symlinks` flag
|
||||
### 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
|
||||
### Other
|
||||
- Replaced a bunch of `PathBuf`s with `Path`s, which should reduce memory usage
|
||||
- Formatting improvements
|
||||
|
||||
## 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)
|
||||
### Fixed
|
||||
- Using `-s` to skip hidden files no longer skips all files if the root directory itself is hidden
|
||||
### 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
|
||||
### 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
|
||||
|
||||
### 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
|
||||
### Other
|
||||
- Use [`xdg-mime`] by default on Linux, [`infer`] elsewhere
|
||||
|
||||
## 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
|
||||
### Added
|
||||
- Automatically disable [`xdg-mime`] backend on Windows
|
||||
- Exit codes
|
||||
- Improved error handling
|
||||
- Retrieve extension sets from [`mime_guess`] rather than hardcoding them
|
||||
### 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
|
||||
### Added
|
||||
- Windows support
|
||||
|
||||
## 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`
|
||||
- [`infer`] backend, configurable with [Cargo features](https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features)
|
||||
### Fixed
|
||||
- Fixed broken singlethreaded support
|
||||
### Other
|
||||
- Use a global backend instance instead of passing `&db` around constantly
|
||||
- Use `rustfmt` 0u0
|
||||
|
||||
## v0.2.0 - 2021-02-15
|
||||
### Added
|
||||
- Output a script rather than a list of misnamed files
|
||||
- Parallel file scanning
|
||||
- Logging support
|
||||
### Fixed
|
||||
- Handle filenames with invalid UTF-8
|
||||
### Other
|
||||
- Now licensed (under GPLv3)
|
||||
- Replaced [`structopt`] with [`clap`] 3 (beta)
|
||||
- Specify 1.43.0 as minimum supported Rust version
|
||||
|
||||
## 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 -->
|
||||
[`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
|
1020
Cargo.lock
generated
1020
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
80
Cargo.toml
80
Cargo.toml
|
@ -1,57 +1,87 @@
|
|||
[package]
|
||||
name = "fif"
|
||||
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
|
||||
version = "0.2.3+hotfix"
|
||||
version = "0.7.2"
|
||||
authors = ["Lynnesbian <lynne@bune.city>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later"
|
||||
rust-version = "1.43.0" # cached requires 1.42.0
|
||||
repository = "https://git.bune.city/lynnesbian/fif"
|
||||
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/", "Cross.toml", "*.sh"]
|
||||
#resolver = "2"
|
||||
#license-file = "LICENSE"
|
||||
exclude = [".idea/", "*.toml", "!Cargo.toml", "*.sh", "*.py", "*.yml", "*.md", ".mailmap", "pkg/"]
|
||||
|
||||
[badges]
|
||||
maintenance = { status = "experimental" }
|
||||
|
||||
[features]
|
||||
default = ["multi-threaded", "infer-backend"]
|
||||
multi-threaded = ["rayon"]
|
||||
default = ["multi-threaded", "json"]
|
||||
multi-threaded = ["rayon", "num_cpus"]
|
||||
infer-backend = ["infer"]
|
||||
xdg-mime-backend = ["xdg-mime"]
|
||||
json = ["serde", "serde_json"]
|
||||
|
||||
[dependencies]
|
||||
walkdir = "2.3.1"
|
||||
walkdir = "2.4.0"
|
||||
log = "0.4.14"
|
||||
smartstring = "0.2.6"
|
||||
mime_guess = "2.0.3"
|
||||
mime = "0.3.16"
|
||||
mime_guess = { package = "new_mime_guess", version = "4.0.0" }
|
||||
snailquote = "0.3.0"
|
||||
once_cell = "1.5.2"
|
||||
once_cell = "1.8.0"
|
||||
rayon = { version = "1.5.0", optional = true }
|
||||
infer = { version = "0.3.4", optional = true }
|
||||
exitcode = "1.1.2"
|
||||
cfg-if = "1.0.0"
|
||||
itertools = "0.13.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"
|
||||
|
||||
# use git version while waiting on a release incorporating https://github.com/ebassi/xdg-mime-rs/commit/de5a6dd
|
||||
[target.'cfg(not(target_os = "windows"))'.dependencies]
|
||||
xdg-mime = {git = "https://github.com/ebassi/xdg-mime-rs", version = "0.3", rev = "de5a6dd", optional = true }
|
||||
# various clap dependencies with MSRV-incompatible versions:
|
||||
anstyle-query = "=1.0.0"
|
||||
anstyle-parse = "=0.2.1"
|
||||
anstyle = "=1.0.2"
|
||||
clap_lex = "=0.5.0"
|
||||
colorchoice = "=1.0.0"
|
||||
|
||||
[target.'cfg(not(unix))'.dependencies]
|
||||
xdg-mime = { version = "0.4.0", optional = true }
|
||||
infer = "=0.13.0" # 0.14.0 uses `let else`, which requires rust 1.65
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
xdg-mime = "0.4.0"
|
||||
infer = { version = "=0.13.0", optional = true }
|
||||
|
||||
[dependencies.clap]
|
||||
version = "3.0.0-beta.2"
|
||||
version = "~4.3" #4.4 has some deps that can't be satisfied on our MSRV
|
||||
default-features = false
|
||||
features = ["wrap_help", "color", "derive", "std"]
|
||||
features = ["wrap_help", "color", "derive", "std", "unicode"]
|
||||
|
||||
[dependencies.env_logger]
|
||||
version = "0.8.2"
|
||||
version = "0.10.0" # 0.11 depends on is_terminal_polyfill 1.70.1, which requires rust 1.70
|
||||
default-features = false
|
||||
features = ["termcolor", "atty"]
|
||||
features = ["color"]
|
||||
|
||||
[dependencies.cached]
|
||||
version = "0.23.0"
|
||||
default-features = false
|
||||
[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
|
||||
predicates-tree = "=1.0.9"
|
||||
predicates-core = "=1.0.6"
|
||||
regex = { version = "=1.9.5", default-features = false, features = ["std"] } # 1.9.6 requires rust 1.65
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
|
||||
# optimise dependencies, even when producing debug builds
|
||||
# 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"
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
[build.env]
|
||||
passthrough = ["RUST_BACKTRACE", "RUST_LOG"]
|
||||
passthrough = ["RUST_BACKTRACE", "RUST_LOG", "FIF_LOG"]
|
||||
|
|
170
LICENSES/CC-BY-SA-4.0.txt
Normal file
170
LICENSES/CC-BY-SA-4.0.txt
Normal 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 licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then 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 Adapter’s 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 Adapter’s 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
121
LICENSES/CC0-1.0.txt
Normal 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.
|
232
LICENSES/GPL-3.0-or-later.txt
Normal file
232
LICENSES/GPL-3.0-or-later.txt
Normal 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>.
|
241
README.md
241
README.md
|
@ -1,36 +1,253 @@
|
|||
fif
|
||||
===
|
||||
[](https://crates.io/crates/fif)
|
||||
[](https://git.bune.city/lynnesbian/fif/src/branch/master/LICENSE)
|
||||
<div align="center">
|
||||
|
||||
A command-line tool for detecting and optionally correcting files with incorrect extensions.
|
||||
# fif
|
||||
|
||||
## Installation
|
||||

|
||||
|
||||
[
|
||||
](https://crates.io/crates/fif)
|
||||
[
|
||||
](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#version-policy)
|
||||
[
|
||||
](https://gitlab.com/Lynnesbian/fif/-/blob/master/LICENSE)
|
||||
[
|
||||
](https://gitlab.com/Lynnesbian/fif/-/pipelines/latest)
|
||||
[
|
||||
](https://github.com/rust-secure-code/safety-dance/)
|
||||
[
|
||||
](https://deps.rs/repo/gitlab/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>
|
||||
|
||||
fif recursively scans the given directory and outputs a shell script to fix the name of any files with incorrect
|
||||
extensions. By default, fif will scan all non-hidden files in the given directory, and will ignore symlinks.
|
||||
|
||||
As fif prints a shell script to stdout rather than acting on the files directly, you may wish to redirect its output to
|
||||
a file, e.g. `fif ~/Documents > output.sh`. You can also pipe the output directly into your shell, e.g.
|
||||
`fif ~/Documents | bash`, although this is not recommended - you should look over fif's output and verify for yourself
|
||||
that it won't do anything that will give you a headache before running it.
|
||||
|
||||
## Features
|
||||
- :white_check_mark: Cross platform
|
||||
- :white_check_mark: Multi-threaded
|
||||
- :white_check_mark: Configurable
|
||||
|
||||
## Building
|
||||
fif can be built, installed, and tested with [Cargo], as with most rust programs:
|
||||
```bash
|
||||
git clone https://gitlab.com/Lynnesbian/fif/
|
||||
cd fif
|
||||
# run tests (optional)
|
||||
cargo test --locked
|
||||
# build fif with its default feature set
|
||||
cargo build --locked --release
|
||||
```
|
||||
The `--locked` flag ensures that Cargo uses the dependency versions specified in [the lock
|
||||
file](https://gitlab.com/Lynnesbian/fif/-/blob/master/Cargo.lock), and the `--release` flag builds fif with release
|
||||
optimisations enabled -- this takes longer, but produces a much faster binary.
|
||||
|
||||
### Installing
|
||||
```bash
|
||||
# install the fif crate (to ~/.cargo/bin or %USERPROFILE%\.cargo\bin by default)
|
||||
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, 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:
|
||||
|
||||
```bash
|
||||
# xdg-mime
|
||||
cargo install fif --locked --features=xdg-mime-backend
|
||||
# infer
|
||||
cargo install fif --locked --features=infer-backend
|
||||
```
|
||||
|
||||
It is also possible to get a more minimal build by installing without default features:
|
||||
```bash
|
||||
cargo install fif --locked --no-default-features
|
||||
```
|
||||
This will disable some non-essential but nice to have features, like multi-threading support.
|
||||
|
||||
For more info on fif's compile-time features, see [the wiki](https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features).
|
||||
|
||||
## Usage
|
||||
See `fif --help` for more.
|
||||
|
||||
### The basics
|
||||
The simplest way to use fif looks like this:
|
||||
|
||||
```bash
|
||||
fif -E images ~/Pictures
|
||||
fif ~/Downloads
|
||||
```
|
||||
|
||||
This command will scan all of the files with extensions used by image files (.jpg, .png, etc) in your `~/Pictures`
|
||||
directory.
|
||||
This command will scan all non-hidden files in your `~/Downloads` directory.
|
||||
|
||||
You can also manually specify a set of extensions to use:
|
||||
The `-e` and `-E` flags can be used to specify individual extensions and sets of extensions to scan, respectively:
|
||||
|
||||
```bash
|
||||
# only scan files with the extensions .jpeg, .jpg, .zip, and .docx
|
||||
fif -e jpeg,jpg,zip,docx ~/Documents
|
||||
# only scan files with "image extensions" - .jpg, .png, .gif, .webp...
|
||||
fif -E images ~/Pictures
|
||||
# scan .zip files, videos, and audio
|
||||
fif -e zip -E videos,audio ~/Downloads
|
||||
```
|
||||
|
||||
By default, fif will output a bash script that can be used to fix all the files it found with incorrect file extensions.
|
||||
Both `-e` and `-E` have equivalent `-x` and `-X` flags that exclude the given extensions rather than including them:
|
||||
```bash
|
||||
# scan everything except filenames ending in .zip
|
||||
fif -x zip ~/Downloads
|
||||
# scan all files with image extensions, but not .jpg and .jpeg files
|
||||
fif -x jpg,jpeg -E images ~/Pictures
|
||||
# scan everything except text and system files
|
||||
fif -X text,system ~/.local/share
|
||||
```
|
||||
|
||||
### Output
|
||||
By default, fif will output a bash script (or PowerShell script on Windows) that can be used to fix all the files it
|
||||
found with incorrect file extensions.
|
||||
|
||||
You might find it useful to output this script to a file (rather than to stdout):
|
||||
|
||||
```bash
|
||||
fif -E images ~/Pictures > output.sh
|
||||
fif ~/Documents > output.sh
|
||||
```
|
||||
|
||||
You can also manually specify an output format to use:
|
||||
|
||||
```bash
|
||||
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:
|
||||
```bash
|
||||
# also log debug info
|
||||
fif -v ~/Downloads
|
||||
# ...and trace info
|
||||
fif -vv ~/Downloads
|
||||
```
|
||||
|
||||
You can also reduce the level of logging with the `-q` flag:
|
||||
```bash
|
||||
# don't show info
|
||||
fif -q ~/Downloads
|
||||
# ...or warnings
|
||||
fif -qq ~/Downloads
|
||||
# ...or even errors!
|
||||
fif -qqq ~/Downloads
|
||||
```
|
||||
|
||||
The verbosity of the logging can also be modified by setting the environment variable `FIF_LOG` or `RUST_LOG` to `off`,
|
||||
`trace`, `debug`, `info`, `warn`, or `error`. Values set by `FIF_LOG` override `RUST_LOG`, and both override the `-v`
|
||||
and `-q` flags.
|
||||
|
||||
For example:
|
||||
|
||||
```bash
|
||||
# show all levels except trace
|
||||
FIF_LOG=debug fif ~/Downloads
|
||||
# only show errors
|
||||
FIF_LOG=error fif ~/Downloads
|
||||
```
|
||||
|
||||
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 |
|
||||
| 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. |
|
||||
|
||||
For a more comprehensive explanation of all of fif's parameters and how to use them, run `fif --help` (or `fif -h` for
|
||||
a more concise overview).
|
||||
|
||||
<!-- links -->
|
||||
[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/
|
||||
|
||||
|
||||
## 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/>.
|
||||
|
|
31
build.rs
Normal file
31
build.rs
Normal file
|
@ -0,0 +1,31 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 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"))]
|
||||
// fail build if the user has set both the infer and xdg-mime backends
|
||||
return Err(String::from(
|
||||
"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(())
|
||||
}
|
61
clippy.sh
61
clippy.sh
|
@ -1,17 +1,56 @@
|
|||
#!/bin/bash
|
||||
fd -e rs -x touch {}
|
||||
cargo clippy -- \
|
||||
-W clippy::nursery \
|
||||
-W clippy::perf \
|
||||
-W clippy::pedantic \
|
||||
-W clippy::complexity \
|
||||
-W clippy::cargo \
|
||||
-A clippy::unused_io_amount \
|
||||
-A clippy::redundant_closure_for_method_calls \
|
||||
-A clippy::shadow_unrelated \
|
||||
|
||||
# SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
set -e
|
||||
source "$HOME"/.cargo/env || true
|
||||
|
||||
_extra=""
|
||||
_ver=""
|
||||
if [ "$1" == "ci" ]; then
|
||||
# deny on warnings when running in CI
|
||||
_extra="-Dwarnings"
|
||||
elif [ "$1" == "nightly" ]; then
|
||||
_ver="+nightly"
|
||||
fi
|
||||
|
||||
# allow find to fail
|
||||
find . -name '*.rs' -exec touch "{}" \; || true
|
||||
|
||||
_backends=( "xdg-mime-backend" "infer-backend" )
|
||||
|
||||
for backend in "${_backends[@]}"; do
|
||||
cargo $_ver clippy --tests --features="$backend" -- \
|
||||
-W clippy::nursery \
|
||||
-W clippy::perf \
|
||||
-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 \
|
||||
-W clippy::string_to_string \
|
||||
-A clippy::unused_io_amount \
|
||||
-A clippy::redundant_closure_for_method_calls \
|
||||
-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 \
|
||||
-A clippy::doc_markdown \
|
||||
"$_extra"
|
||||
done
|
||||
|
||||
# ALLOWS:
|
||||
# unused_io_amount: there are two places where i want to read up to X bytes and i'm fine with getting less than that
|
||||
# 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: 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
|
||||
# doc_markdown: way too many false positives
|
||||
|
|
3
clippy.toml
Normal file
3
clippy.toml
Normal file
|
@ -0,0 +1,3 @@
|
|||
# avoid-breaking-exported-api = false # only available on nightly for now
|
||||
cognitive-complexity-threshold = 15
|
||||
msrv = "1.64.0"
|
8
doc/README.md
Normal file
8
doc/README.md
Normal 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
|
3
doc/screenshot.png
Normal file
3
doc/screenshot.png
Normal file
|
@ -0,0 +1,3 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:60c185b6396c7383e5cce310b1ab7aab164e10a808ec1f728555a1a803b97a93
|
||||
size 62085
|
|
@ -1,4 +0,0 @@
|
|||
max_width = 120
|
||||
hard_tabs = true
|
||||
tab_spaces = 2
|
||||
newline_style = "Unix"
|
8
rustfmt.toml
Normal file
8
rustfmt.toml
Normal file
|
@ -0,0 +1,8 @@
|
|||
max_width = 120
|
||||
fn_single_line = true
|
||||
hard_tabs = true
|
||||
tab_spaces = 2
|
||||
newline_style = "Unix"
|
||||
group_imports = "StdExternalCrate"
|
||||
array_width = 100
|
||||
fn_call_width = 80
|
|
@ -1,28 +0,0 @@
|
|||
use clap::Clap;
|
||||
|
||||
#[derive(Clap, PartialEq, Debug)]
|
||||
pub enum ExtensionSet {
|
||||
Images,
|
||||
Audio,
|
||||
Videos,
|
||||
Media,
|
||||
Documents,
|
||||
Archives,
|
||||
}
|
||||
|
||||
impl ExtensionSet {
|
||||
pub fn extensions(&self) -> Vec<&str> {
|
||||
match self {
|
||||
Self::Images => mime_guess::get_mime_extensions_str("image/*"),
|
||||
Self::Videos => mime_guess::get_mime_extensions_str("video/*"),
|
||||
Self::Audio => mime_guess::get_mime_extensions_str("audio/*"),
|
||||
Self::Documents => Some(&[
|
||||
"doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "tsv", "pdf", "odt", "ods", "odp",
|
||||
][..]),
|
||||
// many compressed file types follow the name scheme "application/x.+compressed.*" - maybe this can be used
|
||||
// somehow to extract extensions for compressed files from mime_guess?
|
||||
Self::Archives => Some(&["zip", "tar", "gz", "zst", "xz", "rar", "7z", "bz", "bz2"][..]),
|
||||
_ => todo!(),
|
||||
}.unwrap().to_vec()
|
||||
}
|
||||
}
|
424
src/files.rs
Normal file
424
src/files.rs
Normal file
|
@ -0,0 +1,424 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 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
|
||||
}
|
|
@ -1,18 +1,100 @@
|
|||
use std::path::PathBuf;
|
||||
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use mime_guess::Mime;
|
||||
use smartstring::alias::String;
|
||||
//! 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 crate::inspectors::mime_extension_lookup;
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use mime::Mime;
|
||||
#[cfg(feature = "json")]
|
||||
use serde::{ser::SerializeStruct, Serializer};
|
||||
|
||||
use crate::files::mime_extension_lookup;
|
||||
use crate::String;
|
||||
|
||||
/// Information about a successfully scanned file.
|
||||
#[derive(Eq, PartialEq, Debug)]
|
||||
pub struct Findings {
|
||||
pub file: PathBuf, // TODO: replace with Path???? <'a> and all that
|
||||
/// The location of the scanned file.
|
||||
pub file: PathBuf,
|
||||
/// Whether or not the file's extension is valid for its MIME type.
|
||||
pub valid: bool,
|
||||
/// 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.clone()).map(|extensions| extensions[0].to_owned())
|
||||
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>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
// the second parameter is the number of fields in the struct -- in this case, 3
|
||||
let mut state = serializer.serialize_struct("Findings", 3)?;
|
||||
|
||||
state.serialize_field("file", &self.file)?;
|
||||
state.serialize_field("valid", &self.valid)?;
|
||||
state.serialize_field("mime", &self.mime.essence_str())?;
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 MIME type of the given file.
|
||||
Mime(&'a Path),
|
||||
}
|
||||
|
||||
impl<'a> Display for ScanError<'a> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Couldn't {} file: {}",
|
||||
match self {
|
||||
Self::File(_) => "read",
|
||||
Self::Mime(_) => "determine MIME type of",
|
||||
},
|
||||
match self {
|
||||
Self::File(f) | Self::Mime(f) => f.to_string_lossy(),
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
384
src/formats.rs
384
src/formats.rs
|
@ -1,55 +1,119 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 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};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::PathBuf;
|
||||
use std::path::Path;
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
use snailquote::escape;
|
||||
|
||||
use crate::scanerror::ScanError;
|
||||
use crate::findings::ScanError;
|
||||
use crate::utils::CLAP_LONG_VERSION;
|
||||
use crate::Findings;
|
||||
use crate::String;
|
||||
|
||||
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
|
||||
/// A macro for creating an array of [`Writable`]s without needing to pepper your code with `into()`s.
|
||||
/// # Usage
|
||||
/// ```
|
||||
/// use crate::fif::writables;
|
||||
/// use crate::fif::formats::{Writable, smart_write};
|
||||
/// let mut f = std::io::stdout();
|
||||
///
|
||||
/// // Instead of...
|
||||
/// smart_write(&mut f, &["hello".into(), Writable::Newline]);
|
||||
/// // ...just use:
|
||||
/// smart_write(&mut f, writables!["hello", Newline]);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! writables {
|
||||
[$($args:tt),+] => {
|
||||
&[$(writables!(@do $args),)*]
|
||||
};
|
||||
|
||||
type Entries = [Result<Findings, (ScanError, PathBuf)>];
|
||||
(@do Newline) => {
|
||||
$crate::formats::Writable::Newline
|
||||
};
|
||||
|
||||
enum Writable<'a> {
|
||||
(@do $arg:expr) => {
|
||||
$arg.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
/// Does the same thing as [`writables`], but adds a Newline to the end.
|
||||
macro_rules! writablesln {
|
||||
[$($args:tt),+] => {
|
||||
&[$(writables!(@do $args),)* writables!(@do Newline)]
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Writable<'a> {
|
||||
String(&'a str),
|
||||
Path(&'a PathBuf),
|
||||
Space,
|
||||
Path(&'a Path),
|
||||
Newline,
|
||||
}
|
||||
|
||||
// the lifetime of a lifetime
|
||||
impl<'a> From<&'a str> for Writable<'a> {
|
||||
fn from(s: &'a str) -> Writable<'a> {
|
||||
Writable::String(s)
|
||||
}
|
||||
fn from(s: &'a str) -> Self { Writable::String(s) }
|
||||
}
|
||||
|
||||
impl<'a> From<&'a PathBuf> for Writable<'a> {
|
||||
fn from(p: &'a PathBuf) -> Writable<'a> {
|
||||
Writable::Path(p)
|
||||
}
|
||||
impl<'a> From<&'a Path> for Writable<'a> {
|
||||
fn from(p: &'a Path) -> Self { Writable::Path(p) }
|
||||
}
|
||||
|
||||
fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
|
||||
impl<'a> From<&'a OsStr> for Writable<'a> {
|
||||
fn from(p: &'a OsStr) -> Self { Writable::Path(p.as_ref()) }
|
||||
}
|
||||
|
||||
fn generated_by() -> String { format!("Generated by fif {}", CLAP_LONG_VERSION.as_str()).into() }
|
||||
|
||||
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 => writeln!(f, )?,
|
||||
Writable::String(s) => write!(f, "{}", s)?,
|
||||
Writable::Newline => {
|
||||
cfg_if! {
|
||||
if #[cfg(windows)] {
|
||||
write!(f, "\r\n")?;
|
||||
} else {
|
||||
writeln!(f,)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Writable::String(s) => write!(f, "{s}")?,
|
||||
Writable::Path(path) => {
|
||||
if let Some(string) = path.to_str() {
|
||||
write!(f, "{}", escape(string))?
|
||||
if let Some(path_str) = path.to_str() {
|
||||
let escaped = escape(path_str);
|
||||
if escaped.as_ref() == path_str {
|
||||
// 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}'")?;
|
||||
} else {
|
||||
write!(f, "{escaped}")?;
|
||||
}
|
||||
} else {
|
||||
write!(f, "'''")?;
|
||||
#[cfg(unix)]
|
||||
f.write_all(&*path.as_os_str().as_bytes())?;
|
||||
#[cfg(windows)]
|
||||
write!(f, "{}", path.as_os_str().to_string_lossy())?; // TODO: implement bonked strings for windows
|
||||
// f.write_all(&*path.as_os_str().encode_wide().collect::<Vec<u16>>())?;
|
||||
write!(f, "'''")?
|
||||
write!(f, "'")?;
|
||||
cfg_if! {
|
||||
if #[cfg(windows)] {
|
||||
// TODO: implement bonked strings for windows
|
||||
// something like:
|
||||
// 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())?;
|
||||
}
|
||||
}
|
||||
write!(f, "'")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -57,96 +121,208 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub trait Format {
|
||||
fn new() -> Self;
|
||||
fn rename<W: Write>(&self, f: &mut W, from: &PathBuf, to: &PathBuf) -> io::Result<()>;
|
||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()>;
|
||||
fn unreadable<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()>;
|
||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()>;
|
||||
fn header<W: Write>(&self, entries: &Entries, f: &mut W) -> io::Result<()>;
|
||||
fn footer<W: Write>(&self, entries: &Entries, f: &mut W) -> io::Result<()>;
|
||||
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)?;
|
||||
|
||||
fn write_all<W: Write>(&self, entries: &Entries, f: &mut W) -> io::Result<()> {
|
||||
// TODO: clean this up - it's kinda messy
|
||||
self.header(entries, f)?;
|
||||
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Ok(finding) => {
|
||||
if let Some(ext) = finding.recommended_extension() {
|
||||
self.rename(f, &finding.file, &finding.file.with_extension(ext.as_str()))?
|
||||
} else {
|
||||
self.no_known_extension(f, &finding.file)?
|
||||
}
|
||||
}
|
||||
|
||||
Err(error) => {
|
||||
// something went wrong 0uo
|
||||
match error.0 {
|
||||
// failed to read the file
|
||||
ScanError::File => self.unreadable(f, &error.1)?,
|
||||
// file was read successfully, but we couldn't determine a mimetype
|
||||
ScanError::Mime => self.unknown_type(f, &error.1)?,
|
||||
}
|
||||
}
|
||||
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 MIME type
|
||||
ScanError::Mime(path) => self.unknown_type(f, path)?,
|
||||
}
|
||||
}
|
||||
|
||||
self.footer(entries, f)
|
||||
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(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)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: maybe make a batch script version for windows
|
||||
pub struct Script {}
|
||||
pub trait Format {
|
||||
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl Format for Script {
|
||||
fn new() -> Self {
|
||||
Self {}
|
||||
/// Bourne-Shell compatible script.
|
||||
pub struct Shell;
|
||||
|
||||
impl Format for Shell {
|
||||
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, "\t", to))
|
||||
}
|
||||
|
||||
fn rename<W: Write>(&self, f: &mut W, from: &PathBuf, to: &PathBuf) -> io::Result<()> {
|
||||
smart_write(f, &[
|
||||
"mv -v -i -- ".into(),
|
||||
from.into(),
|
||||
Writable::Space,
|
||||
to.into(),
|
||||
Writable::Newline
|
||||
])
|
||||
}
|
||||
|
||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()> {
|
||||
smart_write(f, &[
|
||||
"echo No known extension for ".into(),
|
||||
path.into(),
|
||||
Writable::Newline
|
||||
])
|
||||
}
|
||||
|
||||
fn unreadable<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()> {
|
||||
smart_write(f, &[
|
||||
"# Failed to read ".into(),
|
||||
path.into(),
|
||||
Writable::Newline
|
||||
])
|
||||
}
|
||||
|
||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &PathBuf) -> io::Result<()> {
|
||||
smart_write(f, &[
|
||||
"# Failed to detect mime type for ".into(),
|
||||
path.into(),
|
||||
Writable::Newline
|
||||
])
|
||||
}
|
||||
|
||||
fn header<W: Write>(&self, _: &Entries, f: &mut W) -> io::Result<()> {
|
||||
write!(
|
||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(
|
||||
f,
|
||||
"#!/usr/bin/env sh\n# Generated by fif {}.\n\nset -e\n\n",
|
||||
VERSION.unwrap_or("???")
|
||||
writablesln!["cat <<- '???'", Newline, "No known extension for ", path, Newline, "???"],
|
||||
)
|
||||
}
|
||||
|
||||
fn footer<W: Write>(&self, _: &Entries, f: &mut W) -> io::Result<()> {
|
||||
writeln!(f, "\necho 'Done.'")
|
||||
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["# Failed to read", path])
|
||||
}
|
||||
|
||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["# Failed to detect MIME type for ", path])
|
||||
}
|
||||
|
||||
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) -> 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;
|
||||
|
||||
impl Format for PowerShell {
|
||||
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())],
|
||||
)
|
||||
}
|
||||
|
||||
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, "'@"],
|
||||
)
|
||||
}
|
||||
|
||||
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(
|
||||
f,
|
||||
writablesln!["Write-Output @'", Newline, "Failed to read ", path, Newline, "'@"],
|
||||
)
|
||||
}
|
||||
|
||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["<# Failed to detect MIME type for ", path, " #>"])
|
||||
}
|
||||
|
||||
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||
smart_write(
|
||||
f,
|
||||
writablesln!["#!/usr/bin/env pwsh", 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, writables![Newline])
|
||||
}
|
||||
|
||||
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 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])
|
||||
}
|
||||
|
||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["No known extension for ", path])
|
||||
}
|
||||
|
||||
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["Encountered IO error while accessing ", path])
|
||||
}
|
||||
|
||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||
smart_write(f, writablesln!["Couldn't determine type for ", path])
|
||||
}
|
||||
|
||||
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) -> io::Result<()> {
|
||||
smart_write(
|
||||
f,
|
||||
// writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
|
||||
&[Writable::Newline],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "json")]
|
||||
pub struct Json;
|
||||
|
||||
#[cfg(feature = "json")]
|
||||
impl Format for Json {
|
||||
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
|
||||
#[derive(serde::Serialize)]
|
||||
struct SerdeEntries<'a> {
|
||||
errors: &'a [ScanError<'a>],
|
||||
findings: &'a [Findings],
|
||||
}
|
||||
|
||||
let result = serde_json::to_writer_pretty(f, &SerdeEntries { errors, findings });
|
||||
|
||||
if let Err(err) = result {
|
||||
log::error!("Error while serialising: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,109 +0,0 @@
|
|||
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 smartstring::alias::String;
|
||||
|
||||
use crate::mimedb::MimeDb;
|
||||
|
||||
// use log::{debug, warn};
|
||||
|
||||
// from looking at the files in https://github.com/bojand/infer/tree/master/src/matchers, the format with the largest
|
||||
// buffer size requirement for identification requires 262 bytes, and the next largest buffer necessary is only 131
|
||||
// bytes. as only two formats need more than 128 bytes, it would be fairly reasonable to only read 128 bytes.
|
||||
// unfortunately, the format that requires 262 bytes for identification is tar, an extremely popular format (in the *nix
|
||||
// world, at least). however, tar files almost always appear wrapped in other formats (.tar.gz, .tar.zst, etc) anyway,
|
||||
// so maybe it's fine...? maybe this should be configurable by the user? i don't know.
|
||||
// empirical testing (or rather, starting from 256 and incrementing until it worked) reveals that xdg-mime requires
|
||||
// at least 265 bytes to identify a tar file.
|
||||
|
||||
// additionally, since many formats can by identified with ≤64 bytes, it's worth reading 64 bytes, checking for the mime
|
||||
// type, and then reading the full 512 bytes if necessary. in most cases, this will end up being faster on the whole,
|
||||
// even though two reads are needed for certain formats, unless the directory being scanned is predominantly made up of
|
||||
// such formats.
|
||||
|
||||
const INITIAL_BUF_SIZE: usize = 64;
|
||||
const BUF_SIZE: usize = 512;
|
||||
|
||||
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)?;
|
||||
|
||||
// this lint can be ignored: it's okay if the file isn't long enough to fill the buffer, as we only care about the
|
||||
// first few bytes for the purpose of mime sniffing
|
||||
#[allow(clippy::unused_io_amount)]
|
||||
file.read(&mut buffer)?;
|
||||
|
||||
let r = db.get_type(&buffer);
|
||||
|
||||
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 64 bytes into a buffer, but i can't see an obvious way to reuse those 64 bytes that's
|
||||
// faster than simply moving the seek position back to the start of the file and re-reading the whole 512 bytes.
|
||||
// for example, starting with a buffer of 64 bytes, then creating a new 512 byte buffer from the contents of the first
|
||||
// buffer with (512 - 64) blank bytes, then finally reading the rest, is much slower than simply reading the file
|
||||
// twice. 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))
|
||||
}
|
||||
|
||||
// TODO: avoid cloning mime if possible, although i don't really see how it would be - maybe instead of passing the mime
|
||||
// object, pass a hash of it?
|
||||
cached! {
|
||||
MIMEXT;
|
||||
fn mime_extension_lookup(mime: Mime) -> Option<Vec<String>> = {
|
||||
|
||||
// match on the mime's `essence_str` 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.
|
||||
match mime_guess::get_mime_extensions_str(mime.essence_str()) {
|
||||
Some(exts) => {
|
||||
let possible_exts: Vec<String> = exts.iter().map(|e| String::from(*e)).collect();
|
||||
|
||||
Some(if mime == mime_guess::mime::IMAGE_JPEG {
|
||||
// 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 mime == mime_guess::mime::TEXT_XML {
|
||||
// a somewhat similar case arises with XML files - the first suggested extension is "addin", 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.
|
||||
[vec![String::from("xml"), String::from("svg")], possible_exts].concat()
|
||||
|
||||
} else if mime == Mime::from_str("application/zip").unwrap() {
|
||||
// until proper document support is added, treat all common document extensions as zips
|
||||
[vec![
|
||||
String::from("zip"),
|
||||
String::from("docx"),
|
||||
String::from("pptx"),
|
||||
String::from("xlsx"),
|
||||
String::from("odt"),
|
||||
String::from("ods"),
|
||||
String::from("odp"),
|
||||
String::from("pages"),
|
||||
String::from("key"),
|
||||
String::from("numbers")], possible_exts].concat()
|
||||
} else {
|
||||
possible_exts
|
||||
})
|
||||
},
|
||||
None => None
|
||||
}
|
||||
}
|
||||
}
|
56
src/lib.rs
Normal file
56
src/lib.rs
Normal file
|
@ -0,0 +1,56 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 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(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(mime_db::XdgDb::init);
|
||||
}
|
||||
}
|
437
src/main.rs
437
src/main.rs
|
@ -1,269 +1,238 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 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/>.
|
||||
|
||||
use std::io::{stdout, BufWriter};
|
||||
use std::path::{Path, PathBuf};
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(
|
||||
trivial_casts,
|
||||
unused_lifetimes,
|
||||
unused_qualifications,
|
||||
missing_copy_implementations,
|
||||
unused_allocation
|
||||
)]
|
||||
|
||||
use clap::Clap;
|
||||
use log::{debug, error, info, trace, warn};
|
||||
use once_cell::sync::OnceCell;
|
||||
#[cfg(feature = "multi-threaded")]
|
||||
use rayon::prelude::*;
|
||||
use smartstring::alias::String;
|
||||
use walkdir::{DirEntry, WalkDir};
|
||||
|
||||
use crate::findings::Findings;
|
||||
use crate::formats::{Format, Script};
|
||||
use crate::mimedb::MimeDb;
|
||||
use crate::parameters::OutputFormat;
|
||||
use crate::scanerror::ScanError;
|
||||
use std::io::{stdin, stdout, BufWriter, Write};
|
||||
use std::process::exit;
|
||||
|
||||
mod extensionset;
|
||||
mod findings;
|
||||
mod formats;
|
||||
mod inspectors;
|
||||
mod mimedb;
|
||||
mod parameters;
|
||||
mod scanerror;
|
||||
use cfg_if::cfg_if;
|
||||
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};
|
||||
|
||||
#[cfg(feature = "infer-backend")]
|
||||
static MIMEDB: OnceCell<mimedb::InferDb> = OnceCell::new();
|
||||
|
||||
#[cfg(feature = "xdg-mime-backend")]
|
||||
static MIMEDB: OnceCell<mimedb::XdgDb> = OnceCell::new();
|
||||
|
||||
// TODO: test if this actually works on a windows machine
|
||||
#[cfg(windows)]
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_hidden(entry: &DirEntry) -> bool {
|
||||
entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.map_or(false, |f| f.starts_with('.') && f != ".")
|
||||
}
|
||||
|
||||
fn wanted_file(args: ¶meters::Parameters, exts: &[&str], entry: &DirEntry) -> bool {
|
||||
if !args.scan_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;
|
||||
}
|
||||
|
||||
let ext = extension_from_path(entry.path());
|
||||
|
||||
if ext.is_none() {
|
||||
return false;
|
||||
} // don't scan files without extensions. TODO - this should be configurable
|
||||
|
||||
exts.contains(&ext.unwrap().to_lowercase().as_str())
|
||||
}
|
||||
|
||||
fn extension_from_path(path: &Path) -> Option<String> {
|
||||
path.extension(). // Get the path's extension
|
||||
map(|e| String::from(e.to_string_lossy())) // Convert from OsStr to String
|
||||
}
|
||||
|
||||
fn scan_file(entry: &DirEntry) -> Result<Findings, (ScanError, PathBuf)> {
|
||||
// try to determine mimetype for this entry
|
||||
let result = inspectors::mime_type(MIMEDB.get().unwrap(), entry.path());
|
||||
|
||||
if result.is_err() {
|
||||
// an error occurred while trying to read the file
|
||||
// error!("{}: {}", entry.path().to_string_lossy(), error);
|
||||
return Err((ScanError::File, entry.path().to_path_buf()));
|
||||
}
|
||||
|
||||
let result = result.unwrap();
|
||||
if result.is_none() {
|
||||
// the file was read successfully, but we were unable to determine its mimetype
|
||||
// warn!("Couldn't determine mimetype for {}", entry.path().to_string_lossy());
|
||||
return Err((ScanError::Mime, entry.path().to_path_buf()));
|
||||
}
|
||||
|
||||
let result = result.unwrap();
|
||||
|
||||
// set of known extensions for the given mimetype
|
||||
let known_exts = inspectors::mime_extension_lookup(result.clone());
|
||||
// file extension for this particular file
|
||||
let entry_ext = extension_from_path(entry.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_lowercase().into()),
|
||||
// either this file has no extension, or there is no known set of extensions for this mimetype :(
|
||||
Some(_) | None => false,
|
||||
};
|
||||
|
||||
Ok(Findings {
|
||||
file: entry.path().to_path_buf(),
|
||||
valid,
|
||||
mime: result,
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_from_walkdir(entries: &[DirEntry]) -> Vec<Result<Findings, (ScanError, PathBuf)>> {
|
||||
#[cfg(feature = "multi-threaded")]
|
||||
{
|
||||
// rather than using a standard par_iter, split the entries into chunks of 32 first.
|
||||
// this allows each spawned thread to handle 32 files before before closing, rather than creating a new thread for
|
||||
// each file. this leads to a pretty substantial speedup that i'm pretty substantially happy about 0u0
|
||||
entries
|
||||
.par_chunks(32) // split into chunks of 32
|
||||
.flat_map(|chunk| {
|
||||
chunk // return Vec<...> instead of Chunk<Vec<...>>
|
||||
.iter() // iter over the chunk, which is a slice of DirEntry structs
|
||||
.map(|entry| scan_file(entry))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "multi-threaded"))]
|
||||
{
|
||||
entries.iter().map(|entry: &DirEntry| scan_file(entry)).collect()
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
|
||||
fn main() {
|
||||
let args = parameters::Parameters::parse();
|
||||
let args: parameters::Parameters = parameters::Parameters::parse();
|
||||
|
||||
let mut builder = env_logger::Builder::from_default_env();
|
||||
let mut builder = env_logger::Builder::new();
|
||||
builder
|
||||
// .format(|buf, r| writeln!(buf, "{} - {}", r.level(), r.args()))
|
||||
.format_module_path(false) // don't include module in logs, as it's not necessary
|
||||
.format_timestamp(None) // don't include timestamps (unnecessary, and the feature flag is disabled anyway)
|
||||
// .target(env_logger::Target::Stdout) // log to stdout rather than stderr
|
||||
.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| {
|
||||
let mut style = buf.default_level_style(r.level());
|
||||
// use bold for warnings and errors
|
||||
style.set_bold(r.level() <= Level::Warn);
|
||||
// only use the first character of the log level name
|
||||
let abbreviation = style.value(r.level().to_string().chars().next().unwrap());
|
||||
// e.g. [D] Debug message
|
||||
writeln!(buf, "[{}] {}", abbreviation, r.args())
|
||||
})
|
||||
.init();
|
||||
|
||||
#[cfg(feature = "infer-backend")]
|
||||
MIMEDB
|
||||
.set(mimedb::InferDb::init())
|
||||
.or(Err("Failed to initialise Infer backend!"))
|
||||
.unwrap();
|
||||
trace!(
|
||||
"fif {}, running on {} {}",
|
||||
CLAP_LONG_VERSION.as_str(),
|
||||
std::env::consts::ARCH,
|
||||
os_name()
|
||||
);
|
||||
|
||||
#[cfg(feature = "xdg-mime-backend")]
|
||||
MIMEDB
|
||||
.set(mimedb::XdgDb::init())
|
||||
.or(Err("Failed to initialise XDG Mime backend!"))
|
||||
.unwrap();
|
||||
debug!("Iterating directory: {:?}", args.dir);
|
||||
|
||||
debug!("Iterating directory: {:?}", args.dirs);
|
||||
let extensions = args.extensions();
|
||||
let excludes = args.excluded_extensions();
|
||||
|
||||
let extensions: Vec<&str> = if let Some(exts) = &args.exts {
|
||||
exts.iter().map(|s| s.as_str()).collect()
|
||||
} else if let Some(exts) = &args.ext_set {
|
||||
exts.extensions().to_vec()
|
||||
if let Some(extensions) = &extensions {
|
||||
debug!("Checking files with extensions: {:?}", extensions);
|
||||
} else if let Some(excludes) = &excludes {
|
||||
debug!("Skipping files with extensions: {:?}", excludes);
|
||||
} else {
|
||||
unreachable!()
|
||||
debug!("Checking files regardless of extensions");
|
||||
}
|
||||
|
||||
let entries = match scan_directory(&args.dir, extensions.as_ref(), excludes.as_ref(), &args.get_scan_opts()) {
|
||||
// no need to log anything for fatal errors - fif will already have printed something obvious like
|
||||
// "[ERROR] /fake/path: No such file or directory (os error 2)". we can assume that if this has happened, the dir
|
||||
// given as input doesn't exist or is otherwise unreadable.
|
||||
None => exit(exitcode::NOINPUT),
|
||||
Some(e) => e,
|
||||
};
|
||||
|
||||
debug!("Checking files with extensions: {:?}", extensions);
|
||||
|
||||
let stepper = WalkDir::new(&args.dirs).into_iter();
|
||||
let mut probably_fatal_error = false;
|
||||
let entries: Vec<DirEntry> = stepper
|
||||
.filter_entry(|e| wanted_file(&args, &extensions, e)) // 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()
|
||||
})
|
||||
.filter(|e| !e.file_type().is_dir()) // remove directories from the final list
|
||||
.collect();
|
||||
|
||||
if entries.is_empty() {
|
||||
if probably_fatal_error {
|
||||
// no need to log anything for fatal errors - fif will already have printed something obvious like
|
||||
// "[ERROR] /fake/path: No such file or directory (os error 2)". we can assume that if this has happened, the dir
|
||||
// given as input doesn't exist or is otherwise unreadable.
|
||||
exit(exitcode::NOINPUT);
|
||||
}
|
||||
|
||||
warn!("No files matching requested options found.");
|
||||
exit(exitcode::DATAERR);
|
||||
exit(exitcode::OK);
|
||||
}
|
||||
|
||||
trace!("Found {} items to check", entries.len());
|
||||
|
||||
let results: Vec<_> = scan_from_walkdir(&entries)
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "multi-threaded")] {
|
||||
let use_threads = args.jobs != 1;
|
||||
|
||||
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 };
|
||||
|
||||
// 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");
|
||||
}
|
||||
|
||||
} else { // `multi-threading` feature disabled
|
||||
let use_threads = false;
|
||||
trace!("Multithreading disabled at compile time");
|
||||
}
|
||||
}
|
||||
|
||||
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(exitcode::OK);
|
||||
}
|
||||
|
||||
// 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(
|
||||
|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!("{:?} is fine", result.as_ref().unwrap().file); false } else { true }
|
||||
)
|
||||
.collect();
|
||||
.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();
|
||||
|
||||
for result in &results {
|
||||
match result {
|
||||
Ok(r) => {
|
||||
info!(
|
||||
"{:?} should have file extension {}",
|
||||
r.file,
|
||||
r.recommended_extension().unwrap_or_else(|| "???".into())
|
||||
)
|
||||
if args.fix {
|
||||
fn ask(message: &str) -> bool {
|
||||
let mut buf = String::with_capacity(1);
|
||||
print!("{message} [y/N] ");
|
||||
|
||||
// flush stdout to ensure message is displayed
|
||||
stdout().flush().expect("Failed to flush stdout");
|
||||
|
||||
if let Err(e) = stdin().read_line(&mut buf) {
|
||||
// something went wrong while reading input - just exit
|
||||
error!("{}", e);
|
||||
exit(exitcode::IOERR)
|
||||
}
|
||||
Err(f) => warn!("{:#?}: Error 0uo - {}", f.1, f.0),
|
||||
buf.starts_with('y') || buf.starts_with('Y')
|
||||
}
|
||||
}
|
||||
|
||||
if results.is_empty() {
|
||||
info!("All files have valid extensions!")
|
||||
}
|
||||
let prompt = args.prompt.unwrap_or(Prompt::Error);
|
||||
|
||||
match args.output_format {
|
||||
OutputFormat::Script => {
|
||||
let s = Script::new();
|
||||
if s.write_all(&results, &mut BufWriter::new(stdout().lock())).is_err() {
|
||||
exit(exitcode::IOERR);
|
||||
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;
|
||||
}
|
||||
}
|
||||
OutputFormat::Text => todo!(),
|
||||
|
||||
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");
|
||||
|
|
148
src/mime_db.rs
Normal file
148
src/mime_db.rs
Normal file
|
@ -0,0 +1,148 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Backend-neutral Mime database abstraction.
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
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>;
|
||||
}
|
||||
|
||||
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 = mime.as_bytes();
|
||||
|
||||
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
|
||||
}
|
||||
|
||||
impl MimeDb for InferDb {
|
||||
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 which i mean, starts with the pattern "\s*<".
|
||||
|
||||
// so, here comes our fancy pants """""SGML-ish validator"""""
|
||||
for c in buf {
|
||||
match c {
|
||||
// whitespace (according to https://www.w3.org/TR/xml/#NT-S)
|
||||
b'\t' | b'\r' | b'\n' | b'\x20' => continue,
|
||||
b'<' => break,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
|
||||
// finally, to check whether or not the file is an SVG:
|
||||
// - 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
|
||||
// - 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 :(
|
||||
buf
|
||||
.split(|c| *c == b'<')
|
||||
.any(|buf| identifiers.iter().any(|id| buf.starts_with(id)))
|
||||
});
|
||||
|
||||
Self { db: info }
|
||||
}
|
||||
|
||||
fn get_type(&self, data: &[u8]) -> Option<Mime> {
|
||||
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,
|
||||
}
|
||||
|
||||
impl MimeDb for XdgDb {
|
||||
fn init() -> Self {
|
||||
Self { db: xdg_mime::SharedMimeInfo::new() }
|
||||
}
|
||||
|
||||
fn get_type(&self, data: &[u8]) -> Option<Mime> {
|
||||
self.db.get_mime_type_for_data(data).map(|m| m.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,82 +0,0 @@
|
|||
#[cfg(feature = "infer-backend")]
|
||||
use std::str::FromStr;
|
||||
|
||||
use mime_guess::Mime;
|
||||
|
||||
pub trait MimeDb {
|
||||
fn init() -> Self;
|
||||
fn get_type(&self, data: &[u8]) -> Option<Mime>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "infer-backend")]
|
||||
pub struct InferDb {
|
||||
db: infer::Infer,
|
||||
}
|
||||
|
||||
#[cfg(feature = "infer-backend")]
|
||||
impl MimeDb for InferDb {
|
||||
fn init() -> Self {
|
||||
let mut info = infer::Infer::new();
|
||||
|
||||
// jpeg2000 support because why the stinch not
|
||||
info.add("image/jpeg2000", ".jp2", |buf| {
|
||||
buf.len() > 23 && buf[..23] == b"\x00\x00\x00\x0C\x6A\x50\x20\x20\x0D\x0A\x87\x0A\x6A\x70\x32\x20"[..]
|
||||
});
|
||||
|
||||
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
|
||||
|
||||
// so, here comes our fancy pants """""SGML-ish validator"""""
|
||||
for c in buf {
|
||||
match c {
|
||||
// whitespace (according to https://www.w3.org/TR/xml/#NT-S)
|
||||
b'\t' | b'\r' | b'\n' | b'\x20' => continue,
|
||||
b'<' => break,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
|
||||
// finally, to check whether or not the file is an SVG:
|
||||
// - 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
|
||||
// - 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 :(
|
||||
buf
|
||||
.split(|c| *c == b'<')
|
||||
.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())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "xdg-mime-backend")]
|
||||
pub struct XdgDb {
|
||||
db: xdg_mime::SharedMimeInfo,
|
||||
}
|
||||
|
||||
#[cfg(feature = "xdg-mime-backend")]
|
||||
impl MimeDb for XdgDb {
|
||||
fn init() -> Self {
|
||||
Self {
|
||||
db: xdg_mime::SharedMimeInfo::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_type(&self, data: &[u8]) -> Option<Mime> {
|
||||
self.db.get_mime_type_for_data(&data).map(|m| m.0)
|
||||
}
|
||||
}
|
|
@ -1,41 +1,351 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Command line argument parsing logic and associated functions.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::extensionset::ExtensionSet;
|
||||
use clap::Clap;
|
||||
use smartstring::{LazyCompact, SmartString};
|
||||
use cfg_if::cfg_if;
|
||||
use clap::{ArgAction, Parser, ValueEnum};
|
||||
|
||||
#[derive(Clap, PartialEq, Debug)]
|
||||
pub enum OutputFormat {
|
||||
Script,
|
||||
Text,
|
||||
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, 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")]
|
||||
Sh,
|
||||
/// A PowerShell script.
|
||||
#[clap(alias = "powershell")]
|
||||
PowerShell,
|
||||
/// Plain text.
|
||||
Text,
|
||||
/// JSON.
|
||||
#[cfg(feature = "json")]
|
||||
Json,
|
||||
}
|
||||
|
||||
#[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(Parser, Debug)]
|
||||
#[allow(clippy::struct_excessive_bools)]
|
||||
#[clap(
|
||||
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-2024 Lynnesbian under the GPL3 (or later) License.",
|
||||
after_long_help = "Copyright © 2021-2024 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.",
|
||||
max_term_width = 120
|
||||
)]
|
||||
/// [`Clap`]-derived struct used to parse command line arguments.
|
||||
pub struct Parameters {
|
||||
/// Only examine files with these extensions (Comma-separated list)
|
||||
/// 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_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).
|
||||
/// `media` includes all extensions from the `audio`, `video`, and `images` sets, making `-E media` equivalent to
|
||||
/// `-E audio,video,images`.
|
||||
#[clap(
|
||||
short,
|
||||
short = 'E',
|
||||
long,
|
||||
use_delimiter = true,
|
||||
require_delimiter = true,
|
||||
required_unless_present = "ext-set"
|
||||
value_enum,
|
||||
use_value_delimiter = true,
|
||||
value_delimiter = ',',
|
||||
value_name = "set",
|
||||
help_heading = "FILTERING"
|
||||
)]
|
||||
pub exts: Option<Vec<SmartString<LazyCompact>>>,
|
||||
pub ext_set: Vec<ExtensionSet>,
|
||||
|
||||
/// write good docs 0uo
|
||||
#[clap(short = 'E', long, arg_enum, required_unless_present = "exts")]
|
||||
pub ext_set: Option<ExtensionSet>,
|
||||
/// Don't scan files with these extensions.
|
||||
/// This option takes precedence over extensions specified with `-e` or `-E`.
|
||||
#[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>>,
|
||||
|
||||
/// Don't skip hidden files and directories
|
||||
#[clap(short, long)]
|
||||
/// Exclude files using a preset list of extensions.
|
||||
/// This option takes precedence over extensions specified with `-e` or `-E`.
|
||||
#[clap(
|
||||
short = 'X',
|
||||
long,
|
||||
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, help_heading = "FILTERING")]
|
||||
pub scan_hidden: bool,
|
||||
|
||||
/// Output format to use. See "--help formats" for more information.
|
||||
#[clap(short, long, default_value = "script", arg_enum)]
|
||||
/// 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, 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, value_enum, value_name = "format", help_heading = "OUTPUT")]
|
||||
pub output_format: OutputFormat,
|
||||
|
||||
/// Directory to process
|
||||
// TODO: right now this can only take a single directory - should this be improved?
|
||||
#[clap(name = "DIR", default_value = ".", parse(from_os_str))]
|
||||
pub dirs: PathBuf,
|
||||
/// Output verbosity. Each additional `-v` increases verbosity.
|
||||
/// Can be overridden by `FIF_LOG` or `RUST_LOG`.
|
||||
#[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, 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, help_heading = "OUTPUT")]
|
||||
pub canonical_paths: bool,
|
||||
|
||||
/// The directory to process.
|
||||
#[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,
|
||||
}
|
||||
|
||||
/// 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(exts.into())
|
||||
}
|
||||
|
||||
/// Further options relating to scanning.
|
||||
#[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,
|
||||
/// Whether files without extensions should be scanned.
|
||||
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 {
|
||||
/// Returns an optional vec of the extensions to be scanned - i.e., extensions specified via the `-e` or `-E` flag,
|
||||
/// minus the extensions excluded with the `-x` flag; i.e., the difference between the included and excluded sets.
|
||||
pub fn extensions(&self) -> Option<BTreeSet<&str>> {
|
||||
if let Some(included) = self.included_extensions() {
|
||||
if let Some(excluded) = self.excluded_extensions() {
|
||||
// return included extensions without excluded extensions
|
||||
// ...maybe i should have called them "suffixes" instead of extensions...
|
||||
Some(included.into_iter().filter(|ext| !excluded.contains(ext)).collect())
|
||||
} else {
|
||||
// no extensions excluded - just return all included
|
||||
Some(included)
|
||||
}
|
||||
} else {
|
||||
// no extensions included - return none
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an optional vec of extensions that were specified by `-e` or `-E`. Note that this doesn't account for
|
||||
/// extensions excluded by the exclusion flags.
|
||||
pub fn included_extensions(&self) -> Option<BTreeSet<&str>> {
|
||||
let mut included = BTreeSet::new();
|
||||
if let Some(exts) = self.exts.as_ref() {
|
||||
// -e
|
||||
included.extend(exts.iter().map(|ext| ext.as_str()));
|
||||
}
|
||||
|
||||
if !&self.ext_set.is_empty() {
|
||||
// -E
|
||||
included.extend(self.ext_set.iter().flat_map(|set| set.extensions()));
|
||||
}
|
||||
|
||||
match included {
|
||||
x if x.is_empty() => None,
|
||||
x => Some(x),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an optional vec of extensions that were specified by `-x` or `-X`.
|
||||
pub fn excluded_extensions(&self) -> Option<BTreeSet<&str>> {
|
||||
let mut excluded = BTreeSet::new();
|
||||
if let Some(exclude) = self.exclude.as_ref() {
|
||||
// -x
|
||||
excluded.extend(exclude.iter().map(|ext| ext.as_str()));
|
||||
}
|
||||
|
||||
if !&self.exclude_set.is_empty() {
|
||||
// -X
|
||||
excluded.extend(self.exclude_set.iter().flat_map(|set| set.extensions()));
|
||||
}
|
||||
|
||||
// excluded doesn't sound like a word anymore
|
||||
// tongue twister: enter X-options' excellent extension exclusion
|
||||
match excluded {
|
||||
x if x.is_empty() => None,
|
||||
x => Some(x),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
0 => {
|
||||
match self.verbose {
|
||||
0 => LevelFilter::Info, // no verbosity flags specified
|
||||
1 => LevelFilter::Debug, // -v
|
||||
_ => LevelFilter::Trace, // -vv...
|
||||
}
|
||||
}
|
||||
1 => LevelFilter::Warn, // -q
|
||||
2 => LevelFilter::Error, // -qq
|
||||
_ => LevelFilter::Off, // -qqq...
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets of extensions for use with [Parameter](crate::parameters::Parameters)'s `-E` flag.
|
||||
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
|
||||
pub enum ExtensionSet {
|
||||
/// Extensions used for image file formats, such as `png`, `jpeg`, `webp`, etc.
|
||||
Images,
|
||||
/// Extensions used for audio file formats, such as `mp3`, `ogg`, `flac`, etc.
|
||||
Audio,
|
||||
/// Extensions used for video file formats, such as `mkv`, `mp4`, `mov`, etc.
|
||||
#[clap(alias = "videos")]
|
||||
Video,
|
||||
/// Extensions used for media file formats. This acts as a combination of the [Images](ExtensionSet::Images),
|
||||
/// [Audio](ExtensionSet::Audio) and [Video](ExtensionSet::Video) variants.
|
||||
Media,
|
||||
/// Extensions used for document file formats, such as `pdf`, `odt`, `docx`, etc.
|
||||
Documents,
|
||||
/// Extensions used for text file formats, such as `txt`, `toml`, `html`, etc.
|
||||
Text,
|
||||
/// Extensions used for archive file formats, such as `zip`, `zst`, `gz`, etc.
|
||||
Archives,
|
||||
/// Extensions used for system file formats, such as `mbr`, `crash`, `dll`, etc.
|
||||
System,
|
||||
}
|
||||
|
||||
impl ExtensionSet {
|
||||
/// The list of known extensions for this `ExtensionSet`.
|
||||
pub fn extensions(&self) -> Vec<&str> {
|
||||
match self {
|
||||
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::Documents => vec![
|
||||
"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "tsv", "odt", "ods", "odp", "oda", "rtf", "ps",
|
||||
"pages", "key", "numbers",
|
||||
],
|
||||
Self::Text => [
|
||||
mime_guess::get_mime_extensions_str("text/*").unwrap(),
|
||||
&["js", "pl", "csh", "sh", "bash", "zsh", "fish", "bat", "php"],
|
||||
]
|
||||
.concat(),
|
||||
// many compressed file types follow the name scheme "application/x.+compressed.*" - maybe this can be used
|
||||
// somehow to extract extensions for compressed files from mime_guess?
|
||||
Self::Archives => vec![
|
||||
"zip", "tar", "gz", "zst", "xz", "rar", "7z", "bz", "bz2", "tgz", "rpa", "txz", "tz2", "sea", "sitx", "z",
|
||||
"cpio",
|
||||
],
|
||||
Self::System => vec![
|
||||
"com", "dll", "exe", "sys", "reg", "nt", "cpl", "msi", "efi", "bio", "rcv", "mbr", "sbf", "grub", "ko",
|
||||
"dylib", "pdb", "hdmp", "crash", "cab",
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +0,0 @@
|
|||
use std::fmt::{Display, Formatter, Result};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ScanError {
|
||||
File,
|
||||
Mime,
|
||||
}
|
||||
|
||||
impl Display for ScanError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match self {
|
||||
Self::File => "Couldn't read file",
|
||||
Self::Mime => "Couldn't determine mime type",
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
562
src/tests/mod.rs
Normal file
562
src/tests/mod.rs
Normal file
|
@ -0,0 +1,562 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
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";
|
||||
|
||||
#[test]
|
||||
/// Ensure that `extension_from_path` successfully returns the extension from a set of paths.
|
||||
fn get_ext() {
|
||||
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!(path.extension(), ext);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure that the MIME types for JPEG, PNG, PDF, and ZIP are detected from their magic numbers.
|
||||
fn detect_type() {
|
||||
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() {
|
||||
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.
|
||||
fn simple_directory() {
|
||||
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 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)).unwrap_or_else(|_| panic!("Failed to create file: {name}"));
|
||||
|
||||
file
|
||||
.write_all(bytes)
|
||||
.unwrap_or_else(|_| panic!("Failed to write to file: {name}"));
|
||||
drop(file);
|
||||
}
|
||||
|
||||
let scan_opts = ScanOpts {
|
||||
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.");
|
||||
|
||||
// there should be one file missing: "ignore.fake_ext"
|
||||
assert_eq!(entries.len(), files.len() - 1);
|
||||
|
||||
let use_threads = cfg!(feature = "multi-threaded");
|
||||
|
||||
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.
|
||||
|
||||
// paths should be canonical
|
||||
assert_eq!(canonicalize(&result.file).unwrap(), canonical_result.file);
|
||||
|
||||
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!(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 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()));
|
||||
|
||||
// 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 = result.file.as_path().extension().unwrap();
|
||||
assert_eq!(
|
||||
result.mime,
|
||||
match ext.to_string_lossy().borrow() {
|
||||
"jpg" | "jpeg" => IMAGE_JPEG,
|
||||
"png" => IMAGE_PNG,
|
||||
"pdf" => APPLICATION_PDF,
|
||||
"zip" => APPLICATION_ZIP.clone(),
|
||||
_ => APPLICATION_OCTET_STREAM, // general "fallback" type
|
||||
},
|
||||
"Incorrect MIME type detected - got {:?} for a {:?} file",
|
||||
result.mime,
|
||||
ext
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure that command line argument parsing works correctly - flags are interpreted, booleans are set, and so on.
|
||||
fn argument_parsing() {
|
||||
use crate::parameters::ScanOpts;
|
||||
|
||||
// pass `-f`, which enables following symlinks, and `-E images`, which scans files with image extensions
|
||||
let args: Parameters = Parameters::parse_from(vec!["fif", "-f", "-E", "images"]);
|
||||
|
||||
// check if "jpg" is in the list of extensions to be scanned
|
||||
assert!(
|
||||
args
|
||||
.extensions()
|
||||
.expect("args.extensions() should be Some(_)!")
|
||||
.contains(&"jpg"),
|
||||
"args.extensions() should contain the `images` set!"
|
||||
);
|
||||
|
||||
// make sure "scan_hidden" is false
|
||||
assert!(!args.scan_hidden);
|
||||
|
||||
// exts should be none
|
||||
assert!(args.exts.is_none());
|
||||
|
||||
// there shouldn't be any excluded extensions
|
||||
assert!(args.excluded_extensions().is_none());
|
||||
|
||||
// get the ScanOpts, and make sure they match expectations
|
||||
assert_eq!(
|
||||
args.get_scan_opts(),
|
||||
ScanOpts {
|
||||
hidden: false,
|
||||
extensionless: false,
|
||||
follow_symlinks: true,
|
||||
ignore_unknown_exts: false,
|
||||
},
|
||||
"ScanOpts are incorrect"
|
||||
);
|
||||
}
|
||||
|
||||
#[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"] {
|
||||
assert_eq!(
|
||||
Parameters::parse_from(vec!["fif", flag, "images", "directory"]).dir,
|
||||
PathBuf::from("directory")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure the `exclude` flag (`-x`) overrides `-e` and `-E`.
|
||||
fn exclude_overrides() {
|
||||
// pass `-E images`, which includes many image extensions, and `-x jpg,png`, which should remove "jpg" and "png" from
|
||||
// the extensions list
|
||||
let args: Parameters = Parameters::parse_from(vec!["fif", "-x", "jpg,png", "-E", "images"]);
|
||||
let extensions = args.extensions();
|
||||
assert!(extensions.is_some(), "Extensions should contain the `images` set!");
|
||||
let extensions = extensions.unwrap();
|
||||
|
||||
assert!(!extensions.contains(&"jpg"), "\"jpg\" should be excluded!");
|
||||
assert!(!extensions.contains(&"png"), "\"png\" should be excluded!");
|
||||
assert!(extensions.contains(&"jpeg"), "\"jpeg\" should be included!");
|
||||
|
||||
// pass `-e abc,def,ghi,jkl` and `-x abc,def` -- extensions() should only contain "ghi" and "jkl"
|
||||
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!");
|
||||
assert_eq!(extensions, Some(btreeset!["ghi", "jkl"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure the `exclude_set` flag (`-X`) overrides `-e`.
|
||||
fn exclude_set_overrides_includes() {
|
||||
// pass `-e jpg,flac` and `-X images` -- which should produce the equivalent of `-e flag`
|
||||
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!");
|
||||
assert_eq!(extensions, Some(btreeset!["flac"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure the `exclude_set` flag (`-X`) overrides `-E`.
|
||||
fn exclude_set_overrides_include_set() {
|
||||
// pass `-E media` and `-X images` -- which should produce the equivalent of `-E audio,video`
|
||||
let args: Parameters = Parameters::parse_from(vec!["fif", "-E", "media", "-X", "images"]);
|
||||
let extensions = args.extensions();
|
||||
assert!(extensions.is_some(), "Extensions should be set!");
|
||||
let extensions = extensions.unwrap();
|
||||
|
||||
// ensure all of audio and video's extensions are here
|
||||
for &ext in ExtensionSet::Audio
|
||||
.extensions()
|
||||
.iter()
|
||||
.chain(ExtensionSet::Video.extensions().iter())
|
||||
{
|
||||
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}!");
|
||||
}
|
||||
}
|
||||
|
||||
#[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"],
|
||||
// `-E` without specifying a set:
|
||||
vec!["fif", "-E"],
|
||||
// `-E` with an invalid set:
|
||||
vec!["fif", "-E", "pebis"],
|
||||
// `-X` with an invalid set:
|
||||
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 {
|
||||
// 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 mut rng = rand::thread_rng();
|
||||
let mut bytes: [u8; BUF_SIZE * 2] = [0; BUF_SIZE * 2];
|
||||
let mut results: BTreeMap<Mime, i32> = BTreeMap::new();
|
||||
|
||||
for _ in 1..1000 {
|
||||
rng.fill_bytes(&mut bytes);
|
||||
if let Some(detected_type) = MIMEDB.get_type(&bytes) {
|
||||
*results.entry(detected_type).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (mime, count) in &results {
|
||||
println!("{mime}:\t{count} counts");
|
||||
}
|
||||
println!("No type found:\t{} counts", 1000 - results.values().sum::<i32>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure that, for a given file "wrong.bad", which should have extension "good", the shell output contains something
|
||||
/// like "mv wrong.bad wrong.good".
|
||||
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 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.write_all(&mut cursor, &findings, &[]),
|
||||
"PowerShell" => PowerShell.write_all(&mut cursor, &findings, &[]),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
.expect("Failed to write to cursor");
|
||||
|
||||
cursor.set_position(0);
|
||||
cursor
|
||||
.read_to_string(&mut contents)
|
||||
.expect("Failed to read from cursor to string");
|
||||
|
||||
// the output should contain a command like "mv -i misnamed_file.png misnamed_file.jpg"
|
||||
assert!(
|
||||
contents.contains("misnamed_file.jpg") && contents.contains("misnamed_file.png"),
|
||||
"{format} output doesn't contain move command!\n===\n{contents}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "json")]
|
||||
/// Ensure JSON output is valid.
|
||||
fn test_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 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
|
||||
.write_all(&mut cursor, &findings, &[])
|
||||
.expect("Failed to write to cursor");
|
||||
|
||||
cursor.set_position(0);
|
||||
cursor
|
||||
.read_to_string(&mut contents)
|
||||
.expect("Failed to read from cursor to string");
|
||||
|
||||
// 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}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure that the Media extension set contains all (is a superset) of Audio, Video, and Images.
|
||||
fn media_contains_audio_video_images() {
|
||||
use crate::parameters::ExtensionSet::{Audio, Images, Media, Video};
|
||||
let media_exts = Media.extensions();
|
||||
|
||||
// assert every extension in the audio/video/image sets is contained in the media set
|
||||
[Audio.extensions(), Video.extensions(), Images.extensions()]
|
||||
.concat()
|
||||
.into_iter()
|
||||
.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()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Ensure that the `writables!` and `writablesln!` macros produce the output they should.
|
||||
fn writables_is_correct() {
|
||||
use fif::formats::Writable;
|
||||
use fif::{writables, writablesln};
|
||||
|
||||
assert_eq!(
|
||||
&["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]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Test various combinations of verbosity flags.
|
||||
fn verbosity() {
|
||||
use log::LevelFilter;
|
||||
assert!(
|
||||
Parameters::try_parse_from(["fif", "-q", "-v"]).is_err(),
|
||||
"Failed to reject usage of both -q and -v!"
|
||||
);
|
||||
|
||||
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]).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);
|
||||
}
|
63
src/utils.rs
Normal file
63
src/utils.rs
Normal file
|
@ -0,0 +1,63 @@
|
|||
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Various minor utilities.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
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");
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
||||
/// The backend being used; either "Infer" or "XDG-Mime".
|
||||
pub const BACKEND: &str = "Infer";
|
||||
} else {
|
||||
/// The backend being used; either "Infer" or "XDG-Mime".
|
||||
pub const BACKEND: &str = "XDG-Mime";
|
||||
}
|
||||
}
|
||||
|
||||
/// 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("???"));
|
||||
|
||||
/// 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"),
|
||||
};
|
||||
|
||||
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 {
|
||||
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);
|
||||
os_upper.get_mut(0..1).map(|first| first.make_ascii_uppercase());
|
||||
os_upper
|
||||
}
|
||||
}
|
||||
}
|
71
test.py
Executable file
71
test.py
Executable file
|
@ -0,0 +1,71 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def test_archs():
|
||||
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=json,infer-backend --target {arch}-unknown-linux-gnu".split(" "))\
|
||||
.check_returncode()
|
||||
upto += 1
|
||||
|
||||
|
||||
def test_versions():
|
||||
match = re.search(
|
||||
r'rust-version ?= ?"([\d.]+)"',
|
||||
open("Cargo.toml", "r").read(-1)
|
||||
)
|
||||
|
||||
if not match:
|
||||
print("Couldn't find rust-version")
|
||||
exit(1)
|
||||
|
||||
versions = [match.group(1), "stable", "nightly"]
|
||||
backends = ["xdg-mime", "infer"]
|
||||
|
||||
upto = 1
|
||||
target = len(versions) * len(backends) * 2
|
||||
|
||||
for version in versions:
|
||||
for backend in backends:
|
||||
print(f"[{version}, {backend}] Tests ({upto} of {target})")
|
||||
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=json,{backend}-backend -- imgs".split(" "))\
|
||||
.check_returncode()
|
||||
upto += 1
|
||||
|
||||
|
||||
def main():
|
||||
done_something = False
|
||||
if "versions" in sys.argv:
|
||||
test_versions()
|
||||
done_something = True
|
||||
if "archs" in sys.argv:
|
||||
test_archs()
|
||||
done_something = True
|
||||
|
||||
if not done_something:
|
||||
print("You must supply at least one of `versions` or `archs` as an argument! 0uo")
|
||||
sys.exit(2)
|
||||
|
||||
print("Done! You might want to run cargo clean...")
|
||||
subprocess.run(["du", "-sh", "target"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Loading…
editor.table_modal.header
Reference in a new issue