Compare commits

...

43 Commits

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

See merge request Lynnesbian/fif!2
2022-01-17 00:12:19 +00:00
Hannes Braun c4f0cd8d12
Update infer to 0.6.0 2022-01-15 19:36:38 +01:00
Lynne Megido 6b821f1e1e
cargo update 2022-01-05 11:36:20 +10:00
Lynne Megido 8e5ddd8e4a
minor readme changes 2022-01-01 13:35:32 +10:00
29 changed files with 1032 additions and 609 deletions

View File

@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
---

4
.gitattributes vendored Normal file
View File

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

4
.gitignore vendored
View File

@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
/target
@ -20,3 +20,5 @@ cargo-timing*.html
.idea/workspace.xml
*.sync-conflict*
.idea/sonarlint
.directory
*.tmp

View File

@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
image: "rust:latest"
@ -105,7 +105,7 @@ build-base-stable:
build-base-msrv:
extends: build-base-stable
image: "rust:1.54.0"
image: "rust:1.64.0"
cache:
key: msrv
paths:
@ -131,7 +131,7 @@ build-stable:
build-msrv:
extends: build-stable
needs: ["build-base-msrv"]
image: "rust:1.54.0"
image: "rust:1.64.0"
cache:
key: msrv
paths:
@ -156,7 +156,7 @@ test-stable:
test-msrv:
extends: test-stable
image: "rust:1.54.0"
image: "rust:1.64.0"
needs: ["build-msrv"]
cache:
key: msrv

View File

