pax_global_header00006660000000000000000000000064147254007740014524gustar00rootroot0000000000000052 comment=02fbbebb6b89492f00fd226846dbf28f80d86fa3 pushd-0.0.2/000077500000000000000000000000001472540077400126465ustar00rootroot00000000000000pushd-0.0.2/.github/000077500000000000000000000000001472540077400142065ustar00rootroot00000000000000pushd-0.0.2/.github/workflows/000077500000000000000000000000001472540077400162435ustar00rootroot00000000000000pushd-0.0.2/.github/workflows/audit-nightly.yml000066400000000000000000000003221472540077400215450ustar00rootroot00000000000000name: Security audit - nightly on: schedule: - cron: "0 0 * * *" jobs: security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rust-lang/audit@v1 pushd-0.0.2/.github/workflows/audit-on-push.yml000066400000000000000000000004271472540077400214660ustar00rootroot00000000000000name: Security audit - on push on: push: paths: - "**/Cargo.toml" - "**/Cargo.lock" tags-ignore: - "precious-*" jobs: security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rust-lang/audit@v1 pushd-0.0.2/.github/workflows/ci.yml000066400000000000000000000065501472540077400173670ustar00rootroot00000000000000name: Tests and release on: push: branches: - "**" tags-ignore: - "precious-*" pull_request: env: CRATE_NAME: precious GITHUB_TOKEN: ${{ github.token }} RUST_BACKTRACE: 1 jobs: test: name: ${{ matrix.platform.os-name }} with rust ${{ matrix.toolchain }} runs-on: ${{ matrix.platform.runs-on }} strategy: fail-fast: false matrix: platform: - os-name: FreeBSD-x86_64 runs-on: ubuntu-20.04 target: x86_64-unknown-freebsd skip_tests: true - os-name: Linux-x86_64 runs-on: ubuntu-20.04 target: x86_64-unknown-linux-musl - os-name: Linux-aarch64 runs-on: ubuntu-20.04 target: aarch64-unknown-linux-musl - os-name: Linux-arm runs-on: ubuntu-20.04 target: arm-unknown-linux-musleabi - os-name: Linux-i686 runs-on: ubuntu-20.04 target: i686-unknown-linux-musl - os-name: Linux-powerpc runs-on: ubuntu-20.04 target: powerpc-unknown-linux-gnu - os-name: Linux-powerpc64 runs-on: ubuntu-20.04 target: powerpc64-unknown-linux-gnu - os-name: Linux-powerpc64le runs-on: ubuntu-20.04 target: powerpc64le-unknown-linux-gnu - os-name: Linux-riscv64 runs-on: ubuntu-20.04 target: riscv64gc-unknown-linux-gnu - os-name: Linux-s390x runs-on: ubuntu-20.04 target: s390x-unknown-linux-gnu - os-name: NetBSD-x86_64 runs-on: ubuntu-20.04 target: x86_64-unknown-netbsd skip_tests: true - os-name: Windows-aarch64 runs-on: windows-latest target: aarch64-pc-windows-msvc skip_tests: true - os-name: Windows-i686 runs-on: windows-latest target: i686-pc-windows-msvc - os-name: Windows-x86_64 runs-on: windows-latest target: x86_64-pc-windows-msvc - os-name: macOS-x86_64 runs-on: macOS-latest target: x86_64-apple-darwin - os-name: macOS-aarch64 runs-on: macOS-latest target: aarch64-apple-darwin toolchain: - stable include: - platform: os-name: Linux-x86_64 runs-on: ubuntu-20.04 target: x86_64-unknown-linux-musl bin: ubi toolchain: beta - platform: os-name: Linux-x86_64 runs-on: ubuntu-20.04 target: x86_64-unknown-linux-musl bin: ubi toolchain: nightly steps: - uses: actions/checkout@v3 - name: Cache cargo & target directories uses: Swatinem/rust-cache@v2 - name: Build binary uses: houseabsolute/actions-rust-cross@v0 with: command: "build" target: ${{ matrix.platform.target }} toolchain: ${{ matrix.toolchain }} args: "--release" strip: false - name: Run tests uses: houseabsolute/actions-rust-cross@v0 with: command: "test" target: ${{ matrix.platform.target }} toolchain: ${{ matrix.toolchain }} args: "--release" if: ${{ !matrix.platform.skip_tests }} pushd-0.0.2/.github/workflows/lint.yml000066400000000000000000000012051472540077400177320ustar00rootroot00000000000000name: Linting on: [push, pull_request] env: CRATE_NAME: precious GITHUB_TOKEN: ${{ github.token }} RUST_BACKTRACE: 1 jobs: lint: name: Check that code is lint clean using precious runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Cache cargo & target directories uses: Swatinem/rust-cache@v2 - name: Install toolchain uses: dtolnay/rust-toolchain@stable - name: Install mise run: | set -e set -x curl https://mise.run | sh mise install - name: Run precious run: | mise exec -- precious lint -a pushd-0.0.2/.gitignore000066400000000000000000000000421472540077400146320ustar00rootroot00000000000000/Cargo.lock /node_modules /target pushd-0.0.2/CODE_OF_CONDUCT.md000066400000000000000000000062241472540077400154510ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at autarch@urth.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org pushd-0.0.2/Cargo.toml000066400000000000000000000015221472540077400145760ustar00rootroot00000000000000[package] name = "pushd" version = "0.0.2" authors = ["Dave Rolsky "] description = "A library that implements pushd" repository = "https://github.com/houseabsolute/pushd" readme = "README.md" license = "MIT OR Apache-2.0" edition = "2021" [dependencies] log = "0.4.22" thiserror = "2.0.5" [dev-dependencies] serial_test = "3.2.0" tempfile = "3.14.0" [package.metadata.release] tag-name = "v{{version}}" # workaround for https://github.com/cross-rs/cross/issues/1345 [package.metadata.cross.target.x86_64-unknown-netbsd] pre-build = [ "mkdir -p /tmp/netbsd", "curl https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.2/amd64/binary/sets/base.tar.xz -O", "tar -C /tmp/netbsd -xJf base.tar.xz", "cp /tmp/netbsd/usr/lib/libexecinfo.so /usr/local/x86_64-unknown-netbsd/lib", "rm base.tar.xz", "rm -rf /tmp/netbsd", ] pushd-0.0.2/Changes.md000066400000000000000000000002221472540077400145340ustar00rootroot00000000000000## 0.0.2 - 2024-12-08 - Updated the docs with details about returned errors. ## 0.0.1 - 2023-11-06 - First release upon an unsuspecting world. pushd-0.0.2/LICENSE-APACHE000066400000000000000000000261351472540077400146010ustar00rootroot00000000000000 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pushd-0.0.2/LICENSE-MIT000066400000000000000000000020551472540077400143040ustar00rootroot00000000000000MIT License Copyright (c) 2022 David Rolsky Permission 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. pushd-0.0.2/README.md000066400000000000000000000011121472540077400141200ustar00rootroot00000000000000# pushd A simple library for temporarily changing the current working directory. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] pushd = "0.0.1" ``` ## Example ```rust use anyhow::Result use std::path::PathBuf; use pushd::Pushd; fn main() -> Result<()> { write_in_etc()?; // Current working directory is whatever it was before the call to // `write_in_etc`. } fn write_in_etc() -> Result<()> { let path = PathBuf::new("/etc"); let _pd = Pushd::new(path)?; // Current working directory is now /etc // // Do something in /etc. } ``` pushd-0.0.2/git/000077500000000000000000000000001472540077400134315ustar00rootroot00000000000000pushd-0.0.2/git/hooks/000077500000000000000000000000001472540077400145545ustar00rootroot00000000000000pushd-0.0.2/git/hooks/pre-commit.sh000077500000000000000000000002761472540077400171740ustar00rootroot00000000000000#!/bin/bash declare -i status status=0 PRECIOUS=$(which precious) if [[ -z $PRECIOUS ]]; then PRECIOUS=./bin/precious fi if ! "$PRECIOUS" lint -s; then status+=1 fi exit $status pushd-0.0.2/git/setup.pl000077500000000000000000000007021472540077400151300ustar00rootroot00000000000000#!/usr/bin/env perl use strict; use warnings; use Cwd qw( abs_path ); symlink_hook('pre-commit'); sub symlink_hook { my $hook = shift; my $dot = ".git/hooks/$hook"; my $file = "git/hooks/$hook.sh"; my $link = "../../$file"; if ( -e $dot ) { if ( -l $dot ) { return if readlink $dot eq $link; } warn "You already have a hook at $dot!\n"; return; } symlink $link, $dot; } pushd-0.0.2/mise.toml000066400000000000000000000003151472540077400144770ustar00rootroot00000000000000[tools] node = "22.11.0" "npm:prettier" = "3.4.1" shellcheck = "v0.10.0" shfmt = "v3.10.0" taplo = "0.9.3" typos = "1.28.1" "ubi:houseabsolute/omegasort" = "v0.1.3" "ubi:houseabsolute/precious" = "v0.7.3" pushd-0.0.2/package-lock.json000066400000000000000000000016071472540077400160660ustar00rootroot00000000000000{ "name": "pushd", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "prettier": "^2.7.1" } }, "node_modules/prettier": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", "bin": { "prettier": "bin-prettier.js" }, "engines": { "node": ">=10.13.0" }, "funding": { "url": "https://github.com/prettier/prettier?sponsor=1" } } }, "dependencies": { "prettier": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==" } } } pushd-0.0.2/package.json000066400000000000000000000000651472540077400151350ustar00rootroot00000000000000{ "dependencies": { "prettier": "^2.7.1" } } pushd-0.0.2/precious.toml000066400000000000000000000043751472540077400154050ustar00rootroot00000000000000exclude = ["target"] [commands.clippy] type = "lint" include = "**/*.rs" invoke = "once" path-args = "none" working-dir = "root" cmd = [ "cargo", "clippy", "--color", "always", "--all-targets", "--all-features", "--", "-D", "clippy::pedantic", ] ok_exit_codes = 0 lint_failure_exit_codes = 101 expect_stderr = true labels = ["default"] [commands."clippy --fix"] type = "tidy" include = "**/*.rs" invoke = "once" path-args = "none" working-dir = "root" cmd = [ "cargo", "clippy", "--fix", "--allow-dirty", "--locked", "--all-targets", "--all-features", "--", "-D", "clippy::pedantic", ] ok_exit_codes = 0 lint_failure_exit_codes = 101 expect_stderr = true labels = ["default"] [commands.rustfmt] type = "both" include = "**/*.rs" cmd = ["rustfmt", "--edition", "2021"] lint_flags = "--check" ok_exit_codes = [0] lint_failure_exit_codes = [1] labels = ["default", "fast-tidy"] [commands.omegasort-gitignore] type = "both" include = "**/.gitignore" cmd = ["omegasort", "--sort=path"] lint_flags = "--check" tidy_flags = "--in-place" ok_exit_codes = 0 lint_failure_exit_codes = 1 expect_stderr = true labels = ["default", "fast-tidy"] [commands.prettier] type = "both" include = ["**/*.md", "**/*.yml"] cmd = ["prettier", "--no-config", "--prose-wrap", "always", "--print-width", "100"] lint_flags = "--check" tidy_flags = "--write" ok_exit_codes = 0 lint_failure_exit_codes = 1 ignore_stderr = "Code style issues" labels = ["default", "fast-tidy"] [commands.shellcheck] type = "lint" include = "**/*.sh" cmd = "shellcheck" ok_exit_codes = 0 lint_failure_exit_codes = 1 [commands.shfmt] type = "both" include = "**/*.sh" cmd = ["shfmt", "--simplify", "--indent", "4"] lint_flags = "--diff" tidy_flags = "--write" ok_exit_codes = 0 lint_failure_exit_codes = 1 labels = ["default", "fast-tidy"] [commands.typos] type = "lint" include = "**/*" exclude = "**/*.tar.gz" cmd = "typos" invoke = "once" ok-exit-codes = 0 lint-failure-exit-codes = 2 [commands.taplo] type = "both" include = "**/*.toml" cmd = ["taplo", "format", "--option", "indent_string= ", "--option", "column_width=100"] lint_flags = "--check" ok_exit_codes = 0 lint_failure_exit_codes = 1 ignore_stderr = "INFO taplo.+" labels = ["default", "fast-tidy"] pushd-0.0.2/src/000077500000000000000000000000001472540077400134355ustar00rootroot00000000000000pushd-0.0.2/src/lib.rs000066400000000000000000000271731472540077400145630ustar00rootroot00000000000000//! This crate provides a [`Pushd`] type that temporarily changes the current //! directory. //! //! When a [`Pushd`] struct is created it will call [`env::set_current_dir`] //! to change to the given directory. When the [`Pushd`] is dropped, it will //! change back to the original directory. //! //! If the original directory doesn't exist, this error is ignored, since this //! may be because the original directory was a temporary directory. All other //! errors during drop cause a panic by default, but panics can be disabled //! entirely by using the [`Pushd::new_no_panic`] constructor. //! //! # Examples //! //! ``` //! use pushd::Pushd; //! use std::path::PathBuf; //! //! fn in_directory(path: PathBuf) { //! // When the current function exits and this variable is dropped, the //! // current directory will revert back to whatever it was before this //! // `Pushd` was created. //! let _pd = Pushd::new(path); //! // ... //! } //! ``` //! //! # Panics //! //! The [`Pushd`] may panic if it cannot change back to the original directory //! when it's dropped. Use the [`Pushd::new_no_panic`](Pushd::new_no_panic) //! constructor to prevent this. use log::{debug, warn}; use std::error::Error as StdError; use std::{ env, io, path::{Path, PathBuf}, }; use thiserror::Error; /// `Error` is an enum containing the structured errors that can be returned /// by this module. #[derive(Debug, Error)] pub enum PushdError { /// Indicates that the current directory could not be retrieved. It wraps /// the [`io::Error`] returned by [`env::current_dir`]. #[error("Could not get current directory: {source}")] GetCurrentDir { #[from] source: io::Error, }, /// Indicates that the current directory could not be changed. It wraps /// the [`io::Error`] returned by [`env::set_current_dir`]. #[error("Could not set current directory to {path}: {source}")] SetCurrentDir { path: PathBuf, source: io::Error }, } /// A `Pushd` changes the current directory when it's created and returns to /// the original current directory when it's dropped. pub struct Pushd { orig: PathBuf, panic_on_err: bool, popped: bool, } impl Pushd { /// Constructs a new `Pushd` struct. /// /// This accepts any type that implements [`AsRef`]. /// /// The `Pushd` returned by this constructor will panic if it cannot /// change back to its original directory when it is dropped. /// /// This will call /// [`log::debug!`](https://docs.rs/log/latest/log/macro.debug.html) to /// log the directory change. /// /// # Errors /// /// This method will return an error if the current directory cannot be determined. It will also /// return an error if the current directory cannot be changed. pub fn new>(path: P) -> Result { let cwd = env::current_dir()?; env::set_current_dir(path.as_ref()).map_err(|e| PushdError::SetCurrentDir { path: path.as_ref().to_owned(), source: e, })?; debug!( "Set current dir to {} from {}.", path.as_ref().display(), cwd.display(), ); Ok(Pushd { orig: cwd, panic_on_err: true, popped: false, }) } /// Constructs a new `Pushd` struct that will never panic. /// /// This accepts any type that implements `AsRef`. /// /// This will call /// [`log::debug!`](https://docs.rs/log/latest/log/macro.debug.html) to /// log the directory change. /// /// If the [`Pushd`] created by this constructor cannot change back to the /// original directory when it is dropped, then it will simply call /// [`log::warn!`](https://docs.rs/log/latest/log/macro.warn.html) instead /// of panicking. /// /// # Errors /// /// This method will return an error if the current directory cannot be determined. It will also /// return an error if the current directory cannot be changed. pub fn new_no_panic>(path: P) -> Result { let mut pd = Self::new(path)?; pd.panic_on_err = false; Ok(pd) } /// Changes back to the original directory the first time it is called. If /// this method is called repeatedly it will not do anything on subsequent /// calls. /// /// # Errors /// /// This method return an error if the current directory cannot be changed. pub fn pop(&mut self) -> Result<(), PushdError> { if self.popped { return Ok(()); } debug!("Setting current dir back to {}.", self.orig.display()); env::set_current_dir(&self.orig).map_err(|e| PushdError::SetCurrentDir { path: self.orig.clone(), source: e, })?; self.popped = true; Ok(()) } } impl Drop for Pushd { /// Changes back to the original directory. /// /// When the [`Pushd`] struct is dropped, it will change back to the /// original directory. If this fails, it's behavior is as follows: /// /// * If the [`Pushd`] was constructed with [`Pushd::new_no_panic`], it /// will log the error by calling /// [`log::warn!`](https://docs.rs/log/latest/log/macro.warn.html). /// /// * If the [`Pushd`] was constructed with [`Pushd::new`] and the error /// is an [`io::Error`] and the error's [`io::Error::kind`] method returns /// [`io::ErrorKind::NotFound`], it will do nothing. /// /// * Otherwise it will panic with the error from attempting to change the /// current directory. fn drop(&mut self) { if let Err(e) = self.pop() { if !self.panic_on_err { warn!( "Could not return to original dir {}: {e}", self.orig.display(), ); return; } if let Some(s) = e.source() { if let Some(i) = s.downcast_ref::() { if i.kind() == io::ErrorKind::NotFound { return; } } } panic!("Could not return to original dir: {e}"); } } } #[cfg(test)] mod tests { use super::*; use std::fs; // Anything that does pushd must be run serially or else chaos ensues. use serial_test::serial; #[cfg(not(target_os = "windows"))] use std::os::unix::fs::PermissionsExt; #[cfg(not(target_os = "windows"))] use std::panic; use tempfile::tempdir; #[test] #[serial] fn no_errors() -> Result<(), Box> { env::set_current_dir(env::var("CARGO_MANIFEST_DIR")?)?; let cwd = fs::canonicalize(env::current_dir()?)?; { let td = tempdir()?; let _pd = Pushd::new(td.path()); assert_eq!( fs::canonicalize(env::current_dir()?)?, fs::canonicalize(td.path())?, ); } assert_eq!(fs::canonicalize(env::current_dir()?)?, cwd); Ok(()) } #[test] #[serial] fn no_errors_explicit_pop() -> Result<(), Box> { env::set_current_dir(env::var("CARGO_MANIFEST_DIR")?)?; let cwd = fs::canonicalize(env::current_dir()?)?; { let td = tempdir()?; let mut pd = Pushd::new(td.path())?; assert_eq!( fs::canonicalize(env::current_dir()?)?, fs::canonicalize(td.path())?, ); pd.pop()?; assert_eq!(fs::canonicalize(env::current_dir()?)?, cwd); } assert_eq!(fs::canonicalize(env::current_dir()?)?, cwd); Ok(()) } #[cfg(not(target_os = "windows"))] #[test] #[serial] fn not_found_error_on_drop() -> Result<(), Box> { env::set_current_dir(env::var("CARGO_MANIFEST_DIR")?)?; let td1 = tempdir()?; env::set_current_dir(td1.path())?; { let td2 = tempdir()?; let _pd = Pushd::new(td2.path()); assert_eq!( fs::canonicalize(env::current_dir()?)?, fs::canonicalize(td2.path())?, ); // This should delete the original directory before the Pushd's // drop method is called. td1.close()?; } let cwd = env::current_dir(); assert!(cwd.is_err()); assert_eq!(cwd.unwrap_err().kind(), io::ErrorKind::NotFound); Ok(()) } #[cfg(not(target_os = "windows"))] #[test] #[serial] fn permissions_error_panic_on_drop() -> Result<(), Box> { let result = panic::catch_unwind(|| { let man_dir = match env::var("CARGO_MANIFEST_DIR") { Ok(md) => md, Err(e) => { println!("Error getting CARGO_MANIFEST_DIR: {e}"); return; } }; match env::set_current_dir(man_dir) { Ok(()) => (), Err(e) => { println!("Error setting current dir to CARGO_MANIFEST_DIR: {e}"); return; } } let td1 = match tempdir() { Ok(td) => td, Err(e) => { println!("Error creating tempdir: {e}"); return; } }; match env::set_current_dir(td1.path()) { Ok(()) => (), Err(e) => { println!("Error setting current dir to tempdir: {e}"); return; } } { let td2 = match tempdir() { Ok(td) => td, Err(e) => { println!("Error creating tempdir: {e}"); return; } }; let _pd = Pushd::new(td2.path()); let md = match fs::metadata(td1.path()) { Ok(md) => md, Err(e) => { println!("Error getting metadata for tempdir: {e}"); return; } }; let mut perms = md.permissions(); perms.set_mode(0o0400); match fs::set_permissions(td1.path(), perms) { Ok(()) => (), Err(e) => { println!("Error setting permissions for tempdir: {e}"); return; } } } println!("We should never get here"); }); assert!(result.is_err()); assert!(result .unwrap_err() .downcast_ref::() .unwrap() .contains("Permission denied")); Ok(()) } #[cfg(not(target_os = "windows"))] #[test] #[serial] fn permissions_error_no_panic_on_drop() -> Result<(), Box> { env::set_current_dir(env::var("CARGO_MANIFEST_DIR")?)?; let td1 = tempdir()?; env::set_current_dir(td1.path())?; { let td2 = tempdir()?; let _pd = Pushd::new_no_panic(td2.path()); assert_eq!( fs::canonicalize(env::current_dir()?)?, fs::canonicalize(td2.path())?, ); let mut perms = fs::metadata(td1.path())?.permissions(); perms.set_mode(0o0400); fs::set_permissions(td1.path(), perms)?; } let cwd = env::current_dir(); assert!(cwd.is_err()); assert_eq!(cwd.unwrap_err().kind(), io::ErrorKind::NotFound); Ok(()) } }