diff options
| -rw-r--r-- | .gitignore | 4 | ||||
| -rw-r--r-- | BACKLOG.md | 26 | ||||
| -rw-r--r-- | CHANGELOG.md | 133 | ||||
| -rw-r--r-- | Cargo.lock | 1316 | ||||
| -rw-r--r-- | Cargo.toml | 56 | ||||
| -rw-r--r-- | LICENSE-APACHE-2.0 | 12 | ||||
| -rw-r--r-- | LICENSE-MIT | 19 | ||||
| -rw-r--r-- | Makefile | 31 | ||||
| -rw-r--r-- | README.md | 121 | ||||
| -rw-r--r-- | build.rs | 16 | ||||
| -rwxr-xr-x | configure | 18 | ||||
| -rw-r--r-- | deny.toml | 22 | ||||
| -rw-r--r-- | examples/nixos/.gitignore | 2 | ||||
| -rw-r--r-- | examples/nixos/README.md | 13 | ||||
| -rw-r--r-- | examples/nixos/flake.nix | 57 | ||||
| -rw-r--r-- | flake.lock | 77 | ||||
| -rw-r--r-- | flake.nix | 119 | ||||
| -rw-r--r-- | justfile | 35 | ||||
| -rw-r--r-- | src/main.rs | 540 | ||||
| -rw-r--r-- | temp-postgres.1 | 54 | ||||
| -rwxr-xr-x | temp-postgres.sh | 77 | ||||
| -rw-r--r-- | tests/cli.rs | 356 |
22 files changed, 2905 insertions, 199 deletions
@@ -1 +1,3 @@ -config.mk +/.direnv +/.envrc +/target diff --git a/BACKLOG.md b/BACKLOG.md new file mode 100644 index 0000000..d7c0814 --- /dev/null +++ b/BACKLOG.md @@ -0,0 +1,26 @@ +# Backlog + +This is an *informal* project backlog. + +* Check test coverage + * LLVM coverage instrumentation needs Rustup's `llvm-tools` component, which can be provided by + * Nix package `rustc.llvmPackages.llvm` and setting `LLVM_COV`, `LLVM_PROFDATA` + * fenix + * Failed to get any of cargo-llvm-cov, cargo-tarpaulin, and grcov working. Maybe due to `assert_cmd`. + * Even with tarpaulin's `--follow-exec` flag and without `--engine llvm`. + * Same problem with cargo-llvm-cov using crane and fenix, see branch `fenix`. + * Maybe I need to extract a library to get meaningful coverage information. +* Generate shell completions? <https://docs.rs/clap_complete/latest/clap_complete/aot/fn.generate_to.html> +* Generate manual page? <https://docs.rs/clap_mangen/latest/clap_mangen/> +* Generate readme? <https://github.com/webern/cargo-readme> +* Embed PostgreSQL? <https://pglite.dev/> +* Port to Windows? +* Use a PostgreSQL client written in pure Rust? +* Optionally print or redirect `postgres`' stdout and stderr +* Extract library? Merge with <https://crates.io/crates/temp-postgres>? +* Add checks to Nix flake, such as cargo-audit, cargo-deny, etc. using crane? +* Add `--tcp-address` option? +* Try <https://github.com/Canop/clap-help> +* Add `--setup <script>` option? +* Make `DATABASE_URL` environment variable configurable +* How to log SQL queries? diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d898422 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,133 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep A Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +### Added + +* Added informal project backlog + +### Changed + +* Updated Nix flake inputs +* Improved check recipe (requires Rust 1.97) + +### Removed + +* Removed half-baked update recipe + +## [0.4.2] - 2026-07-07 + +### Changed + +* Updated Nix flake inputs +* Updated Rust dependencies + +## [0.4.1] - 2026-06-15 + +### Changed + +* Updated Nix flake inputs +* Updated Rust dependencies +* Upgraded vergen-gitcl + +### Removed + +* Removed direnv configuration + +## [0.4.0] - 2026-04-30 + +This release replaces the POSIX shell script with a Rust binary crate. + +### Added + +* Added structured logging (also known as tracing), and a `--log-filter` option +* Added `-V` and `--version` options to print the short resp. long version +* Added a `--startup-timeout` option +* Added a `--shutdown-timeout` option +* Added an unwrapped package to the Nix flake +* Added an integration test for the command-line interface +* Added a development-oriented justfile +* Documented known limitations in the readme +* Explicitly stated the maintenance status in the readme + +### Changed + +* Rewrote the main POSIX shell script in async Rust +* Changed the license from ISC to MIT or APACHE-2.0 +* Changed the command-line syntax to require a double dash (`--`) before the wrapped command +* Disabled standard output and standard error of all child processes, except for the wrapped command, to enable the user to capture the output of the wrapped command +* Implemented a retry mechanism for the `pg_isready` command, see the `--startup-timeout` option +* Implemented a graceful shutdown upon `SIGINT`, see the `--shutdown-timeout` option +* Implemented the [`NO_COLOR`](https://no-color.org/) preference +* Rewrote short and long built-in help options `-h` and `--help` + +### Removed + +* Removed the mdoc manual page in favor of the improved built-in help options +* Removed the makefile + +### Fixed + +* Fixed wrapped command argument handling +* Fixed handling of `PGDATABASE` and `PGUSER` environment variables +* Fixed `SIGINT` propagation to child processes + +## [0.3.1] - 2026-04-27 + +### Added + +* Added PostgreSQL version-specific packages to Nix flake + +### Changed + +* Enabled auto-login for NixOS example configuration +* Updated Nix flake inputs + +### Fixed + +* Added missing documentation for `--symlink` option to manual page + +## [0.3.0] - 2026-04-16 + +### Added + +* Added option to execute a given command when the PostgreSQL server is ready +* Added `--symlink` option to enable static client configuration +* Added minimal `--help` option +* Added changelog +* Added experimental Nix flake +* Added direnv configuration +* Added NixOS configuration example + +### Changed + +* Turned required arguments `dbname` and `username` into optional flags `--dbname` resp. `--username` +* Listen on UNIX domain socket only to enable multiple running instances +* Ported to Arch Linux +* Ported to FreeBSD + +## [0.2.0] - 2022-11-09 + +### Added + +* Added makefile +* Added readme +* Added manual page + +### Changed + +* Ported to Void Linux + +### Fixed + +* Fixed manual page name + +## [0.1.0] - 2022-05-19 + +### Added + +* Added [original implementation](https://www.skreutz.com/posts/temporary-postgresql-server/) published 2020-10-14 diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8f43cc6 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1316 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "assert_fs" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecf5c70ca07b7f80220bce936f0556a960ca6fb00fc2bd4125b5e581b218137" +dependencies = [ + "anstyle", + "globwalk", + "predicates", + "predicates-core", + "predicates-tree", + "tempfile", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bon" +version = "3.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a602c73c7b0148ec6d12af6fd5cc7a46e2eacc8878271a999abac56eed12f561" +dependencies = [ + "bon-macros", + "rustversion", +] + +[[package]] +name = "bon-macros" +version = "3.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dee98b0db6a962de883bf5d20362dee4d7ca0d12fe39a7c6c73c844e1cd7c1f" +dependencies = [ + "darling", + "ident_case", + "prettyplease", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + +[[package]] +name = "bstr" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bytes" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "anstyle", + "heck", + "proc-macro2", + "pulldown-cmark", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "color-print" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aa954171903797d5623e047d9ab69d91b493657917bdfb8c2c80ecaf9cdb6f4" +dependencies = [ + "color-print-proc-macro", +] + +[[package]] +name = "color-print-proc-macro" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692186b5ebe54007e45a59aea47ece9eb4108e141326c304cdc91699a7118a22" +dependencies = [ + "nom", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "globset" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52dfc19153a48bde0cbd630453615c8151bce3a5adfac7a0aebfbf0a1e1f57e3" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "globwalk" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf760ebf69878d9fd8f110c89703d90ce35095324d1f1edcb595c63945ee757" +dependencies = [ + "bitflags", + "ignore", + "walkdir", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ignore" +version = "0.4.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe112b004901c62c2faa11f4f75e9864e0cc5af8da71c9115d184a3aa888749f" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex" +version = "1.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[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 = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "temp-postgres-command" +version = "0.4.2" +dependencies = [ + "anyhow", + "assert_cmd", + "assert_fs", + "clap", + "color-print", + "humantime", + "nix", + "predicates", + "tempfile", + "testresult", + "tokio", + "tokio-util", + "tracing", + "tracing-subscriber", + "url", + "vergen-gitcl", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "testresult" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614b328ff036a4ef882c61570f72918f7e9c5bee1da33f8e7f91e01daee7e56c" + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vergen" +version = "10.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5574dd2f922b1a46a06a4b1dc11193a4012108fd54cf725e1816cb8183d8778" +dependencies = [ + "anyhow", + "bon", + "rustversion", + "vergen-lib", +] + +[[package]] +name = "vergen-gitcl" +version = "10.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d9fead6d7c515ac3a658e1a65d36925525d5cfdea414e27eb99b99ffd92bfa" +dependencies = [ + "anyhow", + "bon", + "rustversion", + "time", + "vergen", + "vergen-lib", +] + +[[package]] +name = "vergen-lib" +version = "10.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cd42fd155c2c2971f6d00face12ec245fbb604fce011ccaf2306d014c2e97ca" +dependencies = [ + "anyhow", + "bon", + "rustversion", +] + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..cd99212 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,56 @@ +[package] +# Crate temp-postgres on crates.io is a library of a different project. +name = "temp-postgres-command" +version = "0.4.2" +edition = "2024" +authors = ["Stefan Kreutz <mail@skreutz.com>"] +description = "Run the PostgreSQL server off a temporary data directory" +readme = "README.md" +repository = "https://git.skreutz.com/temp-postgres.git" +license = "MIT OR Apache-2.0" +keywords = ["temporary", "postgresql", "database"] +categories = ["command-line-utilities", "database", "development-tools"] +publish = true + +[lints.rust] +unsafe_code = "forbid" +missing_docs = "warn" + +[dependencies] +anyhow = "1.0.103" +clap = { version = "4.6.1", features = [ + "derive", + "unstable-markdown", + "env", + "string", +] } +color-print = "0.3.7" +humantime = "2.4.0" +nix = { version = "0.31.3", features = ["signal"] } +tempfile = "3.27.0" +tokio = { version = "1.52.3", features = [ + "process", + "rt", + "macros", + "rt-multi-thread", + "signal", + "time", + "fs", +] } +tokio-util = "0.7.18" +tracing = "0.1.44" +tracing-subscriber = "0.3.23" +url = "2.5.8" + +[dev-dependencies] +assert_cmd = "2.2.2" +assert_fs = "1.1.4" +predicates = "3.1.4" +testresult = "0.4.1" + +[build-dependencies] +vergen-gitcl = "10.0.1" + +[[bin]] +name = "temp-postgres" +path = "src/main.rs" diff --git a/LICENSE-APACHE-2.0 b/LICENSE-APACHE-2.0 new file mode 100644 index 0000000..ae05ccb --- /dev/null +++ b/LICENSE-APACHE-2.0 @@ -0,0 +1,12 @@ +Copyright 2026 Stefan Kreutz <mail@skreutz.com> + +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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..b54d456 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright 2026 Stefan Kreutz <mail@skreutz.com> + +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. diff --git a/Makefile b/Makefile deleted file mode 100644 index b28ae64..0000000 --- a/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -# Portable makefile supporting OpenBSD and GNU/Linux. - -PREFIX = /usr/local -INSTALL = install -BINDIR = bin -BINOWN = root -BINGRP = root -BINMODE = 555 -MANDIR = man/man -MANOWN = root -MANGRP = root -MANMODE = 444 - -include config.mk - -all: - -clean: - -lint: - shellcheck -a temp-postgres.sh - mandoc -T lint -W warning temp-postgres.1 - -mandoc -T lint -W all temp-postgres.1 - -install: - ${INSTALL} -o ${BINOWN} -g ${BINGRP} -m ${BINMODE} temp-postgres.sh ${DESTDIR}${PREFIX}/${BINDIR}/temp-postgres - ${INSTALL} -o ${MANOWN} -g ${MANGRP} -m ${MANMODE} temp-postgres.1 ${DESTDIR}${PREFIX}/${MANDIR}1/temp-postgres.1 - -uninstall: - rm -f ${DESTDIR}${PREFIX}/${BINDIR}/temp-postgres - rm -f ${DESTDIR}${PREFIX}/${MANDIR}1/temp-postgres.1 @@ -1,37 +1,122 @@ -# Temp PostgreSQL +# temp-postgres -The `temp-postgres` utility runs the PostgreSQL server off a temporary data -directory. See [this][intro] blog post for an introduction. +The `temp-postgres` utility runs the [PostgreSQL](https://www.postgresql.org/) server off a temporary data directory. -[intro]: https://www.skreutz.com/posts/temporary-postgresql-server/ +The project's source code is hosted on <https://git.skreutz.com/temp-postgres.git/>. ## Usage -Create a temporary database "test" with superuser "alex": +Create and serve a temporary database: - $ temp-postgres test alex +```sh +temp-postgres +``` -Connect to the "test" database: +Wrap the `psql` command for an interactive terminal: - $ psql --host=localhost test alex +```sh +temp-postgres -- psql +``` -See the manual page for details. +Run [SQLx integration tests](https://docs.rs/sqlx/latest/sqlx/attr.test.html) against a temporary database: -## Dependencies +```sh +temp-postgres -- cargo test +``` + +**NOTE**: You may need to set `SQLX_OFFLINE=true` for the build process invoked by `cargo test`. + +Or configure `temp-postgres` as a wrapper for [cargo-nextest](https://nexte.st/): + +```toml +experimental = ["wrapper-scripts"] -The `temp-postgres` utility depends on `sh(1)` and `postgres(1)`. +[scripts.wrapper.temp-postgres] +command = 'temp-postgres --' -On OpenBSD you can install the dependencies using `pkg_add(1)`: +[[profile.default.scripts]] +platform = { host = 'cfg(unix)' } +run-wrapper = 'temp-postgres' +``` - $ doas pkg_add postgresql-server postgresql-client +Set up a symlink to enable static client configuration: -On Void Linux you can install the dependencies using `xbps-install(1)`: +```sh +temp-postgres --symlink db +psql --host "$(realpath db)" +``` + +See the built-in help for details: + +```sh +temp-postgres --help +``` + +## Dependencies - $ sudo xbps-install -S dash postgresql postgresql-client +The `temp-postgres` utility has a run-time dependency on [PostgreSQL](https://www.postgresql.org/). ## Installation - $ ./configure - $ make - $ sudo make install +You can install `temp-postgres` using Cargo: + +```sh +# From crates.io +cargo install temp-postgres-command + +# From the hosted Git repository +cargo --config net.git-fetch-with-cli=true install --git https://git.skreutz.com/temp-postgres.git/ + +# From your local source copy +cargo install --path . +``` + +Alternatively you can run or install `temp-postgres` using the experimental Nix flake: + +```sh +# Default package +nix run git+https://git.skreutz.com/temp-postgres.git -- --help + +# Fixed PostgreSQL major version +nix run git+https://git.skreutz.com/temp-postgres.git#temp-postgres_18 -- --help + +# Unwrapped package (to be used with your own PostgreSQL installation) +nix run git+https://git.skreutz.com/temp-postgres.git#temp-postgres-unwrapped -- --help +``` + +**NOTE**: Try using Nix' `--refresh` flag, or adding `?ref=main&shallow=0` to the URL if you experience caching issues. + +See the [NixOS example](./examples/nixos) for how to install `temp-postgres` on NixOS using Nix flakes. + +## Limitations + +For now, `temp-postgres` supports only UNIX-like systems. + +`temp-postgres` may fail to clean up resources. +While `temp-postgres` performs a graceful shutdown on `SIGINT`, it terminates immediately when the graceful shutdown times out, and on `SIGTERM`. + +## Maintenance + +`temp-postgres` is semi-actively maintained. +I intend to fix bugs, and keep it working. + +Releases adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), see the [changelog](CHANGELOG.md). + +The minimum supported Rust version (MSRV) is the latest stable release. + +The Nix flake is experimental. + +## Contribution + +Contributions are welcome! +Please [contact](https://www.skreutz.com/contact/) me via email. + +## License + +This work is dual-licensed under [MIT](LICENSE-MIT) or [Apache License, Version 2.0](LICENSE-APACHE-2.0). + +## History +The `temp-postgres` utility started as a POSIX shell script, first published in a [blog post](https://www.skreutz.com/posts/temporary-postgresql-server/) on 15 October 2020. +Six years later, in 2026, I rewrote the shell script in async Rust, partially because I wanted to improve error and signal handling, partially because why not ☺. +I chose *async* Rust because signal handling is fundamentally asynchronous. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..ae339f8 --- /dev/null +++ b/build.rs @@ -0,0 +1,16 @@ +//! Build script. + +fn main() -> Result<(), Box<dyn std::error::Error>> { + // Embed build information. + vergen_gitcl::Emitter::new() + .idempotent() + .add_instructions( + &vergen_gitcl::Gitcl::builder() + .sha(true) // Short + .dirty(false) // Ignore untracked files + .build(), + )? + .emit()?; + + Ok(()) +} diff --git a/configure b/configure deleted file mode 100755 index 9a1e936..0000000 --- a/configure +++ /dev/null @@ -1,18 +0,0 @@ -#! /bin/sh - -set -o errexit -set -o nounset - -exec 3>config.mk - -case "$( uname )" in - OpenBSD) - echo 'BINGRP = bin' 1>&3 - echo 'MANGRP = bin' 1>&3 - ;; - Linux) - echo 'BINMODE = 755' 1>&3 - echo 'MANMODE = 644' 1>&3 - echo 'MANDIR = share/man/man' 1>&3 - ;; -esac diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..814bc78 --- /dev/null +++ b/deny.toml @@ -0,0 +1,22 @@ +# cargo-deny configuration +# +# Default config: <https://github.com/EmbarkStudios/cargo-deny/blob/main/deny.template.toml> +# Docs: <https://embarkstudios.github.io/cargo-deny/> +# Project: <https://github.com/EmbarkStudios/cargo-deny> +# + +[licenses] +# See <https://spdx.org/licenses/> for possible licenses. +allow = ["Apache-2.0", "MIT", "Unicode-3.0"] +confidence-threshold = 1.0 + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = [] + +[sources.allow-org] +github = [] +gitlab = [] +bitbucket = [] diff --git a/examples/nixos/.gitignore b/examples/nixos/.gitignore new file mode 100644 index 0000000..abd4cf1 --- /dev/null +++ b/examples/nixos/.gitignore @@ -0,0 +1,2 @@ +/flake.lock +/nixos.qcow2 diff --git a/examples/nixos/README.md b/examples/nixos/README.md new file mode 100644 index 0000000..ea6b9f4 --- /dev/null +++ b/examples/nixos/README.md @@ -0,0 +1,13 @@ +# NixOS example + +This example shows how to install `temp-postgres` on NixOS using Nix flakes. + +You can actually run this configuration as a virtual machine on QEMU: + +```sh +# Use the latest version of temp-postgres. +nix run ".#nixosConfigurations.myhost.config.system.build.vm" + +# Use the worktree version of temp-postgres. +nix run --override-input temp-postgres ../.. ".#nixosConfigurations.myhost.config.system.build.vm" +``` diff --git a/examples/nixos/flake.nix b/examples/nixos/flake.nix new file mode 100644 index 0000000..9bab354 --- /dev/null +++ b/examples/nixos/flake.nix @@ -0,0 +1,57 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + temp-postgres = { + # Try adding "?ref=main&shallow=0" to the URL if you experience caching issues. + url = "git+https://git.skreutz.com/temp-postgres.git"; + # Optionally use your global Nixpkgs input. + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { + self, + nixpkgs, + temp-postgres, + }@inputs: + { + nixosConfigurations.myhost = + let + system = "x86_64-linux"; + in + nixpkgs.lib.nixosSystem { + inherit system; + specialArgs = { + inherit system inputs; + }; + modules = [ + # The following goes typically into ./configuration.nix + { + environment.systemPackages = [ + inputs.temp-postgres.packages.${system}.default + + # Optionally select the PostgreSQL version provided by Nixpkgs. + #inputs.temp-postgres.packages.${system}.temp-postgres_18 + ]; + + users.users.stefan = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + initialPassword = "sesame"; + }; + services.getty.autologinUser = "stefan"; + system.stateVersion = "26.05"; + + # Dummy values to avoid failed assertions during `nix flake check`. + fileSystems."/" = { + device = "/dev/null"; + fsType = "ext4"; + }; + boot.loader.grub.devices = [ "/dev/null" ]; + } + ]; + }; + }; +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..61a12de --- /dev/null +++ b/flake.lock @@ -0,0 +1,77 @@ +{ + "nodes": { + "crane": { + "locked": { + "lastModified": 1787326676, + "narHash": "sha256-lWhBbBvC05/xwivKBBiM2YNizpmgqCgyOIzomvRuwxs=", + "owner": "ipetkov", + "repo": "crane", + "rev": "692f7e9ef2ece8125b466f66f2af532b3edaed0d", + "type": "github" + }, + "original": { + "owner": "ipetkov", + "repo": "crane", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1785627969, + "narHash": "sha256-4dtXQk/NMePegK/nWp5NSeuZKLATItOq61lpEvmXqGw=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "427bf4bd9435fdf21321c8cc628c24efc14c0f7a", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1787209939, + "narHash": "sha256-WvvHR4kSQLAbtouMC/ruZ5UpLwlUcY3K4FAllMN+yGk=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "391b592eb44808b3bd0cb80bb71b63a5a118b8bb", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1785031560, + "narHash": "sha256-OmshNvn2vupOFpYinLUu+1Dnpu4n7Q5N3ggGVNHpkUI=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "0e79af5e3d4dcfcd676ab5ba3f95d2e3352e078c", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "root": { + "inputs": { + "crane": "crane", + "flake-parts": "flake-parts", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..1ca32d2 --- /dev/null +++ b/flake.nix @@ -0,0 +1,119 @@ +{ + description = "Run the PostgreSQL server off a temporary data directory"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + crane.url = "github:ipetkov/crane"; + }; + + outputs = + inputs@{ + self, + nixpkgs, + flake-parts, + crane, + ... + }: + flake-parts.lib.mkFlake { inherit inputs; } { + systems = [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + + perSystem = + { + self', + pkgs, + lib, + ... + }: + let + craneLib = crane.mkLib pkgs; + src = craneLib.cleanCargoSource ./.; + commonArgs = { + inherit src; + strictDeps = true; + }; + cargoArtifacts = craneLib.buildDepsOnly commonArgs; + crate = craneLib.buildPackage ( + commonArgs + // { + inherit cargoArtifacts; + nativeBuildInputs = [ + pkgs.coreutils + pkgs.postgresql + ]; + meta.mainProgram = "temp-postgres"; + VERGEN_GIT_SHA = + if self ? shortRev then + self.shortRev + else if self ? dirtyShortRev then + lib.strings.removeSuffix "-dirty" self.dirtyShortRev + else + "unknown"; + VERGEN_GIT_DIRTY = if self ? dirtyShortRev then "true" else "false"; + } + ); + version = crate.version; + revision = self.shortRev or self.dirtyShortRev or "unknown"; + wrap = + { + postgresql, + suffix ? "", + }: + pkgs.stdenv.mkDerivation { + name = "temp-postgres-${version}-${revision}${suffix}"; + version = "${version}-${revision}"; + nativeBuildInputs = [ pkgs.makeBinaryWrapper ]; + buildCommand = '' + mkdir -p $out/bin + makeWrapper ${crate}/bin/temp-postgres $out/bin/temp-postgres \ + --prefix PATH : ${lib.makeBinPath [ postgresql ]} + ''; + }; + postgresqlVersions = lib.mapAttrs' ( + name: drv: + let + postgresqlVersion = lib.removePrefix "postgresql_" name; + in + lib.nameValuePair "temp-postgres_${postgresqlVersion}" (wrap { + postgresql = drv; + suffix = "_${postgresqlVersion}"; + }) + ) pkgs.postgresqlVersions; + in + { + packages = { + default = self'.packages.temp-postgres; + temp-postgres = wrap { postgresql = pkgs.postgresql; }; + temp-postgres-unwrapped = crate; + } + // postgresqlVersions; + + devShells.default = pkgs.mkShell { + nativeBuildInputs = with pkgs; [ + cargo + cargo-audit + cargo-deny + cargo-edit + clippy + just + nixfmt + postgresql + rust-analyzer + rustc + rustfmt + taplo + watchexec + ]; + shellHook = '' + export FLAKE=${self} + ''; + }; + + formatter = pkgs.nixfmt-tree; + }; + }; +} diff --git a/justfile b/justfile new file mode 100644 index 0000000..1e0efea --- /dev/null +++ b/justfile @@ -0,0 +1,35 @@ +alias fmt := format + +_default: + @just --list + +# Auto-format source code. +format: + cargo fmt --all + env RUST_LOG=warn taplo format + find . -type f -iname justfile -print0 | xargs -0rn 1 just --fmt --unstable --justfile + find . -type f -name '*.nix' -print0 | xargs -0rn 1 nixfmt + +# Run all checks. +[env("CARGO_BUILD_WARNINGS", "deny")] +check: + @# Check format + cargo fmt --all --check + env RUST_LOG=warn taplo format --check + find . -type f -iname justfile -print0 | xargs -0rn 1 just --fmt --unstable --check --justfile + @# nix fmt -- --ci # treefmt --ci is not read-only + find . -type f -name '*.nix' -print0 | xargs -0rn 1 nixfmt --check + @# Lint + env RUST_LOG=warn taplo lint + cargo clippy --workspace --all-targets --all-features -- --deny warnings + @# Build + cargo build --workspace --all-targets --all-features --keep-going + cargo doc --all-features --no-deps --document-private-items --keep-going + @# Test + cargo test --workspace --all-targets --all-features + @# Check dependencies for known security vulnerabilities, licenses, etc. + cargo audit + cargo deny --workspace --all-features check --show-stats bans licenses sources + @# Check Nix flake + nix flake check --print-build-logs --verbose + cd examples/nixos/ && nix flake check --print-build-logs --verbose --override-input temp-postgres ../.. diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..60417ec --- /dev/null +++ b/src/main.rs @@ -0,0 +1,540 @@ +//! Run the PostgreSQL server off a temporary data directory. +//! +//! See the [supported command-line arguments](Args). + +use std::{ + collections::HashMap, + ffi::{OsStr, OsString}, + os::unix::fs::PermissionsExt, + path::PathBuf, + process::{ExitCode, ExitStatus, Stdio}, + time::Duration, +}; + +use anyhow::{Context, bail}; +use clap::{Parser, ValueHint, builder::NonEmptyStringValueParser}; +use tokio::{process::Command, signal::unix::SignalKind, time::Instant}; +use tokio_util::sync::CancellationToken; +use tracing::{debug, info, trace, warn}; +use url::Url; + +// For clap. +macro_rules! version { + () => { + crate::version() + }; +} + +const EXTRA_HELP: &str = color_print::cstr!( + r#"<strong><underline>Exit status:</underline></strong> + +Exits 0 on success, and >0 if an error occurs. Specifically, exits 2 on usage error, and 130 when interrupted. Propagates the exit status of the given command, if any. +"# +); + +/// Command-line arguments. +#[derive(Debug, Clone, Parser)] +#[command(name = "temp-postgres", version, long_version = version!(), about, author, after_long_help = EXTRA_HELP, next_display_order = None)] +#[deny(clippy::missing_docs_in_private_items)] +struct Args { + /// Database name. + /// + /// Defaults to the PostgreSQL user name. + #[arg(short = 'd', long, env = "PGDATABASE", value_parser = NonEmptyStringValueParser::new())] + dbname: Option<String>, + + /// PostgreSQL user name. + /// + /// If not set, PostgreSQL uses the current operating system user. + #[arg(short = 'u', long, env = "PGUSER", value_parser = NonEmptyStringValueParser::new())] + username: Option<String>, + + /// Create a symbolic link to the temporary directory. + /// + /// The given path must not exist. + /// + /// The symbolic link will be created when the PostgreSQL server is ready. + /// It will be removed when the program ends if it (still) points to the temporary directory. + /// + /// Example: Static client configuration. + /// + /// ```sh + /// temp-postgres --symlink db + /// psql --host "$(realpath db)" + /// ``` + // Clap ensures that arguments passed on the command-line are non-empty. + // Add a value parser when binding to an environment variable. + #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath)] + symlink: Option<OsString>, + + /// Log level. + #[arg(long, value_enum, default_value_t = LogLevel::Info)] + log_level: LogLevel, + + /// Postgres startup timeout. + #[arg(long, value_name = "DURATION", value_parser = humantime::parse_duration, default_value = "5s")] + startup_timeout: Duration, + + /// Graceful shutdown timeout. + /// + /// `temp-postgres` performs a graceful shutdown upon SIGINT. + /// The signal is propagated to child processes, namely the `postgres` command, and the wrapped command, if any. + /// Child processes are killed (with SIGKILL) if they don't shut down in time. + #[arg(long, value_name = "DURATION", value_parser = humantime::parse_duration, default_value = "5s")] + shutdown_timeout: Duration, + + /// Command to execute once the PostgreSQL server is ready. + /// + /// The following environment variables will be passed to the command: + /// + /// - PGHOST, the absolute path to the directory in which the UNIX domain socket file is stored + /// - PGDATABASE, the database name + /// - PGUSER, the PostgreSQL user name + /// - DATABASE_URL, a connection URI + /// + /// See also the PostgreSQL documentation on environment variables and connection URIs: + /// + /// - <https://www.postgresql.org/docs/current/libpq-envars.html> + /// - <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS> + /// + /// Example: Wrap the `psql` command to connect to the temporary database once the server is ready. + /// + /// ```sh + /// temp-postgres -- psql + /// ``` + #[arg(last = true, value_hint = ValueHint::CommandWithArguments)] + command: Vec<OsString>, +} + +/// Log level. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)] +enum LogLevel { + Off, + Error, + Warn, + Info, + Debug, + Trace, +} + +impl From<LogLevel> for tracing_subscriber::filter::LevelFilter { + fn from(value: LogLevel) -> Self { + match value { + LogLevel::Off => tracing_subscriber::filter::LevelFilter::OFF, + LogLevel::Error => tracing_subscriber::filter::LevelFilter::ERROR, + LogLevel::Warn => tracing_subscriber::filter::LevelFilter::WARN, + LogLevel::Info => tracing_subscriber::filter::LevelFilter::INFO, + LogLevel::Debug => tracing_subscriber::filter::LevelFilter::DEBUG, + LogLevel::Trace => tracing_subscriber::filter::LevelFilter::TRACE, + } + } +} + +#[tokio::main] +async fn main() -> ExitCode { + let args = Args::parse(); // May exit 0 or 2. Respects `NO_COLOR`. + let result = async { + let mut subscriber = tracing_subscriber::fmt() + .with_max_level(args.log_level.to_owned()) + .with_writer(std::io::stderr); // Enable user to capture standard output of wrapped command. + if std::env::var_os("NO_COLOR").is_some() { + subscriber = subscriber.with_ansi(false); + } + subscriber.init(); + debug!(version = version(), "starting"); + debug!(arguments = ?args, "parsed command-line arguments"); + + run(args).await + }; + match result.await { + Ok(_) => ExitCode::SUCCESS, + Err(err) => { + // Relying on tracing to print error. + //eprintln!("Error: {err:?}"); + if err.is::<InterruptError>() { + ExitCode::from(130) + } else if let Some(err) = err.downcast_ref::<WrappedCommandError>() { + match err.0.code().and_then(|code| u8::try_from(code).ok()) { + Some(code) => ExitCode::from(code), + None => ExitCode::FAILURE, + } + } else { + ExitCode::FAILURE + } + } + } +} + +#[tracing::instrument(level = "info", skip_all, err(Debug))] +async fn run(args: Args) -> Result<(), anyhow::Error> { + let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt()) + .context("Failed to register SIGINT handler")?; + debug!("registered SIGINT handler"); + + let tmp = tempfile::Builder::new() + .prefix("temp-postgres-") + .permissions(std::fs::Permissions::from_mode(0o700)) + .tempdir() + .context("Failed to create temporary directory")?; + debug!(directory = %&tmp.path().display(), "created temporary directory"); + + let token = CancellationToken::new(); + let mut server = tokio::spawn(serve(args.clone(), tmp.path().to_path_buf(), token.clone())); + debug!("spawned server task"); + + let result = tokio::select! { + _ = sigint.recv() => { + info!("received SIGINT, shutting down ..."); + token.cancel(); + tokio::select! { + _ = tokio::time::sleep(args.shutdown_timeout) => { + warn!("graceful shutdown timed out, aborting ..."); + server.abort(); + server.await? + } + r = &mut server => { + debug!("server task finished"); + r? + } + } + } + r = &mut server => { + debug!("server task finished"); + r? + }, + }; + + if let Some(symlink) = &args.symlink { + if let Ok(target) = tokio::fs::canonicalize(&symlink).await + && let Ok(tmp) = tokio::fs::canonicalize(&tmp.path()).await + && target == tmp + { + match tokio::fs::remove_file(symlink).await { + Ok(()) => debug!(?symlink, "removed symlink"), + Err(err) => warn!(?symlink, error = ?err, "failed to remove symlink"), + } + } else { + warn!(?symlink, directory = %&tmp.path().display(), "keeping symlink because it doesn't point to temporary directory"); + } + } + + let tmp_dir = tmp.path().to_path_buf(); + match tmp.close() { + Ok(()) => debug!(directory = %tmp_dir.display(), "removed temporary directory"), + Err(err) => { + warn!(directory = %tmp_dir.display(), error = ?err, "failed to remove temporary directory") + } + } + result +} + +#[tracing::instrument(level = "info", skip_all, err)] +async fn serve( + args: Args, + tmp_dir: PathBuf, + token: CancellationToken, +) -> Result<(), anyhow::Error> { + // WORKAROUND: PostgreSQL expects a non-empty dbname when username is set. + let args = Args { + dbname: args.dbname.clone().or(args.username.clone()), + ..args + }; + + // TODO: Check token.is_cancelled() before every command? + let mut optional_initdb_args = Vec::<&OsStr>::new(); + if let Some(ref username) = args.username { + optional_initdb_args.push("--username".as_ref()); + optional_initdb_args.push(username.as_ref()); + } + let status = Command::new("initdb") + .arg("--pgdata") + .arg(&tmp_dir) + .args(optional_initdb_args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) // In case this task gets aborted + .status() + .await + .context("Failed to spawn or wait for initdb command")?; + if !status.success() { + bail!("initdb command exited error: {status}"); + } + debug!("initialized database"); + + let mut postgres = Command::new("postgres") + .arg("-h") + .arg("") // Don't bind to a TCP/IP address + .arg("-k") + .arg(&tmp_dir) + .arg("-D") + .arg(&tmp_dir) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .context("Failed to spawn postgres command")?; + debug!("spawned postgres command"); + + let now = Instant::now(); + tokio::time::sleep(Duration::from_millis(50)).await; + for i in 1.. { + match is_ready(tmp_dir.as_ref(), args.username.as_deref()).await { + Ok(status) => { + if status.success() { + debug!("PostgreSQL server is ready"); + break; + } else if status.code() == Some(1) || status.code() == Some(2) { + if now.elapsed() < args.startup_timeout { + trace!("retrying pg_isready command ..."); + } else { + bail!("pg_isready timed out after {i} attempts"); + } + } else { + bail!("pg_isready command exited error: {status}"); + } + } + Err(err) => return Err(err), + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + + let mut optional_createdb_args = Vec::<&OsStr>::new(); + if let Some(ref username) = args.username { + optional_createdb_args.push("--username".as_ref()); + optional_createdb_args.push(username.as_ref()); + } + if let Some(ref dbname) = args.dbname { + // Positional argument + optional_createdb_args.push(dbname.as_ref()); + } + let status = Command::new("createdb") + .arg("--host") + .arg(&tmp_dir) + .arg("--no-password") + .args(optional_createdb_args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .status() + .await + .context("Failed to spawn or wait for createdb command")?; + if !status.success() { + bail!("createdb command exited error: {status}"); + } + debug!("Created PostgreSQL database"); + + let mut url = Url::parse("postgresql://")?; + if let Some(ref dbname) = args.dbname { + url.set_path(dbname); + } + url.query_pairs_mut() + .append_pair("host", &tmp_dir.display().to_string()); + if let Some(ref username) = args.username { + url.query_pairs_mut().append_pair("user", username); + } + + info!( + PGHOST = %&tmp_dir.display(), + PGDATABASE = &args.dbname, + PGUSER = &args.username, + DATABASE_URL = %&url, + "You can connect using the following parameters" + ); + + if let Some(symlink) = &args.symlink { + tokio::fs::symlink(&tmp_dir, symlink) + .await + .context("Failed to create symlink")?; + debug!(?symlink, "created symlink"); + } + + let mut wrapped_command = match args.command.split_first() { + None => None, + Some((head, tail)) => { + let mut optional_env = HashMap::new(); + if let Some(ref username) = args.username { + optional_env.insert("PGUSER", username); + } + if let Some(ref dbname) = args.dbname { + optional_env.insert("PGDATABASE", dbname); + } + let command = Command::new(head) + .args(tail) + .env("PGHOST", &tmp_dir) + .env("DATABASE_URL", url.as_str()) // for SQLx with SQLX_OFFLINE=true + .envs(optional_env) + .kill_on_drop(true) + .spawn() + .context("Failed to spawn wrapped command")?; + debug!("spawned wrapped command"); + Some(command) + } + }; + + tokio::select! { + _ = token.cancelled() => { + debug!("token cancelled"); + debug!("shutting down child processes ..."); + // Propagating SIGINT to child processes in case it was send to temp-postgres only. + // Halving shutdown timeout to avoid being aborted by parent task. + let shutdown_timeout = args.shutdown_timeout.checked_div(2).unwrap(); + let (wrapped_command_result, postgres_result) = tokio::join!( + async { + if let Some(ref mut c) = wrapped_command { + interrupt_or_kill(c, shutdown_timeout).await + } else { + Ok(None) + } + }, + interrupt_or_kill(&mut postgres, shutdown_timeout), + ); + if wrapped_command.is_some() { + match wrapped_command_result { + // Exit code is probably 130 + Ok(status) => debug!(?status, "successfully shut down wrapped command"), + Err(err) => warn!(error = ?err, "failed to shut down wrapped command"), + } + } + match postgres_result { + // Exit code is probably 130 + Ok(status) => debug!(?status, "successfully shut down postgres command"), + Err(err) => warn!(error = ?err, "failed to shut down postgres command"), + } + Err(InterruptError{})? + }, + r = postgres.wait() => { + debug!("postgres command finished"); + debug!("shutting down wrapped command ..."); + if let Some(ref mut c) = wrapped_command { + match interrupt_or_kill(c, args.shutdown_timeout).await { + // Exit code is probably 130 + Ok(status) => debug!(?status, "successfully shut down wrapped command"), + Err(err) => warn!(error = ?err, "failed to shut down wrapped command"), + } + } + let status = r.context("failed to wait for postgres command")?; + if !status.success() { + bail!("postgres command exited error: {status}"); + } + Ok(()) + }, + r = conditional_wait(&mut wrapped_command) => { + debug!("wrapped command finished"); + debug!("shutting down postgres command ..."); + match interrupt_or_kill(&mut postgres, args.shutdown_timeout).await { + // Exit code is probably 130 + Ok(status) => debug!(?status, "successfully shut down postgres command"), + Err(err) => warn!(error = ?err, "failed to shut down postgres command"), + } + let status = r.context("failed to wait for wrapped command")?; + if !status.success() { + Err(WrappedCommandError(status))?; + } + Ok(()) + }, + } +} + +fn interrupt(child: &tokio::process::Child) -> Result<(), anyhow::Error> { + // std::os::unix::process::ChildExt::send_signal is nightly-only experimental + if let Some(id) = child.id() { + nix::sys::signal::kill( + nix::unistd::Pid::from_raw(id as i32), + nix::sys::signal::Signal::SIGINT, + ) + .context("Failed to send SIGINT to process {id}")?; + } + Ok(()) +} + +async fn interrupt_or_kill( + child: &mut tokio::process::Child, + timeout: Duration, +) -> Result<Option<ExitStatus>, anyhow::Error> { + interrupt(child)?; + tokio::select! { + r = child.wait() => { + r.map(Some).context("Failed to wait for child process") + }, + _ = tokio::time::sleep(timeout) => { + child.kill().await.context("Failed to kill child process")?; + Ok(None) + } + } +} + +async fn is_ready(tmp_dir: &OsStr, username: Option<&str>) -> Result<ExitStatus, anyhow::Error> { + let mut optional_isready_args = Vec::<&OsStr>::new(); + if let Some(ref username) = username { + optional_isready_args.push("--username".as_ref()); + optional_isready_args.push(username.as_ref()); + } + Command::new("pg_isready") + .arg("--host") + .arg(tmp_dir) + .arg("--dbname") + .arg("dummy") // No database created yet + .arg("--timeout") + .arg("3") // Default + .args(optional_isready_args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .status() + .await + .context("Failed to spawn or wait for pg_isready command") +} + +async fn conditional_wait( + child: &mut Option<tokio::process::Child>, +) -> Result<std::process::ExitStatus, std::io::Error> { + match child { + None => std::future::pending().await, + Some(child) => child.wait().await, + } +} + +#[derive(Debug)] +struct WrappedCommandError(ExitStatus); + +impl std::fmt::Display for WrappedCommandError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Wrapped command exited error: {}", self.0) + } +} + +impl std::error::Error for WrappedCommandError {} + +#[derive(Debug)] +struct InterruptError {} + +impl std::fmt::Display for InterruptError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Interrupted") + } +} + +impl std::error::Error for InterruptError {} + +fn version() -> String { + // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates + let package_version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"); + let revision = option_env!("VERGEN_GIT_SHA").unwrap_or("unknown"); + let dirty = option_env!("VERGEN_GIT_DIRTY").and_then(|s| s.trim().parse::<bool>().ok()); + + let mut version = format!("{package_version}-{revision}"); + if let Some(true) = dirty { + version.push_str("-dirty"); + } + version +} + +#[test] +fn cli() { + use clap::CommandFactory; + Args::command().debug_assert(); +} diff --git a/temp-postgres.1 b/temp-postgres.1 deleted file mode 100644 index caf4b78..0000000 --- a/temp-postgres.1 +++ /dev/null @@ -1,54 +0,0 @@ -.\" Copyright (c) 2022 Stefan Kreutz <mail@skreutz.com> -.\" -.\" Permission to use, copy, modify, and distribute this software for any -.\" purpose with or without fee is hereby granted, provided that the above -.\" copyright notice and this permission notice appear in all copies. -.\" -.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -.Dd $Mdocdate: May 19 2022 $ -.Dt TEMP-POSTGRES 1 -.Os -.Sh NAME -.Nm temp-postgres -.Nd temporary PostgreSQL server -.Sh SYNOPSIS -.Nm temp-postgres -.Ar database -.Ar superuser -.Sh DESCRIPTION -The -.Nm -utility runs the PostgreSQL server off a temporary data directory. -.Pp -It expects exactly two arguments: -a -.Ar database -name -and a -.Ar superuser -name. -You may also set the port using PGPORT, see -.Xr postgres 1 . -.Sh EXIT STATUS -.Ex -std temp-postgres -.Sh EXAMPLES -Create a temporary database "test" with superuser "alex": -.Bd -literal -offset indent -$ temp-postgres test alex -.Ed -.Pp -Connect to the "test" database: -.Bd -literal -offset indent -$ psql --host=localhost test alex -.Ed -.Sh SEE ALSO -.Xr postgres 1 , -.Xr psql 1 -.Sh AUTHORS -.An Stefan Kreutz Aq Mt mail@skreutz.com diff --git a/temp-postgres.sh b/temp-postgres.sh deleted file mode 100755 index 48bb9e8..0000000 --- a/temp-postgres.sh +++ /dev/null @@ -1,77 +0,0 @@ -#! /bin/sh - -# Copyright (c) 2019, 2020, 2022 Stefan Kreutz <mail@skreutz.com> -# -# Permission to use, copy, modify, and distribute this software for any purpose -# with or without fee is hereby granted, provided that the above copyright -# notice and this permission notice appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -# PERFORMANCE OF THIS SOFTWARE. - -set -o nounset - -# Remove the temporary directory before exiting. -trap 'quit' INT -quit() { - code="${1:-0}" - trap '' INT TERM - kill -TERM 0 - wait - rm -rf "${tmpdir-}" || { - ( >&2 printf "temp-postgres: failed to remove temporary directory: %s\\n" "${tmpdir}" ) - [ "${code}" -ne 0 ] || code=1 - } - exit "${code}" -} - -# Parse arguments. -[ $# -eq 2 ] || { - ( >&2 printf "temp-postgres: invalid arguments\\n" ) - printf "Usage: temp-postgres <dbname> <username>\\n" - quit 1 -} -dbname="$1" -username="$2" - -# Create a temporary directory -tmpdir="$( mktemp -d )" || { - ( >&2 printf "temp-postgres: failed to create temporary directory\\n" ) - quit 1 -} - -# Initialize the directory -initdb --pgdata="${tmpdir}" --username="${username}" || { - ( >&2 printf "temp-postgres: failed to initialize database\\n" ) - quit 1 -} - -# Serve the directory -( postgres -k "${tmpdir}" -D "${tmpdir}" </dev/null ) & - -# Test the connection -sleep 1 -pg_isready --host="${tmpdir}" --dbname="nope" --username="${username}" --timeout=10 || { - ( >&2 printf "temp-postgres: failed to connect to server\\n" ) - quit 1 -} - -# Create the database -createdb --host="${tmpdir}" --username="${username}" --no-password "${dbname}" || { - ( >&2 printf "temp-postgres: failed to create database\\n" ) - quit 1 -} - -printf ' -Connect with the following command: - -\tpsql --host=localhost "%s" "%s" - -' "${dbname}" "${username}" - -wait diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..0b99f8b --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,356 @@ +//! Command-line interface integration test. + +use std::{ + process::{Child, Stdio}, + time::Duration, +}; + +use assert_cmd::{Command, prelude::*}; +use assert_fs::TempDir; +use predicates::prelude::*; +use testresult::TestResult; + +#[test] +fn short_help() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("-h") + .assert() + .success() + .stdout(predicate::str::contains("Usage")) + .stderr(predicate::str::is_empty()); + Ok(()) +} + +#[test] +fn long_help() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--help") + .assert() + .success() + .stdout(predicate::str::contains("Usage")) + .stderr(predicate::str::is_empty()); + Ok(()) +} + +#[test] +fn short_version() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("-V") + .assert() + .success() + .stdout(predicate::str::is_match( + r#"^temp-postgres [0-9]+\.[0-9]+\.[0-9]+\n$"#, + )?) + .stderr(predicate::str::is_empty()); + Ok(()) +} + +#[test] +fn long_version() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--version") + .assert() + .success() + .stdout(predicate::str::is_match( + r#"^temp-postgres [0-9]+\.[0-9]+\.[0-9]+-[0-9a-f]{7}(-dirty)?\n$"#, + )?) + .stderr(predicate::str::is_empty()); + Ok(()) +} + +#[test] +fn wrapped_true() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--") + .arg("true") + .assert() + .success() + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("PGHOST")); + Ok(()) +} + +#[test] +fn wrapped_false() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--") + .arg("false") + .assert() + .failure() + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("Wrapped command exited error")); + Ok(()) +} + +#[test] +fn log_level_off() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--log-level") + .arg("off") + .arg("--") + .arg("true") + .assert() + .success() + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::is_empty()); + Ok(()) +} + +#[test] +fn no_such_flag() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--foo") + .assert() + .code(2) + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("unexpected argument")); + Ok(()) +} + +#[test] +fn unexpected_argument() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("foo") + .assert() + .code(2) + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("unexpected argument")); + Ok(()) +} + +#[test] +fn missing_username_argument() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--username") + .assert() + .code(2) + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("--username")); + Ok(()) +} + +#[test] +fn empty_username_argument() -> TestResult { + Command::cargo_bin("temp-postgres")? + .arg("--username") + .arg("") + .assert() + .code(2) + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::contains("--username")); + Ok(()) +} + +#[test] +fn symlink() -> TestResult { + let tmp_dir = TempDir::new()?; + let symlink = tmp_dir.join("db"); + let child = std::process::Command::cargo_bin("temp-postgres")? + .arg("--username") + .arg("alex") + .arg("--dbname") + .arg("myproject") + .arg("--symlink") + .arg(&symlink) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + for i in (0..100).rev() { + std::thread::sleep(Duration::from_millis(200)); + if symlink.exists() { + break; + } else if i > 0 { + continue; + } else { + panic!("symlink not created in time"); + } + } + Command::new("psql") + .arg("--no-psqlrc") + .arg("--no-align") + .arg("--tuples-only") + .arg("--host") + .arg(&symlink) + .arg("--dbname") + .arg("myproject") + .arg("--username") + .arg("alex") + .write_stdin("SELECT current_database(), usename FROM pg_user;") + .assert() + .success() + .stdout(predicate::str::is_match(r#"^myproject|alex\n$"#)?) + .stderr(predicate::str::is_empty()); + interrupt(&child); + child.wait_with_output()?.assert().code(130); + Ok(()) +} + +#[test] +fn interrupted() -> TestResult { + let tmp_dir = TempDir::new()?; + let symlink = tmp_dir.join("db"); + let child = std::process::Command::cargo_bin("temp-postgres")? + .arg("--symlink") + .arg(&symlink) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + for i in (0..100).rev() { + std::thread::sleep(Duration::from_millis(200)); + if symlink.exists() { + break; + } else if i > 0 { + continue; + } else { + panic!("symlink not created in time"); + } + } + interrupt(&child); + child.wait_with_output()?.assert().code(130); + Ok(()) +} + +#[test] +fn interrupted_empty_command() -> TestResult { + let tmp_dir = TempDir::new()?; + let symlink = tmp_dir.join("db"); + let child = std::process::Command::cargo_bin("temp-postgres")? + .arg("--symlink") + .arg(&symlink) + .arg("--") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + for i in (0..100).rev() { + std::thread::sleep(Duration::from_millis(200)); + if symlink.exists() { + break; + } else if i > 0 { + continue; + } else { + panic!("symlink not created in time"); + } + } + interrupt(&child); + child.wait_with_output()?.assert().code(130); + Ok(()) +} + +#[test] +fn interrupted_sleep_command() -> TestResult { + let tmp_dir = TempDir::new()?; + let symlink = tmp_dir.join("db"); + let child = std::process::Command::cargo_bin("temp-postgres")? + .arg("--symlink") + .arg(&symlink) + .arg("--") + .arg("sleep") + .arg("30") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + for i in (0..100).rev() { + std::thread::sleep(Duration::from_millis(200)); + if symlink.exists() { + break; + } else if i > 0 { + continue; + } else { + panic!("symlink not created in time"); + } + } + interrupt(&child); + child.wait_with_output()?.assert().code(130); + Ok(()) +} + +#[test] +fn wrapped_cat() -> TestResult { + assert_cmd::Command::cargo_bin("temp-postgres")? + .arg("--") + .arg("cat") + .write_stdin("foo") + .assert() + .success() + .stdout(predicate::str::is_match(r#"^foo$"#)?) + .stderr(predicate::str::contains("PGHOST")); + Ok(()) +} + +#[test] +fn wrapped_psql_with_username() -> TestResult { + assert_cmd::Command::cargo_bin("temp-postgres")? + .arg("--username") + .arg("alex") + .arg("--") + .arg("psql") + .arg("--no-psqlrc") + .arg("--no-align") + .arg("--tuples-only") + .write_stdin("SELECT current_database(), usename FROM pg_user;") + .assert() + .success() + .stdout(predicate::str::is_match(r#"^alex|alex\n$"#)?) + .stderr(predicate::str::contains("PGHOST")); + Ok(()) +} + +#[test] +fn wrapped_psql_with_username_and_dbname() -> TestResult { + assert_cmd::Command::cargo_bin("temp-postgres")? + .arg("--username") + .arg("alex") + .arg("--dbname") + .arg("myproject") + .arg("--") + .arg("psql") + .arg("--no-psqlrc") + .arg("--no-align") + .arg("--tuples-only") + .write_stdin("SELECT current_database(), usename FROM pg_user;") + .assert() + .success() + .stdout(predicate::str::is_match(r#"^myproject|alex\n$"#)?) + .stderr(predicate::str::contains("PGHOST")); + Ok(()) +} + +#[test] +fn wrapped_psql_with_database_url() -> TestResult { + assert_cmd::Command::cargo_bin("temp-postgres")? + .arg("--username") + .arg("alex") + .arg("--dbname") + .arg("myproject") + .arg("--") + .arg("env") + .arg("--unset") + .arg("PGHOST") + .arg("--unset") + .arg("PGDATABASE") + .arg("--unset") + .arg("PGUSER") + .arg("--") + .arg("bash") + .arg("-c") + .arg("psql --no-psqlrc --no-align --tuples-only \"$DATABASE_URL\"") + .write_stdin("SELECT current_database(), usename FROM pg_user;") + .assert() + .success() + .stdout(predicate::str::is_match(r#"^myproject|alex\n$"#)?) + .stderr(predicate::str::contains("PGHOST")); + Ok(()) +} + +fn interrupt(child: &Child) { + // std::os::unix::process::ChildExt::send_signal is nightly-only experimental + nix::sys::signal::kill( + nix::unistd::Pid::from_raw(child.id() as i32), + nix::sys::signal::Signal::SIGINT, + ) + .unwrap(); +} |