@ -3,7 +3,7 @@ Upstream-Name: fif
Upstream-Contact: Lynnesbian <lynne@bune.city>
Source: https://gitlab.com/Lynnesbian/fif/
Files: .idea/**/* .idea/* Cargo.lock .mailmap .kateproject
Files: .idea/**/* .idea/* Cargo.lock .mailmap .kateproject *.toml
Copyright: Lynnesbian
License: CC0-1.0

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

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

View File

@ -4,9 +4,47 @@ 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
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v0.7.1 - 2024-01-24
### Changed
- Updated and pinned dependencies, using the latest MSRV-compatible versions available.
## v0.7.0 - 2023-03-15
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.64.0**.
- Update [`clap`] to v4.0
- Update [`infer`] to v0.13.0, bringing support for formats such as [CPIO](https://en.wikipedia.org/wiki/Cpio) and
[OpenRaster](https://www.openraster.org/index.html)
## v0.6.0 - 2022-09-04
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.57.0**.
- Update [`clap`] to v3.2.0
- Update [`smartstring`] to v1.0 - this should (slightly) improve performance on 32-bit big endian architectures
such as PowerPC
## v0.5.2 - 2022-05-02
### Added
- Output now contains a reminder to use `fif --fix`
### Changed
- Some extensions are considered to be always valid - these are:
- "filepart", "part", "crdownload": Partially downloaded files, renaming could break download
- "bak", "backup": Backup copies are a common idiom (e.g. "game.exe.bak") and should be respected
### Fixed
- Support for many file types that are subcategories of others (e.g., fif will no longer rename apk files to zip) (#1)
## v0.5.1 - 2022-04-12
### Added
- When using the [`infer`] backend, fif is now able to detect [Mach-O](https://en.wikipedia.org/wiki/Mach-O) binaries
### Changed
- Help output is now sorted manually, and flags are grouped by functionality
### Other
- (@hannesbraun) Updated [`infer`] to v0.6.0 (!2)
- Update [`clap`] to v3.1.0, fixing deprecated code
- Pin [`smartstring`] to a version that works on our MSRV
## v0.5.0 - 2022-01-01
### Changed
- The Minimum Supported Rust Version (MSRV) is now **1.54.0**.
- 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
@ -75,6 +113,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
what a ".fake" file is, setting this flag will prevent it from renaming "photo.fake" to "photo.jpg". This is useful
for avoiding the case where fif incorrectly mislabels an obscure format it isn't aware of as something else.
- (@herbygillot) Added [MacPorts](https://www.macports.org/) install instructions (!1)
### Other
- Refactored `formats.rs`
- More accurate dependency versions in `Cargo.toml` to ensure that the MSRV stays supported

760
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,11 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
[package]
name = "fif"
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
version = "0.5.0"
version = "0.7.1"
authors = ["Lynnesbian <lynne@bune.city>"]
edition = "2018"
edition = "2021"
license = "GPL-3.0-or-later"
rust-version = "1.54.0" # clap 3 requires >=1.54.0
rust-version = "1.64.0" # clap 4.1 requires >=1.64.0
repository = "https://gitlab.com/Lynnesbian/fif"
readme = "README.md"
keywords = ["mime", "mimetype", "utilities", "tools"]
@ -26,56 +23,46 @@ xdg-mime-backend = ["xdg-mime"]
json = ["serde", "serde_json"]
[dependencies]
walkdir = "~2.3.2"
walkdir = "2.4.0"
log = "0.4.14"
mime = "0.3.16"
mime_guess = { package = "new_mime_guess", features = ["phf-map"], version = "4.0.0" }
mime_guess = { package = "new_mime_guess", version = "4.0.0" }
snailquote = "0.3.0"
once_cell = "1.8.0"
rayon = { version = "1.5.0", optional = true }
exitcode = "1.1.2"
cfg-if = "1.0.0"
itertools = "0.10.0"
itertools = "0.12.0"
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
num_cpus = { version = "1.13.0", optional = true }
parking_lot = "0.12.0"
smartstring = "1"
maplit = "1.0.2"
parking_lot = "0.11.2"
[target.'cfg(not(unix))'.dependencies]
xdg-mime = { version = "0.3.3", optional = true }
infer = "0.5.0"
infer = "=0.13.0" # 0.14.0 uses `let else`, which requires rust 1.65
[target.'cfg(unix)'.dependencies]
xdg-mime = "0.3.3"
infer = { version = "0.5.0", optional = true }
[target.'cfg(not(all(target_endian = "big", target_pointer_width = "32")))'.dependencies]
# the seemingly weird target constraint here is due to this:
# https://github.com/bodil/smartstring/blob/v0.2.9/src/config.rs#L91-L93
# 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, versions before 0.2.4 didn't impl Display, so we need at least that version for displaying Strings.
smartstring = ">= 0.2.4"
infer = { version = "=0.13.0", optional = true }
[dependencies.clap]
# beta.4 requires rust >= 1.54.0 (and beta.3 was yanked)
version = "3.0.0"
version = "~4.1"
default-features = false
features = ["wrap_help", "color", "derive", "std", "unicode"]
[dependencies.env_logger]
version = "0.9.0"
version = "0.10.0"
default-features = false
features = ["termcolor", "atty"]
features = ["color"]
[dev-dependencies]
tempfile = "3.2.0"
rand = "0.8.3"
assert_cmd = "2.0.2"
regex = { version = "1.5.4", default-features = false, features = ["std"] }
assert_cmd = "=2.0.5" # higher versions than this have dependencies that require later rust versions
regex = { version = "=1.9.5", default-features = false, features = ["std"] } # 1.9.6 requires rust 1.65
[profile.release]
lto = "thin"
@ -88,4 +75,4 @@ opt-level = 3
opt-level = 3
[package.metadata]
msrv = "1.54.0"
msrv = "1.64.0"

View File

@ -1,5 +1,2 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
[build.env]
passthrough = ["RUST_BACKTRACE", "RUST_LOG", "FIF_LOG"]

View File

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

View File

@ -1,71 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 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.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View File

@ -7,7 +7,7 @@
[![Version](https://img.shields.io/crates/v/fif.svg?logo=rust&style=flat-square)
](https://crates.io/crates/fif)
[![Minimum Supported Rust Version](https://img.shields.io/badge/msrv-1.54.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)
[![License](https://img.shields.io/crates/l/fif.svg?style=flat-square)
](https://gitlab.com/Lynnesbian/fif/-/blob/master/LICENSE)
@ -71,7 +71,8 @@ used on [*nix systems](https://en.wikipedia.org/wiki/Unix-like) (Linux, macOS, *
systems.
`xdg-mime` should work on any *nix system with the [Shared MIME Info] library installed (consult your package
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system.
manager), although I've only tested it on Linux and FreeBSD. `infer` should work on any system, but it supports far
fewer file types than `xdg-mime` does, thanks to the excellent Shared MIME Info library.
You can override the default backend for your system at compile time like so:
@ -139,6 +140,25 @@ You can also manually specify an output format to use:
fif -O powershell ~/Documents > output.ps1
```
#### The `--fix` flag
If, however, you'd rather have fif fix the misnamed files itself, rather than relying on a shell script, you can use
the `--fix` flag:
```bash
# rename any misnamed .jpg files in the user's pictures directory
fif ~/Pictures --fix -e jpg
# fix any misnamed files found in the user's downloads
fif ~/Downloads --fix
```
By default, fif will avoid taking any potentially destructive actions (renaming a file to a name that already exists).
This behaviour can be disabled with the `--overwrite` flag, which will instead prompt you to overwrite the existing
file. fif will also prompt you to retry on errors.
For more information on how the `--fix` flag works, and how it behaves in conjunction with the `--overwrite` flag
and `--prompt` parameter, see [the corresponding wiki page](https://gitlab.com/Lynnesbian/fif/-/wikis/Fix).
### Logging
By default, fif will log any info, warnings, and errors encountered during execution. This can be changed with the `-v`
flag:
@ -212,6 +232,10 @@ same line (["OTBS"](https://en.wikipedia.org/wiki/Indentation_style#Variant:_1TB
For more detailed information on the formatting rules used by this project, see the configured options in
[`rustfmt.toml`](https://gitlab.com/Lynnesbian/fif/-/blob/master/rustfmt.toml).
## Additional credits
Some of the code for correctly handling files with multiple valid extensions (particularly in the case of the
Portable Executable format) comes from [Czkawka](https://github.com/qarmin/czkawka)
## License
Copyright (C) 2021 Lynnesbian

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
use std::process::Command;
@ -14,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
// whole bunch of extra dependencies (including chrono and git2), and also blocks compilation on the current MSRV.
// this method is less clever and robust, but it works!
let git = Command::new("git").args(&["rev-parse", "--short", "HEAD"]).output();
let git = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output();
let hash = match git {
Ok(output) => String::from_utf8_lossy(&*output.stdout).into(),
Ok(output) => String::from_utf8_lossy(&output.stdout).into(),
Err(_) => {
// git not being present (or failing) shouldn't block compilation
println!("cargo:warning=Failed to retrieve git commit hash");

View File

@ -1,6 +1,6 @@
#!/bin/bash
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-FileCopyrightText: 2021-2022 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
set -e

View File

@ -1,6 +1,3 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
# avoid-breaking-exported-api = false # only available on nightly for now
cognitive-complexity-threshold = 15
msrv = "1.54.0"
msrv = "1.64.0"

8
doc/README.md Normal file
View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 130 B

View File

@ -1,6 +1,3 @@
# SPDX-FileCopyrightText: 2021 Lynnesbian
# SPDX-License-Identifier: CC0-1.0
max_width = 120
fn_single_line = true
hard_tabs = true

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! File handling - scanning, detecting MIME types, and so on.
@ -127,16 +127,38 @@ pub fn scan_file(entry: &DirEntry, canonical_paths: bool) -> Result<Findings, Sc
Ok(Some(result)) => result,
};
// set of known extensions for the given MIME type
let known_exts = mime_extension_lookup(result.essence_str().into());
// file extension for this particular file
let entry_ext = path.extension();
// determine whether or not the file's current extension is valid
let valid = if let Some(entry_ext) = path.extension() {
// discard invalid UTF-8 and convert to lowercase. all extensions in both backend's databases are lowercase
// ascii, so this assumption is fine.
let entry_ext = entry_ext.to_string_lossy().to_lowercase();
let valid = match known_exts {
// there is a known set of extensions for this MIME type, and the file has an extension
Some(e) if entry_ext.is_some() => e.contains(&entry_ext.unwrap().to_string_lossy().to_lowercase().into()),
// either this file has no extension, or there is no known set of extensions for this MIME type :(
Some(_) | None => false,
// if the file has any of these extensions, it is probably either:
// - a copy of another file renamed for backup purposes (e.g. a word processor might save by renaming "my.doc" to
// "my.doc.bak", then creating "my.doc", leaving the backup for safekeeping), which shouldn't be renamed so as
// not to break the backup program
// - a partially downloaded file, which shouldn't be renamed to avoid corrupting it and blocking the downloader
// from resuming
if ["bak", "backup", "filepart", "part", "crdownload"]
.iter()
.any(|ext| ext == &entry_ext)
{
true
} else {
// otherwise, check to see whether there's a known extension for this file type
// retrieve set of known extensions for the given MIME type
let known_exts = mime_extension_lookup(result.essence_str().into());
match known_exts {
// there is a known set of extensions for this MIME type - is entry_ext in the given set?
Some(e) => e.contains(&entry_ext.into()),
// there is no known set of extensions for this MIME type :(
None => false,
}
}
} else {
// this file has no extension
false
};
let path = if canonical_paths {
@ -262,9 +284,8 @@ pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
file.seek(SeekFrom::Start(0))?;
read = file.read(&mut buffer);
match read {
Ok(_) => break,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => break,
Err(_) | Ok(_) => break,
}
}
@ -296,7 +317,7 @@ pub fn mime_type<T: MimeDb>(db: &T, path: &Path) -> io::Result<Option<Mime>> {
// attempt to read up to BUF_SIZE bytes of the file.
let mut buffer = [0; BUF_SIZE];
file.seek(SeekFrom::Start(0))?;
file.read(&mut buffer)?;
_ = file.read(&mut buffer)?;
Ok(db.get_type(&buffer))
}
@ -350,16 +371,47 @@ pub fn mime_extension_lookup(essence: String) -> Option<Vec<String>> {
// 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...
// 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")],
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, and .scr 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"), String::from("scr")], possible_exts].concat()
// .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
})

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! The [`Findings`] and [`ScanError`] structs, used for conveying whether a given file was able to be scanned, whether
//! its MIME type could be inferred, and whether the file should be renamed.

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Logic for handling the various output formats that fif can output to.
@ -31,7 +31,6 @@ use crate::String;
/// // ...just use:
/// smart_write(&mut f, writables!["hello", Newline]);
/// ```
#[macro_export]
macro_rules! writables {
[$($args:tt),+] => {
@ -55,7 +54,7 @@ macro_rules! writablesln {
};
}
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
pub enum Writable<'a> {
String(&'a str),
Path(&'a Path),
@ -90,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) => {
if let Some(path_str) = path.to_str() {
let escaped = escape(path_str);
@ -98,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
// need to be escaped. however, it's Best Practice™ to escape such strings anyway, so we prefix/suffix the
// escaped string with single quotes.
write!(f, "'{}'", escaped)?;
write!(f, "'{escaped}'")?;
} else {
write!(f, "{}", escaped)?;
write!(f, "{escaped}")?;
}
} else {
write!(f, "'")?;
@ -111,7 +110,7 @@ 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>>())?;
write!(f, "{}", path.as_os_str().to_string_lossy())?;
} else {
f.write_all(&*path.as_os_str().as_bytes())?;
f.write_all(path.as_os_str().as_bytes())?;
}
}
write!(f, "'")?;
@ -197,6 +196,7 @@ impl FormatSteps for Shell {
if let Ok(working_directory) = std::env::current_dir() {
smart_write(f, writablesln!["# Run from ", (working_directory.as_path())])?;
}
write!(f, "# Happy with these changes? Run `fif --fix` from the same directory!")?;
smart_write(f, writablesln![Newline, "set -e", Newline])
}
@ -253,6 +253,7 @@ impl FormatSteps for PowerShell {
if let Ok(working_directory) = std::env::current_dir() {
smart_write(f, writablesln!["<# Run from ", (working_directory.as_path()), " #>"])?;
}
write!(f, "<# Happy with these changes? Run `fif --fix` from the same directory! #>")?;
smart_write(f, writables![Newline])
}
@ -287,7 +288,11 @@ impl FormatSteps for Text {
}
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) -> io::Result<()> {

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! This library consists of all of the things fif needs to run. It only exists as a library to separate code, and to
//! make documentation and testing a bit easier. I don't recommend using this as a library for your crate, as it may

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
// fif - a command-line tool for detecting and optionally correcting files with incorrect extensions.
@ -132,7 +132,7 @@ fn main() {
if args.fix {
fn ask(message: &str) -> bool {
let mut buf = String::with_capacity(1);
print!("{} [y/N] ", message);
print!("{message} [y/N] ");
// flush stdout to ensure message is displayed
stdout().flush().expect("Failed to flush stdout");
@ -163,10 +163,10 @@ fn main() {
// 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)) {
} 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 {:#?} already exists, overwrite?", rename_to))
!rename_to.exists() || ask(&format!("Destination {rename_to:#?} already exists, overwrite?"))
} else {
// handles: --prompt always --overwrite [n]
// user was prompted and replied "no"
@ -182,7 +182,7 @@ fn main() {
loop {
// until file is renamed successfully
match std::fs::rename(&f.file, &rename_to) {
Ok(_) => {
Ok(()) => {
info!("Renamed {:#?} -> {:#?}", f.file, rename_to);
renamed += 1;
break;
@ -191,7 +191,7 @@ fn main() {
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: {:#?}. Try again?", e)) {
if prompt == Prompt::Never || !ask(&format!("Error while renaming file: {e:#?}. Try again?")) {
failed += 1;
break;
}

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Backend-neutral Mime database abstraction.
@ -32,7 +32,7 @@ cfg_if! {
}
fn open_document_check(buf: &[u8], kind: &str) -> bool {
let mime = format!("application/vnd.oasis.opendocument.{}", kind);
let mime = format!("application/vnd.oasis.opendocument.{kind}");
let mime = mime.as_bytes();
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
@ -42,26 +42,44 @@ cfg_if! {
fn init() -> Self {
let mut info = infer::Infer::new();
// In addition to the file inferences provided by Infer, I've also added a few of my own below. Some of them
// replace Infer's existing ones, some of them are less than perfect, and still others are for relatively
// obscure formats, so I'm not really sure whether or not they should be contributed upstream.
// OpenDocument Text (used by e.g. LibreOffice Writer)
info.add("application/vnd.oasis.opendocument.text", "odt", |buf| {
open_document_check(buf, "text")
});
// OpenDocument Spreadsheet (LibreOffice Calc)
info.add("application/vnd.oasis.opendocument.spreadsheet", "ods", |buf| {
open_document_check(buf, "spreadsheet")
});
// OpenOffice Presentation (LibreOffice Impress)
info.add("application/vnd.oasis.opendocument.presentation", "odp", |buf| {
open_document_check(buf, "presentation")
});
// Ren'Py Archive (Ren'Py: https://www.renpy.org/)
info.add("application/x-rpa", "rpa", |buf| {
buf.len() >= 34 && buf.starts_with(b"RPA-") && buf[7] == b' ' && buf[24] ==b' '
});
info.add("audio/x-aiff", "aiff", |buf| {
// as added by https://github.com/bojand/infer/pull/48/files
// this should be removed when (if) that PR is accepted
buf.starts_with(b"\x46\x4f\x52\x4d\x41\x49\x46\x46")
// Mach-O Binaries (The executable format used by macOS)
// my source for most of this info is this article: https://h3adsh0tzz.com/2020/01/macho-file-format/
info.add("application/x-mach-binary", "macho", |buf| {
// a 32-bit mach-o header occupies 28 bits of space, so any input smaller than that cannot be a mach-o
// binary, even if it starts with the magic numbers.
// java class files also start with 0xCAFEBABE. since infer doesn't support detecting these files,
// collisions are not an issue. if, however, infer does gain support for identifying java class files, the
// 0xCAFEBABE check should be removed, as java bytecode files are far more prevalent than 32-bit universal
// mach-o binaries [citation needed].
// check for magic numbers (0xFEEDCACF, 0xFEEDFACE, 0xCAFEBABE) in both big and little endian forms
buf.len() >= 28 && [b"\xFE\xED\xFA\xCF", b"\xFE\xED\xFA\xCE", b"\xCA\xFE\xBA\xBE", b"\xCF\xFA\xED\xFE",
b"\xCE\xFA\xED\xFE", b"\xBE\xBA\xFE\xCA"].iter().any(|magic_numbers| buf.starts_with(&magic_numbers[..]))
});
// info.add("application/x-msi", "msi", |buf| {
@ -70,10 +88,10 @@ cfg_if! {
// buf.starts_with(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1")
// });
// Scalable Vector Graphics
info.add("image/svg+xml", "svg", |buf| {
// before doing the moderately expensive SVG check, we should make sure that the input is actually SGML-ish,
// by which i mean, starts with anywhere from zero to ∞-1 whitespace characters, and then a less than sign,
// and then there's some other stuff we don't care about right now
// by which i mean, starts with the pattern "\s*<".
// so, here comes our fancy pants """""SGML-ish validator"""""
for c in buf {
@ -89,8 +107,8 @@ cfg_if! {
// - split the buffer up into chunks separated by the less than sign
// - check to see if this chunk starts with any of these identifiers:
let identifiers: Vec<&[u8]> = vec![b"svg", b"SVG", b"!DOCTYPE svg", b"!DOCTYPE SVG"];
// - if it does, the nested `any` will short circuit and immediately return true, causing the parent `any` to do
// the same
// - if it does, the nested `any` will short circuit and immediately return true, causing the parent `any` to
// do the same
// - and finally, if none of the chunks match, we'll return false
// TODO: this is kind of messy, i'd like to clean it up somehow :(

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Command line argument parsing logic and associated functions.
@ -7,7 +7,7 @@ use std::collections::BTreeSet;
use std::path::PathBuf;
use cfg_if::cfg_if;
use clap::{Parser, ArgEnum};
use clap::{ArgAction, Parser, ValueEnum};
use crate::utils::{CLAP_LONG_VERSION, CLAP_VERSION};
use crate::String as StringType;
@ -22,7 +22,7 @@ cfg_if! {
}
}
#[derive(ArgEnum, PartialEq, Debug, Copy, Clone)]
#[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 {
@ -39,7 +39,7 @@ pub enum OutputFormat {
Json,
}
#[derive(ArgEnum, PartialEq, Debug, Copy, Clone)]
#[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 {
@ -58,8 +58,8 @@ pub enum Prompt {
long_version = CLAP_LONG_VERSION.as_str(),
author = option_env!("CARGO_PKG_AUTHORS").unwrap_or("Lynnesbian"),
about = option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("File Info Fixer"),
before_help = "Copyright © 2021 Lynnesbian under the GPL3 (or later) License.",
after_long_help = "Copyright © 2021 Lynnesbian\n\
before_help = "Copyright © 2021-2022 Lynnesbian under the GPL3 (or later) License.",
after_long_help = "Copyright © 2021-2022 Lynnesbian\n\
This program is free software: you can redistribute it and/or modify \
it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 \
of the License, or (at your option) any later version.",
@ -68,26 +68,25 @@ pub enum Prompt {
/// [`Clap`]-derived struct used to parse command line arguments.
pub struct Parameters {
/// Automatically rename files to use the correct extension, prompting the user for every rename.
#[clap(long)]
#[clap(long, help_heading = "RENAMING")]
pub fix: bool,
/// Requires --fix. Should fif prompt you `Never`, only on `Error`s and overwrites, or `Always`?
#[clap(short = 'p', long, arg_enum, requires = "fix")]
#[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")]
#[clap(long, requires = "fix", help_heading = "RENAMING")]
pub overwrite: bool,
// NOTE: clap's comma-separated argument parser makes it impossible to specify extensions with commas in their name -
// `-e sil\,ly` is treated as ["sil", "ly"] rather than as ["silly"], no matter how i escape the comma (in bash,
// anyway). is this really an issue? it does technically exclude some perfectly valid extensions, but i've never seen
// a file extension with a comma in its name before.
// NOTE: it is impossible (as far as i can tell) to accept extensions with commas in their name. i don't know why
// you would ever want a file named something like "example.xy,z", though... fif's -e and -x flags don't support this.
/// Only examine files with these extensions.
/// Multiple extensions can be specified by either using the flag multiple times (`-e jpg -e png -e gif`), or by
/// separating them with commas (`-e jpg,png,gif`).
#[clap(short, long, use_delimiter = true, require_delimiter = true, value_name = "ext", takes_value = true, validator = validate_exts)]
#[clap(short, long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", num_args(1),
value_parser = validate_exts, help_heading = "FILTERING")]
pub exts: Option<Vec<StringType>>,
/// Use these preset lists of extensions as the search filter (comma-separated list).
@ -96,17 +95,18 @@ pub struct Parameters {
#[clap(
short = 'E',
long,
arg_enum,
use_delimiter = true,
require_delimiter = true,
value_name = "set"
value_enum,
use_value_delimiter = true,
value_delimiter = ',',
value_name = "set",
help_heading = "FILTERING"
)]
pub ext_set: Vec<ExtensionSet>,
/// Don't scan files with these extensions.
/// This option takes precedence over extensions specified with `-e` or `-E`.
#[clap(short = 'x', long, use_delimiter = true, require_delimiter = true, value_name = "ext", validator =
validate_exts)]
#[clap(short = 'x', long, use_value_delimiter = true, value_delimiter = ',', value_name = "ext", value_parser =
validate_exts, help_heading = "FILTERING")]
pub exclude: Option<Vec<StringType>>,
/// Exclude files using a preset list of extensions.
@ -114,72 +114,73 @@ pub struct Parameters {
#[clap(
short = 'X',
long,
arg_enum,
use_delimiter = true,
require_delimiter = true,
value_name = "set"
value_enum,
use_value_delimiter = true,
value_delimiter = ',',
value_name = "set",
help_heading = "FILTERING"
)]
pub exclude_set: Vec<ExtensionSet>,
/// Don't skip hidden files and directories.
/// Even if this flag is not present, fif will still recurse into a hidden root directory - for example, `fif
/// ~/.hidden` will recurse into `~/.hidden` regardless of whether or not -s was passed as an argument.
#[clap(short, long)]
#[clap(short, long, help_heading = "FILTERING")]
pub scan_hidden: bool,
/// Scan files without extensions.
/// By default, fif will ignore files without extensions - for example, a jpeg file named `photo` won't be considered
/// misnamed. Supplying the -S flag will cause fif to recommend renaming this file to `photo.jpg`.
#[clap(short = 'S', long)]
#[clap(short = 'S', long, help_heading = "FILTERING")]
pub scan_extensionless: bool,
/// Follow symlinks.
#[clap(short, long, help_heading = "FILTERING")]
pub follow_symlinks: bool,
/// Don't rename files with extensions unknown to fif.
/// For example, with this option, fif will not rename "image.unknown" to "image.jpg"
#[clap(short = 'I', long, help_heading = "FILTERING")]
pub ignore_unknown_exts: bool,
/// Output format to use.
/// By default, fif will output a PowerShell script on Windows, and a Bourne Shell script on other platforms.
#[clap(short, long, default_value = DEFAULT_FORMAT, arg_enum, value_name = "format")]
#[clap(short, long, default_value = DEFAULT_FORMAT, value_enum, value_name = "format", help_heading = "OUTPUT")]
pub output_format: OutputFormat,
/// Follow symlinks.
#[clap(short, long)]
pub follow_symlinks: bool,
/// Output verbosity. Each additional `-v` increases verbosity.
/// Can be overridden by FIF_LOG or RUST_LOG.
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
pub verbose: u8,
/// Output quietness. Each additional `-q` decreases verbosity.
/// Can be overridden by FIF_LOG or RUST_LOG.
#[clap(short, long, parse(from_occurrences), group = "verbosity")]
#[clap(short, long, action = ArgAction::Count, group = "verbosity", help_heading = "OUTPUT")]
pub quiet: u8,
/// Use canonical (absolute) paths in output.
/// A canonical path is the "one true path" to a given file, and is always an absolute path. While a file may have
/// many absolute paths (for example, on Windows, '\\?\C:\file.txt' and 'C:\file.txt' are both absolute paths to the
/// same file), but only one canonical path. This does not effect logged output.
#[clap(long)]
#[clap(long, help_heading = "OUTPUT")]
pub canonical_paths: bool,
/// The directory to process.
#[clap(name = "DIR", default_value = ".", parse(from_os_str))]
#[clap(name = "DIR", default_value = ".", value_parser)]
pub dir: PathBuf,
/// 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)]
pub ignore_unknown_exts: bool,
#[cfg(feature = "multi-threaded")]
/// Number of jobs (threads) to use when scanning results.
/// The default behaviour is to use one thread per CPU thread. This behaviour can be manually requested by setting
/// `-j 0`. Using `-j 1` will disable multi-threading behaviour, as if you had compiled fif with the multi-threading
/// feature disabled. Setting more jobs than you have CPU threads is not recommended.
#[clap(short = 'j', long, default_value = "0")]
#[clap(short = 'j', long, default_value = "0", help_heading = "MISC")]
pub jobs: usize,
}
/// Validation function for argument parsing that ensures passed-in extensions are lowercase, and that the user
/// didn't supply an empty list.
fn validate_exts(exts: &str) -> Result<(), String> {
fn validate_exts(exts: &str) -> Result<StringType, String> {
// TODO: i would much rather accept uppercase exts and convert them to lowercase than just rejecting lowercase exts...
if exts.is_empty() {
@ -189,11 +190,11 @@ fn validate_exts(exts: &str) -> Result<(), String> {
if exts.to_lowercase() != exts {
return Err(String::from("Supplied extensions must be lowercase"));
}
Ok(())
Ok(exts.into())
}
/// Further options relating to scanning.
#[derive(PartialEq, Debug, Copy, Clone)]
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ScanOpts {
/// Whether hidden files and directories should be scanned.
@ -296,7 +297,7 @@ impl Parameters {
}
/// Sets of extensions for use with [Parameter](crate::parameters::Parameters)'s `-E` flag.
#[derive(ArgEnum, PartialEq, Debug, Copy, Clone)]
#[derive(ValueEnum, Eq, PartialEq, Debug, Copy, Clone)]
pub enum ExtensionSet {
/// Extensions used for image file formats, such as `png`, `jpeg`, `webp`, etc.
Images,

View File

@ -1,6 +1,5 @@
// SPDX-FileCopyrightText: 2021 2021 Lynnesbian
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
use std::collections::{BTreeMap, HashMap};
use std::ffi::OsStr;
@ -103,11 +102,11 @@ fn simple_directory() {
set_current_dir(dir.path()).expect("Failed to change directory.");
for (name, bytes) in &files {
let mut file = File::create(dir.path().join(name)).expect(&*format!("Failed to create file: {}", name));
let mut file = File::create(dir.path().join(name)).unwrap_or_else(|_| panic!("Failed to create file: {name}"));
file
.write_all(bytes)
.expect(&*format!("Failed to write to file: {}", name));
.unwrap_or_else(|_| panic!("Failed to write to file: {name}"));
drop(file);
}
@ -131,8 +130,6 @@ fn simple_directory() {
for (result, canonical_result) in results.iter().zip(canonical_results.iter()) {
// there should be no IO errors during this test. any IO errors encountered are outside the scope of this test.
// let result = result.as_ref().expect("Error while scanning file");
// let canonical_result = canonical_result.as_ref().expect("Error while scanning file");
// paths should be canonical
assert_eq!(canonicalize(&result.file).unwrap(), canonical_result.file);
@ -228,7 +225,7 @@ fn argument_parsing() {
#[test]
/// Ensure that `fif -e jpg dir` is interpreted as "scan for jpg files in dir" and not "scan for jpg and dir files"
fn positional_args() {
for flag in &["-x", "-e", "-X", "-E"] {
for flag in ["-x", "-e", "-X", "-E"] {
assert_eq!(
Parameters::parse_from(vec!["fif", flag, "images", "directory"]).dir,
PathBuf::from("directory")
@ -282,12 +279,12 @@ fn exclude_set_overrides_include_set() {
.iter()
.chain(ExtensionSet::Video.extensions().iter())
{
assert!(extensions.contains(&ext), "Extensions should contain {}!", ext);
assert!(extensions.contains(&ext), "Extensions should contain {ext}!");
}
// ensure all of images' extensions are excluded
for ext in ExtensionSet::Images.extensions() {
assert!(!extensions.contains(&ext), "Extensions should not contain {}!", ext);
assert!(!extensions.contains(&ext), "Extensions should not contain {ext}!");
}
}
@ -318,7 +315,7 @@ fn rejects_bad_args() {
for test in &tests {
// first, try testing the flags against the Parameters struct...
assert!(Parameters::try_parse_from(test).is_err(), "Failed to reject {:?}", test);
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();
@ -351,6 +348,7 @@ fn accepts_good_args() {
/// 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;
@ -359,18 +357,16 @@ fn check_version_output() {
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()),
"\"{}\" does not match the expected `-v` format!",
output
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})\)"#)
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!",
@ -395,7 +391,7 @@ fn identify_random_bytes() {
}
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>());
}
@ -432,9 +428,7 @@ fn outputs_move_commands() {
// the output should contain a command like "mv -i misnamed_file.png misnamed_file.jpg"
assert!(
contents.contains("misnamed_file.jpg") && contents.contains("misnamed_file.png"),
"{} output doesn't contain move command!\n===\n{}",
format,
contents
"{format} output doesn't contain move command!\n===\n{contents}"
);
}
}
@ -468,8 +462,7 @@ fn test_json() {
// the output should contain the file's MIME type
assert!(
contents.contains(IMAGE_JPEG.essence_str()),
"JSON output doesn't contain move command!\n===\n{}",
contents
"JSON output doesn't contain move command!\n===\n{contents}"
);
}
@ -486,8 +479,8 @@ fn media_contains_audio_video_images() {
.for_each(|ext| assert!(media_exts.contains(&ext)));
assert_eq!(
Parameters::parse_from(&["fif", "-E", "media"]).extensions(),
Parameters::parse_from(&["fif", "-E", "audio,video,images"]).extensions()
Parameters::parse_from(["fif", "-E", "media"]).extensions(),
Parameters::parse_from(["fif", "-E", "audio,video,images"]).extensions()
);
}
@ -513,7 +506,7 @@ fn writables_is_correct() {
fn verbosity() {
use log::LevelFilter;
assert!(
Parameters::try_parse_from(&["fif", "-q", "-v"]).is_err(),
Parameters::try_parse_from(["fif", "-q", "-v"]).is_err(),
"Failed to reject usage of both -q and -v!"
);
@ -530,7 +523,7 @@ fn verbosity() {
];
for (flags, level) in expected_results {
assert_eq!(Parameters::parse_from(&["fif", flags]).get_verbosity(), level);
assert_eq!(Parameters::parse_from(["fif", flags]).get_verbosity(), level);
}
}
@ -567,20 +560,3 @@ fn sort_findings() {
assert_eq!(findings.next().unwrap().file, Path::new("ccc"));
assert_eq!(findings.next(), None);
}
#[test]
#[cfg(not(all(target_endian = "big", target_pointer_width = "32")))]
/// Ensures that [`SmartString`]s don't deviate from std's Strings
fn validate_string_type() {
use std::string::String as StdString;
use fif::String as SmartString;
assert_eq!(SmartString::new(), StdString::new());
assert_eq!(SmartString::from("smol"), StdString::from("smol"));
assert_eq!(
SmartString::from("A long and therefore heap-allocated string"),
StdString::from("A long and therefore heap-allocated string")
);
smartstring::validate();
}

View File

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 Lynnesbian
// SPDX-License-Identifier: LGPL-3.0-or-later
// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
//! Various minor utilities.

17
test.py
View File

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