aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Fischer <martin@push-f.com>2026-12-03 08:11:11 +0100
committerMartin Fischer <martin@push-f.com>2026-12-04 09:11:05 +0100
commita7c41f1de23ba951da838ca24009a8399a1e1c46 (patch)
tree64c8ff38ce80317d762e4239533c2283015bac48
initial commitHEADmaster
-rw-r--r--.envrc4
-rw-r--r--.gitignore2
-rw-r--r--Cargo.lock356
-rw-r--r--Cargo.toml11
-rw-r--r--README.md24
-rw-r--r--default.nix78
-rw-r--r--npins/default.nix252
-rw-r--r--npins/sources.json11
-rw-r--r--src/main.rs441
-rw-r--r--tests/cli.rs216
10 files changed, 1395 insertions, 0 deletions
diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..5bee049
--- /dev/null
+++ b/.envrc
@@ -0,0 +1,4 @@
+watch_file default.nix
+watch_file npins/default.nix
+watch_file npins/sources.json
+use nix -A devShells.default
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d787b70
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+/target
+/result
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..519bde5
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,356 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anstream"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "clap"
+version = "4.6.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_complete"
+version = "4.6.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
+dependencies = [
+ "clap",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e"
+
+[[package]]
+name = "errno"
+version = "0.3.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[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 = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[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 = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+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 = "rustix"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[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 = "treeimp"
+version = "0.0.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "clap_complete",
+ "serde",
+ "serde_json",
+ "tempfile",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[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 = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..5dbb8b9
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "treeimp"
+edition = "2024"
+
+[dependencies]
+anyhow = "1.0"
+clap = { version = "4.6.10", features = ["derive"] }
+clap_complete = "4.6.12"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+tempfile = "3.15"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fb9f05a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,24 @@
+# treeimp
+
+`treeimp` vendors directories (imports trees) from remote Git repositories.
+Sources and destinations are declared in `treeimp.nix`; each source may
+also be transformed by a Nix function before it is copied into place.
+
+Run `treeimp init` to create an example configuration:
+
+```nix
+{
+ example = {
+ url = "https://git.example.com/example.git";
+ ref = "main";
+ source = "path/to/directory";
+ destination = "vendor/example";
+ transform = source: source;
+ };
+}
+```
+
+Run `treeimp sync` to import the configured sources. For each source,
+`treeimp.lock` records the last commit that changed its configured source
+directory, along with that commit's date in UTC. Commits that do not change
+the configured source directory leave the lock entry and destination unchanged.
diff --git a/default.nix b/default.nix
new file mode 100644
index 0000000..0e7f9f8
--- /dev/null
+++ b/default.nix
@@ -0,0 +1,78 @@
+{
+ sources ? import ./npins,
+ pkgs ? import sources.nixpkgs { },
+}:
+
+let
+ package = pkgs.rustPlatform.buildRustPackage {
+ pname = "treeimp";
+ version = "0-git";
+ src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
+ cargoLock.lockFile = ./Cargo.lock;
+ nativeBuildInputs = [
+ pkgs.installShellFiles
+ ];
+ nativeCheckInputs = [
+ pkgs.gitMinimal
+ pkgs.nix
+ ];
+ postInstall = ''
+ installShellCompletion --cmd treeimp \
+ --bash <($out/bin/treeimp completions bash) \
+ --fish <($out/bin/treeimp completions fish) \
+ --zsh <($out/bin/treeimp completions zsh)
+ '';
+ };
+in
+{
+ packages.default = package;
+
+ checks = {
+ cargo-fmt =
+ pkgs.runCommand "cargo-fmt-check"
+ {
+ nativeBuildInputs = [
+ pkgs.cargo
+ pkgs.rustfmt
+ ];
+ }
+ ''
+ cd ${./.}
+ cargo fmt --check --all
+ touch $out
+ '';
+
+ cargo-clippy =
+ pkgs.runCommandCC "cargo-clippy-check"
+ {
+ nativeBuildInputs = [
+ pkgs.cargo
+ pkgs.clippy
+ pkgs.rustPlatform.cargoSetupHook
+ ];
+ cargoDeps = package.cargoDeps;
+ }
+ ''
+ cp -R ${./.} source
+ chmod -R u+w source
+ cd source
+ cargoSetupPostUnpackHook
+ cargoSetupPostPatchHook
+ export CARGO_TARGET_DIR=$TMPDIR/target
+ export HOME=$TMPDIR
+ cargo clippy --all-targets --all-features -- -D warnings
+ touch $out
+ '';
+ };
+
+ devShells.default = pkgs.mkShell {
+ packages = [
+ pkgs.cargo
+ pkgs.rustc
+ pkgs.rustfmt
+ pkgs.clippy
+ pkgs.nix
+ pkgs.gitMinimal
+ ];
+ };
+}
diff --git a/npins/default.nix b/npins/default.nix
new file mode 100644
index 0000000..b7f402e
--- /dev/null
+++ b/npins/default.nix
@@ -0,0 +1,252 @@
+/*
+ This file is provided under the MIT licence:
+
+ 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.
+*/
+# Generated by npins. Do not modify; will be overwritten regularly
+let
+ # Backwards-compatibly make something that previously didn't take any arguments take some
+ # The function must return an attrset, and will unfortunately be eagerly evaluated
+ # Same thing, but it catches eval errors on the default argument so that one may still call it with other arguments
+ mkFunctor =
+ fn:
+ let
+ e = builtins.tryEval (fn { });
+ in
+ (if e.success then e.value else { error = fn { }; }) // { __functor = _self: fn; };
+
+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
+ range =
+ first: last: if first > last then [ ] else builtins.genList (n: first + n) (last - first + 1);
+
+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257
+ stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1));
+
+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
+ stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
+ concatStrings = builtins.concatStringsSep "";
+
+ # If the environment variable NPINS_OVERRIDE_${name} is set, then use
+ # the path directly as opposed to the fetched source.
+ # (Taken from Niv for compatibility)
+ mayOverride =
+ name: path:
+ let
+ envVarName = "NPINS_OVERRIDE_${saneName}";
+ saneName = stringAsChars (c: if (builtins.match "[a-zA-Z0-9]" c) == null then "_" else c) name;
+ ersatz = builtins.getEnv envVarName;
+ in
+ if ersatz == "" then
+ path
+ else
+ # this turns the string into an actual Nix path (for both absolute and
+ # relative paths)
+ builtins.trace "Overriding path of \"${name}\" with \"${ersatz}\" due to set \"${envVarName}\"" (
+ if builtins.substring 0 1 ersatz == "/" then
+ /. + ersatz
+ else
+ /. + builtins.getEnv "PWD" + "/${ersatz}"
+ );
+
+ mkSource =
+ name: spec:
+ {
+ pkgs ? null,
+ }:
+ assert spec ? type;
+ let
+ # Unify across builtin and pkgs fetchers.
+ # `fetchGit` requires a wrapper because of slight API differences.
+ fetchers =
+ if pkgs == null then
+ {
+ inherit (builtins) fetchTarball fetchurl;
+ # Frustratingly, due to flakes and `fetchTree`, `fetchGit`
+ # has a different signature than the other builtin
+ # fetchers
+ fetchGit = args: (builtins.fetchGit args).outPath;
+ }
+ else
+ {
+ fetchTarball =
+ {
+ url,
+ sha256,
+ }:
+ pkgs.fetchzip {
+ inherit url sha256;
+ extension = "tar";
+ };
+ inherit (pkgs) fetchurl;
+ fetchGit =
+ {
+ url,
+ submodules,
+ rev,
+ name,
+ narHash,
+ }:
+ pkgs.fetchgit {
+ inherit url rev name;
+ fetchSubmodules = submodules;
+ hash = narHash;
+ };
+ };
+
+ path =
+ if spec.type == "Git" then
+ mkGitSource fetchers spec
+ else if spec.type == "GitRelease" then
+ mkGitSource fetchers spec
+ else if spec.type == "PyPi" then
+ mkPyPiSource fetchers spec
+ else if spec.type == "Channel" then
+ mkChannelSource fetchers spec
+ else if spec.type == "Tarball" then
+ mkTarballSource fetchers spec
+ else if spec.type == "Container" then
+ mkContainerSource pkgs spec
+ else
+ builtins.throw "Unknown source type ${spec.type}";
+ in
+ spec // { outPath = mayOverride name path; };
+
+ mkGitSource =
+ {
+ fetchTarball,
+ fetchGit,
+ ...
+ }:
+ {
+ repository,
+ revision,
+ url ? null,
+ submodules,
+ hash,
+ ...
+ }:
+ assert repository ? type;
+ # At the moment, either it is a plain git repository (which has an url), or it is a GitHub/GitLab repository
+ # In the latter case, there we will always be an url to the tarball
+ if url != null && !submodules then
+ fetchTarball {
+ inherit url;
+ sha256 = hash;
+ }
+ else
+ let
+ url =
+ if repository.type == "Git" then
+ repository.url
+ else if repository.type == "GitHub" then
+ "https://github.com/${repository.owner}/${repository.repo}.git"
+ else if repository.type == "GitLab" then
+ "${repository.server}/${repository.repo_path}.git"
+ else if repository.type == "Forgejo" then
+ "${repository.server}/${repository.owner}/${repository.repo}.git"
+ else
+ throw "Unrecognized repository type ${repository.type}";
+ urlToName =
+ url: rev:
+ let
+ matched = builtins.match "^.*/([^/]*)(\\.git)?$" url;
+
+ short = builtins.substring 0 7 rev;
+
+ appendShort = if (builtins.match "[a-f0-9]*" rev) != null then "-${short}" else "";
+ in
+ "${if matched == null then "source" else builtins.head matched}${appendShort}";
+ name = urlToName url revision;
+ in
+ fetchGit {
+ rev = revision;
+ narHash = hash;
+
+ inherit name submodules url;
+ };
+
+ mkPyPiSource =
+ { fetchurl, ... }:
+ {
+ url,
+ hash,
+ ...
+ }:
+ fetchurl {
+ inherit url;
+ sha256 = hash;
+ };
+
+ mkChannelSource =
+ { fetchTarball, ... }:
+ {
+ url,
+ hash,
+ ...
+ }:
+ fetchTarball {
+ inherit url;
+ sha256 = hash;
+ };
+
+ mkTarballSource =
+ { fetchTarball, ... }:
+ {
+ url,
+ locked_url ? url,
+ hash,
+ ...
+ }:
+ fetchTarball {
+ url = locked_url;
+ sha256 = hash;
+ };
+
+ mkContainerSource =
+ pkgs:
+ {
+ image_name,
+ image_tag,
+ image_digest,
+ hash,
+ ...
+ }:
+ if pkgs == null then
+ builtins.throw "container sources require passing in a Nixpkgs value: https://github.com/andir/npins/blob/master/README.md#using-the-nixpkgs-fetchers"
+ else
+ pkgs.dockerTools.pullImage {
+ imageName = image_name;
+ imageDigest = image_digest;
+ finalImageTag = image_tag;
+ hash = hash;
+ };
+in
+mkFunctor (
+ {
+ input ? ./sources.json,
+ }:
+ let
+ data =
+ if builtins.isPath input then
+ # while `readFile` will throw an error anyways if the path doesn't exist,
+ # we still need to check beforehand because *our* error can be caught but not the one from the builtin
+ # See: <https://git.lix.systems/lix-project/lix/issues/1098>
+ if builtins.pathExists input then
+ builtins.fromJSON (builtins.readFile input)
+ else
+ throw "Input path ${toString input} does not exist"
+ else if builtins.isAttrs input then
+ input
+ else
+ throw "Unsupported input type ${builtins.typeOf input}, must be a path or an attrset";
+ version = data.version;
+ in
+ if version == 7 then
+ builtins.mapAttrs (name: spec: mkFunctor (mkSource name spec)) data.pins
+ else
+ throw "Unsupported format version ${toString version} in sources.json. Try running `npins upgrade`"
+)
diff --git a/npins/sources.json b/npins/sources.json
new file mode 100644
index 0000000..95f179a
--- /dev/null
+++ b/npins/sources.json
@@ -0,0 +1,11 @@
+{
+ "pins": {
+ "nixpkgs": {
+ "type": "Channel",
+ "name": "nixpkgs-unstable",
+ "url": "https://releases.nixos.org/nixpkgs/nixpkgs-27.05pre1133810.478c8314389e/nixexprs.tar.xz",
+ "hash": "sha256-Nk+eBvdls+yiU9jMbA5oNgWcqnMhd3heBx+e1hha4UI="
+ }
+ },
+ "version": 7
+}
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..b4d003e
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,441 @@
+use std::collections::BTreeMap;
+use std::env;
+use std::fs::{self, OpenOptions};
+use std::io::Write;
+use std::os::unix::fs::{PermissionsExt, symlink};
+use std::path::{Component, Path, PathBuf};
+use std::process::{self, Output};
+
+use anyhow::{Context, Result, anyhow, bail};
+use clap::{CommandFactory, Parser, Subcommand};
+use clap_complete::{Shell, generate};
+use serde::{Deserialize, Serialize};
+use tempfile::TempDir;
+
+const CONFIG_FILE: &str = "treeimp.nix";
+const LOCK_FILE: &str = "treeimp.lock";
+
+#[derive(Parser, Debug)]
+#[command(about = "Vendor directories from remote Git repositories")]
+struct Args {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Subcommand, Debug)]
+enum Command {
+ /// Write an example treeimp.nix.
+ Init,
+ /// Import configured sources.
+ Sync,
+ /// Generate shell completions.
+ #[command(hide = true)]
+ Completions { shell: Shell },
+}
+
+#[derive(Deserialize, Debug)]
+struct Source {
+ url: String,
+ #[serde(rename = "ref")]
+ git_ref: String,
+ source: PathBuf,
+ destination: PathBuf,
+}
+
+#[derive(Clone, Deserialize, Serialize, Debug)]
+struct LockedSource {
+ commit: String,
+ date: String,
+}
+
+type Lock = BTreeMap<String, LockedSource>;
+
+struct PreparedSource {
+ name: String,
+ destination: PathBuf,
+ output: PathBuf,
+ nar_hash: String,
+ lock: LockedSource,
+ _temporary_directory: TempDir,
+}
+
+fn main() {
+ if let Err(error) = run(Args::parse().command) {
+ eprintln!("treeimp: {error:#}");
+ std::process::exit(1);
+ }
+}
+
+fn run(command: Command) -> Result<()> {
+ match command {
+ Command::Init => init(),
+ Command::Sync => sync(),
+ Command::Completions { shell } => {
+ generate(
+ shell,
+ &mut Args::command(),
+ "treeimp",
+ &mut std::io::stdout(),
+ );
+ Ok(())
+ }
+ }
+}
+
+fn init() -> Result<()> {
+ let path = env::current_dir()
+ .context("getting the current directory")?
+ .join(CONFIG_FILE);
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&path)
+ .with_context(|| format!("creating {CONFIG_FILE}"))?;
+ file.write_all(
+ br#"{
+ example = {
+ url = "https://git.example.com/example.git";
+ ref = "main";
+ source = "path/to/directory";
+ destination = "vendor/example";
+ transform = source: source;
+ };
+}
+"#,
+ )?;
+ println!("created {CONFIG_FILE}");
+ Ok(())
+}
+
+fn sync() -> Result<()> {
+ let root = env::current_dir().context("getting the current directory")?;
+ let config = root.join(CONFIG_FILE);
+ if !config.is_file() {
+ bail!("{} does not exist", config.display());
+ }
+
+ let sources = evaluate_sources(&config)?;
+ let lock_path = root.join(LOCK_FILE);
+ let mut lock = Lock::new();
+ let temporary_root = tempfile::tempdir().context("creating temporary directory")?;
+ let mut updates = Vec::new();
+
+ for (name, source) in sources {
+ validate_source_path(&source.source)
+ .with_context(|| format!("invalid source path for {name:?}"))?;
+ let destination = if source.destination.is_absolute() {
+ source.destination.clone()
+ } else {
+ root.join(&source.destination)
+ };
+ let prepared = prepare_source(&name, &source, &config, temporary_root.path())?;
+
+ let current_hash = hash_if_present(&destination)?;
+ lock.insert(name.clone(), prepared.lock.clone());
+ if current_hash.as_deref() == Some(&prepared.nar_hash) {
+ println!("{name}: unchanged");
+ continue;
+ }
+
+ updates.push(PreparedSource {
+ name,
+ destination,
+ output: prepared.output,
+ nar_hash: prepared.nar_hash,
+ lock: prepared.lock,
+ _temporary_directory: prepared._temporary_directory,
+ });
+ }
+
+ for update in &updates {
+ replace_tree(&update.output, &update.destination)
+ .with_context(|| format!("replacing {}", update.destination.display()))?;
+ println!("{}: updated", update.name);
+ }
+ write_lock(&lock_path, &lock)?;
+ Ok(())
+}
+
+fn evaluate_sources(config: &Path) -> Result<BTreeMap<String, Source>> {
+ let config = nix_string(config.as_os_str().to_string_lossy().as_ref())?;
+ let expression = format!(
+ "let sources = import (builtins.toPath {config}); in builtins.mapAttrs (_: source: {{ inherit (source) url ref source destination; }}) sources"
+ );
+ let output = nix(&["eval", "--impure", "--json", "--expr", &expression])?;
+ serde_json::from_slice(&output.stdout).context("decoding source settings returned by Nix")
+}
+
+fn prepare_source(
+ name: &str,
+ source: &Source,
+ config: &Path,
+ temporary_root: &Path,
+) -> Result<PreparedSource> {
+ let checkout = tempfile::Builder::new()
+ .prefix("checkout-")
+ .tempdir_in(temporary_root)
+ .context("creating Git checkout")?;
+ git(checkout.path(), &["init", "--quiet"])?;
+ git(
+ checkout.path(),
+ &[
+ "fetch",
+ "--quiet",
+ "--no-tags",
+ &source.url,
+ &source.git_ref,
+ ],
+ )?;
+ let tip = git_stdout(checkout.path(), &["rev-parse", "FETCH_HEAD^{commit}"])?;
+ let source_path = path_for_git(&source.source);
+ let commit = git_stdout(
+ checkout.path(),
+ &["rev-list", "-1", &tip, "--", &source_path],
+ )?;
+ if commit.is_empty() {
+ bail!("source {name:?}: no commit affecting {source_path:?}");
+ }
+ let date = git_stdout(
+ checkout.path(),
+ &[
+ "show",
+ "-s",
+ "--date=format-local:%Y-%m-%dT%H:%M:%SZ",
+ "--format=%cd",
+ &commit,
+ ],
+ )?;
+ git(
+ checkout.path(),
+ &[
+ "-c",
+ "advice.detachedHead=false",
+ "checkout",
+ "--quiet",
+ "--detach",
+ &commit,
+ ],
+ )?;
+
+ let input = checkout.path().join(&source.source);
+ if !input.is_dir() {
+ bail!(
+ "source {name:?}: {} is not a directory at commit {commit}",
+ source.source.display()
+ );
+ }
+ let output = transform_source(config, name, &input)?;
+ if !output.is_dir() {
+ bail!("source {name:?}: transform output is not a directory");
+ }
+ let nar_hash = hash_path(&output)?;
+
+ Ok(PreparedSource {
+ name: name.to_owned(),
+ destination: source.destination.clone(),
+ output,
+ nar_hash,
+ lock: LockedSource { commit, date },
+ _temporary_directory: checkout,
+ })
+}
+
+fn transform_source(config: &Path, name: &str, input: &Path) -> Result<PathBuf> {
+ let config = nix_string(config.as_os_str().to_string_lossy().as_ref())?;
+ let name = nix_string(name)?;
+ let input = nix_string(input.as_os_str().to_string_lossy().as_ref())?;
+ let expression = format!(
+ "let sources = import (builtins.toPath {config}); source = builtins.path {{ path = builtins.toPath {input}; name = \"treeimp-source\"; }}; transform = (builtins.getAttr {name} sources).transform; in transform source"
+ );
+ let output = nix(&[
+ "build",
+ "--impure",
+ "--no-link",
+ "--print-out-paths",
+ "--expr",
+ &expression,
+ ])?;
+ let paths: Vec<_> = String::from_utf8(output.stdout)
+ .context("Nix returned a non-UTF-8 output path")?
+ .lines()
+ .filter(|line| !line.is_empty())
+ .map(PathBuf::from)
+ .collect();
+ match paths.as_slice() {
+ [path] => Ok(path.clone()),
+ _ => bail!(
+ "Nix build returned {} output paths, expected one",
+ paths.len()
+ ),
+ }
+}
+
+fn hash_if_present(path: &Path) -> Result<Option<String>> {
+ match fs::symlink_metadata(path) {
+ Ok(_) => hash_path(path).map(Some),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(error).with_context(|| format!("examining {}", path.display())),
+ }
+}
+
+fn hash_path(path: &Path) -> Result<String> {
+ let path = path
+ .to_str()
+ .ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))?;
+ let output = nix(&["hash", "path", "--type", "sha256", path])?;
+ String::from_utf8(output.stdout)
+ .context("Nix returned a non-UTF-8 hash")
+ .map(|hash| hash.trim().to_owned())
+}
+
+fn replace_tree(source: &Path, destination: &Path) -> Result<()> {
+ let parent = destination
+ .parent()
+ .ok_or_else(|| anyhow!("destination has no parent: {}", destination.display()))?;
+ fs::create_dir_all(parent)
+ .with_context(|| format!("creating destination parent {}", parent.display()))?;
+ let staging = tempfile::Builder::new()
+ .prefix(".treeimp-")
+ .tempdir_in(parent)?;
+ let staged_tree = staging.path().join("tree");
+ copy_tree(source, &staged_tree)?;
+
+ if fs::symlink_metadata(destination).is_ok() {
+ remove_tree(destination)?;
+ }
+ fs::rename(&staged_tree, destination)?;
+ Ok(())
+}
+
+fn copy_tree(source: &Path, destination: &Path) -> Result<()> {
+ let metadata = fs::symlink_metadata(source)?;
+ let file_type = metadata.file_type();
+ if file_type.is_symlink() {
+ symlink(fs::read_link(source)?, destination)?;
+ } else if file_type.is_dir() {
+ fs::create_dir(destination)?;
+ fs::set_permissions(destination, fs::Permissions::from_mode(0o755))?;
+ for entry in fs::read_dir(source)? {
+ let entry = entry?;
+ copy_tree(&entry.path(), &destination.join(entry.file_name()))?;
+ }
+ } else if file_type.is_file() {
+ fs::copy(source, destination)?;
+ let mode = if metadata.permissions().mode() & 0o111 != 0 {
+ 0o755
+ } else {
+ 0o644
+ };
+ fs::set_permissions(destination, fs::Permissions::from_mode(mode))?;
+ } else {
+ bail!("unsupported file type: {}", source.display());
+ }
+ Ok(())
+}
+
+fn remove_tree(path: &Path) -> Result<()> {
+ let metadata = fs::symlink_metadata(path)?;
+ if metadata.is_dir() && !metadata.file_type().is_symlink() {
+ fs::remove_dir_all(path)?;
+ } else {
+ fs::remove_file(path)?;
+ }
+ Ok(())
+}
+
+fn write_lock(path: &Path, lock: &Lock) -> Result<()> {
+ let parent = path.parent().unwrap_or_else(|| Path::new("."));
+ let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
+ serde_json::to_writer_pretty(temporary.as_file_mut(), lock)?;
+ temporary.as_file_mut().write_all(b"\n")?;
+ temporary.as_file_mut().sync_all()?;
+ temporary
+ .as_file_mut()
+ .set_permissions(fs::Permissions::from_mode(0o644))?;
+ temporary.persist(path).map_err(|error| error.error)?;
+ Ok(())
+}
+
+fn validate_source_path(path: &Path) -> Result<()> {
+ if path.as_os_str().is_empty() || path.is_absolute() {
+ bail!("source must be a non-empty repository-relative path");
+ }
+ for component in path.components() {
+ if matches!(
+ component,
+ Component::ParentDir | Component::RootDir | Component::Prefix(_)
+ ) {
+ bail!("source must not escape the repository");
+ }
+ }
+ Ok(())
+}
+
+fn path_for_git(path: &Path) -> String {
+ if path == Path::new(".") {
+ ".".to_owned()
+ } else {
+ path.to_string_lossy().trim_start_matches("./").to_owned()
+ }
+}
+
+fn nix_string(value: &str) -> Result<String> {
+ serde_json::to_string(value).context("encoding a Nix string")
+}
+
+fn nix(arguments: &[&str]) -> Result<Output> {
+ command(
+ "nix",
+ &["--extra-experimental-features", "nix-command"],
+ arguments,
+ None,
+ )
+}
+
+fn git(directory: &Path, arguments: &[&str]) -> Result<Output> {
+ let mut command = process::Command::new("git");
+ let output = command
+ .args(arguments)
+ .current_dir(directory)
+ .env("TZ", "UTC")
+ .output()
+ .context("running git")?;
+ if output.status.success() {
+ return Ok(output);
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ bail!("git {} failed: {}", arguments.join(" "), stderr.trim())
+}
+
+fn git_stdout(directory: &Path, arguments: &[&str]) -> Result<String> {
+ let output = git(directory, arguments)?;
+ String::from_utf8(output.stdout)
+ .context("Git returned non-UTF-8 output")
+ .map(|value| value.trim().to_owned())
+}
+
+fn command(
+ program: &str,
+ prefix: &[&str],
+ arguments: &[&str],
+ directory: Option<&Path>,
+) -> Result<Output> {
+ let mut command = process::Command::new(program);
+ command.args(prefix).args(arguments);
+ if let Some(directory) = directory {
+ command.current_dir(directory);
+ }
+ let output = command
+ .output()
+ .with_context(|| format!("running {program}"))?;
+ if output.status.success() {
+ return Ok(output);
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ bail!(
+ "{} {} failed: {}",
+ program,
+ arguments.join(" "),
+ stderr.trim()
+ )
+}
diff --git a/tests/cli.rs b/tests/cli.rs
new file mode 100644
index 0000000..5098b9d
--- /dev/null
+++ b/tests/cli.rs
@@ -0,0 +1,216 @@
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+
+use serde_json::Value;
+use tempfile::TempDir;
+
+#[test]
+fn sync_initial() {
+ let fixture = fixture();
+
+ let output = treeimp(&fixture.workspace, &["sync"]);
+ assert_success(&output, "sync");
+ assert_eq!(String::from_utf8_lossy(&output.stdout), "local: updated\n");
+ assert_eq!(
+ read_files(&fixture.workspace.join("vendor/local")),
+ vec![("message.txt".to_owned(), "first\n".to_owned())]
+ );
+
+ let lock: Value = serde_json::from_slice(
+ &fs::read(fixture.workspace.join("treeimp.lock")).expect("read lock file"),
+ )
+ .expect("decode lock file");
+ assert_eq!(
+ lock,
+ serde_json::json!({
+ "local": {
+ "commit": fixture.initial_commit,
+ "date": "2024-01-01T00:00:00Z"
+ }
+ })
+ );
+}
+
+#[test]
+fn sync_unchanged() {
+ let fixture = fixture();
+ assert_success(&treeimp(&fixture.workspace, &["sync"]), "initial sync");
+ let lock_path = fixture.workspace.join("treeimp.lock");
+ let initial_lock = fs::read(&lock_path).expect("read initial lock file");
+
+ let output = treeimp(&fixture.workspace, &["sync"]);
+ assert_success(&output, "unchanged sync");
+ assert_eq!(
+ String::from_utf8_lossy(&output.stdout),
+ "local: unchanged\n"
+ );
+ assert_eq!(
+ fs::read(lock_path).expect("read unchanged lock file"),
+ initial_lock
+ );
+}
+
+#[test]
+fn sync_changed() {
+ let fixture = fixture();
+ assert_success(&treeimp(&fixture.workspace, &["sync"]), "initial sync");
+ fs::write(fixture.upstream.join("source/message.txt"), "second\n").expect("update source file");
+ let updated_commit = commit(&fixture.upstream, "update source", "2024-01-03T00:00:00Z");
+
+ let output = treeimp(&fixture.workspace, &["sync"]);
+ assert_success(&output, "updated sync");
+ assert_eq!(String::from_utf8_lossy(&output.stdout), "local: updated\n");
+ assert_eq!(
+ read_files(&fixture.workspace.join("vendor/local")),
+ vec![("message.txt".to_owned(), "second\n".to_owned())]
+ );
+ let lock: Value = serde_json::from_slice(
+ &fs::read(fixture.workspace.join("treeimp.lock")).expect("read updated lock file"),
+ )
+ .expect("decode updated lock file");
+ assert_eq!(
+ lock,
+ serde_json::json!({
+ "local": {
+ "commit": updated_commit,
+ "date": "2024-01-03T00:00:00Z"
+ }
+ })
+ );
+}
+
+struct Fixture {
+ _temporary: TempDir,
+ upstream: PathBuf,
+ workspace: PathBuf,
+ initial_commit: String,
+}
+
+fn fixture() -> Fixture {
+ let temporary = TempDir::new().expect("create temporary directory");
+ let upstream = temporary.path().join("upstream");
+ let workspace = temporary.path().join("workspace");
+ fs::create_dir_all(upstream.join("source")).expect("create upstream source directory");
+ fs::create_dir(&workspace).expect("create workspace");
+
+ git(&upstream, &["init", "--quiet", "--initial-branch=main"]);
+ fs::write(upstream.join("source/message.txt"), "first\n").expect("write source file");
+ let initial_commit = commit(&upstream, "initial source", "2024-01-01T00:00:00Z");
+
+ fs::write(upstream.join("unrelated.txt"), "not imported\n").expect("write unrelated file");
+ let _ = commit(&upstream, "unrelated change", "2024-01-02T00:00:00Z");
+
+ let url = serde_json::to_string(
+ upstream
+ .to_str()
+ .expect("temporary repository path is valid UTF-8"),
+ )
+ .expect("encode repository path");
+ fs::write(
+ workspace.join("treeimp.nix"),
+ format!(
+ r#"{{
+ local = {{
+ url = {url};
+ ref = "main";
+ source = "source";
+ destination = "vendor/local";
+ transform = source: source;
+ }};
+}}
+"#,
+ ),
+ )
+ .expect("write treeimp config");
+
+ Fixture {
+ _temporary: temporary,
+ upstream,
+ workspace,
+ initial_commit,
+ }
+}
+
+fn read_files(root: &Path) -> Vec<(String, String)> {
+ fn visit(root: &Path, directory: &Path, files: &mut Vec<(String, String)>) {
+ for entry in fs::read_dir(directory).expect("read directory") {
+ let path = entry.expect("read directory entry").path();
+ if path.is_dir() {
+ visit(root, &path, files);
+ continue;
+ }
+ let relative = path
+ .strip_prefix(root)
+ .expect("file is below root")
+ .to_str()
+ .expect("relative path is valid UTF-8")
+ .to_owned();
+ let contents = fs::read_to_string(&path).expect("read file");
+ files.push((relative, contents));
+ }
+ }
+
+ let mut files = Vec::new();
+ visit(root, root, &mut files);
+ files.sort_by(|(left, _), (right, _)| left.cmp(right));
+ files
+}
+
+fn git(repository: &Path, arguments: &[&str]) -> String {
+ let output = Command::new("git")
+ .current_dir(repository)
+ .args(arguments)
+ .output()
+ .expect("run Git");
+ assert_success(&output, &format!("git {}", arguments.join(" ")));
+ String::from_utf8(output.stdout)
+ .expect("Git output is UTF-8")
+ .trim()
+ .to_owned()
+}
+
+fn commit(repository: &Path, message: &str, date: &str) -> String {
+ git(repository, &["add", "."]);
+ let output = Command::new("git")
+ .current_dir(repository)
+ .args(["commit", "--quiet", "-m", message])
+ .env("GIT_AUTHOR_NAME", "Treeimp Test")
+ .env("GIT_AUTHOR_EMAIL", "treeimp@example.invalid")
+ .env("GIT_COMMITTER_NAME", "Treeimp Test")
+ .env("GIT_COMMITTER_EMAIL", "treeimp@example.invalid")
+ .env("GIT_AUTHOR_DATE", date)
+ .env("GIT_COMMITTER_DATE", date)
+ .output()
+ .expect("commit changes");
+ assert_success(&output, "git commit");
+ git(repository, &["rev-parse", "HEAD"])
+}
+
+fn treeimp(workspace: &Path, arguments: &[&str]) -> Output {
+ let nix_directory = workspace.join(".nix");
+ let store_directory = nix_directory.join("store");
+ let state_directory = nix_directory.join("state");
+ fs::create_dir_all(&store_directory).expect("create private Nix store directory");
+ fs::create_dir_all(&state_directory).expect("create private Nix state directory");
+
+ Command::new(env!("CARGO_BIN_EXE_treeimp"))
+ .current_dir(workspace)
+ .args(arguments)
+ // Make it work when run from a Nix build sandbox.
+ .env("NIX_REMOTE", "local")
+ .env("NIX_STORE_DIR", store_directory)
+ .env("NIX_STATE_DIR", state_directory)
+ .output()
+ .expect("run treeimp")
+}
+
+fn assert_success(output: &Output, operation: &str) {
+ assert!(
+ output.status.success(),
+ "{operation} failed with {}\nstdout:\n{}\nstderr:\n{}",
+ output.status,
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+}