clircle-0.4.0/.cargo_vcs_info.json0000644000000001360000000000100124520ustar { "git": { "sha1": "99745d8be43426178281a85df50ef01ca5960c9f" }, "path_in_vcs": "" }clircle-0.4.0/.github/workflows/ci.yml000064400000000000000000000025621046102023000157620ustar 00000000000000name: CI on: push: branches: - main pull_request: jobs: build: name: Build, test, and lint strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] rust: ["1.56.0", stable] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} components: clippy - run: cargo build - run: cargo test - run: cargo clippy build_extra: name: Build on extra platforms runs-on: ubuntu-latest strategy: fail-fast: false matrix: target: - aarch64-linux-android - aarch64-unknown-linux-gnu - arm-linux-androideabi - arm-unknown-linux-gnueabihf - i586-unknown-linux-gnu - i686-linux-android - i686-unknown-linux-gnu - x86_64-linux-android steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable with: targets: ${{ matrix.target }} - run: cargo build --target ${{ matrix.target }} rustfmt: name: Check formatting runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - run: cargo fmt --all -- --check clircle-0.4.0/.gitignore000064400000000000000000000000231046102023000132250ustar 00000000000000/target Cargo.lock clircle-0.4.0/Cargo.lock0000644000000174150000000000100104350ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "cc" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clircle" version = "0.4.0" dependencies = [ "cfg-if", "libc", "nix", "serde", "tempfile", "winapi", ] [[package]] name = "errno" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", "windows-sys", ] [[package]] name = "errno-dragonfly" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" dependencies = [ "cc", "libc", ] [[package]] name = "fastrand" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" dependencies = [ "instant", ] [[package]] name = "hermit-abi" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" [[package]] name = "instant" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if", ] [[package]] name = "io-lifetimes" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ "hermit-abi", "libc", "windows-sys", ] [[package]] name = "libc" version = "0.2.146" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" [[package]] name = "linux-raw-sys" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "nix" version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069" dependencies = [ "bitflags", "cfg-if", "libc", ] [[package]] name = "proc-macro2" version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ "bitflags", ] [[package]] name = "rustix" version = "0.37.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0" dependencies = [ "bitflags", "errno", "io-lifetimes", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "serde" version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "syn" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" dependencies = [ "autocfg", "cfg-if", "fastrand", "redox_syscall", "rustix", "windows-sys", ] [[package]] name = "unicode-ident" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" clircle-0.4.0/Cargo.toml0000644000000030410000000000100104460ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "clircle" version = "0.4.0" authors = ["Niklas Mohrin "] description = "Detect IO circles in your CLI apps arguments." homepage = "https://github.com/niklasmohrin/clircle" documentation = "https://docs.rs/clircle" readme = "README.md" keywords = [ "cycle", "arguments", "argv", "io", ] categories = [ "command-line-interface", "filesystem", "os", ] license = "MIT OR Apache-2.0" repository = "https://github.com/niklasmohrin/clircle" [dependencies.cfg-if] version = "1.0.0" [dependencies.serde] version = "1.0.117" features = ["derive"] optional = true [dev-dependencies.tempfile] version = "3.1.0" [features] default = ["serde"] [target."cfg(not(windows))".dependencies.libc] version = "0.2" [target."cfg(not(windows))".dev-dependencies.nix] version = "0.24.1" features = ["term"] default-features = false [target."cfg(windows)".dependencies.winapi] version = "0.3.9" features = [ "winnt", "winbase", "processenv", "handleapi", "ntdef", "fileapi", "std", ] clircle-0.4.0/Cargo.toml.orig000064400000000000000000000017641046102023000141410ustar 00000000000000[package] name = "clircle" version = "0.4.0" authors = ["Niklas Mohrin "] license = "MIT OR Apache-2.0" rust-version = "1.56" edition = "2021" description = "Detect IO circles in your CLI apps arguments." homepage = "https://github.com/niklasmohrin/clircle" repository = "https://github.com/niklasmohrin/clircle" documentation = "https://docs.rs/clircle" readme = "README.md" categories = ["command-line-interface", "filesystem", "os"] keywords = ["cycle", "arguments", "argv", "io"] [features] default = ["serde"] [dependencies] serde = { version = "1.0.117", optional = true, features = ["derive"] } cfg-if = "1.0.0" [target.'cfg(not(windows))'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3.9", features = ["winnt", "winbase", "processenv", "handleapi", "ntdef", "fileapi", "std"] } [dev-dependencies] tempfile = "3.1.0" [target.'cfg(not(windows))'.dev-dependencies.nix] version = "0.24.1" default-features = false features = ["term"] clircle-0.4.0/LICENSE-APACHE000064400000000000000000000227731046102023000132010ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS clircle-0.4.0/LICENSE-MIT000064400000000000000000000017771046102023000127120ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. clircle-0.4.0/README.md000064400000000000000000000046271046102023000125320ustar 00000000000000# Clircle [![CI](https://github.com/niklasmohrin/clircle/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/niklasmohrin/clircle/actions/workflows/ci.yml) [![crates.io version](https://img.shields.io/crates/v/clircle)](https://crates.io/crates/clircle) [![MSRV](https://img.shields.io/badge/MSRV-1.56.0-blue)](https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html) Clircle provides a cross-platform API to detect read / write cycles from your user-supplied arguments. You can get the important identifiers of a file (from a path) and for all three stdio streams, if they are piped from or to a file as well. ## Why? Imagine you want to read data from a couple of files and output something according to the contents of these files. If the user redirects the output of your program to one of the input files, you might end up in an infinite circle of reading and writing. The crate provides the struct `Identifier` which is a platform dependent type alias, so that you can use it on all platforms and do not need to introduce any conditional compilation yourself. On both Unix and Windows systems, `Identifier` holds information to identify a file on a disk. The `Clircle` trait is implemented on both of these structs and requires `TryFrom` for the `clircle::Stdio` enum and for `&Path`, so that all possible inputs can be represented as an `Identifier`. Finally, `Clircle` is a subtrait of `Eq`, so that the identifiers can be conveniently compared and circles can be detected. The `clircle` crate also provides some convenience functions around the comparison of `Clircle` implementors. ## Why should I use this and not just `fs::Metadata`? The `clircle` crate seamlessly works on Linux **and** Windows through a single API, so no conditional compilation is needed at all. Furthermore, `MetadataExt` is not stable on Windows yet, meaning you would have to dig into the Windows APIs yourself to get the information needed to identify a file. ## Where did this crate come from? This crate originated in a pull request to the [`bat`](https://github.com/sharkdp/bat) project. The `bat` tool strives to be a drop-in replacement for the unix tool `cat`. Since `cat` detects these cycles, `bat` has to do so too, which is where most of this code came into play. However, it was decided, that the new logic was - useful for other projects and - too platform specific for `bat`s scope. So now, you can use `clircle` too! clircle-0.4.0/examples/return_code.rs000064400000000000000000000016041046102023000157400ustar 00000000000000//! This example collects all given arguments, interprets them as paths, gathers information //! about them and checks if stdout is being redirected to one of the given files. //! If that's the case, the return code will be set to 1. In both cases, there is an according //! output to stderr. use clircle::{stdout_among_inputs, Identifier}; use std::convert::TryFrom; use std::fs::File; fn main() { let inputs: Vec<_> = std::env::args().collect(); let inputs: Result, _> = inputs .iter() .map(File::open) .map(Result::unwrap) .map(Identifier::try_from) .collect(); let inputs = inputs.expect("There was an argument that could not be converted to an Idenfier!"); if stdout_among_inputs(&inputs) { eprintln!("Cycle detected!"); std::process::exit(1); } else { eprintln!("No cycle detected.") } } clircle-0.4.0/src/clircle_unix.rs000064400000000000000000000154641046102023000150710ustar 00000000000000use crate::{Clircle, Stdio}; use std::convert::TryFrom; use std::fs::File; use std::io::{self, Seek}; use std::os::unix::fs::MetadataExt; use std::os::unix::io::{FromRawFd, IntoRawFd, RawFd}; use std::{cmp, hash, ops}; /// Re-export of libc pub use libc; /// Implementation of `Clircle` for Unix. #[derive(Debug)] pub struct UnixIdentifier { device: u64, inode: u64, size: u64, is_regular_file: bool, file: Option, owns_fd: bool, } impl UnixIdentifier { fn file(&self) -> &File { self.file.as_ref().expect("Called file() on an identifier that has already been destroyed, this should never happen! Please file a bug!") } fn current_file_offset(&self) -> io::Result { self.file().stream_position() } fn has_content_left_to_read(&self) -> io::Result { Ok(self.current_file_offset()? < self.size) } /// Creates a `UnixIdentifier` from a raw file descriptor. The preferred way to create a /// `UnixIdentifier` is through one of the `TryFrom` implementations. /// /// # Safety /// /// The `owns_fd` argument should only be true, if the given file descriptor owns the resource /// it points to (for example a file). /// If it is true, a `File` can be obtained back with `Clircle::into_inner`, or it will be /// closed when the `UnixIdentifier` is dropped. /// /// # Errors /// /// The underlying call to `File::metadata` fails. pub unsafe fn try_from_raw_fd(fd: RawFd, owns_fd: bool) -> io::Result { Self::try_from(File::from_raw_fd(fd)).map(|mut ident| { ident.owns_fd = owns_fd; ident }) } } impl Clircle for UnixIdentifier { #[must_use] fn into_inner(mut self) -> Option { if self.owns_fd { self.owns_fd = false; self.file.take() } else { None } } /// This method implements the conflict check that is used in the GNU coreutils program `cat`. #[must_use] fn surely_conflicts_with(&self, other: &Self) -> bool { PartialEq::eq(self, other) && self.is_regular_file && other.has_content_left_to_read().unwrap_or(true) } } impl TryFrom for UnixIdentifier { type Error = >::Error; fn try_from(stdio: Stdio) -> Result { let fd = match stdio { Stdio::Stdin => libc::STDIN_FILENO, Stdio::Stdout => libc::STDOUT_FILENO, Stdio::Stderr => libc::STDERR_FILENO, }; // Safety: It is okay to create the file, because it won't be dropped later since the // `owns_fd` field is not set. unsafe { Self::try_from_raw_fd(fd, false) } } } impl ops::Drop for UnixIdentifier { fn drop(&mut self) { if !self.owns_fd { let _ = self.file.take().map(IntoRawFd::into_raw_fd); } } } impl TryFrom for UnixIdentifier { type Error = io::Error; fn try_from(file: File) -> Result { file.metadata().map(|metadata| Self { device: metadata.dev(), inode: metadata.ino(), size: metadata.size(), is_regular_file: metadata.file_type().is_file(), file: Some(file), owns_fd: true, }) } } impl cmp::PartialEq for UnixIdentifier { #[must_use] fn eq(&self, other: &Self) -> bool { self.device == other.device && self.inode == other.inode } } impl Eq for UnixIdentifier {} impl hash::Hash for UnixIdentifier { fn hash(&self, state: &mut H) { self.device.hash(state); self.inode.hash(state); } } #[cfg(test)] mod tests { use super::*; use std::error::Error; use std::io::Write; use nix::pty::{openpty, OpenptyResult}; use nix::unistd::close; #[test] fn test_fd_closing() -> Result<(), Box> { let dir = tempfile::tempdir().expect("Couldn't create tempdir."); let dir_path = dir.path().to_path_buf(); // 1) Check that the file returned by into_inner is still valid let file = File::create(dir_path.join("myfile"))?; let ident = UnixIdentifier::try_from(file)?; let mut file = ident .into_inner() .ok_or("Did not get file back from identifier")?; // Check if file can be written to without weird errors file.write_all(b"Some test content")?; // 2) Check that dropping the Identifier does not close the file, if owns_fd is false let fd = file.into_raw_fd(); let ident = unsafe { UnixIdentifier::try_from_raw_fd(fd, false) }; if let Err(e) = ident { let _ = dbg!(close(fd)); return Err(Box::new(e)); } let ident = ident.unwrap(); drop(ident); close(fd).map_err(|e| { format!( "Error closing file, that I told UnixIdentifier not to close: {}", e ) })?; // 3) Check that the file is closed on drop, if owns_fd is true let fd = File::open(dir_path.join("myfile"))?.into_raw_fd(); let ident = unsafe { UnixIdentifier::try_from_raw_fd(fd, true) }; if let Err(e) = ident { let _ = dbg!(close(fd)); return Err(Box::new(e)); } let ident = ident.unwrap(); drop(ident); close(fd).expect_err("This file descriptor should have been closed already!"); Ok(()) } #[test] fn test_pty_equal_but_not_conflicting() -> Result<(), &'static str> { let OpenptyResult { master, slave } = openpty(None, None).expect("Could not open pty."); let res = unsafe { UnixIdentifier::try_from_raw_fd(slave, false) } .map_err(|_| "Error creating UnixIdentifier from pty fd") .and_then(|ident| { if !ident.eq(&ident) { return Err("ident != ident"); } if ident.surely_conflicts_with(&ident) { return Err("pty fd does not conflict with itself, but conflict detected"); } let second_ident = unsafe { UnixIdentifier::try_from_raw_fd(slave, false) } .map_err(|_| "Error creating second Identifier to pty")?; if !ident.eq(&second_ident) { return Err("ident != second_ident"); } if ident.surely_conflicts_with(&second_ident) { return Err( "Two Identifiers to the same pty should not conflict, but they do.", ); } Ok(()) }); let r1 = close(master); let r2 = close(slave); r1.expect("Error closing master end of pty"); r2.expect("Error closing slave end of pty"); res } } clircle-0.4.0/src/clircle_windows.rs000064400000000000000000000105431046102023000155710ustar 00000000000000use crate::{Clircle, Stdio}; use winapi::shared::ntdef::NULL; use winapi::um::{ fileapi::{GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION}, handleapi::INVALID_HANDLE_VALUE, processenv::GetStdHandle, winbase::{FILE_TYPE_DISK, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE}, }; use std::convert::TryFrom; use std::fs::File; use std::mem::MaybeUninit; use std::os::windows::io::{FromRawHandle, IntoRawHandle, RawHandle}; use std::{cmp, hash, io, mem, ops}; /// Re-export of winapi pub use winapi; /// Implementation of `Clircle` for Windows. #[derive(Debug)] pub struct WindowsIdentifier { volume_serial: u32, file_index: u64, handle: RawHandle, owns_handle: bool, } impl WindowsIdentifier { unsafe fn try_from_raw_handle(handle: RawHandle, owns_handle: bool) -> Result { if handle == INVALID_HANDLE_VALUE || handle == NULL { return Err(io::Error::new( io::ErrorKind::InvalidInput, "Tried to convert handle to WindowsIdentifier that was invalid or null.", )); } // SAFETY: This function can be called with any valid handle. // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfiletype if GetFileType(handle) != FILE_TYPE_DISK { return Err(io::Error::new( io::ErrorKind::InvalidInput, "Tried to convert handle to WindowsIdentifier that was not a file handle.", )); } let mut fi = MaybeUninit::::uninit(); // SAFETY: This function is safe to call, if the handle is valid and a handle to a file. // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle let success = GetFileInformationByHandle(handle, fi.as_mut_ptr()); if success == 0 { Err(io::Error::last_os_error()) } else { // SAFETY: If the return value of GetFileInformationByHandle is non-zero, the struct // has successfully been initialized (see link above). let fi = fi.assume_init(); Ok(Self { volume_serial: fi.dwVolumeSerialNumber, file_index: u64::from(fi.nFileIndexHigh) << 32 | u64::from(fi.nFileIndexLow), handle, owns_handle, }) } } unsafe fn take_handle(&mut self) -> Option { if self.owns_handle { self.owns_handle = false; Some(mem::replace(&mut self.handle, INVALID_HANDLE_VALUE)) } else { None } } } impl Clircle for WindowsIdentifier { #[must_use] fn into_inner(mut self) -> Option { Some(unsafe { File::from_raw_handle(self.take_handle()?) }) } } impl TryFrom for WindowsIdentifier { type Error = io::Error; fn try_from(stdio: Stdio) -> Result { let std_handle_id = match stdio { Stdio::Stdin => STD_INPUT_HANDLE, Stdio::Stdout => STD_OUTPUT_HANDLE, Stdio::Stderr => STD_ERROR_HANDLE, }; // SAFETY: This method can safely be called with one of the above constants. // https://docs.microsoft.com/en-us/windows/console/getstdhandle let handle = unsafe { GetStdHandle(std_handle_id) }; if handle == INVALID_HANDLE_VALUE || handle == NULL { return Err(io::Error::last_os_error()); } unsafe { Self::try_from_raw_handle(handle, false) } } } impl TryFrom for WindowsIdentifier { type Error = io::Error; fn try_from(file: File) -> Result { unsafe { Self::try_from_raw_handle(file.into_raw_handle(), true) } } } impl ops::Drop for WindowsIdentifier { fn drop(&mut self) { unsafe { if let Some(handle) = self.take_handle() { drop(File::from_raw_handle(handle)); } } } } impl cmp::PartialEq for WindowsIdentifier { #[must_use] fn eq(&self, other: &Self) -> bool { self.volume_serial == other.volume_serial && self.file_index == other.file_index } } impl Eq for WindowsIdentifier {} impl hash::Hash for WindowsIdentifier { fn hash(&self, state: &mut H) { self.volume_serial.hash(state); self.file_index.hash(state); } } clircle-0.4.0/src/lib.rs000064400000000000000000000134321046102023000131500ustar 00000000000000//! The `clircle` crate helps you detect IO circles in your CLI applications. //! //! Imagine you want to read data from a couple of files and output something according to the //! contents of these files. If the user redirects the output of your program to one of the input //! files, you might end up in an infinite circle of reading and writing. //! //! The crate provides the struct `Identifier` which is a platform dependent type alias, so that //! you can use it on all platforms and do not need to introduce any conditional compilation //! yourself. `Identifier` implements the `Clircle` trait, which is where you should look for the //! public functionality. //! //! The `Clircle` trait is implemented on both of these structs and requires `TryFrom` for the //! `clircle::Stdio` enum and for `File`, so that all possible inputs can be represented as an //! `Identifier`. Additionally, there are `unsafe` methods for each specific implementation, but //! they are not recommended to use. //! Finally, `Clircle` is a subtrait of `Eq`, which allows checking if two `Identifier`s point to //! the same file, even if they don't conflict. If you only need this last feature, you should //! use [`same-file`](https://crates.io/crates/same-file) instead of this crate. //! //! ## Examples //! //! To check if two `Identifier`s conflict, use //! `Clircle::surely_conflicts_with`: //! //! ```rust,no_run //! # fn example() -> Option<()> { //! # use clircle::{Identifier, Clircle, Stdio::{Stdin, Stdout}}; //! # use std::convert::TryFrom; //! let stdin = Identifier::stdin()?; //! let stdout = Identifier::stdout()?; //! //! if stdin.surely_conflicts_with(&stdout) { //! eprintln!("stdin and stdout are conflicting!"); //! } //! # Some(()) //! # } //! ``` //! //! On Linux, the above snippet could be used to detect `cat < x > x`, while allowing just //! `cat`, although stdin and stdout are pointing to the same pty in both cases. On Windows, this //! code will not print anything, because the same operation is safe there. #![deny(clippy::all)] #![deny(missing_docs)] #![warn(clippy::pedantic)] cfg_if::cfg_if! { if #[cfg(unix)] { mod clircle_unix; pub use clircle_unix::{libc, UnixIdentifier}; /// Identifies a file. The type is aliased according to the target platform. pub type Identifier = UnixIdentifier; } else if #[cfg(windows)] { mod clircle_windows; pub use clircle_windows::{winapi, WindowsIdentifier}; /// Identifies a file. The type is aliased according to the target platform. pub type Identifier = WindowsIdentifier; } else { compile_error!("Neither cfg(unix) nor cfg(windows) was true, aborting."); } } #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::fs::File; /// The `Clircle` trait describes the public interface of the crate. /// It contains all the platform-independent functionality. /// Additionally, an implementation of `Eq` is required, that gives a simple way to check for /// conflicts, if using the more elaborate `surely_conflicts_with` method is not wanted. /// This trait is implemented for the structs `UnixIdentifier` and `WindowsIdentifier`. pub trait Clircle: Eq + TryFrom + TryFrom { /// Returns the `File` that was used for `From`. If the instance was created otherwise, /// this may also return `None`. fn into_inner(self) -> Option; /// Checks whether the two values will without doubt conflict. By default, this always returns /// `false`, but implementors can override this method. Currently, only `UnixIdentifier` /// overrides `surely_conflicts_with`. fn surely_conflicts_with(&self, _other: &Self) -> bool { false } /// Shorthand for `try_from(Stdio::Stdin)`. #[must_use] fn stdin() -> Option { Self::try_from(Stdio::Stdin).ok() } #[must_use] /// Shorthand for `try_from(Stdio::Stdout)`. fn stdout() -> Option { Self::try_from(Stdio::Stdout).ok() } #[must_use] /// Shorthand for `try_from(Stdio::Stderr)`. fn stderr() -> Option { Self::try_from(Stdio::Stderr).ok() } } /// The three stdio streams. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[allow(missing_docs)] pub enum Stdio { Stdin, Stdout, Stderr, } /// Finds a common `Identifier` in the two given slices. pub fn output_among_inputs<'o, T>(outputs: &'o [T], inputs: &[T]) -> Option<&'o T> where T: Clircle, { outputs.iter().find(|output| inputs.contains(output)) } /// Checks if `Stdio::Stdout` is in the given slice. pub fn stdout_among_inputs(inputs: &[T]) -> bool where T: Clircle, { T::stdout().map_or(false, |stdout| inputs.contains(&stdout)) } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::hash::Hash; fn contains_duplicates(items: Vec) -> bool where T: Eq + Hash, { let mut set = HashSet::new(); items.into_iter().any(|item| !set.insert(item)) } #[test] fn test_basic_comparisons() -> Result<(), &'static str> { let dir = tempfile::tempdir().expect("Couldn't create tempdir."); let dir_path = dir.path().to_path_buf(); let filenames = ["a", "b", "c", "d"]; let paths: Vec<_> = filenames .iter() .map(|filename| dir_path.join(filename)) .collect(); let identifiers = paths .iter() .map(File::create) .map(Result::unwrap) .map(Identifier::try_from) .map(Result::unwrap) .collect::>(); if contains_duplicates(identifiers) { return Err("Duplicate identifier found for set of unique paths."); } Ok(()) } }