sequoia-directories-0.1.0/.cargo_vcs_info.json0000644000000001360000000000100150120ustar { "git": { "sha1": "b0634dc26e112d55498bda5ea37eec7297a0edd9" }, "path_in_vcs": "" }sequoia-directories-0.1.0/.codespellrc000064400000000000000000000004111046102023000160760ustar 00000000000000[codespell] skip = Cargo.lock,*.bin,*.gpg,*.pgp,./.git,data,highlight.js,*/target,Makefile,*.html,*/cargo,*.xml,*.xmlv2, ignore-words-list = crate,ede,iff,mut,nd,te,uint,KeyServer,keyserver,Keyserver,keyservers,Keyservers,keypair,keypairs,KeyPair,fpr,dedup,ba,ned, sequoia-directories-0.1.0/.gitignore000064400000000000000000000000341046102023000155670ustar 00000000000000.dir-locals-2.el *~ /target sequoia-directories-0.1.0/.gitlab-ci.yml000064400000000000000000000055071046102023000162450ustar 00000000000000# Only ever create pipelines for tags or branches. # Avoid creation of detached pipelines for merge requests. workflow: rules: - if: $CI_COMMIT_TAG - if: $CI_COMMIT_BRANCH stages: - lint - test - deploy cache: &general_cache_config # default key is default # default policy is pull-push paths: - target/ - $CARGO_HOME .rust-stable: image: 192.168.122.1:5000/sequoia-pgp/build-docker-image/rust-stable:latest before_script: - if [ -d target ]; then find target | wc --lines; du -sh target; fi - if [ -d cargo ]; then find cargo | wc --lines; du -sh $CARGO_HOME; fi - rustc --version - cargo --version after_script: - du -sh target - du -sh $CARGO_HOME cache: # inherit all general cache settings <<: *general_cache_config # override the key key: "rust-stable" .trixie: image: 192.168.122.1:5000/sequoia-pgp/build-docker-image/trixie:latest before_script: - if [ -d target ]; then find target | wc --lines; du -sh target; fi - if [ -d cargo ]; then find cargo | wc --lines; du -sh $CARGO_HOME; fi - rustc --version - cargo --version after_script: - du -sh target - du -sh $CARGO_HOME cache: # inherit all general cache settings <<: *general_cache_config # override the key key: "trixie" codespell: stage: lint extends: .trixie before_script: - codespell --version script: - codespell --config .codespellrc --summary after_script: [] test-trixie: stage: test extends: .trixie script: - cargo run --example list-dirs - cargo test --all test-rust-stable: stage: test extends: .rust-stable script: - cargo run --example list-dirs - cargo test --all # Test on Alpine Linux which uses the musl libc. test-alpine-musl: image: alpine script: - apk add coreutils findutils rust cargo clang-dev - cargo run --example list-dirs - cargo test --all deny: stage: lint extends: .rust-stable script: - cargo deny check cache: [] test-windows-msvc: tags: - win - win2019 stage: test image: 192.168.122.1:5000/sequoia-pgp/build-docker-image/windows-msvc only: variables: # Forks of this project most likely use gitlab's shared windows runners, which # do not use the docker executor, so disable the windows jobs for forks. - $CI_PROJECT_NAMESPACE == "sequoia-pgp" before_script: - rustup install stable --profile minimal - rustup default stable - rustc --version - cargo --version script: - cargo run --example list-dirs - cargo test --all after_script: [] variables: CFLAGS: "" # Silence some C warnings when compiling with MSVC cache: # inherit all general cache settings <<: *general_cache_config # override the key key: "windows-msvc" variables: CARGO_FLAGS: --color always CARGO_INCREMENTAL: 0 sequoia-directories-0.1.0/Cargo.lock0000644000000236340000000000100127750ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "anyhow" version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3" [[package]] name = "bitflags" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "directories" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35" dependencies = [ "dirs-sys", ] [[package]] name = "dirs-sys" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", "redox_users", "windows-sys 0.48.0", ] [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "fastrand" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "libc" version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "libredox" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags", "libc", ] [[package]] name = "linux-raw-sys" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "proc-macro2" version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "redox_users" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" dependencies = [ "getrandom", "libredox", "thiserror", ] [[package]] name = "rustix" version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.52.0", ] [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "sequoia-directories" version = "0.1.0" dependencies = [ "anyhow", "directories", "same-file", "tempfile", "thiserror", ] [[package]] name = "syn" version = "2.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", "rustix", "windows-sys 0.52.0", ] [[package]] name = "thiserror" version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "winapi-util" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets 0.52.5", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ "windows_aarch64_gnullvm 0.52.5", "windows_aarch64_msvc 0.52.5", "windows_i686_gnu 0.52.5", "windows_i686_gnullvm", "windows_i686_msvc 0.52.5", "windows_x86_64_gnu 0.52.5", "windows_x86_64_gnullvm 0.52.5", "windows_x86_64_msvc 0.52.5", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" [[package]] name = "windows_i686_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" sequoia-directories-0.1.0/Cargo.toml0000644000000021020000000000100130030ustar # 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.70" name = "sequoia-directories" version = "0.1.0" authors = [ "Justus Winter ", "Neal H. Walfield ", ] description = "Directories used by Sequoia" homepage = "https://sequoia-pgp.org/" readme = "README.md" keywords = ["openpgp"] license = "LGPL-2.0-or-later" repository = "https://gitlab.com/sequoia-pgp/sequoia-directories" [dependencies.anyhow] version = "1" [dependencies.directories] version = "5" [dependencies.same-file] version = "1" [dependencies.tempfile] version = "3" [dependencies.thiserror] version = "1" sequoia-directories-0.1.0/Cargo.toml.orig000064400000000000000000000010071046102023000164670ustar 00000000000000[package] name = "sequoia-directories" description = "Directories used by Sequoia" version = "0.1.0" authors = [ "Justus Winter ", "Neal H. Walfield ", ] homepage = "https://sequoia-pgp.org/" repository = "https://gitlab.com/sequoia-pgp/sequoia-directories" readme = "README.md" keywords = ["openpgp"] license = "LGPL-2.0-or-later" edition = "2021" rust-version = "1.70" [dependencies] anyhow = "1" directories = "5" same-file = "1" tempfile = "3" thiserror = "1" sequoia-directories-0.1.0/LICENSE.txt000064400000000000000000000627541046102023000154430ustar 00000000000000sequoia-directories is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. sequoia-directories 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. --- GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. 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 not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library 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 specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! sequoia-directories-0.1.0/README.md000064400000000000000000000127061046102023000150670ustar 00000000000000A small crate that returns the platform-specific configuration, data, and cache directories. This crate is primarily for use by Sequoia libraries, and applications to locate their configuration, data, and cache directories. By default, Sequoia uses the system's standard locations for user data, configuration files, and cache data. On Linux, for instance, this means following [the XDG base directory specification]. [the XDG base directory specification]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html Sequoia programs also support using an alternate home directory. In this case, the user data, configuration files, and cache data are placed under a single, unified directory. This is a lightweight way to partially isolate a program. An alternate home location can be specified when instantiating a `Home` object. The user is also able to override the default by setting the `SEQUOIA_HOME` environment variable. The default home location is the user's home directory. On Linux, this usually looks like `/home/USER`. ## Examples Typical usage: ```rust use sequoia_directories::Home; use sequoia_directories::Component; use sequoia_directories::Result; fn main() -> Result<()> { // The user can still override this by setting the SEQUOIA_HOME // environment variable. let home = Home::new(None)?; println!("keystore's data directory: {}", home.data_dir(Component::Keystore).display()); Ok(()) } ``` The directories on a Linux-based system: ```text $ cargo run --example list-dirs | sed 's#/home/[^ /]*#/home/USER#; s#/tmp/[^ /]*#/tmp/TMPDIR#;' Default configuration --------------------- home: /home/USER (default: true) base config: /home/USER/.config cert-d: config dir: /home/USER/.config/pgp.cert.d data dir: /home/USER/.local/share/pgp.cert.d cache dir: /home/USER/.cache/pgp.cert.d keystore: config dir: /home/USER/.config/sequoia/keystore data dir: /home/USER/.local/share/sequoia/keystore cache dir: /home/USER/.cache/sequoia/keystore sq: config dir: /home/USER/.config/sequoia/sq data dir: /home/USER/.local/share/sequoia/sq cache dir: /home/USER/.cache/sequoia/sq foo: config dir: /home/USER/.config/sequoia/foo data dir: /home/USER/.local/share/sequoia/foo cache dir: /home/USER/.cache/sequoia/foo /tmp/TMPDIR --------------- home: /tmp/TMPDIR (default: false) base config: /tmp/TMPDIR cert-d: config dir: /tmp/TMPDIR/config/pgp.cert.d data dir: /tmp/TMPDIR/data/pgp.cert.d cache dir: /tmp/TMPDIR/cache/pgp.cert.d keystore: config dir: /tmp/TMPDIR/config/keystore data dir: /tmp/TMPDIR/data/keystore cache dir: /tmp/TMPDIR/cache/keystore sq: config dir: /tmp/TMPDIR/config/sq data dir: /tmp/TMPDIR/data/sq cache dir: /tmp/TMPDIR/cache/sq foo: config dir: /tmp/TMPDIR/config/foo data dir: /tmp/TMPDIR/data/foo cache dir: /tmp/TMPDIR/cache/foo ``` The directories on a Windows system (our CI): ```text $ cargo run --example list-dirs Default configuration --------------------- home: C:\Users\ContainerAdministrator (default: true) base config: C:\Users\ContainerAdministrator\AppData\Roaming cert-d: config dir: C:\Users\ContainerAdministrator\AppData\Roaming\pgp.cert.d data dir: C:\Users\ContainerAdministrator\AppData\Roaming\pgp.cert.d cache dir: C:\Users\ContainerAdministrator\AppData\Local\pgp.cert.d keystore: config dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\config\keystore data dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\data\keystore cache dir: C:\Users\ContainerAdministrator\AppData\Local\Sequoia-PGP\sequoia\cache\keystore sq: config dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\config\sq data dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\data\sq cache dir: C:\Users\ContainerAdministrator\AppData\Local\Sequoia-PGP\sequoia\cache\sq foo: config dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\config\foo data dir: C:\Users\ContainerAdministrator\AppData\Roaming\Sequoia-PGP\sequoia\data\foo cache dir: C:\Users\ContainerAdministrator\AppData\Local\Sequoia-PGP\sequoia\cache\foo C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly ------------------------------------------------------------- home: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly (default: false) base config: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly cert-d: config dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\config\pgp.cert.d data dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\data\pgp.cert.d cache dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\cache\pgp.cert.d keystore: config dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\config\keystore data dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\data\keystore cache dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\cache\keystore sq: config dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\config\sq data dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\data\sq cache dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\cache\sq foo: config dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\config\foo data dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\data\foo cache dir: C:\Users\ContainerAdministrator\AppData\Local\Temp\.tmpPrPmly\cache\foo ``` sequoia-directories-0.1.0/deny.toml000064400000000000000000000017071046102023000154430ustar 00000000000000[advisories] ignore = [ # fehler is unmaintained. # # fehler is used by subplot and thus an indirect dependency. Remove # when a new version subplot is released without fehler. See # https://gitlab.com/subplot/subplot/-/issues/340. "RUSTSEC-2023-0067", # yaml-rust is unmaintained. # # yaml-rust is used by subplot/roadmap/serde_yaml thus an indirect # dependency. Remove when a new version of roadmap is released that # uses a newer version of serde_yaml. See # https://gitlab.com/larswirzenius/roadmap/-/issues/13 "RUSTSEC-2024-0320", ] unmaintained = "deny" yanked = "deny" [bans] multiple-versions = "allow" deny = [ # does not have responsible disclosure policy: # https://github.com/briansmith/ring#bug-reporting {name = "ring"}, ] [licenses] allow = [ "Apache-2.0", "BSD-3-Clause", "BSL-1.0", "CC0-1.0", "GPL-2.0", "GPL-3.0", "ISC", "LGPL-2.0", "LGPL-3.0", "MIT", "MPL-2.0", "Unicode-DFS-2016", ] sequoia-directories-0.1.0/examples/list-dirs.rs000064400000000000000000000026041046102023000177020ustar 00000000000000//! Dump a default configuration, and a non-default configuration. use sequoia_directories::Home; use sequoia_directories::Component; use sequoia_directories::Result; fn main() -> Result<()> { let dump = |title: &str, home: &Home| { println!(); println!("{}", title); println!( "{}", std::iter::repeat("-") .take(title.chars().count()) .collect::>() .join("")); println!("home: {} (default: {})", home.location().display(), home.is_default_location()); println!("base config: {}", home.base_config_dir().display()); for (s, c) in [ ("cert-d", Component::CertD), ("keystore", Component::Keystore), ("sq", Component::Sq), ("foo", Component::Other("foo".into())), ].iter() { println!("{}:", s); println!(" config dir: {}", home.config_dir(c).display()); println!(" data dir: {}", home.data_dir(c).display()); println!(" cache dir: {}", home.cache_dir(c).display()); } }; dump("Default configuration", &Home::new(None)?); let tmpdir = tempfile::tempdir()?; let tmpdir = tmpdir.path().to_path_buf(); let home = Home::new(tmpdir.clone())?; dump(&format!("{}", tmpdir.display()), &home); Ok(()) } sequoia-directories-0.1.0/src/lib.rs000064400000000000000000000467621046102023000155240ustar 00000000000000//! Directories used by Sequoia. //! //! This crate is primarily for use by Sequoia libraries, and //! applications to locate their configuration, data, and cache //! directories. //! //! By default, Sequoia uses the system's standard locations for user //! data, configuration files, and cache data. On Linux, for //! instance, this means following [the XDG base directory //! specification]. //! //! [the XDG base directory specification]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html //! //! Sequoia programs also support using an alternate home directory. //! In this case, the user data, configuration files, and cache data //! are placed under a single, unified directory. This is a //! lightweight way to partially isolate a program. //! //! An alternate home location can be specified when instantiating a //! `Home` object. The user is also able to override the default by //! setting the `SEQUOIA_HOME` environment variable. The default home //! location is the user's home directory. On Linux, this usually //! looks like `/home/USER`. //! //! In a few cases, a program might need to use multiple home //! directories. For instance, a program might not want to use the //! user's default configuration, or certificate store, but does want //! to use the default key store. This is possible by instantiating //! multiple [`Home`] objects, and querying the appropriate home //! directory. //! //! When a program specifies an alternate home directory, we check if //! it aliases the default home directory. This check is performed at //! the file system level, and not just by comparing the paths. If //! the specified directory aliases the default directory, we treat it //! as the default and use the default layout. //! //! Some programs may act differently depending on whether the home //! location is the default or not. For instance, the keystore uses //! the user's default gpg-agent when using the default home location. use std::borrow::Borrow; use std::io; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::OnceLock; use directories::BaseDirs; use directories::ProjectDirs; #[macro_use] mod macros; const TRACE: bool = false; /// Make sure the example in the README works. #[cfg(doctest)] mod doctest { #[doc=include_str!("../README.md")] struct ReadMe; } /// Errors used in this crate. /// /// Note: This enum cannot be exhaustively matched to allow future /// extensions. #[non_exhaustive] #[derive(thiserror::Error, Debug)] pub enum Error { #[error("The set of standard directories is not known on this platform")] NoStandardDirectories, #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Other(#[from] anyhow::Error), } /// This crate's `Result` type. pub type Result = anyhow::Result; /// A Sequoia component. #[derive(Debug, Clone)] pub enum Component { /// The cert-d component. /// /// See the [Shared OpenPGP Certificate Directory] specification. CertD, /// Key store component. Keystore, /// `sq`. Sq, /// An as-yet unspecified component. Other(String), } impl Component { /// Returns whether the component is a Sequoia component, and its /// sub-directory. fn dir(&self) -> (bool, &str) { match self { Component::CertD => (false, "pgp.cert.d"), Component::Keystore => (true, "keystore"), Component::Sq => (true, "sq"), Component::Other(c) => (true, &**c), } } } #[derive(Debug, Clone)] struct Dirs { base: BaseDirs, project: ProjectDirs, } /// A Sequoia home directory. /// /// This is used to determine the location of various components' /// configuration, data, and cache directories. #[derive(Debug, Clone)] pub struct Home { /// The home location. location: PathBuf, // If Some, then then we're using the default location. dirs: Option, // If this is an ephmeral home directory. An ephemeral home // directory when the last copy of this structure is dropped. ephemeral: Option>, } impl std::fmt::Display for Home { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.is_default_location() { write!(f, "default ({})", self.location.display()) } else if self.ephemeral.is_some() { write!(f, "ephemeral ({})", self.location.display()) } else { write!(f, "{}", self.location.display()) } } } impl Home { /// The environment variable that overrides the default home /// location. pub const ENV: &'static str = "SEQUOIA_HOME"; /// Returns the default home location. /// /// The default home location is the user's home directory, e.g., /// `/home/user`. When using the home directory, the actual files /// are placed according to the operating system's conventions. /// On systems that support the XDG guidelines, for instance, data /// is placed under `$XDG_DATA_HOME/sequoia`, which usually looks /// like `/home/user/.local/share/sequoia`. /// /// Returns an error if the default location can't be determined. pub fn default_location() -> Result { static DEFAULT_LOCATION: OnceLock> = OnceLock::new(); let dirs = DEFAULT_LOCATION.get_or_init(|| { let dirs = BaseDirs::new()?; Some(dirs.home_dir().to_path_buf()) }); if let Some(dirs) = dirs { Ok(dirs.clone()) } else { Err(Error::NoStandardDirectories) } } /// Returns an instance of `Home`. /// /// Returns an instance of `Home`. If `home` is not `None`, the /// specified location is used. Otherwise, if the environment /// variable `SEQUOIA_HOME` is set, that is used. Otherwise, the /// default location as returned by [`Home::default_location`] is /// used. pub fn new

