Compare commits
99 commits
35322075ab
...
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 |
34 changed files with 2455 additions and 984 deletions
|
@ -1,3 +1,6 @@
|
||||||
|
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
|
||||||
|
# SPDX-License-Identifier: CC0-1.0
|
||||||
|
|
||||||
---
|
---
|
||||||
kind: pipeline
|
kind: pipeline
|
||||||
type: docker
|
type: docker
|
||||||
|
|
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
|
11
.gitignore
vendored
11
.gitignore
vendored
|
@ -1,5 +1,9 @@
|
||||||
|
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
|
||||||
|
# SPDX-License-Identifier: CC0-1.0
|
||||||
|
|
||||||
/target
|
/target
|
||||||
/imgs
|
/imgs
|
||||||
|
/imgs.tar.zst
|
||||||
/fif_*
|
/fif_*
|
||||||
/old
|
/old
|
||||||
/.mypy_cache
|
/.mypy_cache
|
||||||
|
@ -7,9 +11,14 @@
|
||||||
*.sh
|
*.sh
|
||||||
!clippy.sh
|
!clippy.sh
|
||||||
cargo-timing*.html
|
cargo-timing*.html
|
||||||
todo.txt
|
/*.txt
|
||||||
/pkg/*
|
/pkg/*
|
||||||
/out
|
/out
|
||||||
/packages
|
/packages
|
||||||
/fif
|
/fif
|
||||||
/fif.exe
|
/fif.exe
|
||||||
|
.idea/workspace.xml
|
||||||
|
*.sync-conflict*
|
||||||
|
.idea/sonarlint
|
||||||
|
.directory
|
||||||
|
*.tmp
|
||||||
|
|
|
@ -1,8 +1,12 @@
|
||||||
|
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
|
||||||
|
# SPDX-License-Identifier: CC0-1.0
|
||||||
|
|
||||||
image: "rust:latest"
|
image: "rust:latest"
|
||||||
|
|
||||||
variables:
|
variables:
|
||||||
CARGO_HOME: $CI_PROJECT_DIR/.cargo
|
CARGO_HOME: $CI_PROJECT_DIR/.cargo
|
||||||
PACKAGE_REGISTRY_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/fif"
|
PACKAGE_REGISTRY_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/fif"
|
||||||
|
RUSTFLAGS: "-C debuginfo=0"
|
||||||
|
|
||||||
cache:
|
cache:
|
||||||
paths:
|
paths:
|
||||||
|
@ -34,6 +38,7 @@ stages:
|
||||||
script:
|
script:
|
||||||
- cargo install cargo-sweep
|
- cargo install cargo-sweep
|
||||||
- cargo sweep -i
|
- 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
|
# 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
|
# for the purposes of caching - by building once *before* executing the parallel cargo-build step, we ensure that
|
||||||
|
@ -56,7 +61,7 @@ stages:
|
||||||
- multi-threaded infer-backend
|
- multi-threaded infer-backend
|
||||||
|
|
||||||
script:
|
script:
|
||||||
cargo build --no-default-features --locked --features="json $FEATURES"
|
cargo run --no-default-features --locked --features="json $FEATURES" -- --version
|
||||||
|
|
||||||
# test with various features on and off.
|
# test with various features on and off.
|
||||||
.cargo-test:
|
.cargo-test:
|
||||||
|
@ -81,15 +86,8 @@ clippy:
|
||||||
cleanup-stable:
|
cleanup-stable:
|
||||||
extends: .cargo-cleanup
|
extends: .cargo-cleanup
|
||||||
|
|
||||||
# commented out because cargo-sweep no longer works on our MSRV
|
# there's no point running cargo sweep on MSRV, since it's always at the same version (and therefore cargo sweep will
|
||||||
#cleanup-msrv:
|
# never delete anything)
|
||||||
# extends: cleanup-stable
|
|
||||||
# image: "rust:1.43.0"
|
|
||||||
# cache:
|
|
||||||
# key: msrv
|
|
||||||
# paths:
|
|
||||||
# - target
|
|
||||||
# - .cargo
|
|
||||||
|
|
||||||
cleanup-nightly:
|
cleanup-nightly:
|
||||||
extends: cleanup-stable
|
extends: cleanup-stable
|
||||||
|
@ -107,8 +105,7 @@ build-base-stable:
|
||||||
|
|
||||||
build-base-msrv:
|
build-base-msrv:
|
||||||
extends: build-base-stable
|
extends: build-base-stable
|
||||||
# needs: ["cleanup-msrv"]
|
image: "rust:1.64.0"
|
||||||
image: "rust:1.43.0"
|
|
||||||
cache:
|
cache:
|
||||||
key: msrv
|
key: msrv
|
||||||
paths:
|
paths:
|
||||||
|
@ -134,7 +131,7 @@ build-stable:
|
||||||
build-msrv:
|
build-msrv:
|
||||||
extends: build-stable
|
extends: build-stable
|
||||||
needs: ["build-base-msrv"]
|
needs: ["build-base-msrv"]
|
||||||
image: "rust:1.43.0"
|
image: "rust:1.64.0"
|
||||||
cache:
|
cache:
|
||||||
key: msrv
|
key: msrv
|
||||||
paths:
|
paths:
|
||||||
|
@ -159,7 +156,7 @@ test-stable:
|
||||||
|
|
||||||
test-msrv:
|
test-msrv:
|
||||||
extends: test-stable
|
extends: test-stable
|
||||||
image: "rust:1.43.0"
|
image: "rust:1.64.0"
|
||||||
needs: ["build-msrv"]
|
needs: ["build-msrv"]
|
||||||
cache:
|
cache:
|
||||||
key: msrv
|
key: msrv
|
||||||
|
|
|
@ -4,6 +4,31 @@
|
||||||
<content url="file://$MODULE_DIR$">
|
<content url="file://$MODULE_DIR$">
|
||||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||||
<sourceFolder url="file://$MODULE_DIR$/src/test" isTestSource="true" />
|
<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$/target" />
|
||||||
<excludeFolder url="file://$MODULE_DIR$/imgs" />
|
<excludeFolder url="file://$MODULE_DIR$/imgs" />
|
||||||
<excludeFolder url="file://$MODULE_DIR$/old" />
|
<excludeFolder url="file://$MODULE_DIR$/old" />
|
||||||
|
|
|
@ -3,6 +3,9 @@
|
||||||
<option name="myName" value="Project Default" />
|
<option name="myName" value="Project Default" />
|
||||||
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
|
<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="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">
|
<inspection_tool class="ShellCheck" enabled="true" level="ERROR" enabled_by_default="true">
|
||||||
<shellcheck_settings value="SC2016" />
|
<shellcheck_settings value="SC2016" />
|
||||||
</inspection_tool>
|
</inspection_tool>
|
||||||
|
|
9
.idea/markdown.xml
Normal file
9
.idea/markdown.xml
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>
|
|
@ -6,6 +6,7 @@
|
||||||
<option name="requiredFeatures" value="true" />
|
<option name="requiredFeatures" value="true" />
|
||||||
<option name="allFeatures" value="false" />
|
<option name="allFeatures" value="false" />
|
||||||
<option name="emulateTerminal" value="false" />
|
<option name="emulateTerminal" value="false" />
|
||||||
|
<option name="withSudo" value="false" />
|
||||||
<option name="backtrace" value="SHORT" />
|
<option name="backtrace" value="SHORT" />
|
||||||
<envs>
|
<envs>
|
||||||
<env name="RUST_LOG" value="debug" />
|
<env name="RUST_LOG" value="debug" />
|
||||||
|
|
3
.idea/scopes/Default.xml
Normal file
3
.idea/scopes/Default.xml
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>
|
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}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
99
CHANGELOG.md
99
CHANGELOG.md
|
@ -4,10 +4,90 @@ Dates are given in YYYY-MM-DD format - for example, the 15th of October 2021 is
|
||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to
|
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).
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## Unreleased
|
## 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
|
### Added
|
||||||
- AIFF (Audio Interchange File Format, a PCM audio format like WAV) detection to [`infer`]
|
- 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
|
- `--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
|
### Other
|
||||||
- Refactoring - split fif into `main.rs` and `lib.rs`, moved file-related functionality (directory scanning, etc.) into
|
- Refactoring - split fif into `main.rs` and `lib.rs`, moved file-related functionality (directory scanning, etc.) into
|
||||||
files module, removed string module, etc.
|
files module, removed string module, etc.
|
||||||
|
@ -16,6 +96,8 @@ files module, removed string module, etc.
|
||||||
"Features" heading into "Added" and "Changed" sections, renaming "Bugfixes" to "Fixed", and removing the
|
"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
|
headings that (pointlessly?) previously divided the changelog into v0.3, v0.2, and v0.1
|
||||||
- A few minor grammar tweaks and reorganisations
|
- 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
|
## v0.3.6 - 2021-08-16
|
||||||
### Other
|
### Other
|
||||||
|
@ -36,6 +118,7 @@ this version of `clap`, which caused the build to fail. Also, `clap` 3 beta 4 de
|
||||||
- `-I`/`--ignore-unknown-exts` flag for ignoring files with unknown extensions - for example, if fif doesn't know
|
- `-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
|
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.
|
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
|
### Other
|
||||||
- Refactored `formats.rs`
|
- Refactored `formats.rs`
|
||||||
- More accurate dependency versions in `Cargo.toml` to ensure that the MSRV stays supported
|
- More accurate dependency versions in `Cargo.toml` to ensure that the MSRV stays supported
|
||||||
|
@ -100,7 +183,7 @@ this version of `clap`, which caused the build to fail. Also, `clap` 3 beta 4 de
|
||||||
- System extension set (`.dll`, `.so`, `.exe`...)
|
- System extension set (`.dll`, `.so`, `.exe`...)
|
||||||
- [`infer`] backend now supports Ren'Py archive (`.rpa`) files
|
- [`infer`] backend now supports Ren'Py archive (`.rpa`) files
|
||||||
### Changed
|
### Changed
|
||||||
- Output is now sorted: Files that couldn't be read, then files with no known mimetype, then files with no known
|
- 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
|
extensions, then files with the wrong extension
|
||||||
- Added Apple iWork document formats to Documents extension set (`.pages`, `.key`, `.numbers`)
|
- Added Apple iWork document formats to Documents extension set (`.pages`, `.key`, `.numbers`)
|
||||||
### Fixed
|
### Fixed
|
||||||
|
@ -132,7 +215,7 @@ this version of `clap`, which caused the build to fail. Also, `clap` 3 beta 4 de
|
||||||
### Added
|
### Added
|
||||||
- fif can now traverse symlinks with the `-f`/`--follow-symlinks` flag
|
- fif can now traverse symlinks with the `-f`/`--follow-symlinks` flag
|
||||||
### Changed
|
### Changed
|
||||||
- Better mime type detection:
|
- Better MIME type detection:
|
||||||
- Consider "some/x-thing" and "some/thing" to be identical
|
- 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
|
- 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
|
- Extensions are no longer mandatory - running fif without `-e` or `-E` will scan all files, regardless of extension
|
||||||
|
@ -244,10 +327,14 @@ Initial commit!
|
||||||
- Only supported flags are `-e` (specify extensions) and `-s` (scan hidden files)
|
- Only supported flags are `-e` (specify extensions) and `-s` (scan hidden files)
|
||||||
|
|
||||||
<!-- links -->
|
<!-- links -->
|
||||||
[`xdg-mime`]: https://crates.io/crates/xdg-mime
|
[`cached`]: https://crates.io/crates/cached
|
||||||
[`structopt`]: https://crates.io/crates/structopt
|
|
||||||
[`clap`]: https://crates.io/crates/clap
|
[`clap`]: https://crates.io/crates/clap
|
||||||
[`infer`]: https://crates.io/crates/infer
|
[`infer`]: https://crates.io/crates/infer
|
||||||
[`mime_guess`]: https://crates.io/crates/mime_guess
|
[`mime_guess`]: https://crates.io/crates/mime_guess
|
||||||
[`new_mime_guess`]: https://crates.io/crates/new_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
|
[`snailquote`]: https://crates.io/crates/snailquote
|
||||||
|
[`structopt`]: https://crates.io/crates/structopt
|
||||||
|
[`xdg-mime`]: https://crates.io/crates/xdg-mime
|
||||||
|
|
978
Cargo.lock
generated
978
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
72
Cargo.toml
72
Cargo.toml
|
@ -1,87 +1,77 @@
|
||||||
[package]
|
[package]
|
||||||
name = "fif"
|
name = "fif"
|
||||||
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
|
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
|
||||||
version = "0.3.6"
|
version = "0.7.2"
|
||||||
authors = ["Lynnesbian <lynne@bune.city>"]
|
authors = ["Lynnesbian <lynne@bune.city>"]
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
license = "GPL-3.0-or-later"
|
license = "GPL-3.0-or-later"
|
||||||
rust-version = "1.43.0" # cached breaks on 1.42.0, i think it needs https://github.com/rust-lang/rust/pull/67642/
|
rust-version = "1.64.0" # clap 4.1 requires >=1.64.0
|
||||||
repository = "https://gitlab.com/Lynnesbian/fif"
|
repository = "https://gitlab.com/Lynnesbian/fif"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
keywords = ["mime", "mimetype", "utilities", "tools"]
|
keywords = ["mime", "mimetype", "utilities", "tools"]
|
||||||
categories = ["command-line-utilities"]
|
categories = ["command-line-utilities"]
|
||||||
exclude = [".idea/", "*.toml", "!Cargo.toml", "*.sh", "*.py", "*.yml", "*.md", ".mailmap", "pkg/"]
|
exclude = [".idea/", "*.toml", "!Cargo.toml", "*.sh", "*.py", "*.yml", "*.md", ".mailmap", "pkg/"]
|
||||||
#resolver = "2"
|
|
||||||
#license-file = "LICENSE"
|
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
maintenance = { status = "experimental" }
|
maintenance = { status = "experimental" }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["multi-threaded", "json"]
|
default = ["multi-threaded", "json"]
|
||||||
multi-threaded = ["rayon"]
|
multi-threaded = ["rayon", "num_cpus"]
|
||||||
infer-backend = ["infer"]
|
infer-backend = ["infer"]
|
||||||
xdg-mime-backend = ["xdg-mime"]
|
xdg-mime-backend = ["xdg-mime"]
|
||||||
json = ["serde", "serde_json"]
|
json = ["serde", "serde_json"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
walkdir = "~2.3.2"
|
walkdir = "2.4.0"
|
||||||
log = "0.4.14"
|
log = "0.4.14"
|
||||||
mime = "0.3.16"
|
mime = "0.3.16"
|
||||||
mime_guess = { package = "new_mime_guess", features = ["phf-map"], version = "3.0.0" }
|
mime_guess = { package = "new_mime_guess", version = "4.0.0" }
|
||||||
snailquote = "0.3.0"
|
snailquote = "0.3.0"
|
||||||
once_cell = "1.8.0"
|
once_cell = "1.8.0"
|
||||||
rayon = { version = "1.5.0", optional = true }
|
rayon = { version = "1.5.0", optional = true }
|
||||||
exitcode = "1.1.2"
|
exitcode = "1.1.2"
|
||||||
cfg-if = "1.0.0"
|
cfg-if = "1.0.0"
|
||||||
itertools = "0.10.0"
|
itertools = "0.13.0"
|
||||||
serde = { version = "1.0", features = ["derive"], optional = true }
|
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||||
serde_json = { version = "1.0", optional = true }
|
serde_json = { version = "1.0", optional = true }
|
||||||
bitflags = "~1.2.1" # 1.3+ requires Rust >= 1.46
|
num_cpus = { version = "1.13.0", optional = true }
|
||||||
|
parking_lot = "0.12.0"
|
||||||
|
smartstring = "1"
|
||||||
|
maplit = "1.0.2"
|
||||||
|
|
||||||
|
# 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]
|
[target.'cfg(not(unix))'.dependencies]
|
||||||
xdg-mime = { version = "0.3.3", optional = true }
|
xdg-mime = { version = "0.4.0", optional = true }
|
||||||
infer = "0.5.0"
|
infer = "=0.13.0" # 0.14.0 uses `let else`, which requires rust 1.65
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
xdg-mime = "0.3.3"
|
xdg-mime = "0.4.0"
|
||||||
infer = { version = "0.5.0", optional = true }
|
infer = { version = "=0.13.0", optional = true }
|
||||||
|
|
||||||
[target.'cfg(not(all(target_endian = "big", target_pointer_width = "32")))'.dependencies]
|
|
||||||
# the seemingly weird target constraint here is due to this:
|
|
||||||
# https://github.com/bodil/smartstring/blob/v0.2.7/src/config.rs#L102-L104
|
|
||||||
# essentially, smartstring is intentionally blocked from compiling on 32-bit big endian archs, so our dependency on it
|
|
||||||
# needs to be too. otherwise, fif won't work on platforms like powerpc, even though this dependency is the only
|
|
||||||
# blocker -- fif runs just fine on powerpc without smartstring. or at least, just fine under qemu user-mode powerpc ~u0
|
|
||||||
|
|
||||||
# additionally, smartstring 0.2.8 requires rust >=1.46 (due to https://github.com/rust-lang/rust/issues/49146), and
|
|
||||||
# 0.2.3 doesn't impl Display on its SmartString type.
|
|
||||||
# so, we need at least 0.2.4 so we can println! strings, and at most 0.2.7 until we bump the MSRV to at least 1.46.
|
|
||||||
# see https://github.com/bodil/smartstring/blob/master/CHANGELOG.md
|
|
||||||
smartstring = "<= 0.2.7, >= 0.2.4"
|
|
||||||
|
|
||||||
[dependencies.clap]
|
[dependencies.clap]
|
||||||
# beta.4 requires rust >= 1.54.0 (and beta.3 was yanked)
|
version = "~4.3" #4.4 has some deps that can't be satisfied on our MSRV
|
||||||
version = "=3.0.0-beta.2"
|
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["wrap_help", "color", "derive", "std"]
|
features = ["wrap_help", "color", "derive", "std", "unicode"]
|
||||||
|
|
||||||
[dependencies.clap_derive]
|
|
||||||
# without this, clap beta.2 will install clap_derive beta.4 :c
|
|
||||||
version = "=3.0.0-beta.2"
|
|
||||||
|
|
||||||
[dependencies.env_logger]
|
[dependencies.env_logger]
|
||||||
version = "0.9.0"
|
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"]
|
|
||||||
|
|
||||||
[dependencies.cached]
|
|
||||||
version = "0.25.0"
|
|
||||||
default-features = false
|
default-features = false
|
||||||
|
features = ["color"]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.2.0"
|
tempfile = "3.2.0"
|
||||||
rand = "0.8.3"
|
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]
|
[profile.release]
|
||||||
lto = "thin"
|
lto = "thin"
|
||||||
|
@ -94,4 +84,4 @@ opt-level = 3
|
||||||
opt-level = 3
|
opt-level = 3
|
||||||
|
|
||||||
[package.metadata]
|
[package.metadata]
|
||||||
msrv = "1.43.0"
|
msrv = "1.64.0"
|
||||||
|
|
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>.
|
49
README.md
49
README.md
|
@ -7,7 +7,7 @@
|
||||||
|
|
||||||
[![Version](https://img.shields.io/crates/v/fif.svg?logo=rust&style=flat-square)
|
[![Version](https://img.shields.io/crates/v/fif.svg?logo=rust&style=flat-square)
|
||||||
](https://crates.io/crates/fif)
|
](https://crates.io/crates/fif)
|
||||||
[![Minimum Supported Rust Version](https://img.shields.io/badge/msrv-1.43.0-orange?logo=rust&style=flat-square)
|
[![Minimum Supported Rust Version](https://img.shields.io/badge/msrv-1.57.0-orange?logo=rust&style=flat-square)
|
||||||
](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#version-policy)
|
](https://gitlab.com/Lynnesbian/fif/-/blob/master/README.md#version-policy)
|
||||||
[![License](https://img.shields.io/crates/l/fif.svg?style=flat-square)
|
[![License](https://img.shields.io/crates/l/fif.svg?style=flat-square)
|
||||||
](https://gitlab.com/Lynnesbian/fif/-/blob/master/LICENSE)
|
](https://gitlab.com/Lynnesbian/fif/-/blob/master/LICENSE)
|
||||||
|
@ -17,6 +17,8 @@
|
||||||
](https://github.com/rust-secure-code/safety-dance/)
|
](https://github.com/rust-secure-code/safety-dance/)
|
||||||
[![Dependency versions](https://deps.rs/repo/gitlab/lynnesbian/fif/status.svg)
|
[![Dependency versions](https://deps.rs/repo/gitlab/lynnesbian/fif/status.svg)
|
||||||
](https://deps.rs/repo/gitlab/lynnesbian/fif)
|
](https://deps.rs/repo/gitlab/lynnesbian/fif)
|
||||||
|
[![REUSE status](https://api.reuse.software/badge/gitlab.com/Lynnesbian/fif/)
|
||||||
|
](https://api.reuse.software/info/gitlab.com/Lynnesbian/fif/)
|
||||||
|
|
||||||
*A command-line tool for detecting and optionally correcting files with incorrect extensions.*
|
*A command-line tool for detecting and optionally correcting files with incorrect extensions.*
|
||||||
</div>
|
</div>
|
||||||
|
@ -57,10 +59,10 @@ cargo install --locked fif
|
||||||
To update, simply re-run the `install` command, or use a tool like [cargo-update
|
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`.
|
](https://github.com/nabijaczleweli/cargo-update), which can update crates installed via `cargo install`.
|
||||||
|
|
||||||
On macOS, `fif` can now be installed using [MacPorts](https://www.macports.org), via the following steps:
|
On macOS, `fif` can be installed through [MacPorts](https://www.macports.org):
|
||||||
```bash
|
```bash
|
||||||
$ sudo port selfupdate
|
sudo port selfupdate
|
||||||
$ sudo port install fif
|
sudo port install fif
|
||||||
```
|
```
|
||||||
|
|
||||||
### Cargo Features
|
### Cargo Features
|
||||||
|
@ -69,7 +71,8 @@ used on [*nix systems](https://en.wikipedia.org/wiki/Unix-like) (Linux, macOS, *
|
||||||
systems.
|
systems.
|
||||||
|
|
||||||
`xdg-mime` should work on any *nix system with the [Shared MIME Info] library installed (consult your package
|
`xdg-mime` should work on any *nix system with the [Shared MIME Info] library installed (consult your package
|
||||||
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system.
|
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system, but it supports far
|
||||||
|
fewer file types than `xdg-mime` does, thanks to the excellent Shared MIME Info library.
|
||||||
|
|
||||||
You can override the default backend for your system at compile time like so:
|
You can override the default backend for your system at compile time like so:
|
||||||
|
|
||||||
|
@ -137,6 +140,25 @@ You can also manually specify an output format to use:
|
||||||
fif -O powershell ~/Documents > output.ps1
|
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
|
### Logging
|
||||||
By default, fif will log any info, warnings, and errors encountered during execution. This can be changed with the `-v`
|
By default, fif will log any info, warnings, and errors encountered during execution. This can be changed with the `-v`
|
||||||
flag:
|
flag:
|
||||||
|
@ -174,7 +196,7 @@ The five logging levels are used as follows:
|
||||||
| Level | Description | Example |
|
| Level | Description | Example |
|
||||||
|-|-|-|
|
|-|-|-|
|
||||||
| error | Errors that cause fif to stop running | fif was unable to open the provided directory |
|
| error | Errors that cause fif to stop running | fif was unable to open the provided directory |
|
||||||
| warn | Warnings that don't cause fif to stop running | fif was unable to determine the mime type of a given file |
|
| warn | Warnings that don't cause fif to stop running | fif was unable to determine the MIME type of a given file |
|
||||||
| info | Information pertaining to fif's status | The provided directory was scanned without issue, and no files are in need of renaming |
|
| 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 |
|
| 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. |
|
| trace | Trace info - usually not important to end users | "Found 15 items to check", "Scan successful", etc. |
|
||||||
|
@ -197,10 +219,23 @@ number will be updated as follows:
|
||||||
when adding the ability to exclude extensions, and when fif gained the ability to output a bash script rather than a
|
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.
|
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
|
- 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 flag).
|
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.
|
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
|
## License
|
||||||
Copyright (C) 2021 Lynnesbian
|
Copyright (C) 2021 Lynnesbian
|
||||||
|
|
||||||
|
|
7
build.rs
7
build.rs
|
@ -1,3 +1,6 @@
|
||||||
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
#[allow(unreachable_code, clippy::pedantic)]
|
#[allow(unreachable_code, clippy::pedantic)]
|
||||||
|
@ -11,9 +14,9 @@ fn main() -> Result<(), String> {
|
||||||
// a more robust way of doing this would be to use vergen (https://github.com/rustyhorde/vergen), but it pulls in a
|
// 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.
|
// 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!
|
// this method is less clever and robust, but it works!
|
||||||
let git = Command::new("git").args(&["rev-parse", "--short", "HEAD"]).output();
|
let git = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output();
|
||||||
let hash = match git {
|
let hash = match git {
|
||||||
Ok(output) => String::from_utf8_lossy(&*output.stdout).into(),
|
Ok(output) => String::from_utf8_lossy(&output.stdout).into(),
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// git not being present (or failing) shouldn't block compilation
|
// git not being present (or failing) shouldn't block compilation
|
||||||
println!("cargo:warning=Failed to retrieve git commit hash");
|
println!("cargo:warning=Failed to retrieve git commit hash");
|
||||||
|
|
13
clippy.sh
13
clippy.sh
|
@ -1,4 +1,8 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
|
# SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
# SPDX-License-Identifier: CC0-1.0
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
source "$HOME"/.cargo/env || true
|
source "$HOME"/.cargo/env || true
|
||||||
|
|
||||||
|
@ -23,6 +27,7 @@ for backend in "${_backends[@]}"; do
|
||||||
-W clippy::pedantic \
|
-W clippy::pedantic \
|
||||||
-W clippy::complexity \
|
-W clippy::complexity \
|
||||||
-W clippy::cargo \
|
-W clippy::cargo \
|
||||||
|
-W clippy::style \
|
||||||
-W clippy::float_cmp_const \
|
-W clippy::float_cmp_const \
|
||||||
-W clippy::lossy_float_literal \
|
-W clippy::lossy_float_literal \
|
||||||
-W clippy::multiple_inherent_impl \
|
-W clippy::multiple_inherent_impl \
|
||||||
|
@ -32,11 +37,10 @@ for backend in "${_backends[@]}"; do
|
||||||
-A clippy::shadow_unrelated \
|
-A clippy::shadow_unrelated \
|
||||||
-A clippy::option_if_let_else \
|
-A clippy::option_if_let_else \
|
||||||
-A clippy::multiple-crate-versions \
|
-A clippy::multiple-crate-versions \
|
||||||
-A clippy::cast-possible-truncation \
|
|
||||||
-A clippy::cast-possible-wrap \
|
|
||||||
-A clippy::must_use_candidate \
|
-A clippy::must_use_candidate \
|
||||||
-A clippy::missing_panics_doc \
|
-A clippy::missing_panics_doc \
|
||||||
-A clippy::missing_errors_doc \
|
-A clippy::missing_errors_doc \
|
||||||
|
-A clippy::doc_markdown \
|
||||||
"$_extra"
|
"$_extra"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
@ -45,9 +49,8 @@ done
|
||||||
# redundant_closure...: the alternative is often much more verbose
|
# redundant_closure...: the alternative is often much more verbose
|
||||||
# shadow_unrelated: sometimes things that seem unrelated are actually related ;)
|
# 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
|
# option_if_let_else: the suggested code is usually harder to read than the original
|
||||||
# multiple_crate_versions: cached uses an old version of hashbrown :c
|
# multiple_crate_versions: this doesn't actually trip right now, but it's not something i would want CI to fail over
|
||||||
# cast_possible_truncation: only ever used where it would be totally fine
|
|
||||||
# cast_possible_wrap: ditto
|
|
||||||
# must_use_candidate: useless
|
# 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_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
|
# missing_errors_doc: ditto
|
||||||
|
# doc_markdown: way too many false positives
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
# avoid-breaking-exported-api = false # only available on nightly for now
|
# avoid-breaking-exported-api = false # only available on nightly for now
|
||||||
cognitive-complexity-threshold = 15
|
cognitive-complexity-threshold = 15
|
||||||
|
msrv = "1.64.0"
|
||||||
|
|
8
doc/README.md
Normal file
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
|
Binary file not shown.
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 130 B |
|
@ -3,3 +3,6 @@ fn_single_line = true
|
||||||
hard_tabs = true
|
hard_tabs = true
|
||||||
tab_spaces = 2
|
tab_spaces = 2
|
||||||
newline_style = "Unix"
|
newline_style = "Unix"
|
||||||
|
group_imports = "StdExternalCrate"
|
||||||
|
array_width = 100
|
||||||
|
fn_call_width = 80
|
||||||
|
|
371
src/files.rs
371
src/files.rs
|
@ -1,32 +1,57 @@
|
||||||
use crate::findings::{Findings, ScanError};
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
use crate::mime_db::MimeDb;
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
use crate::parameters::ScanOpts;
|
|
||||||
use crate::{String, MIMEDB};
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
//! File handling - scanning, detecting MIME types, and so on.
|
||||||
|
|
||||||
|
use std::collections::{BTreeSet, HashMap};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io;
|
use std::io::{self, Read, Seek, SeekFrom};
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use cached::cached;
|
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
|
use itertools::{Either, Itertools};
|
||||||
use log::{debug, error};
|
use log::{debug, error};
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
use mime_guess::from_ext;
|
use mime_guess::from_ext;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use parking_lot::RwLock;
|
||||||
use walkdir::{DirEntry, WalkDir};
|
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! {
|
cfg_if! {
|
||||||
if #[cfg(windows)] {
|
if #[cfg(windows)] {
|
||||||
/// Determines whether or not a file is hidden by checking its win32 file attributes.
|
/// Determines whether or not a file is hidden by checking its win32 file attributes.
|
||||||
pub fn is_hidden(entry: &DirEntry) -> bool {
|
pub fn is_hidden(entry: &DirEntry) -> bool {
|
||||||
use std::os::windows::prelude::*;
|
use std::os::windows::prelude::*;
|
||||||
std::fs::metadata(entry.path()) // try to get metadata for file
|
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2; // http://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
|
||||||
.map_or(
|
std::fs::metadata(entry.path()) // try to get metadata for file
|
||||||
false, // if getting metadata/attributes fails, assume it's not hidden
|
.map_or(
|
||||||
|f| f.file_attributes() & 0x2 > 0, // flag for hidden - https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
|
false, // if getting metadata/attributes fails, assume it's not hidden
|
||||||
)
|
|f| f.file_attributes() & FILE_ATTRIBUTE_HIDDEN > 0,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
/// Determines whether or not a file is hidden by checking for a leading full stop.
|
/// Determines whether or not a file is hidden by checking for a leading full stop.
|
||||||
|
@ -88,30 +113,52 @@ pub fn wanted_file(
|
||||||
/// Inspects the given entry, returning a [`Findings`] on success and a [`ScanError`] on failure.
|
/// 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
|
/// In the event of an IO error, the returned [`ScanError`] will be of type [`ScanError::File`]. Otherwise, a
|
||||||
/// [`ScanError::Mime`] will be returned, meaning that the file was scanned successfully, but a mimetype could not be
|
/// [`ScanError::Mime`] will be returned, meaning that the file was scanned successfully, but a MIME type could not be
|
||||||
/// determined.
|
/// determined.
|
||||||
pub fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, ScanError> {
|
pub fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, ScanError> {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
// try to determine mimetype for this entry
|
// try to determine MIME type for this entry
|
||||||
let result = match mime_type(MIMEDB.get().unwrap(), path) {
|
let result = match mime_type(&*MIMEDB, path) {
|
||||||
// an error occurred while trying to read the file
|
// an error occurred while trying to read the file
|
||||||
Err(_) => return Err(ScanError::File(path)),
|
Err(_) => return Err(ScanError::File(path)),
|
||||||
// the file was read successfully, but we were unable to determine its mimetype
|
// the file was read successfully, but we were unable to determine its MIME type
|
||||||
Ok(None) => return Err(ScanError::Mime(path)),
|
Ok(None) => return Err(ScanError::Mime(path)),
|
||||||
// a mimetype was found!
|
// a MIME type was found!
|
||||||
Ok(Some(result)) => result,
|
Ok(Some(result)) => result,
|
||||||
};
|
};
|
||||||
|
|
||||||
// set of known extensions for the given mimetype
|
// determine whether or not the file's current extension is valid
|
||||||
let known_exts = mime_extension_lookup(result.essence_str().into());
|
let valid = if let Some(entry_ext) = path.extension() {
|
||||||
// file extension for this particular file
|
// discard invalid UTF-8 and convert to lowercase. all extensions in both backend's databases are lowercase
|
||||||
let entry_ext = path.extension();
|
// ascii, so this assumption is fine.
|
||||||
|
let entry_ext = entry_ext.to_string_lossy().to_lowercase();
|
||||||
|
|
||||||
let valid = match known_exts {
|
// if the file has any of these extensions, it is probably either:
|
||||||
// there is a known set of extensions for this mimetype, and the file has an extension
|
// - a copy of another file renamed for backup purposes (e.g. a word processor might save by renaming "my.doc" to
|
||||||
Some(e) if entry_ext.is_some() => e.contains(&entry_ext.unwrap().to_string_lossy().to_lowercase().into()),
|
// "my.doc.bak", then creating "my.doc", leaving the backup for safekeeping), which shouldn't be renamed so as
|
||||||
// either this file has no extension, or there is no known set of extensions for this mimetype :(
|
// not to break the backup program
|
||||||
Some(_) | None => false,
|
// - 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 {
|
let path = if canonical_paths {
|
||||||
|
@ -131,29 +178,50 @@ pub fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, Sc
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes a slice of [`DirEntry`]s and calls [`scan_file`] on each one, returning the results in a vector.
|
/// 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) -> Vec<Result<Findings, ScanError>> {
|
pub fn scan_from_walkdir(
|
||||||
|
entries: &[DirEntry],
|
||||||
|
canonical_paths: bool,
|
||||||
|
use_threads: bool,
|
||||||
|
) -> (Vec<Findings>, Vec<ScanError>) {
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
if #[cfg(feature = "multi-threaded")] {
|
if #[cfg(feature = "multi-threaded")] {
|
||||||
use rayon::prelude::*;
|
use rayon::prelude::*;
|
||||||
|
const CHUNKS: usize = 32;
|
||||||
|
|
||||||
// split the entries into chunks of 32, and iterate over each chunk of entries in a separate thread
|
if use_threads && entries.len() > CHUNKS {
|
||||||
entries
|
// split the entries into chunks of 32, and iterate over each chunk of entries in a separate thread
|
||||||
.par_chunks(32)
|
return entries
|
||||||
.flat_map(|chunk| {
|
.par_chunks(CHUNKS)
|
||||||
chunk
|
.flat_map_iter(|chunk| {
|
||||||
.iter() // iter over the chunk, which is a slice of DirEntry structs
|
chunk
|
||||||
.map(|entry| scan_file(entry, canonical_paths))
|
.iter() // iter over the chunk, which is a slice of DirEntry structs
|
||||||
.collect::<Vec<_>>()
|
.map(|entry| scan_file(entry, canonical_paths))
|
||||||
})
|
.collect::<Vec<_>>()
|
||||||
.collect()
|
}).partition_map(|result| match result {
|
||||||
|
Ok(f) => Either::Left(f),
|
||||||
|
Err(e) => Either::Right(e),
|
||||||
|
});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
entries.iter().map(|entry: &DirEntry| scan_file(entry, canonical_paths)).collect()
|
// 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
|
/// Scans a given directory with [`WalkDir`], filters with [`wanted_file`], checks for errors, and returns a vector of
|
||||||
/// [DirEntry]s.
|
/// [`DirEntry`]s.
|
||||||
pub fn scan_directory(
|
pub fn scan_directory(
|
||||||
dirs: &Path,
|
dirs: &Path,
|
||||||
exts: Option<&BTreeSet<&str>>,
|
exts: Option<&BTreeSet<&str>>,
|
||||||
|
@ -178,11 +246,7 @@ pub fn scan_directory(
|
||||||
// TODO: is there a way to just say `map_or(x, |y| y).thing()` instead of `map_or(x.thing(), |y| y.thing())`?
|
// 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
|
// 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 :(
|
// implements ToString (which they both do). map_or doesn't work on trait objects though :(
|
||||||
error!(
|
error!("{}: {}", path, err.io_error().map_or(err.to_string(), |e| e.to_string()));
|
||||||
"{}: {}",
|
|
||||||
path,
|
|
||||||
err.io_error().map_or(err.to_string(), |e| e.to_string())
|
|
||||||
);
|
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
e.ok()
|
e.ok()
|
||||||
|
@ -206,122 +270,155 @@ pub fn scan_directory(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The number of bytes to read initially.
|
/// Tries to identify the MIME type of a file from a given path.
|
||||||
///
|
|
||||||
/// Rather than reading the entire file all at once into a [`BUF_SIZE`] buffer, it tends to be faster to read a small
|
|
||||||
/// chunk of the file and trying to identify that, proceeding with the larger buffer if that fails. Many file formats
|
|
||||||
/// can be identified with the first few dozen bytes, so the "happy path" will likely be taken in the majority of cases.
|
|
||||||
pub const INITIAL_BUF_SIZE: usize = 128;
|
|
||||||
|
|
||||||
/// The number of bytes to read if the file couldn't be identified from its first [`INITIAL_BUF_SIZE`] bytes.
|
|
||||||
pub const BUF_SIZE: usize = 8192;
|
|
||||||
|
|
||||||
/// Tries to identify the mimetype of a file from a given path.
|
|
||||||
pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
|
pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
|
||||||
let mut buffer = [0; INITIAL_BUF_SIZE];
|
let mut buffer = [0; INITIAL_BUF_SIZE];
|
||||||
let mut file = File::open(path)?;
|
let mut file = File::open(path)?;
|
||||||
|
|
||||||
// read a small amount to start with
|
// read a small amount to start with
|
||||||
file.read(&mut buffer)?;
|
|
||||||
|
|
||||||
let r = db.get_type(&buffer).filter(|mime|
|
let mut read = io::Result::Ok(0);
|
||||||
// some mime types should be investigated further, reading up to BUF_SIZE even if they've been determined already
|
|
||||||
|
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)
|
// 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
|
mime != &mime::TEXT_XML
|
||||||
// another is ZIP - many file formats (DOCX, ODT, JAR...) are just ZIP files with particular data structures.
|
// 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
|
// determining that a file is in one of the MS office formats in particular requires looking quite far into the
|
||||||
// file.
|
// file.
|
||||||
&& mime != &Mime::from_str("application/zip").unwrap()
|
&& mime != &*APPLICATION_ZIP
|
||||||
// doc/ppt/xls files are a subset of what's known as an "OLE2 compound document storage", at least according to
|
// 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
|
// 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.
|
// will allow it to be detected correctly as the appropriate filetype.
|
||||||
&& mime != &Mime::from_str("application/x-ole-storage").unwrap());
|
&& mime != &*APPLICATION_X_OLE_STORAGE);
|
||||||
|
|
||||||
if r.is_some() {
|
if r.is_some() {
|
||||||
return Ok(r);
|
return Ok(r);
|
||||||
}
|
}
|
||||||
|
|
||||||
// attempt to read up to the BUF_SIZE bytes of the file.
|
// attempt to read up to BUF_SIZE bytes of the file.
|
||||||
// we've already read the first 128 bytes into a buffer, but i can't see an obvious way to reuse them in a way that's
|
|
||||||
// faster than simply moving the seek position back to the start of the file and re-reading the whole BUF_SIZE bytes.
|
|
||||||
// for example, reading (BUF_SIZE - INITIAL_BUF_SIZE) bytes, then concatenating the original INITIAL_BUF_SIZE buffer
|
|
||||||
// with this new one would presumably be faster - but it's not. i think it's more expensive to create the iterator,
|
|
||||||
// collect the contents, etc. i'll have to look into this more. i don't at all doubt that there IS a way to do this
|
|
||||||
// efficiently, and i can think of a way in principle, but i'm not sure how to express it in a way that is both
|
|
||||||
// idiomatic/safe and fast.
|
|
||||||
let mut buffer = [0; BUF_SIZE];
|
let mut buffer = [0; BUF_SIZE];
|
||||||
file.seek(SeekFrom::Start(0))?;
|
file.seek(SeekFrom::Start(0))?;
|
||||||
file.read(&mut buffer)?;
|
_ = file.read(&mut buffer)?;
|
||||||
Ok(db.get_type(&buffer))
|
Ok(db.get_type(&buffer))
|
||||||
}
|
}
|
||||||
|
|
||||||
cached! {
|
/// Returns a list of known extensions for this MIME type, if any.
|
||||||
MIMEXT;
|
/// This function uses the [`Mime`]'s "essence" rather than the [`Mime`] itself - [`mime_guess::get_mime_extensions`]
|
||||||
fn mime_extension_lookup(essence: String) -> Option<Vec<String>> = {
|
/// ignores the type suffix, treating "image/svg+xml" as "image/svg", and thus fails to find any extensions. Passing the
|
||||||
// Returns a list of known extensions for this mime type, if any.
|
/// `essence_str` (which includes the suffix) fixes this.
|
||||||
// This function uses the [Mime]'s "essence" rather than the [Mime] itself - mime_guess::get_mime_extensions ignores
|
pub fn mime_extension_lookup(essence: String) -> Option<Vec<String>> {
|
||||||
// the type suffix, treating "image/svg+xml" as "image/svg", and thus fails to find any extensions. Passing the
|
if let Some(exts) = MIMEXT.read().get(&essence) {
|
||||||
// essence_str (which includes the suffix) fixes this.
|
return exts.clone();
|
||||||
// ↑ this is supposed to be a doc comment, but the cached! macro doesn't support that... i would switch to the
|
}
|
||||||
// proc_macro version of cached, but it has a huge number of deps :c
|
|
||||||
|
|
||||||
let essence = essence.as_str();
|
let mut exts = mime_guess::get_mime_extensions_str(essence.as_str());
|
||||||
let mut exts = mime_guess::get_mime_extensions_str(essence);
|
if exts.is_none() {
|
||||||
if exts.is_none() {
|
// no matches :c
|
||||||
// no matches :c
|
// mime_guess' database isn't exactly perfect... there are a lot of times where the db will return "some/x-thing"
|
||||||
// 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.
|
||||||
// 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
|
||||||
// so, if there appear to be no extensions, try replacing "some/x-thing" with "some/thing", or "some/thing" with
|
// "some/x-thing".
|
||||||
// "some/x-thing".
|
if essence.contains("/x-") {
|
||||||
if essence.contains("/x-") {
|
// replace e.g. "application/x-gzip" with "application/gzip"
|
||||||
// replace e.g. "application/x-gzip" with "application/gzip"
|
exts = mime_guess::get_mime_extensions_str(&essence.replace("/x-", "/"));
|
||||||
exts = mime_guess::get_mime_extensions_str(&essence.replace("/x-", "/"));
|
} else {
|
||||||
} else {
|
// replace e.g. "video/mp2t" with "video/x-mp2t"
|
||||||
// replace e.g. "video/mp2t" with "video/x-mp2t"
|
exts = mime_guess::get_mime_extensions_str(&essence.replace('/', "/x-"));
|
||||||
exts = mime_guess::get_mime_extensions_str(&essence.replace("/", "/x-"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match exts {
|
|
||||||
Some(exts) => {
|
|
||||||
let possible_exts: Vec<String> = exts.iter().map(|e| String::from(*e)).collect();
|
|
||||||
|
|
||||||
Some(if essence == mime::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" {
|
|
||||||
// neither xdg-mime nor infer seem to be able to detect office XML files properly...
|
|
||||||
[vec![String::from("zip"), String::from("docx"), String::from("xlsx"), String::from("pptx")], possible_exts].concat()
|
|
||||||
|
|
||||||
} else if essence == "application/x-ms-dos-executable" {
|
|
||||||
// both .dll and .exe files are given the same mime type... but you definitely don't want to rename one to the
|
|
||||||
// other!
|
|
||||||
[vec![String::from("dll"), String::from("exe")], possible_exts].concat()
|
|
||||||
} else {
|
|
||||||
possible_exts
|
|
||||||
})
|
|
||||||
},
|
|
||||||
None => None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,25 +1,61 @@
|
||||||
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
//! The [`Findings`] and [`ScanError`] structs, used for conveying whether a given file was able to be scanned, whether
|
||||||
|
//! its MIME type could be inferred, and whether the file should be renamed.
|
||||||
|
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
#[cfg(feature = "json")]
|
||||||
|
use serde::{ser::SerializeStruct, Serializer};
|
||||||
|
|
||||||
use crate::files::mime_extension_lookup;
|
use crate::files::mime_extension_lookup;
|
||||||
use crate::String;
|
use crate::String;
|
||||||
|
|
||||||
#[cfg(feature = "json")]
|
/// Information about a successfully scanned file.
|
||||||
use serde::{ser::SerializeStruct, Serializer};
|
#[derive(Eq, PartialEq, Debug)]
|
||||||
use std::fmt::{Display, Formatter};
|
|
||||||
|
|
||||||
/// Information about a scanned file.
|
|
||||||
#[derive(Ord, PartialOrd, Eq, PartialEq)]
|
|
||||||
pub struct Findings {
|
pub struct Findings {
|
||||||
/// The location of the scanned file.
|
/// The location of the scanned file.
|
||||||
pub file: PathBuf,
|
pub file: PathBuf,
|
||||||
/// Whether or not the file's extension is valid for its mimetype.
|
/// Whether or not the file's extension is valid for its MIME type.
|
||||||
pub valid: bool,
|
pub valid: bool,
|
||||||
/// The file's mimetype.
|
/// The file's MIME type.
|
||||||
pub mime: Mime,
|
pub mime: Mime,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Findings {
|
||||||
|
/// Returns the recommended extension for this file, if known.
|
||||||
|
pub fn recommended_extension(&self) -> Option<String> {
|
||||||
|
mime_extension_lookup(self.mime.essence_str().into()).map(|extensions| extensions[0].clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the recommended path for this file - i.e. what it should be renamed to - if known.
|
||||||
|
pub fn recommended_path(&self) -> Option<PathBuf> {
|
||||||
|
self
|
||||||
|
.recommended_extension()
|
||||||
|
.map(|ext| self.file.with_extension(ext.as_str()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd<Self> for Findings {
|
||||||
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for Findings {
|
||||||
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
|
// files with no recommended extension should appear first, so that fif outputs the "no known extension for x"
|
||||||
|
// comments before the "mv x y" instructions
|
||||||
|
match (self.recommended_extension(), other.recommended_extension()) {
|
||||||
|
(None, Some(_)) => Ordering::Greater,
|
||||||
|
(Some(_), None) => Ordering::Less,
|
||||||
|
_ => self.file.cmp(&other.file),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "json")]
|
#[cfg(feature = "json")]
|
||||||
impl serde::Serialize for Findings {
|
impl serde::Serialize for Findings {
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
@ -36,19 +72,14 @@ impl serde::Serialize for Findings {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Findings {
|
/// Errors that can occur while scanning a file with [`scan_file`](crate::files::scan_file).
|
||||||
pub fn recommended_extension(&self) -> Option<String> {
|
|
||||||
mime_extension_lookup(self.mime.essence_str().into()).map(|extensions| extensions[0].clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq)]
|
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq)]
|
||||||
#[cfg_attr(feature = "json", derive(serde::Serialize))]
|
#[cfg_attr(feature = "json", derive(serde::Serialize))]
|
||||||
#[cfg_attr(feature = "json", serde(tag = "type", content = "path"))]
|
#[cfg_attr(feature = "json", serde(tag = "type", content = "path"))]
|
||||||
pub enum ScanError<'a> {
|
pub enum ScanError<'a> {
|
||||||
/// Something went wrong while trying to read the given file.
|
/// Something went wrong while trying to read the given file.
|
||||||
File(&'a Path),
|
File(&'a Path),
|
||||||
/// Failed to determine the mimetype of the given file.
|
/// Failed to determine the MIME type of the given file.
|
||||||
Mime(&'a Path),
|
Mime(&'a Path),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,7 +90,7 @@ impl<'a> Display for ScanError<'a> {
|
||||||
"Couldn't {} file: {}",
|
"Couldn't {} file: {}",
|
||||||
match self {
|
match self {
|
||||||
Self::File(_) => "read",
|
Self::File(_) => "read",
|
||||||
Self::Mime(_) => "determine mime type of",
|
Self::Mime(_) => "determine MIME type of",
|
||||||
},
|
},
|
||||||
match self {
|
match self {
|
||||||
Self::File(f) | Self::Mime(f) => f.to_string_lossy(),
|
Self::File(f) | Self::Mime(f) => f.to_string_lossy(),
|
||||||
|
|
155
src/formats.rs
155
src/formats.rs
|
@ -1,4 +1,9 @@
|
||||||
//! The various formats that [fif](crate) can output to.
|
// 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::ffi::OsStr;
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
|
@ -7,15 +12,14 @@ use std::os::unix::ffi::OsStrExt;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
use itertools::{Either, Itertools};
|
|
||||||
use snailquote::escape;
|
use snailquote::escape;
|
||||||
|
|
||||||
use crate::findings::ScanError;
|
use crate::findings::ScanError;
|
||||||
use crate::utils::clap_long_version;
|
use crate::utils::CLAP_LONG_VERSION;
|
||||||
use crate::Findings;
|
use crate::Findings;
|
||||||
use crate::String;
|
use crate::String;
|
||||||
|
|
||||||
/// A macro for creating an array of `Writable`s without needing to pepper your code with `into()`s.
|
/// A macro for creating an array of [`Writable`]s without needing to pepper your code with `into()`s.
|
||||||
/// # Usage
|
/// # Usage
|
||||||
/// ```
|
/// ```
|
||||||
/// use crate::fif::writables;
|
/// use crate::fif::writables;
|
||||||
|
@ -27,7 +31,6 @@ use crate::String;
|
||||||
/// // ...just use:
|
/// // ...just use:
|
||||||
/// smart_write(&mut f, writables!["hello", Newline]);
|
/// smart_write(&mut f, writables!["hello", Newline]);
|
||||||
/// ```
|
/// ```
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! writables {
|
macro_rules! writables {
|
||||||
[$($args:tt),+] => {
|
[$($args:tt),+] => {
|
||||||
|
@ -44,17 +47,14 @@ macro_rules! writables {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
/// Does the same thing as [writables], but adds a Newline to the end.
|
/// Does the same thing as [`writables`], but adds a Newline to the end.
|
||||||
macro_rules! writablesln {
|
macro_rules! writablesln {
|
||||||
[$($args:tt),+] => {
|
[$($args:tt),+] => {
|
||||||
&[$(writables!(@do $args),)* writables!(@do Newline)]
|
&[$(writables!(@do $args),)* writables!(@do Newline)]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
type Entries<'a> = [Result<Findings, ScanError<'a>>];
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
|
||||||
pub enum Writable<'a> {
|
pub enum Writable<'a> {
|
||||||
String(&'a str),
|
String(&'a str),
|
||||||
Path(&'a Path),
|
Path(&'a Path),
|
||||||
|
@ -63,18 +63,18 @@ pub enum Writable<'a> {
|
||||||
|
|
||||||
// the lifetime of a lifetime
|
// the lifetime of a lifetime
|
||||||
impl<'a> From<&'a str> for Writable<'a> {
|
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 Path> for Writable<'a> {
|
impl<'a> From<&'a Path> for Writable<'a> {
|
||||||
fn from(p: &'a Path) -> Writable<'a> { Writable::Path(p) }
|
fn from(p: &'a Path) -> Self { Writable::Path(p) }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> From<&'a OsStr> for Writable<'a> {
|
impl<'a> From<&'a OsStr> for Writable<'a> {
|
||||||
fn from(p: &'a OsStr) -> Writable<'a> { Writable::Path(p.as_ref()) }
|
fn from(p: &'a OsStr) -> Self { Writable::Path(p.as_ref()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generated_by() -> String { format!("Generated by fif {}", clap_long_version()).into() }
|
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<()> {
|
pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
|
||||||
// ehhhh
|
// ehhhh
|
||||||
|
@ -89,7 +89,7 @@ pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Writable::String(s) => write!(f, "{}", s)?,
|
Writable::String(s) => write!(f, "{s}")?,
|
||||||
Writable::Path(path) => {
|
Writable::Path(path) => {
|
||||||
if let Some(path_str) = path.to_str() {
|
if let Some(path_str) = path.to_str() {
|
||||||
let escaped = escape(path_str);
|
let escaped = escape(path_str);
|
||||||
|
@ -97,9 +97,9 @@ pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<(
|
||||||
// the escaped string is the same as the input - this will occur for inputs like "file.txt" which don't
|
// 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
|
// need to be escaped. however, it's Best Practice™ to escape such strings anyway, so we prefix/suffix the
|
||||||
// escaped string with single quotes.
|
// escaped string with single quotes.
|
||||||
write!(f, "'{}'", escaped)?;
|
write!(f, "'{escaped}'")?;
|
||||||
} else {
|
} else {
|
||||||
write!(f, "{}", escaped)?;
|
write!(f, "{escaped}")?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
write!(f, "'")?;
|
write!(f, "'")?;
|
||||||
|
@ -110,7 +110,7 @@ pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<(
|
||||||
// f.write_all(&*path.as_os_str().encode_wide().collect::<Vec<u16>>())?;
|
// f.write_all(&*path.as_os_str().encode_wide().collect::<Vec<u16>>())?;
|
||||||
write!(f, "{}", path.as_os_str().to_string_lossy())?;
|
write!(f, "{}", path.as_os_str().to_string_lossy())?;
|
||||||
} else {
|
} else {
|
||||||
f.write_all(&*path.as_os_str().as_bytes())?;
|
f.write_all(path.as_os_str().as_bytes())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
write!(f, "'")?;
|
write!(f, "'")?;
|
||||||
|
@ -126,63 +126,48 @@ pub trait FormatSteps {
|
||||||
fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &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 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 unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
|
||||||
fn header<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()>;
|
fn header<W: Write>(&self, _f: &mut W) -> io::Result<()>;
|
||||||
fn footer<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()>;
|
fn footer<W: Write>(&self, _f: &mut W) -> io::Result<()>;
|
||||||
fn write_steps<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
|
fn write_steps<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
|
||||||
self.header(f, entries)?;
|
self.header(f)?;
|
||||||
|
|
||||||
// output will be generated in the order:
|
|
||||||
// - files that couldn't be read
|
|
||||||
// - files with no known mime type
|
|
||||||
// - files with no known extension
|
|
||||||
// - files with a known extension
|
|
||||||
// files that already have a correct extension won't be represented in the output.
|
|
||||||
|
|
||||||
// sort errors so unreadable files appear before files with unknown mimetypes - ScanError impls Ord such that
|
|
||||||
// ScanError::File > ScanError::Mime
|
|
||||||
let errors = entries.iter().filter_map(|e| e.as_ref().err()).sorted_unstable();
|
|
||||||
// sort files so that files with no known extension come before those with known extensions - None > Some("jpg")
|
|
||||||
let findings = entries
|
|
||||||
.iter()
|
|
||||||
.filter_map(|e| e.as_ref().ok())
|
|
||||||
.sorted_unstable_by(|a, b| b.recommended_extension().cmp(&a.recommended_extension()).reverse());
|
|
||||||
|
|
||||||
for error in errors {
|
for error in errors {
|
||||||
match error {
|
match error {
|
||||||
// failed to read the file
|
// failed to read the file
|
||||||
ScanError::File(path) => self.unreadable(f, path)?,
|
ScanError::File(path) => self.unreadable(f, path)?,
|
||||||
// file was read successfully, but we couldn't determine a mimetype
|
// file was read successfully, but we couldn't determine a MIME type
|
||||||
ScanError::Mime(path) => self.unknown_type(f, path)?,
|
ScanError::Mime(path) => self.unknown_type(f, path)?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if findings.len() != entries.len() {
|
if !errors.is_empty() {
|
||||||
// if these lengths aren't the same, there was at least one error
|
|
||||||
// add a blank line between the errors and commands
|
// add a blank line between the errors and commands
|
||||||
smart_write(f, writables![Newline])?;
|
smart_write(f, writables![Newline])?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for finding in findings {
|
for finding in findings {
|
||||||
if let Some(ext) = finding.recommended_extension() {
|
if let Some(name) = finding.recommended_path() {
|
||||||
self.rename(f, finding.file.as_path(), &finding.file.with_extension(ext.as_str()))?;
|
self.rename(f, finding.file.as_path(), &name)?;
|
||||||
} else {
|
} else {
|
||||||
self.no_known_extension(f, finding.file.as_path())?;
|
self.no_known_extension(f, finding.file.as_path())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.footer(f, entries)
|
self.footer(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait Format {
|
pub trait Format {
|
||||||
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()>;
|
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bourne-Shell compatible script.
|
/// Bourne-Shell compatible script.
|
||||||
pub struct Shell;
|
pub struct Shell;
|
||||||
|
|
||||||
impl Format for Shell {
|
impl Format for Shell {
|
||||||
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
|
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 {
|
impl FormatSteps for Shell {
|
||||||
|
@ -193,14 +178,7 @@ impl FormatSteps for Shell {
|
||||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||||
smart_write(
|
smart_write(
|
||||||
f,
|
f,
|
||||||
writablesln![
|
writablesln!["cat <<- '???'", Newline, "No known extension for ", path, Newline, "???"],
|
||||||
"cat <<- '???'",
|
|
||||||
Newline,
|
|
||||||
"No known extension for ",
|
|
||||||
path,
|
|
||||||
Newline,
|
|
||||||
"???"
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -209,25 +187,21 @@ impl FormatSteps for Shell {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||||
smart_write(f, writablesln!["# Failed to detect mime type for ", path])
|
smart_write(f, writablesln!["# Failed to detect MIME type for ", path])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn header<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
|
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||||
smart_write(
|
smart_write(f, writablesln!["#!/usr/bin/env sh", Newline, "# ", (generated_by().as_str())])?;
|
||||||
f,
|
|
||||||
writablesln!["#!/usr/bin/env sh", Newline, "# ", (generated_by().as_str())],
|
|
||||||
)?;
|
|
||||||
|
|
||||||
if let Ok(working_directory) = std::env::current_dir() {
|
if let Ok(working_directory) = std::env::current_dir() {
|
||||||
smart_write(f, writablesln!["# Run from ", (working_directory.as_path())])?;
|
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])
|
smart_write(f, writablesln![Newline, "set -e", Newline])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn footer<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
|
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> { smart_write(f, writablesln![Newline, "echo 'Done.'"]) }
|
||||||
smart_write(f, writablesln![Newline, "echo 'Done.'"])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PowerShell is a noun, not a type
|
// PowerShell is a noun, not a type
|
||||||
|
@ -236,7 +210,9 @@ impl FormatSteps for Shell {
|
||||||
pub struct PowerShell;
|
pub struct PowerShell;
|
||||||
|
|
||||||
impl Format for PowerShell {
|
impl Format for PowerShell {
|
||||||
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
|
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 {
|
impl FormatSteps for PowerShell {
|
||||||
|
@ -246,26 +222,14 @@ impl FormatSteps for PowerShell {
|
||||||
// there doesn't seem to be a way to rename the file, prompting only if the target already exists.
|
// there doesn't seem to be a way to rename the file, prompting only if the target already exists.
|
||||||
smart_write(
|
smart_write(
|
||||||
f,
|
f,
|
||||||
writablesln![
|
writablesln!["Rename-Item -Verbose -Path ", from, " -NewName ", (to.file_name().unwrap())],
|
||||||
"Rename-Item -Verbose -Path ",
|
|
||||||
from,
|
|
||||||
" -NewName ",
|
|
||||||
(to.file_name().unwrap())
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||||
smart_write(
|
smart_write(
|
||||||
f,
|
f,
|
||||||
writablesln![
|
writablesln!["Write-Output @'", Newline, "No known extension for ", path, Newline, "'@"],
|
||||||
"Write-Output @'",
|
|
||||||
Newline,
|
|
||||||
"No known extension for ",
|
|
||||||
path,
|
|
||||||
Newline,
|
|
||||||
"'@"
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -277,10 +241,10 @@ impl FormatSteps for PowerShell {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
|
||||||
smart_write(f, writablesln!["<# Failed to detect mime type for ", path, " #>"])
|
smart_write(f, writablesln!["<# Failed to detect MIME type for ", path, " #>"])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn header<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
|
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||||
smart_write(
|
smart_write(
|
||||||
f,
|
f,
|
||||||
writablesln!["#!/usr/bin/env pwsh", Newline, "<# ", (generated_by().as_str()), " #>"],
|
writablesln!["#!/usr/bin/env pwsh", Newline, "<# ", (generated_by().as_str()), " #>"],
|
||||||
|
@ -289,18 +253,21 @@ impl FormatSteps for PowerShell {
|
||||||
if let Ok(working_directory) = std::env::current_dir() {
|
if let Ok(working_directory) = std::env::current_dir() {
|
||||||
smart_write(f, writablesln!["<# Run from ", (working_directory.as_path()), " #>"])?;
|
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])
|
smart_write(f, writables![Newline])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn footer<W: Write>(&self, f: &mut W, _: &Entries) -> io::Result<()> {
|
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||||
smart_write(f, writablesln![Newline, "Write-Output 'Done!'"])
|
smart_write(f, writablesln![Newline, "Write-Output 'Done!'"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Text;
|
pub struct Text;
|
||||||
impl Format for Text {
|
impl Format for Text {
|
||||||
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
|
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 {
|
impl FormatSteps for Text {
|
||||||
|
@ -320,14 +287,19 @@ impl FormatSteps for Text {
|
||||||
smart_write(f, writablesln!["Couldn't determine type for ", path])
|
smart_write(f, writablesln!["Couldn't determine type for ", path])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn header<W: Write>(&self, f: &mut W, _entries: &Entries) -> io::Result<()> {
|
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||||
smart_write(f, writablesln![(generated_by().as_str()), Newline])
|
smart_write(f, writablesln![(generated_by().as_str()), Newline])?;
|
||||||
|
if let Ok(working_directory) = std::env::current_dir() {
|
||||||
|
smart_write(f, writablesln!["Run from ", (working_directory.as_path())])?;
|
||||||
|
}
|
||||||
|
write!(f, "Happy with these changes? Run `fif --fix` from the same directory!")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn footer<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
|
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
|
||||||
smart_write(
|
smart_write(
|
||||||
f,
|
f,
|
||||||
writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
|
// writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
|
||||||
|
&[Writable::Newline],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -337,18 +309,13 @@ pub struct Json;
|
||||||
|
|
||||||
#[cfg(feature = "json")]
|
#[cfg(feature = "json")]
|
||||||
impl Format for Json {
|
impl Format for Json {
|
||||||
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
|
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
struct SerdeEntries<'a> {
|
struct SerdeEntries<'a> {
|
||||||
errors: &'a Vec<&'a ScanError<'a>>,
|
errors: &'a [ScanError<'a>],
|
||||||
findings: &'a Vec<&'a Findings>,
|
findings: &'a [Findings],
|
||||||
}
|
}
|
||||||
|
|
||||||
let (errors, findings) = &entries.iter().partition_map(|entry| match entry {
|
|
||||||
Err(e) => Either::Left(e),
|
|
||||||
Ok(f) => Either::Right(f),
|
|
||||||
});
|
|
||||||
|
|
||||||
let result = serde_json::to_writer_pretty(f, &SerdeEntries { errors, findings });
|
let result = serde_json::to_writer_pretty(f, &SerdeEntries { errors, findings });
|
||||||
|
|
||||||
if let Err(err) = result {
|
if let Err(err) = result {
|
||||||
|
|
60
src/lib.rs
60
src/lib.rs
|
@ -1,5 +1,21 @@
|
||||||
|
// 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)]
|
#![forbid(unsafe_code)]
|
||||||
#![warn(trivial_casts, unused_lifetimes, unused_qualifications)]
|
#![warn(
|
||||||
|
trivial_casts,
|
||||||
|
unused_lifetimes,
|
||||||
|
unused_qualifications,
|
||||||
|
missing_copy_implementations,
|
||||||
|
unused_allocation
|
||||||
|
)]
|
||||||
|
|
||||||
pub mod files;
|
pub mod files;
|
||||||
pub mod findings;
|
pub mod findings;
|
||||||
|
@ -8,45 +24,33 @@ pub mod mime_db;
|
||||||
pub mod parameters;
|
pub mod parameters;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use crate::findings::Findings;
|
use crate::findings::Findings;
|
||||||
use crate::mime_db::MimeDb;
|
use crate::mime_db::MimeDb;
|
||||||
|
|
||||||
use cfg_if::cfg_if;
|
|
||||||
use once_cell::sync::OnceCell;
|
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
if #[cfg(not(all(target_endian = "big", target_pointer_width = "32")))] {
|
if #[cfg(not(all(target_endian = "big", target_pointer_width = "32")))] {
|
||||||
// most architectures
|
/// 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;
|
pub use smartstring::alias::String;
|
||||||
} else {
|
} else {
|
||||||
// powerpc and other big endian 32-bit archs
|
/// 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;
|
pub use std::string::String;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
||||||
/// A [OnceCell] holding an instance of [mime_db::MimeDb].
|
/// A [`Lazy`] holding an instance of [`mime_db::MimeDb`]. Initialised at program startup.
|
||||||
pub static MIMEDB: OnceCell<mime_db::InferDb> = OnceCell::new();
|
pub static MIMEDB: Lazy<mime_db::InferDb> = Lazy::new(mime_db::InferDb::init);
|
||||||
} else {
|
} else {
|
||||||
/// A [OnceCell] holding an instance of [mime_db::MimeDb].
|
/// A [`Lazy`] holding an instance of [`mime_db::MimeDb`]. Initialised at program startup.
|
||||||
pub static MIMEDB: OnceCell<mime_db::XdgDb> = OnceCell::new();
|
pub static MIMEDB: Lazy<mime_db::XdgDb> = Lazy::new(mime_db::XdgDb::init);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initialises [`MIMEDB`] with a value dependent on the current backend.
|
|
||||||
pub fn init_db() {
|
|
||||||
cfg_if! {
|
|
||||||
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
|
||||||
MIMEDB
|
|
||||||
.set(crate::mime_db::InferDb::init())
|
|
||||||
.or(Err("Failed to initialise Infer backend!"))
|
|
||||||
.unwrap();
|
|
||||||
} else {
|
|
||||||
MIMEDB
|
|
||||||
.set(crate::mime_db::XdgDb::init())
|
|
||||||
.or(Err("Failed to initialise XDG Mime backend!"))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
221
src/main.rs
221
src/main.rs
|
@ -1,45 +1,40 @@
|
||||||
|
// 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.
|
// fif - a command-line tool for detecting and optionally correcting files with incorrect extensions.
|
||||||
// Copyright (C) 2021 Lynnesbian
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU General Public License as published by
|
|
||||||
// the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
#![warn(trivial_casts, unused_lifetimes, unused_qualifications)]
|
#![warn(
|
||||||
|
trivial_casts,
|
||||||
|
unused_lifetimes,
|
||||||
|
unused_qualifications,
|
||||||
|
missing_copy_implementations,
|
||||||
|
unused_allocation
|
||||||
|
)]
|
||||||
|
|
||||||
use std::io::{stdout, BufWriter, Write};
|
use std::io::{stdin, stdout, BufWriter, Write};
|
||||||
use std::process::exit;
|
use std::process::exit;
|
||||||
|
|
||||||
use clap::Clap;
|
use cfg_if::cfg_if;
|
||||||
use log::{debug, error, info, trace, warn, Level};
|
use clap::Parser;
|
||||||
|
|
||||||
use fif::files::{scan_directory, scan_from_walkdir};
|
use fif::files::{scan_directory, scan_from_walkdir};
|
||||||
use fif::formats::Format;
|
use fif::formats::{self, Format};
|
||||||
use fif::parameters::OutputFormat;
|
use fif::parameters::{self, OutputFormat, Prompt};
|
||||||
use fif::utils::{clap_long_version, os_name};
|
use fif::utils::{os_name, CLAP_LONG_VERSION};
|
||||||
use fif::{formats, init_db, parameters};
|
use itertools::Itertools;
|
||||||
|
use log::{debug, error, info, trace, warn, Level};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
#[allow(clippy::cognitive_complexity)]
|
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
|
||||||
fn main() {
|
fn main() {
|
||||||
let args: parameters::Parameters = parameters::Parameters::parse();
|
let args: parameters::Parameters = parameters::Parameters::parse();
|
||||||
|
|
||||||
let mut builder = env_logger::Builder::new();
|
let mut builder = env_logger::Builder::new();
|
||||||
builder
|
builder
|
||||||
.filter_level(args.default_verbosity()) // set default log level
|
.filter_level(args.get_verbosity()) // set default log level
|
||||||
.parse_default_env() // set log level from RUST_LOG
|
.parse_default_env() // set log level from RUST_LOG
|
||||||
.parse_env("FIF_LOG") // set log level from FIF_LOG
|
.parse_env("FIF_LOG") // set log level from FIF_LOG
|
||||||
.format(|buf, r| {
|
.format(|buf, r| {
|
||||||
|
@ -55,12 +50,10 @@ fn main() {
|
||||||
|
|
||||||
trace!(
|
trace!(
|
||||||
"fif {}, running on {} {}",
|
"fif {}, running on {} {}",
|
||||||
clap_long_version(),
|
CLAP_LONG_VERSION.as_str(),
|
||||||
std::env::consts::ARCH,
|
std::env::consts::ARCH,
|
||||||
os_name()
|
os_name()
|
||||||
);
|
);
|
||||||
trace!("Initialising mimetype database");
|
|
||||||
init_db();
|
|
||||||
|
|
||||||
debug!("Iterating directory: {:?}", args.dir);
|
debug!("Iterating directory: {:?}", args.dir);
|
||||||
|
|
||||||
|
@ -90,54 +83,156 @@ fn main() {
|
||||||
|
|
||||||
trace!("Found {} items to check", entries.len());
|
trace!("Found {} items to check", entries.len());
|
||||||
|
|
||||||
let results: Vec<_> = scan_from_walkdir(&entries, args.canonical_paths)
|
cfg_if! {
|
||||||
.into_iter()
|
if #[cfg(feature = "multi-threaded")] {
|
||||||
.filter(
|
let use_threads = args.jobs != 1;
|
||||||
|result| result.is_err() || !result.as_ref().unwrap().valid,
|
|
||||||
// TODO: find a way to trace! the valid files without doing ↓
|
|
||||||
// || if result.as_ref().unwrap().valid { trace!("{:?} ok", result.as_ref().unwrap().file); false } else { true }
|
|
||||||
)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
trace!("Scanning complete");
|
if use_threads {
|
||||||
|
// 0 is a special case - it should be understood to mean "all available host CPUs"
|
||||||
|
let jobs = if args.jobs == 0 { num_cpus::get() } else { args.jobs };
|
||||||
|
|
||||||
for result in &results {
|
// set up the global thread pool with the requested number of threads
|
||||||
match result {
|
rayon::ThreadPoolBuilder::new().num_threads(jobs).build_global().unwrap();
|
||||||
Ok(r) => {
|
trace!("Multithreading enabled, using {} threads", jobs);
|
||||||
debug!(
|
} else {
|
||||||
"{:?} is of type {}, should have extension \"{}\"",
|
trace!("Multithreading disabled at runtime");
|
||||||
r.file,
|
|
||||||
r.mime,
|
|
||||||
r.recommended_extension().unwrap_or_else(|| "???".into())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Err(f) => warn!("{}", f),
|
|
||||||
|
} else { // `multi-threading` feature disabled
|
||||||
|
let use_threads = false;
|
||||||
|
trace!("Multithreading disabled at compile time");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if results.is_empty() {
|
let (findings, errors) = scan_from_walkdir(&entries, args.canonical_paths, use_threads);
|
||||||
|
trace!("Scanning complete");
|
||||||
|
|
||||||
|
if findings.is_empty() && errors.is_empty() {
|
||||||
info!("All files have valid extensions!");
|
info!("All files have valid extensions!");
|
||||||
exit(exitcode::OK);
|
exit(exitcode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut buffered_stdout = BufWriter::new(stdout());
|
// remove files that already have the correct extension, then sort - first by whether or not they have a
|
||||||
|
// recommended_extension() (with None before Some(ext)), then by filename
|
||||||
|
let findings = findings
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| !f.valid)
|
||||||
|
.sorted_unstable()
|
||||||
|
.collect_vec();
|
||||||
|
// sort errors (File errors before Mime errors), then log a warning for each error
|
||||||
|
let errors = errors
|
||||||
|
.into_iter()
|
||||||
|
.sorted_unstable()
|
||||||
|
.map(|e| {
|
||||||
|
warn!("{}", &e);
|
||||||
|
e
|
||||||
|
})
|
||||||
|
.collect_vec();
|
||||||
|
|
||||||
let result = match args.output_format {
|
if args.fix {
|
||||||
OutputFormat::Sh => formats::Shell.write_all(&mut buffered_stdout, &results),
|
fn ask(message: &str) -> bool {
|
||||||
OutputFormat::PowerShell => formats::PowerShell.write_all(&mut buffered_stdout, &results),
|
let mut buf = String::with_capacity(1);
|
||||||
#[cfg(feature = "json")]
|
print!("{message} [y/N] ");
|
||||||
OutputFormat::Json => formats::Json.write_all(&mut buffered_stdout, &results),
|
|
||||||
OutputFormat::Text => formats::Text.write_all(&mut buffered_stdout, &results),
|
|
||||||
};
|
|
||||||
|
|
||||||
if result.is_err() {
|
// flush stdout to ensure message is displayed
|
||||||
error!("Failed to write to stdout.");
|
stdout().flush().expect("Failed to flush stdout");
|
||||||
exit(exitcode::IOERR);
|
|
||||||
}
|
|
||||||
|
|
||||||
if buffered_stdout.flush().is_err() {
|
if let Err(e) = stdin().read_line(&mut buf) {
|
||||||
error!("Failed to flush stdout.");
|
// something went wrong while reading input - just exit
|
||||||
exit(exitcode::IOERR);
|
error!("{}", e);
|
||||||
|
exit(exitcode::IOERR)
|
||||||
|
}
|
||||||
|
buf.starts_with('y') || buf.starts_with('Y')
|
||||||
|
}
|
||||||
|
|
||||||
|
let prompt = args.prompt.unwrap_or(Prompt::Error);
|
||||||
|
|
||||||
|
let mut renamed = 0_u32; // files that were successfully renamed
|
||||||
|
let mut skipped = 0_u32; // files that were skipped over without trying to rename
|
||||||
|
let mut failed = 0_u32; // files that fif failed to rename - e.g. files that are exclusively locked
|
||||||
|
|
||||||
|
for f in findings {
|
||||||
|
if let Some(rename_to) = f.recommended_path() {
|
||||||
|
let will_rename = {
|
||||||
|
if !args.overwrite && rename_to.exists() {
|
||||||
|
// handles: --prompt never, --prompt error, --prompt always
|
||||||
|
// user didn't specify --overwrite, and the destination exists
|
||||||
|
info!("Not renaming {:#?}: Target {:#?} exists", f.file, rename_to);
|
||||||
|
false
|
||||||
|
} else if prompt == Prompt::Never {
|
||||||
|
// handles: --prompt never --overwrite
|
||||||
|
// user specified --prompt never in conjunction with --overwrite, so always rename
|
||||||
|
true
|
||||||
|
} else if prompt == Prompt::Error || ask(&format!("Rename {:#?} to {:#?}?", &f.file, &rename_to)) {
|
||||||
|
// handles: --prompt error --overwrite, --prompt always --overwrite [y]
|
||||||
|
// if the target exists, prompt before renaming; otherwise, just rename
|
||||||
|
!rename_to.exists() || ask(&format!("Destination {rename_to:#?} already exists, overwrite?"))
|
||||||
|
} else {
|
||||||
|
// handles: --prompt always --overwrite [n]
|
||||||
|
// user was prompted and replied "no"
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !will_rename {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// until file is renamed successfully
|
||||||
|
match std::fs::rename(&f.file, &rename_to) {
|
||||||
|
Ok(()) => {
|
||||||
|
info!("Renamed {:#?} -> {:#?}", f.file, rename_to);
|
||||||
|
renamed += 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Couldn't rename {:#?} to {:#?}: {:#?}", f.file, rename_to, e);
|
||||||
|
// if the user passed --prompt never, continue to the next file
|
||||||
|
// otherwise, prompt user to retry move, retrying until the rename succeeds or they respond "N"
|
||||||
|
if prompt == Prompt::Never || !ask(&format!("Error while renaming file: {e:#?}. Try again?")) {
|
||||||
|
failed += 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// no recommended name :c
|
||||||
|
info!("No known extension for file {:#?} of type {}", f.file, f.mime);
|
||||||
|
skipped += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"Processed {} files: Renamed {}, skipped {}, failed to rename {}",
|
||||||
|
renamed + skipped + failed,
|
||||||
|
renamed,
|
||||||
|
skipped,
|
||||||
|
failed
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
let mut buffered_stdout = BufWriter::new(stdout());
|
||||||
|
|
||||||
|
if match args.output_format {
|
||||||
|
// TODO: simplify this to something like formats::write_all(args.output_format, ...)
|
||||||
|
OutputFormat::Sh => formats::Shell.write_all(&mut buffered_stdout, &findings, &errors),
|
||||||
|
OutputFormat::PowerShell => formats::PowerShell.write_all(&mut buffered_stdout, &findings, &errors),
|
||||||
|
#[cfg(feature = "json")]
|
||||||
|
OutputFormat::Json => formats::Json.write_all(&mut buffered_stdout, &findings, &errors),
|
||||||
|
OutputFormat::Text => formats::Text.write_all(&mut buffered_stdout, &findings, &errors),
|
||||||
|
}
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
error!("Failed to write to stdout.");
|
||||||
|
exit(exitcode::IOERR);
|
||||||
|
}
|
||||||
|
|
||||||
|
if buffered_stdout.flush().is_err() {
|
||||||
|
error!("Failed to flush stdout.");
|
||||||
|
exit(exitcode::IOERR);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("Done");
|
debug!("Done");
|
||||||
|
|
|
@ -1,10 +1,24 @@
|
||||||
//! Backend-neutral Mime database implementation.
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
//! Backend-neutral Mime database abstraction.
|
||||||
|
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
|
||||||
|
/// A thin wrapper around either [`Infer`] or [`xdg-mime::SharedMimeInfo`], depending on which [cargo features]
|
||||||
|
/// fif was compiled with. By default, fif uses an [`Infer`]-based implementation on Windows, and an
|
||||||
|
/// [`xdg-mime`]-based one everywhere else. This behaviour can be changed at compile time by using the aforementioned
|
||||||
|
/// [cargo features].
|
||||||
|
///
|
||||||
|
/// [cargo features]: https://gitlab.com/Lynnesbian/fif/-/wikis/Cargo-Features
|
||||||
|
/// [`Infer`]: https://docs.rs/infer/
|
||||||
|
/// [`xdg-mime::SharedMimeInfo`]: https://docs.rs/xdg-mime/0/xdg_mime/struct.SharedMimeInfo.html
|
||||||
|
/// [`xdg-mime`]: https://docs.rs/xdg-mime/
|
||||||
pub trait MimeDb {
|
pub trait MimeDb {
|
||||||
|
/// Initialise the database.
|
||||||
fn init() -> Self;
|
fn init() -> Self;
|
||||||
|
/// Given a slice of bytes, returns the inferred MIME type, if any.
|
||||||
fn get_type(&self, data: &[u8]) -> Option<Mime>;
|
fn get_type(&self, data: &[u8]) -> Option<Mime>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -12,12 +26,13 @@ cfg_if! {
|
||||||
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// The [`Infer`](https://docs.rs/infer/)-based implementation of [`MimeDb`].
|
||||||
pub struct InferDb {
|
pub struct InferDb {
|
||||||
db: infer::Infer,
|
db: infer::Infer,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_document_check(buf: &[u8], kind: &str) -> bool {
|
fn open_document_check(buf: &[u8], kind: &str) -> bool {
|
||||||
let mime = format!("application/vnd.oasis.opendocument.{}", kind);
|
let mime = format!("application/vnd.oasis.opendocument.{kind}");
|
||||||
let mime = mime.as_bytes();
|
let mime = mime.as_bytes();
|
||||||
|
|
||||||
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
|
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
|
||||||
|
@ -27,40 +42,56 @@ cfg_if! {
|
||||||
fn init() -> Self {
|
fn init() -> Self {
|
||||||
let mut info = infer::Infer::new();
|
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| {
|
info.add("application/vnd.oasis.opendocument.text", "odt", |buf| {
|
||||||
open_document_check(buf, "text")
|
open_document_check(buf, "text")
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// OpenDocument Spreadsheet (LibreOffice Calc)
|
||||||
info.add("application/vnd.oasis.opendocument.spreadsheet", "ods", |buf| {
|
info.add("application/vnd.oasis.opendocument.spreadsheet", "ods", |buf| {
|
||||||
open_document_check(buf, "spreadsheet")
|
open_document_check(buf, "spreadsheet")
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// OpenOffice Presentation (LibreOffice Impress)
|
||||||
info.add("application/vnd.oasis.opendocument.presentation", "odp", |buf| {
|
info.add("application/vnd.oasis.opendocument.presentation", "odp", |buf| {
|
||||||
open_document_check(buf, "presentation")
|
open_document_check(buf, "presentation")
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Ren'Py Archive (Ren'Py: https://www.renpy.org/)
|
||||||
info.add("application/x-rpa", "rpa", |buf| {
|
info.add("application/x-rpa", "rpa", |buf| {
|
||||||
buf.len() >= 34 && buf.starts_with(b"RPA-") && buf[7] == b' ' && buf[24] ==b' '
|
buf.len() >= 34 && buf.starts_with(b"RPA-") && buf[7] == b' ' && buf[24] ==b' '
|
||||||
});
|
});
|
||||||
|
|
||||||
info.add("audio/x-aiff", "aiff", |buf| {
|
// Mach-O Binaries (The executable format used by macOS)
|
||||||
// as added by https://github.com/bojand/infer/pull/48/files
|
// my source for most of this info is this article: https://h3adsh0tzz.com/2020/01/macho-file-format/
|
||||||
// this should be removed when (if) that PR is accepted
|
info.add("application/x-mach-binary", "macho", |buf| {
|
||||||
buf.len() > 11
|
// a 32-bit mach-o header occupies 28 bits of space, so any input smaller than that cannot be a mach-o
|
||||||
&& buf[0] == 0x46
|
// binary, even if it starts with the magic numbers.
|
||||||
&& buf[1] == 0x4F
|
|
||||||
&& buf[2] == 0x52
|
// java class files also start with 0xCAFEBABE. since infer doesn't support detecting these files,
|
||||||
&& buf[3] == 0x4D
|
// collisions are not an issue. if, however, infer does gain support for identifying java class files, the
|
||||||
&& buf[8] == 0x41
|
// 0xCAFEBABE check should be removed, as java bytecode files are far more prevalent than 32-bit universal
|
||||||
&& buf[9] == 0x49
|
// mach-o binaries [citation needed].
|
||||||
&& buf[10] == 0x46
|
|
||||||
&& buf[11] == 0x46
|
// 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| {
|
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,
|
// before doing the moderately expensive SVG check, we should make sure that the input is actually SGML-ish,
|
||||||
// by which i mean, starts with anywhere from zero to ∞-1 whitespace characters, and then a less than sign,
|
// by which i mean, starts with the pattern "\s*<".
|
||||||
// and then there's some other stuff we don't care about right now
|
|
||||||
|
|
||||||
// so, here comes our fancy pants """""SGML-ish validator"""""
|
// so, here comes our fancy pants """""SGML-ish validator"""""
|
||||||
for c in buf {
|
for c in buf {
|
||||||
|
@ -76,8 +107,8 @@ cfg_if! {
|
||||||
// - split the buffer up into chunks separated by the less than sign
|
// - split the buffer up into chunks separated by the less than sign
|
||||||
// - check to see if this chunk starts with any of these identifiers:
|
// - 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"];
|
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
|
// - if it does, the nested `any` will short circuit and immediately return true, causing the parent `any` to
|
||||||
// the same
|
// do the same
|
||||||
// - and finally, if none of the chunks match, we'll return false
|
// - 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 :(
|
// TODO: this is kind of messy, i'd like to clean it up somehow :(
|
||||||
|
@ -90,10 +121,16 @@ cfg_if! {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_type(&self, data: &[u8]) -> Option<Mime> {
|
fn get_type(&self, data: &[u8]) -> Option<Mime> {
|
||||||
self.db.get(data).map(|f| Mime::from_str(f.mime_type()).unwrap())
|
if let Some(mime) = self.db.get(data) {
|
||||||
|
match Mime::from_str(mime.mime_type()) {
|
||||||
|
Err(_) => None,
|
||||||
|
Ok(m) => Some(m),
|
||||||
|
}
|
||||||
|
} else { None }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
/// The [`xdg-mime`](https://docs.rs/xdg-mime/)-based implementation of [`MimeDb`].
|
||||||
pub struct XdgDb {
|
pub struct XdgDb {
|
||||||
db: xdg_mime::SharedMimeInfo,
|
db: xdg_mime::SharedMimeInfo,
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,21 +1,30 @@
|
||||||
//! [Clap] struct used to parse command line arguments.
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
//! Command line argument parsing logic and associated functions.
|
||||||
|
|
||||||
use crate::utils::{clap_long_version, clap_version};
|
|
||||||
use crate::String as StringType;
|
|
||||||
use cfg_if::cfg_if;
|
|
||||||
use clap::{AppSettings, Clap};
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
use clap::{ArgAction, Parser, ValueEnum};
|
||||||
|
|
||||||
|
use crate::utils::{CLAP_LONG_VERSION, CLAP_VERSION};
|
||||||
|
use crate::String as StringType;
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
if #[cfg(windows)] {
|
if #[cfg(windows)] {
|
||||||
|
/// The default [`OutputFormat`] to use.
|
||||||
const DEFAULT_FORMAT: &str = "powershell";
|
const DEFAULT_FORMAT: &str = "powershell";
|
||||||
} else {
|
} else {
|
||||||
|
/// The default [`OutputFormat`] to use.
|
||||||
const DEFAULT_FORMAT: &str = "sh";
|
const DEFAULT_FORMAT: &str = "sh";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clap, PartialEq, Debug)]
|
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
|
||||||
|
/// The format to use when running fif without the `--fix` flag. Specified at runtime with the `-o`/`--output-format`
|
||||||
|
/// flag.
|
||||||
pub enum OutputFormat {
|
pub enum OutputFormat {
|
||||||
/// A Bourne shell compatible script.
|
/// A Bourne shell compatible script.
|
||||||
#[clap(alias = "shell", alias = "bash")]
|
#[clap(alias = "shell", alias = "bash")]
|
||||||
|
@ -30,29 +39,54 @@ pub enum OutputFormat {
|
||||||
Json,
|
Json,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clap, Debug)]
|
#[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)]
|
#[allow(clippy::struct_excessive_bools)]
|
||||||
#[clap(
|
#[clap(
|
||||||
version = clap_version(),
|
version = CLAP_VERSION.as_str(),
|
||||||
long_version = clap_long_version(),
|
long_version = CLAP_LONG_VERSION.as_str(),
|
||||||
author = option_env!("CARGO_PKG_AUTHORS").unwrap_or("Lynnesbian"),
|
author = option_env!("CARGO_PKG_AUTHORS").unwrap_or("Lynnesbian"),
|
||||||
about = option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("File Info Fixer"),
|
about = option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("File Info Fixer"),
|
||||||
before_help = "Copyright © 2021 Lynnesbian under the GPL3 (or later) License.",
|
before_help = "Copyright © 2021-2024 Lynnesbian under the GPL3 (or later) License.",
|
||||||
before_long_help = "Copyright © 2021 Lynnesbian\n\
|
after_long_help = "Copyright © 2021-2024 Lynnesbian\n\
|
||||||
This program is free software: you can redistribute it and/or modify \
|
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 \
|
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.",
|
of the License, or (at your option) any later version.",
|
||||||
setting(AppSettings::ColoredHelp)
|
max_term_width = 120
|
||||||
)]
|
)]
|
||||||
|
/// [`Clap`]-derived struct used to parse command line arguments.
|
||||||
pub struct Parameters {
|
pub struct Parameters {
|
||||||
// NOTE: clap's comma-separated argument parser makes it impossible to specify extensions with commas in their name -
|
/// Automatically rename files to use the correct extension, prompting the user for every rename.
|
||||||
// `-e sil\,ly` is treated as ["sil", "ly"] rather than as ["silly"], no matter how i escape the comma (in bash,
|
#[clap(long, help_heading = "RENAMING")]
|
||||||
// anyway). is this really an issue? it does technically exclude some perfectly valid extensions, but i've never seen
|
pub fix: bool,
|
||||||
// a file extension with a comma in its name before.
|
|
||||||
|
/// 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.
|
/// 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
|
/// 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`).
|
/// separating them with commas (`-e jpg,png,gif`).
|
||||||
#[clap(short, long, use_delimiter = true, require_delimiter = true, value_name = "ext", validator = lowercase_exts)]
|
#[clap(short, long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", num_args(1),
|
||||||
|
value_parser = validate_exts, help_heading = "FILTERING")]
|
||||||
pub exts: Option<Vec<StringType>>,
|
pub exts: Option<Vec<StringType>>,
|
||||||
|
|
||||||
/// Use these preset lists of extensions as the search filter (comma-separated list).
|
/// Use these preset lists of extensions as the search filter (comma-separated list).
|
||||||
|
@ -61,16 +95,18 @@ pub struct Parameters {
|
||||||
#[clap(
|
#[clap(
|
||||||
short = 'E',
|
short = 'E',
|
||||||
long,
|
long,
|
||||||
arg_enum,
|
value_enum,
|
||||||
use_delimiter = true,
|
use_value_delimiter = true,
|
||||||
require_delimiter = true,
|
value_delimiter = ',',
|
||||||
value_name = "set"
|
value_name = "set",
|
||||||
|
help_heading = "FILTERING"
|
||||||
)]
|
)]
|
||||||
pub ext_set: Vec<ExtensionSet>,
|
pub ext_set: Vec<ExtensionSet>,
|
||||||
|
|
||||||
/// Don't scan files with these extensions.
|
/// Don't scan files with these extensions.
|
||||||
/// This option takes precedence over extensions specified with `-e` or `-E`.
|
/// This option takes precedence over extensions specified with `-e` or `-E`.
|
||||||
#[clap(short = 'x', long, use_delimiter = true, require_delimiter = true, value_name = "ext", validator = lowercase_exts)]
|
#[clap(short = 'x', long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", value_parser =
|
||||||
|
validate_exts, help_heading = "FILTERING")]
|
||||||
pub exclude: Option<Vec<StringType>>,
|
pub exclude: Option<Vec<StringType>>,
|
||||||
|
|
||||||
/// Exclude files using a preset list of extensions.
|
/// Exclude files using a preset list of extensions.
|
||||||
|
@ -78,71 +114,87 @@ pub struct Parameters {
|
||||||
#[clap(
|
#[clap(
|
||||||
short = 'X',
|
short = 'X',
|
||||||
long,
|
long,
|
||||||
arg_enum,
|
value_enum,
|
||||||
use_delimiter = true,
|
use_value_delimiter = true,
|
||||||
require_delimiter = true,
|
value_delimiter = ',',
|
||||||
value_name = "set"
|
value_name = "set",
|
||||||
|
help_heading = "FILTERING"
|
||||||
)]
|
)]
|
||||||
pub exclude_set: Vec<ExtensionSet>,
|
pub exclude_set: Vec<ExtensionSet>,
|
||||||
|
|
||||||
/// Don't skip hidden files and directories.
|
/// 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
|
/// 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.
|
/// ~/.hidden` will recurse into `~/.hidden` regardless of whether or not -s was passed as an argument.
|
||||||
#[clap(short, long)]
|
#[clap(short, long, help_heading = "FILTERING")]
|
||||||
pub scan_hidden: bool,
|
pub scan_hidden: bool,
|
||||||
|
|
||||||
/// Scan files without extensions.
|
/// Scan files without extensions.
|
||||||
/// By default, fif will ignore files without extensions - for example, a jpeg file named `photo` won't be considered
|
/// 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`.
|
/// misnamed. Supplying the -S flag will cause fif to recommend renaming this file to `photo.jpg`.
|
||||||
#[clap(short = 'S', long)]
|
#[clap(short = 'S', long, help_heading = "FILTERING")]
|
||||||
pub scan_extensionless: bool,
|
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.
|
/// Output format to use.
|
||||||
/// By default, fif will output a PowerShell script on Windows, and a Bourne Shell script on other platforms.
|
/// By default, fif will output a PowerShell script on Windows, and a Bourne Shell script on other platforms.
|
||||||
#[clap(short, long, default_value = DEFAULT_FORMAT, arg_enum, value_name = "format")]
|
#[clap(short, long, default_value = DEFAULT_FORMAT, value_enum, value_name = "format", help_heading = "OUTPUT")]
|
||||||
pub output_format: OutputFormat,
|
pub output_format: OutputFormat,
|
||||||
|
|
||||||
/// Follow symlinks.
|
|
||||||
#[clap(short, long)]
|
|
||||||
pub follow_symlinks: bool,
|
|
||||||
|
|
||||||
/// Output verbosity. Each additional `-v` increases verbosity.
|
/// Output verbosity. Each additional `-v` increases verbosity.
|
||||||
/// Can be overridden by FIF_LOG or RUST_LOG.
|
/// Can be overridden by `FIF_LOG` or `RUST_LOG`.
|
||||||
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
|
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
|
||||||
pub verbose: u8,
|
pub verbose: u8,
|
||||||
|
|
||||||
/// Output quietness. Each additional `-q` decreases verbosity.
|
/// Output quietness. Each additional `-q` decreases verbosity.
|
||||||
/// Can be overridden by FIF_LOG or RUST_LOG.
|
/// Can be overridden by `FIF_LOG` or `RUST_LOG`.
|
||||||
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
|
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
|
||||||
pub quiet: u8,
|
pub quiet: u8,
|
||||||
|
|
||||||
/// Use canonical (absolute) paths in output.
|
/// 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
|
/// 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
|
/// 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.
|
/// same file), but only one canonical path. This does not effect logged output.
|
||||||
#[clap(long)]
|
#[clap(long, help_heading = "OUTPUT")]
|
||||||
pub canonical_paths: bool,
|
pub canonical_paths: bool,
|
||||||
|
|
||||||
/// The directory to process.
|
/// The directory to process.
|
||||||
#[clap(name = "DIR", default_value = ".", parse(from_os_str))]
|
#[clap(name = "DIR", default_value = ".", value_parser)]
|
||||||
pub dir: PathBuf,
|
pub dir: PathBuf,
|
||||||
|
|
||||||
/// Don't rename files with extensions unknown to fif.
|
#[cfg(feature = "multi-threaded")]
|
||||||
/// For example, with this option, fif will not rename "image.unknown" to "image.jpg"
|
/// Number of jobs (threads) to use when scanning results.
|
||||||
#[clap(short = 'I', long)]
|
/// The default behaviour is to use one thread per CPU thread. This behaviour can be manually requested by setting
|
||||||
pub ignore_unknown_exts: bool,
|
/// `-j 0`. Using `-j 1` will disable multi-threading behaviour, as if you had compiled fif with the multi-threading
|
||||||
|
/// feature disabled. Setting more jobs than you have CPU threads is not recommended.
|
||||||
|
#[clap(short = 'j', long, default_value = "0", help_heading = "MISC")]
|
||||||
|
pub jobs: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lowercase_exts(exts: &str) -> Result<(), String> {
|
/// Validation function for argument parsing that ensures passed-in extensions are lowercase, and that the user
|
||||||
|
/// didn't supply an empty list.
|
||||||
|
fn validate_exts(exts: &str) -> Result<StringType, String> {
|
||||||
// TODO: i would much rather accept uppercase exts and convert them to lowercase than just rejecting lowercase exts...
|
// 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 {
|
if exts.to_lowercase() != exts {
|
||||||
return Err(String::from("Supplied extensions must be lowercase"));
|
return Err(String::from("Supplied extensions must be lowercase"));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(exts.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Further options relating to scanning.
|
/// Further options relating to scanning.
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
|
||||||
#[allow(clippy::struct_excessive_bools)]
|
#[allow(clippy::struct_excessive_bools)]
|
||||||
pub struct ScanOpts {
|
pub struct ScanOpts {
|
||||||
/// Whether hidden files and directories should be scanned.
|
/// Whether hidden files and directories should be scanned.
|
||||||
|
@ -215,6 +267,7 @@ impl Parameters {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Populates a [`ScanOpts`] struct with values from [`self`].
|
||||||
pub const fn get_scan_opts(&self) -> ScanOpts {
|
pub const fn get_scan_opts(&self) -> ScanOpts {
|
||||||
ScanOpts {
|
ScanOpts {
|
||||||
hidden: self.scan_hidden,
|
hidden: self.scan_hidden,
|
||||||
|
@ -224,10 +277,8 @@ impl Parameters {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn default_verbosity(&self) -> log::LevelFilter {
|
/// Gets the verbosity set by the user via the `-v` and `-q` flags.
|
||||||
#![allow(clippy::missing_const_for_fn)]
|
pub const fn get_verbosity(&self) -> log::LevelFilter {
|
||||||
// match was not permitted inside const functions until 1.46
|
|
||||||
|
|
||||||
use log::LevelFilter;
|
use log::LevelFilter;
|
||||||
|
|
||||||
match self.quiet {
|
match self.quiet {
|
||||||
|
@ -246,7 +297,7 @@ impl Parameters {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets of extensions for use with [Parameter](crate::parameters::Parameters)'s `-E` flag.
|
/// Sets of extensions for use with [Parameter](crate::parameters::Parameters)'s `-E` flag.
|
||||||
#[derive(Clap, PartialEq, Debug)]
|
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
|
||||||
pub enum ExtensionSet {
|
pub enum ExtensionSet {
|
||||||
/// Extensions used for image file formats, such as `png`, `jpeg`, `webp`, etc.
|
/// Extensions used for image file formats, such as `png`, `jpeg`, `webp`, etc.
|
||||||
Images,
|
Images,
|
||||||
|
@ -256,7 +307,7 @@ pub enum ExtensionSet {
|
||||||
#[clap(alias = "videos")]
|
#[clap(alias = "videos")]
|
||||||
Video,
|
Video,
|
||||||
/// Extensions used for media file formats. This acts as a combination of the [Images](ExtensionSet::Images),
|
/// Extensions used for media file formats. This acts as a combination of the [Images](ExtensionSet::Images),
|
||||||
/// [Audio](ExtensionSet::Audio) and [Videos](ExtensionSet::Videos) variants.
|
/// [Audio](ExtensionSet::Audio) and [Video](ExtensionSet::Video) variants.
|
||||||
Media,
|
Media,
|
||||||
/// Extensions used for document file formats, such as `pdf`, `odt`, `docx`, etc.
|
/// Extensions used for document file formats, such as `pdf`, `odt`, `docx`, etc.
|
||||||
Documents,
|
Documents,
|
||||||
|
@ -275,12 +326,7 @@ impl ExtensionSet {
|
||||||
Self::Images => mime_guess::get_mime_extensions_str("image/*").unwrap().to_vec(),
|
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::Audio => mime_guess::get_mime_extensions_str("audio/*").unwrap().to_vec(),
|
||||||
Self::Video => mime_guess::get_mime_extensions_str("video/*").unwrap().to_vec(),
|
Self::Video => mime_guess::get_mime_extensions_str("video/*").unwrap().to_vec(),
|
||||||
Self::Media => [
|
Self::Media => [Self::Images.extensions(), Self::Audio.extensions(), Self::Video.extensions()].concat(),
|
||||||
Self::Images.extensions(),
|
|
||||||
Self::Audio.extensions(),
|
|
||||||
Self::Video.extensions(),
|
|
||||||
]
|
|
||||||
.concat(),
|
|
||||||
Self::Documents => vec![
|
Self::Documents => vec![
|
||||||
"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "tsv", "odt", "ods", "odp", "oda", "rtf", "ps",
|
"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "tsv", "odt", "ods", "odp", "oda", "rtf", "ps",
|
||||||
"pages", "key", "numbers",
|
"pages", "key", "numbers",
|
||||||
|
|
351
src/tests/mod.rs
351
src/tests/mod.rs
|
@ -1,51 +1,40 @@
|
||||||
use fif::files::{mime_extension_lookup, BUF_SIZE};
|
// SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
use fif::files::{scan_directory, scan_from_walkdir};
|
// 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::findings::Findings;
|
||||||
use fif::formats::{Format, PowerShell, Shell};
|
use fif::formats::{Format, PowerShell, Shell};
|
||||||
use fif::mime_db::MimeDb;
|
use fif::mime_db::MimeDb;
|
||||||
use fif::String;
|
use fif::utils::APPLICATION_ZIP;
|
||||||
|
use fif::{String, MIMEDB};
|
||||||
use crate::parameters::Parameters;
|
use itertools::Itertools;
|
||||||
use clap::Clap;
|
use maplit::{btreeset, hashmap};
|
||||||
use mime::{Mime, APPLICATION_OCTET_STREAM, APPLICATION_PDF, IMAGE_JPEG, IMAGE_PNG};
|
use mime::{Mime, APPLICATION_OCTET_STREAM, APPLICATION_PDF, IMAGE_JPEG, IMAGE_PNG};
|
||||||
|
|
||||||
use crate::parameters::ExtensionSet;
|
use crate::parameters::ExtensionSet;
|
||||||
use std::collections::HashMap;
|
use crate::parameters::Parameters;
|
||||||
use std::ffi::OsStr;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
const JPEG_BYTES: &[u8] = b"\xFF\xD8\xFF";
|
const JPEG_BYTES: &[u8] = b"\xFF\xD8\xFF";
|
||||||
const PNG_BYTES: &[u8] = b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
|
const PNG_BYTES: &[u8] = b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
|
||||||
const PDF_BYTES: &[u8] = b"%PDF-";
|
const PDF_BYTES: &[u8] = b"%PDF-";
|
||||||
const ZIP_BYTES: &[u8] = b"PK\x03\x04";
|
const ZIP_BYTES: &[u8] = b"PK\x03\x04";
|
||||||
|
|
||||||
cfg_if::cfg_if! {
|
|
||||||
if #[cfg(any(all(unix, feature = "infer-backend"), all(not(unix), not(feature = "xdg-mime-backend"))))] {
|
|
||||||
fn get_mime_db() -> fif::mime_db::InferDb {
|
|
||||||
fif::mime_db::InferDb::init()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fn get_mime_db() -> fif::mime_db::XdgDb {
|
|
||||||
fif::mime_db::XdgDb::init()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn application_zip() -> Mime {
|
|
||||||
use std::str::FromStr;
|
|
||||||
Mime::from_str("application/zip").unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that `extension_from_path` successfully returns the extension from a set of paths.
|
/// Ensure that `extension_from_path` successfully returns the extension from a set of paths.
|
||||||
fn get_ext() {
|
fn get_ext() {
|
||||||
let mut ext_checks: HashMap<_, Option<&OsStr>> = HashMap::new();
|
let ext_checks: HashMap<_, Option<&OsStr>> = hashmap![
|
||||||
ext_checks.insert(Path::new("test.txt"), Some(OsStr::new("txt")));
|
Path::new("test.txt") => Some(OsStr::new("txt")),
|
||||||
ext_checks.insert(Path::new("test.zip"), Some(OsStr::new("zip")));
|
Path::new("test.zip") => Some(OsStr::new("zip")),
|
||||||
ext_checks.insert(Path::new("test.tar.gz"), Some(OsStr::new("gz")));
|
Path::new("test.tar.gz") => Some(OsStr::new("gz")),
|
||||||
ext_checks.insert(Path::new("test."), Some(OsStr::new("")));
|
Path::new("test.") => Some(OsStr::new("")),
|
||||||
ext_checks.insert(Path::new("test"), None);
|
Path::new("test") => None,
|
||||||
ext_checks.insert(Path::new(".hidden"), None);
|
Path::new(".hidden") => None,
|
||||||
|
];
|
||||||
|
|
||||||
for (path, ext) in ext_checks {
|
for (path, ext) in ext_checks {
|
||||||
assert_eq!(path.extension(), ext);
|
assert_eq!(path.extension(), ext);
|
||||||
|
@ -53,64 +42,71 @@ fn get_ext() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that the mime types for JPEG, PNG, PDF, and ZIP are detected from their magic numbers.
|
/// Ensure that the MIME types for JPEG, PNG, PDF, and ZIP are detected from their magic numbers.
|
||||||
fn detect_type() {
|
fn detect_type() {
|
||||||
let db = get_mime_db();
|
assert_eq!(MIMEDB.get_type(JPEG_BYTES), Some(IMAGE_JPEG));
|
||||||
assert_eq!(db.get_type(JPEG_BYTES), Some(IMAGE_JPEG));
|
assert_eq!(MIMEDB.get_type(PNG_BYTES), Some(IMAGE_PNG));
|
||||||
assert_eq!(db.get_type(PNG_BYTES), Some(IMAGE_PNG));
|
assert_eq!(MIMEDB.get_type(PDF_BYTES), Some(APPLICATION_PDF));
|
||||||
assert_eq!(db.get_type(PDF_BYTES), Some(APPLICATION_PDF));
|
assert_eq!(MIMEDB.get_type(ZIP_BYTES), Some(APPLICATION_ZIP.clone()));
|
||||||
assert_eq!(db.get_type(ZIP_BYTES), Some(application_zip()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that `mime_extension_lookup` works as expected, and that the set of extensions for JPEG, PNG, PDF, and ZIP
|
/// 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.
|
/// contain "jpg", "png", "pdf", and "zip", respectively.
|
||||||
fn recommend_ext() {
|
fn recommend_ext() {
|
||||||
assert!(mime_extension_lookup(IMAGE_JPEG.essence_str().into())
|
let tests = hashmap![
|
||||||
.unwrap()
|
&IMAGE_JPEG => "jpg",
|
||||||
.contains(&String::from("jpg")));
|
&IMAGE_PNG => "png",
|
||||||
assert!(mime_extension_lookup(IMAGE_PNG.essence_str().into())
|
&APPLICATION_PDF => "pdf",
|
||||||
.unwrap()
|
&*APPLICATION_ZIP => "zip",
|
||||||
.contains(&String::from("png")));
|
];
|
||||||
assert!(mime_extension_lookup(APPLICATION_PDF.essence_str().into())
|
|
||||||
.unwrap()
|
for (mime, ext) in tests {
|
||||||
.contains(&String::from("pdf")));
|
assert!(
|
||||||
assert!(mime_extension_lookup(application_zip().essence_str().into())
|
mime_extension_lookup(mime.essence_str().into())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.contains(&String::from("zip")));
|
.contains(&String::from(ext)),
|
||||||
|
"mime_extension_lookup for {} didn't contain {}!",
|
||||||
|
mime.essence_str(),
|
||||||
|
ext
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Create a simple directory with some files, run `scan_directory` on it, and ensure that the files have their
|
/// Create a simple directory with some files, run `scan_directory` on it, and ensure that the files have their
|
||||||
/// associated mime types correctly deduced.
|
/// associated MIME types correctly deduced.
|
||||||
fn simple_directory() {
|
fn simple_directory() {
|
||||||
use crate::parameters::ScanOpts;
|
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
use std::env::set_current_dir;
|
use std::env::set_current_dir;
|
||||||
use std::fs::{canonicalize, File};
|
use std::fs::{canonicalize, File};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
use tempfile::tempdir;
|
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
|
// 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.
|
// "wrong.jpg", which is actually a png.
|
||||||
let mut files = HashMap::new();
|
let files = hashmap![
|
||||||
files.insert("test.jpg", JPEG_BYTES);
|
"test.jpg" => JPEG_BYTES,
|
||||||
files.insert("test.jpeg", JPEG_BYTES);
|
"test.jpeg" => JPEG_BYTES,
|
||||||
files.insert("test.png", PNG_BYTES);
|
"test.png" => PNG_BYTES,
|
||||||
files.insert("test.pdf", PDF_BYTES);
|
"test.pdf" => PDF_BYTES,
|
||||||
files.insert("test.zip", ZIP_BYTES);
|
"test.zip" => ZIP_BYTES,
|
||||||
files.insert("wrong.jpg", PNG_BYTES);
|
"wrong.jpg" => PNG_BYTES,
|
||||||
files.insert("ignore.fake_ext", ZIP_BYTES);
|
"ignore.fake_ext" => ZIP_BYTES,
|
||||||
|
];
|
||||||
|
|
||||||
let dir = tempdir().expect("Failed to create temporary directory.");
|
let dir = tempdir().expect("Failed to create temporary directory.");
|
||||||
set_current_dir(dir.path()).expect("Failed to change directory.");
|
set_current_dir(dir.path()).expect("Failed to change directory.");
|
||||||
|
|
||||||
for (name, bytes) in &files {
|
for (name, bytes) in &files {
|
||||||
let mut file = File::create(dir.path().join(name)).expect(&*format!("Failed to create file: {}", name));
|
let mut file = File::create(dir.path().join(name)).unwrap_or_else(|_| panic!("Failed to create file: {name}"));
|
||||||
|
|
||||||
file
|
file
|
||||||
.write_all(bytes)
|
.write_all(bytes)
|
||||||
.expect(&*format!("Failed to write to file: {}", name));
|
.unwrap_or_else(|_| panic!("Failed to write to file: {name}"));
|
||||||
drop(file);
|
drop(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -126,17 +122,14 @@ fn simple_directory() {
|
||||||
// there should be one file missing: "ignore.fake_ext"
|
// there should be one file missing: "ignore.fake_ext"
|
||||||
assert_eq!(entries.len(), files.len() - 1);
|
assert_eq!(entries.len(), files.len() - 1);
|
||||||
|
|
||||||
// initialise global mime DB - this is needed because `scan_from_walkdir` expects it to be present.
|
let use_threads = cfg!(feature = "multi-threaded");
|
||||||
crate::init_db();
|
|
||||||
|
|
||||||
let results = scan_from_walkdir(&entries, false);
|
let results = scan_from_walkdir(&entries, false, use_threads).0;
|
||||||
let canonical_results = scan_from_walkdir(&entries, true);
|
let canonical_results = scan_from_walkdir(&entries, true, use_threads).0;
|
||||||
assert_eq!(results.len(), canonical_results.len());
|
assert_eq!(results.len(), canonical_results.len());
|
||||||
|
|
||||||
for (result, canonical_result) in results.iter().zip(canonical_results.iter()) {
|
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.
|
// there should be no IO errors during this test. any IO errors encountered are outside the scope of this test.
|
||||||
let result = result.as_ref().expect("Error while scanning file");
|
|
||||||
let canonical_result = canonical_result.as_ref().expect("Error while scanning file");
|
|
||||||
|
|
||||||
// paths should be canonical
|
// paths should be canonical
|
||||||
assert_eq!(canonicalize(&result.file).unwrap(), canonical_result.file);
|
assert_eq!(canonicalize(&result.file).unwrap(), canonical_result.file);
|
||||||
|
@ -145,22 +138,33 @@ fn simple_directory() {
|
||||||
// the only invalid file detected should be "wrong.jpg", which is a misnamed png file
|
// the only invalid file detected should be "wrong.jpg", which is a misnamed png file
|
||||||
// 1. ensure detected extension is "jpg"
|
// 1. ensure detected extension is "jpg"
|
||||||
assert_eq!(result.file.as_path().extension().unwrap(), OsStr::new("jpg"));
|
assert_eq!(result.file.as_path().extension().unwrap(), OsStr::new("jpg"));
|
||||||
// 2. ensure detected mime type is IMAGE_PNG
|
// 2. ensure detected MIME type is IMAGE_PNG
|
||||||
assert_eq!(result.mime, IMAGE_PNG);
|
assert_eq!(result.mime, IMAGE_PNG);
|
||||||
// 3. ensure the recommended extension for "wrong.jpg" is "png"
|
// 3. ensure the recommended extension for "wrong.jpg" is "png"
|
||||||
assert_eq!(&result.recommended_extension().unwrap(), &String::from("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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if the recommended extension for this file is in the list of known extensions for its mimetype - for
|
// check if the recommended extension for this file is in the list of known extensions for its MIME type - for
|
||||||
// example, if the file is determined to be an IMAGE_PNG, its recommended extension should be one of the extensions
|
// 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)`.
|
// returned by `mime_extension_lookup(IMAGE_PNG)`.
|
||||||
assert!(mime_extension_lookup(result.mime.essence_str().into())
|
assert!(mime_extension_lookup(result.mime.essence_str().into())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.contains(&result.recommended_extension().unwrap()));
|
.contains(&result.recommended_extension().unwrap()));
|
||||||
|
|
||||||
// make sure the guessed mimetype is correct based on the extension of the scanned file
|
// ensure that the recommended_name function outputs something beginning with "test"
|
||||||
// because we already know that the extensions match the mimetype (as we created these files ourselves earlier in
|
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.
|
// the test), all files with the "jpg" extension should be IMAGE_JPEGs, etc.
|
||||||
let ext = result.file.as_path().extension().unwrap();
|
let ext = result.file.as_path().extension().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -169,7 +173,7 @@ fn simple_directory() {
|
||||||
"jpg" | "jpeg" => IMAGE_JPEG,
|
"jpg" | "jpeg" => IMAGE_JPEG,
|
||||||
"png" => IMAGE_PNG,
|
"png" => IMAGE_PNG,
|
||||||
"pdf" => APPLICATION_PDF,
|
"pdf" => APPLICATION_PDF,
|
||||||
"zip" => application_zip(),
|
"zip" => APPLICATION_ZIP.clone(),
|
||||||
_ => APPLICATION_OCTET_STREAM, // general "fallback" type
|
_ => APPLICATION_OCTET_STREAM, // general "fallback" type
|
||||||
},
|
},
|
||||||
"Incorrect MIME type detected - got {:?} for a {:?} file",
|
"Incorrect MIME type detected - got {:?} for a {:?} file",
|
||||||
|
@ -221,7 +225,7 @@ fn argument_parsing() {
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that `fif -e jpg dir` is interpreted as "scan for jpg files in dir" and not "scan for jpg and dir files"
|
/// 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() {
|
fn positional_args() {
|
||||||
for flag in &["-x", "-e", "-X", "-E"] {
|
for flag in ["-x", "-e", "-X", "-E"] {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Parameters::parse_from(vec!["fif", flag, "images", "directory"]).dir,
|
Parameters::parse_from(vec!["fif", flag, "images", "directory"]).dir,
|
||||||
PathBuf::from("directory")
|
PathBuf::from("directory")
|
||||||
|
@ -247,12 +251,7 @@ fn exclude_overrides() {
|
||||||
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "abc,def,ghi,jkl", "-x", "abc,def"]);
|
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "abc,def,ghi,jkl", "-x", "abc,def"]);
|
||||||
let extensions = args.extensions();
|
let extensions = args.extensions();
|
||||||
assert!(extensions.is_some(), "Extensions should be set!");
|
assert!(extensions.is_some(), "Extensions should be set!");
|
||||||
let extensions = extensions.unwrap();
|
assert_eq!(extensions, Some(btreeset!["ghi", "jkl"]));
|
||||||
|
|
||||||
assert!(!extensions.contains(&"abc"));
|
|
||||||
assert!(!extensions.contains(&"def"));
|
|
||||||
assert!(extensions.contains(&"ghi"));
|
|
||||||
assert!(extensions.contains(&"jkl"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -262,10 +261,7 @@ fn exclude_set_overrides_includes() {
|
||||||
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "jpg,flac", "-X", "images"]);
|
let args: Parameters = Parameters::parse_from(vec!["fif", "-e", "jpg,flac", "-X", "images"]);
|
||||||
let extensions = args.extensions();
|
let extensions = args.extensions();
|
||||||
assert!(extensions.is_some(), "Extensions should be set!");
|
assert!(extensions.is_some(), "Extensions should be set!");
|
||||||
let mut extensions = extensions.unwrap().into_iter();
|
assert_eq!(extensions, Some(btreeset!["flac"]));
|
||||||
|
|
||||||
assert_eq!(extensions.next(), Some("flac"), "Extensions should contain flac!");
|
|
||||||
assert_eq!(extensions.next(), None, "Too many extensions!");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -283,18 +279,19 @@ fn exclude_set_overrides_include_set() {
|
||||||
.iter()
|
.iter()
|
||||||
.chain(ExtensionSet::Video.extensions().iter())
|
.chain(ExtensionSet::Video.extensions().iter())
|
||||||
{
|
{
|
||||||
assert!(extensions.contains(&ext), "Extensions should contain {}!", ext);
|
assert!(extensions.contains(&ext), "Extensions should contain {ext}!");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensure all of images' extensions are excluded
|
// ensure all of images' extensions are excluded
|
||||||
for ext in ExtensionSet::Images.extensions() {
|
for ext in ExtensionSet::Images.extensions() {
|
||||||
assert!(!extensions.contains(&ext), "Extensions should not contain {}!", ext);
|
assert!(!extensions.contains(&ext), "Extensions should not contain {ext}!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that badly formed command line arguments are rejected.
|
/// Ensure that badly formed command line arguments are rejected.
|
||||||
fn rejects_bad_args() {
|
fn rejects_bad_args() {
|
||||||
|
use assert_cmd::Command;
|
||||||
let tests = [
|
let tests = [
|
||||||
// Non-existent flags:
|
// Non-existent flags:
|
||||||
vec!["fif", "-abcdefghijklmnopqrstuvwxyz"],
|
vec!["fif", "-abcdefghijklmnopqrstuvwxyz"],
|
||||||
|
@ -306,32 +303,95 @@ fn rejects_bad_args() {
|
||||||
vec!["fif", "-X", "pebis"],
|
vec!["fif", "-X", "pebis"],
|
||||||
// `-e` with nothing but commas:
|
// `-e` with nothing but commas:
|
||||||
vec!["fif", "-e", ",,,,,"],
|
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 {
|
for test in &tests {
|
||||||
assert!(Parameters::try_parse_from(test).is_err(), "Failed to reject {:?}", test);
|
// first, try testing the flags against the Parameters struct...
|
||||||
|
assert!(Parameters::try_parse_from(test).is_err(), "Failed to reject {test:?}");
|
||||||
|
// ...then, make sure it actually works against the binary
|
||||||
|
let mut cmd = Command::cargo_bin("fif").unwrap();
|
||||||
|
cmd.args(test).assert().failure();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
/// Ensure that a few simple, well-formed command line argument cases pass
|
||||||
|
fn accepts_good_args() {
|
||||||
|
use assert_cmd::Command;
|
||||||
|
|
||||||
|
// all of these commands pass either the version or help flag, ensuring that they won't fail for reasons relating
|
||||||
|
// to filesystem access
|
||||||
|
let tests = [
|
||||||
|
vec!["-V"],
|
||||||
|
vec!["--version"],
|
||||||
|
vec!["-E", "images", "--version"],
|
||||||
|
vec!["-h"],
|
||||||
|
vec!["--help"],
|
||||||
|
vec!["dir_name", "--version"],
|
||||||
|
];
|
||||||
|
|
||||||
|
for test in &tests {
|
||||||
|
let mut cmd = Command::cargo_bin("fif").unwrap();
|
||||||
|
cmd.args(test).assert().success();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
/// Ensures that output from the `-V` and `--version` flags is formatted properly.
|
||||||
|
fn check_version_output() {
|
||||||
|
use std::string::String;
|
||||||
|
|
||||||
|
use assert_cmd::Command;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
// test `-V` matches the format of "fif x.y.z"
|
||||||
|
let mut cmd = Command::cargo_bin("fif").unwrap();
|
||||||
|
let output = cmd.arg("-V").ok().unwrap().stdout;
|
||||||
|
let output = String::from_utf8(output).unwrap();
|
||||||
|
assert!(
|
||||||
|
Regex::new(r"fif v([0-9]\.){2}[0-9]").unwrap().is_match(output.trim()),
|
||||||
|
"\"{output}\" does not match the expected `-v` format!"
|
||||||
|
);
|
||||||
|
|
||||||
|
// test `--version` matches the format of "fif x.y.z (OS, example backend, commit #1234abc)"
|
||||||
|
let mut cmd = Command::cargo_bin("fif").unwrap();
|
||||||
|
let output = cmd.arg("--version").ok().unwrap().stdout;
|
||||||
|
let output = String::from_utf8(output).unwrap();
|
||||||
|
assert!(
|
||||||
|
Regex::new(r"fif v([0-9]\.){2}[0-9] \(.+, .+ backend, (unknown commit|commit #[[:xdigit:]]{7})\)")
|
||||||
|
.unwrap()
|
||||||
|
.is_match(output.trim()),
|
||||||
|
"\"{}\" does not match the expected `--version` format!",
|
||||||
|
output.trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Generate random series of bytes and try to identify them. This test makes no assertions and can only fail if the
|
/// 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.
|
/// mime database somehow panics or hangs.
|
||||||
fn identify_random_bytes() {
|
fn identify_random_bytes() {
|
||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
let db = get_mime_db();
|
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = rand::thread_rng();
|
||||||
let mut bytes: [u8; BUF_SIZE * 2] = [0; BUF_SIZE * 2];
|
let mut bytes: [u8; BUF_SIZE * 2] = [0; BUF_SIZE * 2];
|
||||||
let mut results: HashMap<Mime, i32> = HashMap::new();
|
let mut results: BTreeMap<Mime, i32> = BTreeMap::new();
|
||||||
|
|
||||||
for _ in 1..1000 {
|
for _ in 1..1000 {
|
||||||
rng.fill_bytes(&mut bytes);
|
rng.fill_bytes(&mut bytes);
|
||||||
if let Some(detected_type) = db.get_type(&bytes) {
|
if let Some(detected_type) = MIMEDB.get_type(&bytes) {
|
||||||
*results.entry(detected_type).or_insert(0) += 1;
|
*results.entry(detected_type).or_insert(0) += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (mime, count) in &results {
|
for (mime, count) in &results {
|
||||||
println!("{}:\t{} counts", mime, count);
|
println!("{mime}:\t{count} counts");
|
||||||
}
|
}
|
||||||
println!("No type found:\t{} counts", 1000 - results.values().sum::<i32>());
|
println!("No type found:\t{} counts", 1000 - results.values().sum::<i32>());
|
||||||
}
|
}
|
||||||
|
@ -343,19 +403,19 @@ fn outputs_move_commands() {
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
|
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
|
||||||
let entries = vec![Ok(Findings {
|
let findings = vec![Findings {
|
||||||
file: Path::new("misnamed_file.png").to_path_buf(),
|
file: Path::new("misnamed_file.png").to_path_buf(),
|
||||||
valid: false,
|
valid: false,
|
||||||
mime: IMAGE_JPEG,
|
mime: IMAGE_JPEG,
|
||||||
})];
|
}];
|
||||||
|
|
||||||
for format in &["Shell", "PowerShell"] {
|
for format in &["Shell", "PowerShell"] {
|
||||||
let mut cursor = std::io::Cursor::new(Vec::new());
|
let mut cursor = std::io::Cursor::new(Vec::new());
|
||||||
let mut contents = std::string::String::new();
|
let mut contents = std::string::String::new();
|
||||||
|
|
||||||
match *format {
|
match *format {
|
||||||
"Shell" => Shell.write_all(&mut cursor, &entries),
|
"Shell" => Shell.write_all(&mut cursor, &findings, &[]),
|
||||||
"PowerShell" => PowerShell.write_all(&mut cursor, &entries),
|
"PowerShell" => PowerShell.write_all(&mut cursor, &findings, &[]),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
.expect("Failed to write to cursor");
|
.expect("Failed to write to cursor");
|
||||||
|
@ -368,9 +428,7 @@ fn outputs_move_commands() {
|
||||||
// the output should contain a command like "mv -i misnamed_file.png misnamed_file.jpg"
|
// the output should contain a command like "mv -i misnamed_file.png misnamed_file.jpg"
|
||||||
assert!(
|
assert!(
|
||||||
contents.contains("misnamed_file.jpg") && contents.contains("misnamed_file.png"),
|
contents.contains("misnamed_file.jpg") && contents.contains("misnamed_file.png"),
|
||||||
"{} output doesn't contain move command!\n===\n{}",
|
"{format} output doesn't contain move command!\n===\n{contents}"
|
||||||
format,
|
|
||||||
contents
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -379,20 +437,21 @@ fn outputs_move_commands() {
|
||||||
#[cfg(feature = "json")]
|
#[cfg(feature = "json")]
|
||||||
/// Ensure JSON output is valid.
|
/// Ensure JSON output is valid.
|
||||||
fn test_json() {
|
fn test_json() {
|
||||||
use crate::formats::Json;
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
|
use crate::formats::Json;
|
||||||
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
|
// create an example finding stating that "misnamed_file.png" has been identified as a jpeg file
|
||||||
let entries = vec![Ok(Findings {
|
let findings = vec![Findings {
|
||||||
file: Path::new("misnamed_file.png").to_path_buf(),
|
file: Path::new("misnamed_file.png").to_path_buf(),
|
||||||
valid: false,
|
valid: false,
|
||||||
mime: IMAGE_JPEG,
|
mime: IMAGE_JPEG,
|
||||||
})];
|
}];
|
||||||
|
|
||||||
let mut cursor = std::io::Cursor::new(Vec::new());
|
let mut cursor = std::io::Cursor::new(Vec::new());
|
||||||
let mut contents = std::string::String::new();
|
let mut contents = std::string::String::new();
|
||||||
|
|
||||||
Json
|
Json
|
||||||
.write_all(&mut cursor, &entries)
|
.write_all(&mut cursor, &findings, &[])
|
||||||
.expect("Failed to write to cursor");
|
.expect("Failed to write to cursor");
|
||||||
|
|
||||||
cursor.set_position(0);
|
cursor.set_position(0);
|
||||||
|
@ -400,11 +459,10 @@ fn test_json() {
|
||||||
.read_to_string(&mut contents)
|
.read_to_string(&mut contents)
|
||||||
.expect("Failed to read from cursor to string");
|
.expect("Failed to read from cursor to string");
|
||||||
|
|
||||||
// the output should contain the file's mime type
|
// the output should contain the file's MIME type
|
||||||
assert!(
|
assert!(
|
||||||
contents.contains(IMAGE_JPEG.essence_str()),
|
contents.contains(IMAGE_JPEG.essence_str()),
|
||||||
"JSON output doesn't contain move command!\n===\n{}",
|
"JSON output doesn't contain move command!\n===\n{contents}"
|
||||||
contents
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -421,21 +479,26 @@ fn media_contains_audio_video_images() {
|
||||||
.for_each(|ext| assert!(media_exts.contains(&ext)));
|
.for_each(|ext| assert!(media_exts.contains(&ext)));
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Parameters::parse_from(&["fif", "-E", "media"]).extensions(),
|
Parameters::parse_from(["fif", "-E", "media"]).extensions(),
|
||||||
Parameters::parse_from(&["fif", "-E", "audio,video,images"]).extensions()
|
Parameters::parse_from(["fif", "-E", "audio,video,images"]).extensions()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensure that the `writables!` macro produces the output it should.
|
/// Ensure that the `writables!` and `writablesln!` macros produce the output they should.
|
||||||
fn writables_is_correct() {
|
fn writables_is_correct() {
|
||||||
use fif::formats::Writable;
|
use fif::formats::Writable;
|
||||||
use fif::writables;
|
use fif::{writables, writablesln};
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
&["henlo".into(), Path::new("henlo").into(), Writable::Newline,],
|
&["henlo".into(), Path::new("henlo").into(), Writable::Newline,],
|
||||||
writables!["henlo", (Path::new("henlo")), 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]
|
||||||
|
@ -443,37 +506,57 @@ fn writables_is_correct() {
|
||||||
fn verbosity() {
|
fn verbosity() {
|
||||||
use log::LevelFilter;
|
use log::LevelFilter;
|
||||||
assert!(
|
assert!(
|
||||||
Parameters::try_parse_from(&["fif", "-q", "-v"]).is_err(),
|
Parameters::try_parse_from(["fif", "-q", "-v"]).is_err(),
|
||||||
"Failed to reject usage of both -q and -v!"
|
"Failed to reject usage of both -q and -v!"
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut expected_results = HashMap::new();
|
let expected_results = hashmap![
|
||||||
expected_results.insert("-qqqqqqqq", LevelFilter::Off);
|
"-qqqqqqqq" => LevelFilter::Off,
|
||||||
expected_results.insert("-qqq", LevelFilter::Off);
|
"-qqq" => LevelFilter::Off,
|
||||||
expected_results.insert("-qq", LevelFilter::Error);
|
"-qq" => LevelFilter::Error,
|
||||||
expected_results.insert("-q", LevelFilter::Warn);
|
"-q" => LevelFilter::Warn,
|
||||||
expected_results.insert("-s", LevelFilter::Info);
|
"-s" => LevelFilter::Info,
|
||||||
expected_results.insert("-v", LevelFilter::Debug);
|
"-v" => LevelFilter::Debug,
|
||||||
expected_results.insert("-vv", LevelFilter::Trace);
|
"-vv" => LevelFilter::Trace,
|
||||||
expected_results.insert("-vvv", LevelFilter::Trace);
|
"-vvv" => LevelFilter::Trace,
|
||||||
expected_results.insert("-vvvvvvvv", LevelFilter::Trace);
|
"-vvvvvvvv" => LevelFilter::Trace,
|
||||||
|
];
|
||||||
|
|
||||||
for (flags, level) in expected_results {
|
for (flags, level) in expected_results {
|
||||||
assert_eq!(Parameters::parse_from(&["fif", flags]).default_verbosity(), level);
|
assert_eq!(Parameters::parse_from(["fif", flags]).get_verbosity(), level);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
/// Ensures that smart strings don't deviate from std's Strings
|
/// Ensures `os_name()`'s output is the same as [`std::env::consts::OS`], capitalisation notwithstanding
|
||||||
fn validate_string_type() {
|
fn validate_os_name() {
|
||||||
use fif::String as SmartString;
|
assert_eq!(fif::utils::os_name().to_lowercase(), std::env::consts::OS.to_lowercase());
|
||||||
use std::string::String as StdString;
|
}
|
||||||
assert_eq!(SmartString::new(), StdString::new());
|
|
||||||
assert_eq!(SmartString::from("smol"), StdString::from("smol"));
|
#[test]
|
||||||
assert_eq!(
|
/// Ensures that [`Findings`] are sorted properly.
|
||||||
SmartString::from("A long and therefore heap-allocated string"),
|
fn sort_findings() {
|
||||||
StdString::from("A long and therefore heap-allocated string")
|
let findings = vec![
|
||||||
);
|
Findings {
|
||||||
// uncomment if i ever update to smartstring >= 0.2.9
|
file: Path::new("ccc").to_path_buf(),
|
||||||
// smartstring::validate();
|
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);
|
||||||
}
|
}
|
||||||
|
|
47
src/utils.rs
47
src/utils.rs
|
@ -1,5 +1,13 @@
|
||||||
|
// 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 cfg_if::cfg_if;
|
||||||
use once_cell::sync::OnceCell;
|
use mime::Mime;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use crate::String;
|
use crate::String;
|
||||||
|
|
||||||
|
@ -16,30 +24,23 @@ cfg_if! {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// the version and long_version given to clap need to be a &str, but we want to use format!, which returns a String.
|
/// The version defined in Cargo.toml, prefixed with a v (e.g. "v0.4.0")
|
||||||
// we can't just do something like `version = format!(...).as_str()`, because clap needs to know that the version will
|
pub(crate) static CLAP_VERSION: Lazy<String> = Lazy::new(|| String::from("v") + VERSION.unwrap_or("???"));
|
||||||
// live for a given lifetime, which we need to satisfy by making our String static. of course, you can't use format!
|
|
||||||
// statically, so we need to use a OnceCell or similar to get around this.
|
|
||||||
static CLAP_VERSION: OnceCell<String> = OnceCell::new();
|
|
||||||
static CLAP_LONG_VERSION: OnceCell<String> = OnceCell::new();
|
|
||||||
|
|
||||||
/// Sets [`CLAP_VERSION`] to be the version defined in Cargo.toml, prefixed with a v (e.g. "v0.3.1"), then returns it as
|
/// The version defined in Cargo.toml, prefixed with a v (e.g. "v0.4.0"), followed by the chosen backend and
|
||||||
/// an str.
|
/// abbreviated git commit hash in parentheses - For example, "v0.4.0 (XDG-Mime backend, commit #043e097)"
|
||||||
pub fn clap_version() -> &'static str { CLAP_VERSION.get_or_init(|| String::from("v") + VERSION.unwrap_or("???")) }
|
pub static CLAP_LONG_VERSION: Lazy<String> = Lazy::new(|| {
|
||||||
|
// handle cases where GIT_SHA is set to an empty string
|
||||||
|
let commit = match option_env!("GIT_SHA") {
|
||||||
|
Some(hash) if !hash.trim().is_empty() => String::from("commit #") + hash,
|
||||||
|
_ => String::from("unknown commit"),
|
||||||
|
};
|
||||||
|
|
||||||
/// Sets [`CLAP_LONG_VERSION`] to be similar to [`CLAP_VERSION`], followed by the chosen backend and abbreviated git
|
format!("v{} ({}, {} backend, {})", VERSION.unwrap_or("???"), os_name(), BACKEND, commit).into()
|
||||||
/// commit hash in parentheses (e.g. "v0.3.6 (XDG-Mime backend, commit #043e097)"), then returns it as an str.
|
});
|
||||||
pub fn clap_long_version() -> &'static str {
|
|
||||||
CLAP_LONG_VERSION.get_or_init(|| {
|
/// A [`Mime`] representing the "application/zip" MIME type.
|
||||||
format!(
|
pub static APPLICATION_ZIP: Lazy<Mime> = Lazy::new(|| Mime::from_str("application/zip").unwrap());
|
||||||
"v{} ({} backend, commit #{})",
|
|
||||||
VERSION.unwrap_or("???"),
|
|
||||||
BACKEND,
|
|
||||||
option_env!("GIT_SHA").unwrap_or("???")
|
|
||||||
)
|
|
||||||
.into()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the name of the target operating system with proper casing, like "Windows" or "macOS".
|
/// Returns the name of the target operating system with proper casing, like "Windows" or "macOS".
|
||||||
#[allow(clippy::option_map_unit_fn)]
|
#[allow(clippy::option_map_unit_fn)]
|
||||||
|
|
15
test.py
15
test.py
|
@ -1,9 +1,13 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
# SPDX-FileCopyrightText: 2021-2024 Lynnesbian
|
||||||
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
def test_archs():
|
def test_archs():
|
||||||
archs = ["aarch64", "powerpc", "riscv64gc"]
|
archs = ["aarch64", "powerpc", "riscv64gc"]
|
||||||
upto = 1
|
upto = 1
|
||||||
|
@ -11,9 +15,12 @@ def test_archs():
|
||||||
|
|
||||||
for arch in archs:
|
for arch in archs:
|
||||||
print(f"Testing {arch} ({upto} of {target})")
|
print(f"Testing {arch} ({upto} of {target})")
|
||||||
subprocess.run(f"cross test --features=json,infer-backend --target {arch}-unknown-linux-gnu".split(" ")).check_returncode()
|
subprocess\
|
||||||
|
.run(f"cross test --features=json,infer-backend --target {arch}-unknown-linux-gnu".split(" "))\
|
||||||
|
.check_returncode()
|
||||||
upto += 1
|
upto += 1
|
||||||
|
|
||||||
|
|
||||||
def test_versions():
|
def test_versions():
|
||||||
match = re.search(
|
match = re.search(
|
||||||
r'rust-version ?= ?"([\d.]+)"',
|
r'rust-version ?= ?"([\d.]+)"',
|
||||||
|
@ -37,9 +44,12 @@ def test_versions():
|
||||||
upto += 1
|
upto += 1
|
||||||
|
|
||||||
print(f"[{version}, {backend}] Scanning imgs ({upto} of {target})")
|
print(f"[{version}, {backend}] Scanning imgs ({upto} of {target})")
|
||||||
subprocess.run(f"cargo +{version} run --release --features=json,{backend}-backend -- imgs".split(" ")).check_returncode()
|
subprocess\
|
||||||
|
.run(f"cargo +{version} run --release --features=json,{backend}-backend -- imgs".split(" "))\
|
||||||
|
.check_returncode()
|
||||||
upto += 1
|
upto += 1
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
done_something = False
|
done_something = False
|
||||||
if "versions" in sys.argv:
|
if "versions" in sys.argv:
|
||||||
|
@ -56,5 +66,6 @@ def main():
|
||||||
print("Done! You might want to run cargo clean...")
|
print("Done! You might want to run cargo clean...")
|
||||||
subprocess.run(["du", "-sh", "target"])
|
subprocess.run(["du", "-sh", "target"])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
Loading…
Reference in a new issue