(location: P) -> Result where P: Into> { tracer!(TRACE, "Home::new"); let mut location = location.into(); if let Some(path) = location.as_ref() { t!("location: {}", path.display()); if path.is_relative() { // XXX: Switch to std::path::absolute when that // stabilizes. // // https://doc.rust-lang.org/std/path/fn.absolute.html t!("Canonicalizing relative path"); std::fs::create_dir_all(path)?; let path = path.canonicalize()?; t!(" -> {:?}", path.display()); location = Some(path); } } else { t!("location: use the default"); } let (location, default) = if let Some(location) = location { (location, None) } else if let Ok(location) = std::env::var(Home::ENV) { t!("{} set to {}", Home::ENV, location); (PathBuf::from(location), None) } else { t!("{} is unset", Home::ENV); (Self::default_location()?, Some(true)) }; let default = default.unwrap_or_else(|| { // If the platform doesn't have a home directory, just // return false. Self::aliases_default(&location).unwrap_or(false) }); t!("Location is {}the default location", if default { "" } else { "not " }); let dirs = if default { let (Some(base), Some(project)) = (BaseDirs::new(), ProjectDirs::from("org", "Sequoia-PGP", "sequoia")) else { return Err(Error::NoStandardDirectories) }; Some(Dirs { base, project }) } else { None }; Ok(Self { location, dirs: dirs, ephemeral: None, }) } /// Returns a default instance of `Home`. /// /// Returns a reference to an instance of the default. This /// unconditionally uses [`Home::default_location`]; it ignores /// the environment variable `SEQUOIA_HOME`. /// /// Returns `None` if the platform does not have any known default /// directories. pub fn default() -> Option<&'static Self> { static DEFAULT: OnceLock> = OnceLock::new(); let default = DEFAULT .get_or_init(|| { let path = Self::default_location().ok()?; Some(Self::from_path(path)) }); default.as_ref() } /// Returns an instance of `Home`. /// /// The specified location is used as the home location. The /// environment variable `SEQUOIA_HOME` is ignored. pub fn from_path

(location: P) -> Self where P: ToOwned { let location = location.to_owned(); Self::new(Some(location)) .expect("infallible when specifying a location") } /// Returns an ephemeral instance of `Home`. /// /// A temporary directory is created and used as the home /// location. The environment variable `SEQUOIA_HOME` is ignored. /// /// When the last clone of this structure is dropped, the /// ephemeral directory is removed. pub fn ephemeral() -> Result { let ephemeral = tempfile::Builder::new().prefix("sequoia-").tempdir()?; let dir = ephemeral.path().to_path_buf(); let mut home = Self::from_path(dir); home.ephemeral = Some(Arc::new(ephemeral)); Ok(home) } /// Returns whether the location is ephemeral. /// /// A home location is ephemeral when it is created with /// [`Home::ephemeral`]. pub fn is_ephemeral(&self) -> bool { self.ephemeral.is_some() } /// Returns whether two directories are aliases. /// /// `a` and `b` do not need to exist. `a` may be created. /// /// If `a` and `b` are bit-for-bit identical, this returns true. /// /// Otherwise, this function tries to figure out if `a` designates /// the same directory as `b`. To do this, the function first /// ensures that the two directories exist. If `a` doesn't exist, /// and cannot be created, this function returns an error. If `b` /// doesn't exist, and cannot be created, this function returns /// `Ok(false)`. /// /// This function then compares the files' identities. On /// Unix-like systems, this is done by comparing the files' device /// ids and their inode numbers. On Windows, the equivalent is /// used (cf. `nFileIndexLow`, etc.). /// Returns whether two directories are aliases. /// /// This is similar to [`Home::aliases_default`], but sometimes /// only the location of a component is known, not the home /// location. /// /// # Examples /// /// ``` /// # use sequoia_directories::Home; /// # use sequoia_directories::Component; /// /// let default = Home::default().expect("have defaults"); /// let ephemeral = Home::ephemeral() /// .expect("can create temporary directories"); /// /// let default_keystore = default.data_dir(Component::Keystore); /// let other_keystore = ephemeral.data_dir(Component::Keystore); /// /// assert!(! Home::aliases(&default_keystore, &other_keystore).expect("ok")); /// /// # #[cfg(unix)] /// # { /// let other_keystore_alias = ephemeral.location().join("symlink"); /// std::os::unix::fs::symlink(&other_keystore, &other_keystore_alias).expect("ok"); /// /// // The paths aren't identical. /// assert!(other_keystore != other_keystore_alias); /// // But they alias. /// assert!(Home::aliases(&other_keystore, &other_keystore_alias).expect("ok")); /// # } /// ``` pub fn aliases(a: &Path, b: &Path) -> Result { if a == b { // They are identical. return Ok(true); } // See if they alias. // Make sure `a` exists. If not, return an error. std::fs::create_dir_all(a)?; // Get `same-file` `Handle`s for `a` and // `b`. Comparing two handles returns whether // they alias. let a_handle = same_file::Handle::from_path(a)?; let b_handle = match same_file::Handle::from_path(b) { Ok(handle) => handle, Err(err) => match err.kind() { // If `b` doesn't exist, but `a` does, they can't // possible be aliases. io::ErrorKind::NotFound => return Ok(false), // We can't access `b`, but we can access `a`. This // doesn't mean they don't alias: one could be behind // a symlink. There's not much much more that we can // do. We conservatively assume that they don't // alias. io::ErrorKind::PermissionDenied => return Ok(false), _ => return Err(err.into()), } }; // The specified location and the default location exist. See // if they are the same file. Ok(a_handle == b_handle) } /// Returns whether the specified directory is the default home /// directory. /// /// If `dir` is bit-for-bit identical to the default, this returns /// true. /// /// Otherwise, this function tries to figure out if `dir` /// designates the `default` directory. To do this, the function /// first ensures that the two directories exist. If `dir` /// doesn't exist, and cannot be created, this function returns an /// error. If the default directory doesn't exist, and cannot be /// created, this function returns `Ok(false)`. /// /// This function then compares the file's identity. On Unix-like /// systems, this is done by comparing the files' device ids and /// their inode numbers. On Windows, the equivalent is used /// (cf. `nFileIndexLow`, etc.). pub fn aliases_default(location: &Path) -> Result { let default_location = Self::default_location()?; Self::aliases(location, &default_location) } /// Returns whether this home location is the default home /// location. /// /// This is computed at instantiation time using /// [`Home::aliases_default`]. pub fn is_default_location(&self) -> bool { self.dirs.is_some() } /// Returns the home location. pub fn location(&self) -> &Path { &self.location } /// Returns the Sequoia-global configuration directory. pub fn base_config_dir(&self) -> PathBuf { if let Some(ref dirs) = self.dirs { dirs.base.config_dir().to_path_buf() } else { self.location.to_path_buf() } } /// Returns a component's configuration directory. pub fn config_dir(&self, component: C) -> PathBuf where C: Borrow { let component = component.borrow(); let (sequoia, component) = component.dir(); if let Some(ref dirs) = self.dirs { if sequoia { dirs.project.config_dir().join(component) } else { dirs.base.config_dir().join(component) } } else { self.location.join("config").join(component) } } /// Returns a component's data directory. pub fn data_dir(&self, component: C) -> PathBuf where C: Borrow { let component = component.borrow(); let (sequoia, component) = component.dir(); if let Some(ref dirs) = self.dirs { if sequoia { dirs.project.data_dir().join(component) } else { dirs.base.data_dir().join(component) } } else { self.location.join("data").join(component) } } /// Returns a component's cache directory. pub fn cache_dir(&self, component: C) -> PathBuf where C: Borrow { let component = component.borrow(); let (sequoia, component) = component.dir(); if let Some(ref dirs) = self.dirs { if sequoia { dirs.project.cache_dir().join(component) } else { dirs.base.cache_dir().join(component) } } else { self.location.join("cache").join(component) } } } #[cfg(test)] mod tests { use std::sync::Mutex; use super::*; static REMOVED_SEQUOIA_HOME: Mutex = Mutex::new(false); /// Sets up the test environment. fn setup() { let mut removed = REMOVED_SEQUOIA_HOME.lock().unwrap(); if ! *removed { std::env::remove_var(Home::ENV); *removed = true; } } #[test] fn is_default() -> Result<()> { setup(); let default_location = Home::default_location().expect("supported platform"); eprintln!("default_location: {:?}", default_location); let tmpdir = tempfile::tempdir()?; let tmpdir = tmpdir.path().to_path_buf(); eprintln!("tmpdir: {:?}", tmpdir); std::env::set_current_dir(&tmpdir).expect("can cd to tmpdir"); let mut tmpdir_rel = PathBuf::from("."); for _ in tmpdir.components().skip(1) { tmpdir_rel.push(".."); } for c in tmpdir.components().skip(1) { tmpdir_rel.push(c); } eprintln!("tmpdir_rel: {:?}", tmpdir_rel); // The default should be the default. let home = Home::new(None).expect("supported platform"); assert!(home.is_default_location()); // The default path should be the default (they are // bit-for-bit identical). let home = Home::new(default_location.clone()).unwrap(); assert!(home.is_default_location()); // Append "/." to the end of the default location. The names // are now different, but they still reference the same // directory. let period = default_location.join("."); let home = Home::new(period).unwrap(); assert!(home.is_default_location()); // Assert that a completely different location, which exists, // isn't the default. let home = Home::new(tmpdir.clone()).unwrap(); assert!(! home.is_default_location()); let home = Home::new(tmpdir_rel.clone()).unwrap(); assert!(! home.is_default_location()); // Assert that a completely different location, which does not // exist, isn't considered the default. let non_existant = tmpdir.join("adsflkj"); let home = Home::new(non_existant).unwrap(); assert!(! home.is_default_location()); let non_existant = tmpdir_rel.join("adsflkj"); let home = Home::new(non_existant).unwrap(); assert!(! home.is_default_location()); // Assert that a completely different path that is a link to // the default, is also considered the default. #[cfg(unix)] { let link = tmpdir.join("link"); let link_rel = tmpdir_rel.join("link"); std::os::unix::fs::symlink(default_location, &link) .expect("can create symbolic link in temp dir"); let home = Home::new(link.clone()).unwrap(); assert!(home.is_default_location()); let home = Home::new(link_rel.clone()).unwrap(); assert!(home.is_default_location()); // And add a dot. let home = Home::new(link.join(".")).unwrap(); assert!(home.is_default_location()); let home = Home::new(link_rel.join(".")).unwrap(); assert!(home.is_default_location()); } Ok(()) } } sequoia-directories-0.1.0/src/macros.rs000064400000000000000000000062531046102023000162310ustar 00000000000000use std::cmp; macro_rules! trace { ( $TRACE:expr, $fmt:expr, $($pargs:expr),* ) => { if $TRACE { eprintln!($fmt, $($pargs),*); } }; ( $TRACE:expr, $fmt:expr ) => { trace!($TRACE, $fmt, ); }; } // Converts an indentation level to whitespace. pub(crate) fn indent(i: isize) -> &'static str { let s = " "; &s[0..cmp::min(usize::try_from(i).unwrap_or(0), s.len())] } macro_rules! tracer { ( $TRACE:expr, $func:expr ) => { tracer!($TRACE, $func, 0) }; ( $TRACE:expr, $func:expr, $indent:expr ) => { // Currently, Rust doesn't support $( ... ) in a nested // macro's definition. See: // https://users.rust-lang.org/t/nested-macros-issue/8348/2 #[allow(unused_macros)] macro_rules! t { ( $fmt:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, $fmt) }; ( $fmt:expr, $a:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a)) }; ( $fmt:expr, $a:expr, $b:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f, $g)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f, $g, $h)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f, $g, $h, $i)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr, $j:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f, $g, $h, $i, $j)) }; ( $fmt:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr, $h:expr, $i:expr, $j:expr, $k:expr ) => { trace!($TRACE, "{}{}: {}", crate::macros::indent($indent), $func, format!($fmt, $a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k)) }; } } }