Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d18c49982e | |||
| 58db521b5b | |||
| c21fb5813b | |||
| 33a5a1a262 | |||
| df8e69bce2 | |||
| 58fdcfba9f | |||
| 27ef86c1b4 | |||
| 9fc34e6989 | |||
| 4b79b6dd1d | |||
| d0cbc2f985 | |||
| d53e28668b | |||
| 0b8896d11d | |||
| 8c0c3ad169 | |||
| aebed5639d | |||
| 4514de9ff5 | |||
| 31b9757ef3 | |||
| defb3d1b7d | |||
| e6b654e990 | |||
| 29ddc647e3 | |||
| 67c3e40108 | |||
| 7363ed48b4 | |||
| 96943c1483 | |||
| 9f7195282f | |||
| 30480fb568 | |||
| c3aaea3332 | |||
| fad6f71876 | |||
| 73158e3d47 | |||
| 6f4ae88260 | |||
| a8f8803a92 | |||
| 581a513ebd | |||
| f1e212ead9 | |||
| bc3001a4e6 | |||
| c4fd1d0452 | |||
| 1a65a163a1 | |||
| 4f68a563c6 | |||
| e04e8ceeeb | |||
|
|
b2542b341e | ||
| d402c1f8ce | |||
| e75aead3a8 | |||
| dca2b3c9b4 | |||
| a71711978e | |||
| 90d188e01e | |||
| 2e6166e807 | |||
| 8aaaa55d45 | |||
| df39bb3076 | |||
| bc3d4e1c49 | |||
| 32eb4676ee |
@@ -21,7 +21,8 @@ If you want, add yourself to the `CONTRIBUTORS` file in your pull request.
|
|||||||
|
|
||||||
For Rust, just use `cargo fmt`. For Python, use
|
For Rust, just use `cargo fmt`. For Python, use
|
||||||
[black](https://github.com/psf/black). I'd rather not spend any effort in
|
[black](https://github.com/psf/black). I'd rather not spend any effort in
|
||||||
configuring the formatters (not possible for black anyway).
|
configuring the formatters (not possible for black anyway). For shell scripts,
|
||||||
|
use [`shfmt`](https://github.com/mvdan/sh).
|
||||||
|
|
||||||
## Tooling
|
## Tooling
|
||||||
|
|
||||||
@@ -37,9 +38,12 @@ a separate e2e test suite in python (`just test-e2e`).
|
|||||||
|
|
||||||
To run all tests, run `just test`.
|
To run all tests, run `just test`.
|
||||||
|
|
||||||
When contributing, consider whether it makes sense to add tests that to prevent
|
When contributing, consider whether it makes sense to add tests which could
|
||||||
regressions in the future. When fixing bugs, it makes sense to add tests that
|
prevent regressions in the future. When fixing bugs, it makes sense to add
|
||||||
expose the wrong behaviour beforehand.
|
tests that expose the wrong behaviour beforehand.
|
||||||
|
|
||||||
|
To also ensure proper formatting and that the linter is happy, use `just check`.
|
||||||
|
If that succeeds, your code is most likely fine to push!
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
nonnominandus
|
nonnominandus
|
||||||
|
Maximilian Volk
|
||||||
|
|||||||
121
Cargo.lock
generated
121
Cargo.lock
generated
@@ -80,16 +80,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap"
|
name = "clap"
|
||||||
version = "3.1.18"
|
version = "3.2.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b"
|
checksum = "d53da17d37dba964b9b3ecb5c5a1f193a2762c700e6829201e645b9381c99dc7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atty",
|
"atty",
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"clap_derive",
|
"clap_derive",
|
||||||
"clap_lex",
|
"clap_lex",
|
||||||
"indexmap",
|
"indexmap",
|
||||||
"lazy_static",
|
"once_cell",
|
||||||
"strsim",
|
"strsim",
|
||||||
"termcolor",
|
"termcolor",
|
||||||
"textwrap",
|
"textwrap",
|
||||||
@@ -97,11 +97,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap_derive"
|
name = "clap_derive"
|
||||||
version = "3.1.18"
|
version = "3.2.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "25320346e922cffe59c0bbc5410c8d8784509efb321488971081313cb1e1a33c"
|
checksum = "c11d40217d16aee8508cc8e5fde8b4ff24639758608e5374e731b53f85749fb9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.4.0",
|
"heck",
|
||||||
"proc-macro-error",
|
"proc-macro-error",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -110,18 +110,18 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap_lex"
|
name = "clap_lex"
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213"
|
checksum = "5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"os_str_bytes",
|
"os_str_bytes",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "comfy-table"
|
name = "comfy-table"
|
||||||
version = "5.0.1"
|
version = "6.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b103d85ca6e209388771bfb7aa6b68a7aeec4afbf6f0a0264bfbf50360e5212e"
|
checksum = "121d8a5b0346092c18a4b2fd6f620d7a06f0eb7ac0a45860939a0884bc579c56"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"strum",
|
"strum",
|
||||||
@@ -321,18 +321,18 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "getrandom"
|
name = "getrandom"
|
||||||
version = "0.2.6"
|
version = "0.2.7"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
|
checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"libc",
|
"libc",
|
||||||
"wasi 0.10.2+wasi-snapshot-preview1",
|
"wasi",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "git-repo-manager"
|
name = "git-repo-manager"
|
||||||
version = "0.7.0"
|
version = "0.7.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap",
|
"clap",
|
||||||
"comfy-table",
|
"comfy-table",
|
||||||
@@ -347,6 +347,7 @@ dependencies = [
|
|||||||
"shellexpand",
|
"shellexpand",
|
||||||
"tempdir",
|
"tempdir",
|
||||||
"toml",
|
"toml",
|
||||||
|
"url-escape",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -370,15 +371,6 @@ version = "0.11.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "heck"
|
|
||||||
version = "0.3.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
|
|
||||||
dependencies = [
|
|
||||||
"unicode-segmentation",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.4.0"
|
version = "0.4.0"
|
||||||
@@ -396,9 +388,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "http"
|
name = "http"
|
||||||
version = "0.2.7"
|
version = "0.2.8"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb"
|
checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"fnv",
|
"fnv",
|
||||||
@@ -418,9 +410,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "indexmap"
|
name = "indexmap"
|
||||||
version = "1.8.1"
|
version = "1.8.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee"
|
checksum = "e6012d540c5baa3589337a98ce73408de9b5a25ec9fc2c6fd6be8f0d39e0ca5a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
"hashbrown",
|
"hashbrown",
|
||||||
@@ -531,9 +523,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libz-sys"
|
name = "libz-sys"
|
||||||
version = "1.1.6"
|
version = "1.1.8"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "92e7e15d7610cce1d9752e137625f14e61a28cd45929b6e12e47b50fe154ee2e"
|
checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"libc",
|
"libc",
|
||||||
@@ -592,7 +584,7 @@ checksum = "713d550d9b44d89174e066b7a6217ae06234c10cb47819a88290d2b353c31799"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"log",
|
"log",
|
||||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
"wasi",
|
||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -609,14 +601,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
|
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "openssl-sys"
|
name = "openssl-src"
|
||||||
version = "0.9.73"
|
version = "111.20.0+1.1.1o"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9d5fd19fb3e0a8191c1e34935718976a3e70c112ab9a24af6d7cadccd9d90bc0"
|
checksum = "92892c4f87d56e376e469ace79f1128fdaded07646ddf73aa0be4706ff712dec"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-sys"
|
||||||
|
version = "0.9.74"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "835363342df5fba8354c5b453325b110ffd54044e588c539cf2f20a8014e4cb1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
"cc",
|
"cc",
|
||||||
"libc",
|
"libc",
|
||||||
|
"openssl-src",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
@@ -635,9 +637,9 @@ checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "parking_lot"
|
name = "parking_lot"
|
||||||
version = "0.12.0"
|
version = "0.12.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58"
|
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lock_api",
|
"lock_api",
|
||||||
"parking_lot_core",
|
"parking_lot_core",
|
||||||
@@ -994,17 +996,17 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "strum"
|
name = "strum"
|
||||||
version = "0.23.0"
|
version = "0.24.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cae14b91c7d11c9a851d3fbc80a963198998c2a64eec840477fa92d8ce9b70bb"
|
checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "strum_macros"
|
name = "strum_macros"
|
||||||
version = "0.23.1"
|
version = "0.24.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38"
|
checksum = "9550962e7cf70d9980392878dfaf1dcc3ece024f4cf3bf3c46b978d0bad61d6c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.3.3",
|
"heck",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"rustversion",
|
"rustversion",
|
||||||
@@ -1013,9 +1015,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "1.0.95"
|
version = "1.0.96"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "fbaf6116ab8924f39d52792136fb74fd60a80194cf1b1c6ffa6453eef1c3f942"
|
checksum = "0748dd251e24453cb8717f0354206b91557e4ec8703673a4b30208f2abaf1ebf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -1103,9 +1105,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing"
|
name = "tracing"
|
||||||
version = "0.1.34"
|
version = "0.1.35"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09"
|
checksum = "a400e31aa60b9d44a52a8ee0343b5b18566b03a8321e0d321f695cf56e940160"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"log",
|
"log",
|
||||||
@@ -1127,11 +1129,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing-core"
|
name = "tracing-core"
|
||||||
version = "0.1.26"
|
version = "0.1.27"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f"
|
checksum = "7709595b8878a4965ce5e87ebf880a7d39c9afc6837721b21a5a816a8117d921"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lazy_static",
|
"once_cell",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1152,9 +1154,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.0"
|
version = "1.0.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
|
checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-normalization"
|
name = "unicode-normalization"
|
||||||
@@ -1165,12 +1167,6 @@ dependencies = [
|
|||||||
"tinyvec",
|
"tinyvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-segmentation"
|
|
||||||
version = "1.9.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-width"
|
name = "unicode-width"
|
||||||
version = "0.1.9"
|
version = "0.1.9"
|
||||||
@@ -1189,6 +1185,15 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "url-escape"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "44e0ce4d1246d075ca5abec4b41d33e87a6054d08e2366b63205665e950db218"
|
||||||
|
dependencies = [
|
||||||
|
"percent-encoding",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vcpkg"
|
name = "vcpkg"
|
||||||
version = "0.2.15"
|
version = "0.2.15"
|
||||||
@@ -1207,12 +1212,6 @@ version = "1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
|
checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasi"
|
|
||||||
version = "0.10.2+wasi-snapshot-preview1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasi"
|
name = "wasi"
|
||||||
version = "0.11.0+wasi-snapshot-preview1"
|
version = "0.11.0+wasi-snapshot-preview1"
|
||||||
|
|||||||
21
Cargo.toml
21
Cargo.toml
@@ -1,7 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "git-repo-manager"
|
name = "git-repo-manager"
|
||||||
version = "0.7.0"
|
version = "0.7.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
authors = [
|
authors = [
|
||||||
"Hannes Körber <hannes@hkoerber.de>",
|
"Hannes Körber <hannes@hkoerber.de>",
|
||||||
]
|
]
|
||||||
@@ -53,7 +54,7 @@ version = "=0.14.4"
|
|||||||
version = "=2.1.0"
|
version = "=2.1.0"
|
||||||
|
|
||||||
[dependencies.clap]
|
[dependencies.clap]
|
||||||
version = "=3.1.18"
|
version = "=3.2.5"
|
||||||
features = ["derive", "cargo"]
|
features = ["derive", "cargo"]
|
||||||
|
|
||||||
[dependencies.console]
|
[dependencies.console]
|
||||||
@@ -63,7 +64,7 @@ version = "=0.15.0"
|
|||||||
version = "=1.5.6"
|
version = "=1.5.6"
|
||||||
|
|
||||||
[dependencies.comfy-table]
|
[dependencies.comfy-table]
|
||||||
version = "=5.0.1"
|
version = "=6.0.0"
|
||||||
|
|
||||||
[dependencies.serde_yaml]
|
[dependencies.serde_yaml]
|
||||||
version = "=0.8.24"
|
version = "=0.8.24"
|
||||||
@@ -73,10 +74,22 @@ version = "=1.0.81"
|
|||||||
|
|
||||||
[dependencies.isahc]
|
[dependencies.isahc]
|
||||||
version = "=1.7.2"
|
version = "=1.7.2"
|
||||||
features = ["json"]
|
default-features = false
|
||||||
|
features = ["json", "http2", "text-decoding"]
|
||||||
|
|
||||||
[dependencies.parse_link_header]
|
[dependencies.parse_link_header]
|
||||||
version = "=0.3.2"
|
version = "=0.3.2"
|
||||||
|
|
||||||
|
[dependencies.url-escape]
|
||||||
|
version = "=0.1.1"
|
||||||
|
|
||||||
[dev-dependencies.tempdir]
|
[dev-dependencies.tempdir]
|
||||||
version = "=0.3.7"
|
version = "=0.3.7"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
static-build = [
|
||||||
|
"git2/vendored-openssl",
|
||||||
|
"git2/vendored-libgit2",
|
||||||
|
"isahc/static-curl",
|
||||||
|
"isahc/static-ssl",
|
||||||
|
]
|
||||||
|
|||||||
63
Justfile
63
Justfile
@@ -1,16 +1,27 @@
|
|||||||
set positional-arguments
|
set positional-arguments
|
||||||
|
|
||||||
check: test
|
static_target := "x86_64-unknown-linux-musl"
|
||||||
|
|
||||||
|
check: fmt-check lint test
|
||||||
cargo check
|
cargo check
|
||||||
cargo fmt --check
|
|
||||||
cargo clippy --no-deps -- -Dwarnings
|
clean:
|
||||||
|
cargo clean
|
||||||
|
git clean -f -d -X
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
cargo fmt
|
cargo fmt
|
||||||
git ls-files | grep '\.py$' | xargs black
|
git ls-files | grep '\.py$' | xargs black
|
||||||
|
git ls-files | grep '\.sh$' | xargs -L 1 shfmt --indent 4 --write
|
||||||
|
|
||||||
|
fmt-check:
|
||||||
|
cargo fmt --check
|
||||||
|
git ls-files | grep '\.py$' | xargs black --check
|
||||||
|
git ls-files | grep '\.sh$' | xargs -L 1 shfmt --indent 4 --diff
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
cargo clippy --no-deps
|
cargo clippy --no-deps -- -Dwarnings
|
||||||
|
git ls-files | grep '\.sh$' | xargs -L 1 shellcheck --norc
|
||||||
|
|
||||||
lint-fix:
|
lint-fix:
|
||||||
cargo clippy --no-deps --fix
|
cargo clippy --no-deps --fix
|
||||||
@@ -18,46 +29,44 @@ lint-fix:
|
|||||||
release:
|
release:
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
|
||||||
test-binary-docker:
|
release-static:
|
||||||
env \
|
cargo build --release --target {{static_target}} --features=static-build
|
||||||
GITHUB_API_BASEURL=http://rest:5000/github \
|
|
||||||
GITLAB_API_BASEURL=http://rest:5000/gitlab \
|
|
||||||
cargo build --profile e2e-tests
|
|
||||||
|
|
||||||
test-binary:
|
test-binary:
|
||||||
env \
|
env \
|
||||||
GITHUB_API_BASEURL=http://localhost:5000/github \
|
GITHUB_API_BASEURL=http://rest:5000/github \
|
||||||
GITLAB_API_BASEURL=http://localhost:5000/gitlab \
|
GITLAB_API_BASEURL=http://rest:5000/gitlab \
|
||||||
cargo build --profile e2e-tests
|
cargo build --target {{static_target}} --profile e2e-tests --features=static-build
|
||||||
|
|
||||||
install:
|
install:
|
||||||
cargo install --path .
|
cargo install --path .
|
||||||
|
|
||||||
|
install-static:
|
||||||
|
cargo install --target {{static_target}} --features=static-build --path .
|
||||||
|
|
||||||
|
build:
|
||||||
|
cargo build
|
||||||
|
|
||||||
|
build-static:
|
||||||
|
cargo build --target {{static_target}} --features=static-build
|
||||||
|
|
||||||
test: test-unit test-integration test-e2e
|
test: test-unit test-integration test-e2e
|
||||||
|
|
||||||
test-unit:
|
test-unit +tests="":
|
||||||
cargo test --lib --bins
|
cargo test --lib --bins -- --show-output {{tests}}
|
||||||
|
|
||||||
test-integration:
|
test-integration:
|
||||||
cargo test --test "*"
|
cargo test --test "*"
|
||||||
|
|
||||||
test-e2e-docker +tests=".": test-binary-docker
|
|
||||||
cd ./e2e_tests \
|
|
||||||
&& docker-compose rm --stop -f \
|
|
||||||
&& docker-compose build \
|
|
||||||
&& docker-compose run \
|
|
||||||
--rm \
|
|
||||||
-v $PWD/../target/e2e-tests/grm:/grm \
|
|
||||||
pytest \
|
|
||||||
"GRM_BINARY=/grm python3 ALTERNATE_DOMAIN=alternate-rest -m pytest -p no:cacheprovider --color=yes "$@"" \
|
|
||||||
&& docker-compose rm --stop -f
|
|
||||||
|
|
||||||
test-e2e +tests=".": test-binary
|
test-e2e +tests=".": test-binary
|
||||||
cd ./e2e_tests \
|
cd ./e2e_tests \
|
||||||
&& docker-compose rm --stop -f \
|
&& docker-compose rm --stop -f \
|
||||||
&& docker-compose build \
|
&& docker-compose build \
|
||||||
&& docker-compose up -d rest \
|
&& docker-compose run \
|
||||||
&& GRM_BINARY={{justfile_directory()}}/target/e2e-tests/grm ALTERNATE_DOMAIN=127.0.0.1 python3 -m pytest -p no:cacheprovider --color=yes {{tests}} \
|
--rm \
|
||||||
|
-v $PWD/../target/{{static_target}}/e2e-tests/grm:/grm \
|
||||||
|
pytest \
|
||||||
|
"GRM_BINARY=/grm ALTERNATE_DOMAIN=alternate-rest python3 -m pytest -p no:cacheprovider --color=yes "$@"" \
|
||||||
&& docker-compose rm --stop -f
|
&& docker-compose rm --stop -f
|
||||||
|
|
||||||
update-dependencies: update-cargo-dependencies
|
update-dependencies: update-cargo-dependencies
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Summary
|
# Summary
|
||||||
|
|
||||||
- [Overview](./overview.md)
|
- [Overview](./overview.md)
|
||||||
- [Getting started](./getting_started.md)
|
- [Installation](./installation.md)
|
||||||
- [Repository trees](./repos.md)
|
- [Repository trees](./repos.md)
|
||||||
- [Git Worktrees](./worktrees.md)
|
- [Git Worktrees](./worktrees.md)
|
||||||
- [Forge Integrations](./forge_integration.md)
|
- [Forge Integrations](./forge_integration.md)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ You will end up with your projects cloned into `~/projects/{your_github_username
|
|||||||
|
|
||||||
## Authentication
|
## Authentication
|
||||||
|
|
||||||
The only currently supported authentication option is using personal access
|
The only currently supported authentication option is using a personal access
|
||||||
token.
|
token.
|
||||||
|
|
||||||
### GitHub
|
### GitHub
|
||||||
@@ -27,7 +27,7 @@ See the GitHub documentation for personal access tokens:
|
|||||||
|
|
||||||
The only required permission is the "repo" scope.
|
The only required permission is the "repo" scope.
|
||||||
|
|
||||||
### GitHub
|
### GitLab
|
||||||
|
|
||||||
See the GitLab documentation for personal access tokens:
|
See the GitLab documentation for personal access tokens:
|
||||||
[Link](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html).
|
[Link](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html).
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
# Quickstart
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
Building GRM currently requires the nightly Rust toolchain. The easiest way
|
|
||||||
is using [`rustup`](https://rustup.rs/). Make sure that rustup is properly installed.
|
|
||||||
|
|
||||||
Make sure that the nightly toolchain is installed:
|
|
||||||
|
|
||||||
```
|
|
||||||
$ rustup toolchain install nightly
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ cargo +nightly install --git https://github.com/hakoerber/git-repo-manager.git --branch master
|
|
||||||
```
|
|
||||||
|
|
||||||
If you're brave, you can also run the development build:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ cargo +nightly install --git https://github.com/hakoerber/git-repo-manager.git --branch develop
|
|
||||||
```
|
|
||||||
56
docs/src/installation.md
Normal file
56
docs/src/installation.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# Installation
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Building GRM currently requires the nightly Rust toolchain. The easiest way
|
||||||
|
is using [`rustup`](https://rustup.rs/). Make sure that rustup is properly installed.
|
||||||
|
|
||||||
|
Make sure that the nightly toolchain is installed:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ rustup toolchain install nightly
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, install the build dependencies:
|
||||||
|
|
||||||
|
| Distribution | Command |
|
||||||
|
| ------------- | ------------------------------------------------------------------------------ |
|
||||||
|
| Archlinux | `pacman -S --needed gcc openssl pkg-config` |
|
||||||
|
| Ubuntu/Debian | `apt-get install --no-install-recommends pkg-config gcc libssl-dev zlib1g-dev` |
|
||||||
|
|
||||||
|
Then, it's a simple command to install the latest stable version:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ cargo +nightly install git-repo-manager
|
||||||
|
```
|
||||||
|
|
||||||
|
If you're brave, you can also run the development build:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ cargo +nightly install --git https://github.com/hakoerber/git-repo-manager.git --branch develop
|
||||||
|
```
|
||||||
|
|
||||||
|
## Static build
|
||||||
|
|
||||||
|
Note that by default, you will get a dynamically linked executable.
|
||||||
|
Alternatively, you can also build a statically linked binary. For this, you
|
||||||
|
will need `musl` and a few other build dependencies installed installed:
|
||||||
|
|
||||||
|
| Distribution | Command |
|
||||||
|
| ------------- | --------------------------------------------------------------------------- |
|
||||||
|
| Archlinux | `pacman -S --needed gcc musl perl make` |
|
||||||
|
| Ubuntu/Debian | `apt-get install --no-install-recommends gcc musl-tools libc-dev perl make` |
|
||||||
|
|
||||||
|
(`perl` and `make` are required for the OpenSSL build script)
|
||||||
|
|
||||||
|
The, add the musl target via `rustup`:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ rustup +nightly target add x86_64-unknown-linux-musl
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, use a modified build command to get a statically linked binary:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ cargo +nightly install git-repo-manager --target x86_64-unknown-linux-musl --features=static-build
|
||||||
|
```
|
||||||
@@ -77,6 +77,6 @@ $ grm repos status
|
|||||||
## YAML
|
## YAML
|
||||||
|
|
||||||
By default, the repo configuration uses TOML. If you prefer YAML, just give it
|
By default, the repo configuration uses TOML. If you prefer YAML, just give it
|
||||||
a YAML file instead (file ending does not matter, `grm` will figure out the format
|
a YAML file instead (file ending does not matter, `grm` will figure out the format).
|
||||||
itself). For generating a configuration, pass `--format yaml` to `grm repo find`
|
For generating a configuration, pass `--format yaml` to `grm repo find`
|
||||||
to generate YAML instead of TOML.
|
which generates a YAML config instead of a TOML configuration.
|
||||||
|
|||||||
@@ -5,11 +5,11 @@
|
|||||||
The default workflow when using git is having your repository in a single directory.
|
The default workflow when using git is having your repository in a single directory.
|
||||||
Then, you can check out a certain reference (usually a branch), which will update
|
Then, you can check out a certain reference (usually a branch), which will update
|
||||||
the files in the directory to match the state of that reference. Most of the time,
|
the files in the directory to match the state of that reference. Most of the time,
|
||||||
this is exactly what you need and works perfectly. But especially when you're using
|
this is exactly what you need and works perfectly. But especially when you're working
|
||||||
with branches a lot, you may notice that there is a lot of work required to make
|
with branches a lot, you may notice that there is a lot of work required to make
|
||||||
everything run smootly.
|
everything run smoothly.
|
||||||
|
|
||||||
Maybe you experienced the following: You're working on a feature branch. Then,
|
Maybe you have experienced the following: You're working on a feature branch. Then,
|
||||||
for some reason, you have to change branches (maybe to investigate some issue).
|
for some reason, you have to change branches (maybe to investigate some issue).
|
||||||
But you get the following:
|
But you get the following:
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ error: Your local changes to the following files would be overwritten by checkou
|
|||||||
Now you can create a temporary commit or stash your changes. In any case, you have
|
Now you can create a temporary commit or stash your changes. In any case, you have
|
||||||
some mental overhead before you can work on something else. Especially with stashes,
|
some mental overhead before you can work on something else. Especially with stashes,
|
||||||
you'll have to remember to do a `git stash pop` before resuming your work (I
|
you'll have to remember to do a `git stash pop` before resuming your work (I
|
||||||
cannot count the number of times where is "rediscovered" some code hidden in some
|
cannot count the number of times where I "rediscovered" some code hidden in some
|
||||||
old stash I forgot about.
|
old stash I forgot about.
|
||||||
|
|
||||||
And even worse: If you're currently in the process of resolving merge conflicts or an
|
And even worse: If you're currently in the process of resolving merge conflicts or an
|
||||||
@@ -40,7 +40,7 @@ In any case, Git Worktrees are here for the rescue:
|
|||||||
independent checkouts of your repository on different directories. You can have
|
independent checkouts of your repository on different directories. You can have
|
||||||
multiple directories that correspond to different references in your repository.
|
multiple directories that correspond to different references in your repository.
|
||||||
Each worktree has it's independent working tree (duh) and index, so there is no
|
Each worktree has it's independent working tree (duh) and index, so there is no
|
||||||
to run into conflicts. Changing to a different branch is just a `cd` away (if
|
way to run into conflicts. Changing to a different branch is just a `cd` away (if
|
||||||
the worktree is already set up).
|
the worktree is already set up).
|
||||||
|
|
||||||
## Worktrees in GRM
|
## Worktrees in GRM
|
||||||
@@ -210,7 +210,7 @@ your changes to. I'd rather not delete work that you cannot recover."
|
|||||||
|
|
||||||
Note that `grm` is very cautious here. As your repository will not be deleted,
|
Note that `grm` is very cautious here. As your repository will not be deleted,
|
||||||
you could still recover the commits via [`git-reflog`](https://git-scm.com/docs/git-reflog).
|
you could still recover the commits via [`git-reflog`](https://git-scm.com/docs/git-reflog).
|
||||||
But better safe then sorry! Note that you'd get a similar error message if your
|
But better safe than sorry! Note that you'd get a similar error message if your
|
||||||
worktree had any uncommitted files, for the same reason. Now you can either
|
worktree had any uncommitted files, for the same reason. Now you can either
|
||||||
commit & push your changes, or your tell `grm` that you know what you're doing:
|
commit & push your changes, or your tell `grm` that you know what you're doing:
|
||||||
|
|
||||||
@@ -241,7 +241,7 @@ calls them "persistent branches" and treats them a bit differently:
|
|||||||
`grm wt delete`, which will not require a `--force` flag. Note that of
|
`grm wt delete`, which will not require a `--force` flag. Note that of
|
||||||
course, actual changes in the worktree will still block an automatic cleanup!
|
course, actual changes in the worktree will still block an automatic cleanup!
|
||||||
* As soon as you enable persistent branches, non-persistent branches will only
|
* As soon as you enable persistent branches, non-persistent branches will only
|
||||||
ever cleaned up when merged into a persistent branch.
|
ever be cleaned up when merged into a persistent branch.
|
||||||
|
|
||||||
To elaborate: This is mostly relevant for a feature-branch workflow. Whenever a
|
To elaborate: This is mostly relevant for a feature-branch workflow. Whenever a
|
||||||
feature branch is merged, it can usually be thrown away. As merging is usually
|
feature branch is merged, it can usually be thrown away. As merging is usually
|
||||||
@@ -340,7 +340,7 @@ $ grm wt rebase --pull --rebase
|
|||||||
hell is there a `--rebase` flag in the `rebase` command?"
|
hell is there a `--rebase` flag in the `rebase` command?"
|
||||||
|
|
||||||
Yes, it's kind of weird. Remember that `pull` only ever updates each worktree
|
Yes, it's kind of weird. Remember that `pull` only ever updates each worktree
|
||||||
to their remote branch, if possible. `rebase` rabases onto the **default** branch
|
to their remote branch, if possible. `rebase` rebases onto the **default** branch
|
||||||
instead. The switches to `rebase` are just convenience, so you do not have to
|
instead. The switches to `rebase` are just convenience, so you do not have to
|
||||||
run two commands.
|
run two commands.
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,6 @@ services:
|
|||||||
build: ./docker-rest/
|
build: ./docker-rest/
|
||||||
expose:
|
expose:
|
||||||
- "5000"
|
- "5000"
|
||||||
ports:
|
|
||||||
- "5000:5000"
|
|
||||||
networks:
|
networks:
|
||||||
main:
|
main:
|
||||||
aliases:
|
aliases:
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ def check_headers():
|
|||||||
app.logger.error("Invalid accept header")
|
app.logger.error("Invalid accept header")
|
||||||
abort(500)
|
abort(500)
|
||||||
auth_header = request.headers.get("authorization")
|
auth_header = request.headers.get("authorization")
|
||||||
if auth_header != "token authtoken":
|
if auth_header != "token secret-token:myauthtoken":
|
||||||
app.logger.error("Invalid authorization header: %s", auth_header)
|
app.logger.error("Invalid authorization header: %s", auth_header)
|
||||||
abort(
|
abort(
|
||||||
make_response(
|
make_response(
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ def check_headers():
|
|||||||
app.logger.error("Invalid accept header")
|
app.logger.error("Invalid accept header")
|
||||||
abort(500)
|
abort(500)
|
||||||
auth_header = request.headers.get("authorization")
|
auth_header = request.headers.get("authorization")
|
||||||
if auth_header != "bearer authtoken":
|
if auth_header != "bearer secret-token:myauthtoken":
|
||||||
app.logger.error("Invalid authorization header: %s", auth_header)
|
app.logger.error("Invalid authorization header: %s", auth_header)
|
||||||
abort(
|
abort(
|
||||||
make_response(
|
make_response(
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ def grm(args, cwd=None, is_invalid=False):
|
|||||||
print(f"grmcmd: {args}")
|
print(f"grmcmd: {args}")
|
||||||
print(f"stdout:\n{cmd.stdout}")
|
print(f"stdout:\n{cmd.stdout}")
|
||||||
print(f"stderr:\n{cmd.stderr}")
|
print(f"stderr:\n{cmd.stderr}")
|
||||||
|
assert "secret-token:" not in cmd.stdout
|
||||||
|
assert "secret-token:" not in cmd.stderr
|
||||||
assert "panicked" not in cmd.stderr
|
assert "panicked" not in cmd.stderr
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
|||||||
@@ -141,7 +141,7 @@ def test_repos_find_remote_no_filter(provider, configtype, default, use_config):
|
|||||||
f.write(
|
f.write(
|
||||||
f"""
|
f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@@ -157,7 +157,7 @@ def test_repos_find_remote_no_filter(provider, configtype, default, use_config):
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
]
|
]
|
||||||
@@ -193,7 +193,7 @@ def test_repos_find_remote_user_empty(
|
|||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
|
|
||||||
[filters]
|
[filters]
|
||||||
@@ -213,7 +213,7 @@ def test_repos_find_remote_user_empty(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
"--user",
|
"--user",
|
||||||
@@ -248,6 +248,7 @@ def test_repos_find_remote_user_empty(
|
|||||||
@pytest.mark.parametrize("force_ssh", [True, False])
|
@pytest.mark.parametrize("force_ssh", [True, False])
|
||||||
@pytest.mark.parametrize("use_alternate_endpoint", [True, False])
|
@pytest.mark.parametrize("use_alternate_endpoint", [True, False])
|
||||||
@pytest.mark.parametrize("use_config", [True, False])
|
@pytest.mark.parametrize("use_config", [True, False])
|
||||||
|
@pytest.mark.parametrize("override_remote_name", [True, False])
|
||||||
def test_repos_find_remote_user(
|
def test_repos_find_remote_user(
|
||||||
provider,
|
provider,
|
||||||
configtype,
|
configtype,
|
||||||
@@ -258,13 +259,14 @@ def test_repos_find_remote_user(
|
|||||||
force_ssh,
|
force_ssh,
|
||||||
use_alternate_endpoint,
|
use_alternate_endpoint,
|
||||||
use_config,
|
use_config,
|
||||||
|
override_remote_name,
|
||||||
):
|
):
|
||||||
if use_config:
|
if use_config:
|
||||||
with tempfile.NamedTemporaryFile() as config:
|
with tempfile.NamedTemporaryFile() as config:
|
||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -274,6 +276,8 @@ def test_repos_find_remote_user(
|
|||||||
cfg += f"worktree = {str(worktree).lower()}\n"
|
cfg += f"worktree = {str(worktree).lower()}\n"
|
||||||
if force_ssh:
|
if force_ssh:
|
||||||
cfg += f"force_ssh = true\n"
|
cfg += f"force_ssh = true\n"
|
||||||
|
if override_remote_name:
|
||||||
|
cfg += f'remote_name = "otherremote"\n'
|
||||||
if use_owner:
|
if use_owner:
|
||||||
cfg += """
|
cfg += """
|
||||||
[filters]
|
[filters]
|
||||||
@@ -300,7 +304,7 @@ def test_repos_find_remote_user(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
]
|
]
|
||||||
@@ -310,6 +314,8 @@ def test_repos_find_remote_user(
|
|||||||
args += ["--user", "myuser1"]
|
args += ["--user", "myuser1"]
|
||||||
if force_ssh:
|
if force_ssh:
|
||||||
args += ["--force-ssh"]
|
args += ["--force-ssh"]
|
||||||
|
if override_remote_name:
|
||||||
|
args += ["--remote-name", "otherremote"]
|
||||||
if not worktree_default:
|
if not worktree_default:
|
||||||
args += ["--worktree", str(worktree).lower()]
|
args += ["--worktree", str(worktree).lower()]
|
||||||
if use_alternate_endpoint:
|
if use_alternate_endpoint:
|
||||||
@@ -350,7 +356,10 @@ def test_repos_find_remote_user(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
if override_remote_name:
|
||||||
|
assert repo["remotes"][0]["name"] == "otherremote"
|
||||||
|
else:
|
||||||
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -378,7 +387,7 @@ def test_repos_find_remote_group_empty(
|
|||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -403,7 +412,7 @@ def test_repos_find_remote_group_empty(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
"--group",
|
"--group",
|
||||||
@@ -459,7 +468,7 @@ def test_repos_find_remote_group(
|
|||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -488,7 +497,7 @@ def test_repos_find_remote_group(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
"--group",
|
"--group",
|
||||||
@@ -535,14 +544,14 @@ def test_repos_find_remote_group(
|
|||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
== f"ssh://git@example.com/mygroup1/myproject{i}.git"
|
== f"ssh://git@example.com/mygroup1/myproject{i}.git"
|
||||||
)
|
)
|
||||||
assert repo["remotes"][0]["type"] == "ssh"
|
assert repo["remotes"][0]["type"] == "ssh"
|
||||||
else:
|
else:
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
== f"https://example.com/mygroup1/myproject{i}.git"
|
== f"https://example.com/mygroup1/myproject{i}.git"
|
||||||
@@ -575,7 +584,7 @@ def test_repos_find_remote_user_and_group(
|
|||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -609,7 +618,7 @@ def test_repos_find_remote_user_and_group(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
"--group",
|
"--group",
|
||||||
@@ -659,7 +668,7 @@ def test_repos_find_remote_user_and_group(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -684,7 +693,7 @@ def test_repos_find_remote_user_and_group(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -726,7 +735,7 @@ def test_repos_find_remote_owner(
|
|||||||
with open(config.name, "w") as f:
|
with open(config.name, "w") as f:
|
||||||
cfg = f"""
|
cfg = f"""
|
||||||
provider = "{provider}"
|
provider = "{provider}"
|
||||||
token_command = "echo authtoken"
|
token_command = "echo secret-token:myauthtoken"
|
||||||
root = "/myroot"
|
root = "/myroot"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -761,7 +770,7 @@ def test_repos_find_remote_owner(
|
|||||||
"--provider",
|
"--provider",
|
||||||
provider,
|
provider,
|
||||||
"--token-command",
|
"--token-command",
|
||||||
"echo authtoken",
|
"echo secret-token:myauthtoken",
|
||||||
"--root",
|
"--root",
|
||||||
"/myroot",
|
"/myroot",
|
||||||
"--access",
|
"--access",
|
||||||
@@ -814,7 +823,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -837,7 +846,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -861,7 +870,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh:
|
if force_ssh:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"] == f"ssh://git@example.com/myuser2/myproject3.git"
|
repo["remotes"][0]["url"] == f"ssh://git@example.com/myuser2/myproject3.git"
|
||||||
@@ -890,7 +899,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh or i == 1:
|
if force_ssh or i == 1:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -910,7 +919,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh:
|
if force_ssh:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
@@ -936,7 +945,7 @@ def test_repos_find_remote_owner(
|
|||||||
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
assert repo["worktree_setup"] is (not worktree_default and worktree)
|
||||||
assert isinstance(repo["remotes"], list)
|
assert isinstance(repo["remotes"], list)
|
||||||
assert len(repo["remotes"]) == 1
|
assert len(repo["remotes"]) == 1
|
||||||
assert repo["remotes"][0]["name"] == provider
|
assert repo["remotes"][0]["name"] == "origin"
|
||||||
if force_ssh:
|
if force_ssh:
|
||||||
assert (
|
assert (
|
||||||
repo["remotes"][0]["url"]
|
repo["remotes"][0]["url"]
|
||||||
|
|||||||
@@ -303,7 +303,6 @@ def test_repos_sync_root_is_file(configtype):
|
|||||||
|
|
||||||
cmd = grm(["repos", "sync", "config", "--config", config.name])
|
cmd = grm(["repos", "sync", "config", "--config", config.name])
|
||||||
assert cmd.returncode != 0
|
assert cmd.returncode != 0
|
||||||
assert len(cmd.stdout) == 0
|
|
||||||
assert "not a directory" in cmd.stderr.lower()
|
assert "not a directory" in cmd.stderr.lower()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
164
release.sh
Executable file
164
release.sh
Executable file
@@ -0,0 +1,164 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -o nounset
|
||||||
|
set -o errexit
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
printf '%s\n' "usage: $0 (master|minor|patch)" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($# != 1)); then
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
current_version="$(grep '^version \?=' Cargo.toml | head -1 | cut -d '=' -f 2 | tr -d " '"'"')"
|
||||||
|
|
||||||
|
major="$(printf '%s' "${current_version}" | grep -oP '^\d+')"
|
||||||
|
minor="$(printf '%s' "${current_version}" | grep -oP '\.\d+\.' | tr -d '.')"
|
||||||
|
patch="$(printf '%s' "${current_version}" | grep -oP '\d+$' | tr -d '.')"
|
||||||
|
|
||||||
|
case "$1" in
|
||||||
|
major)
|
||||||
|
((major++)) || true
|
||||||
|
minor=0
|
||||||
|
patch=0
|
||||||
|
;;
|
||||||
|
minor)
|
||||||
|
((minor++)) || true
|
||||||
|
patch=0
|
||||||
|
;;
|
||||||
|
patch)
|
||||||
|
((patch++)) || true
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
new_version="${major}.${minor}.${patch}"
|
||||||
|
|
||||||
|
if ! [[ "${new_version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
printf '%s\n' 'Version has to a complete semver' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
current_branch="$(git rev-parse --abbrev-ref HEAD)"
|
||||||
|
if [[ "${current_branch}" != "develop" ]]; then
|
||||||
|
printf '%s\n' 'You need to be on develop' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
gitstatus="$(git status --porcelain)"
|
||||||
|
if [[ -n "${gitstatus}" ]]; then
|
||||||
|
printf '%s\n' 'There are uncommitted changes' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if git tag --list "v${new_version}" | grep -q .; then
|
||||||
|
printf 'Tag %s already exists\n' "v${new_version}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
for remote in $(git remote); do
|
||||||
|
if git ls-remote --tags "${remote}" | grep -q "refs/tags/v${new_version}$"; then
|
||||||
|
printf 'Tag %s already exists on %s' "v${new_version}" "${remote}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
git fetch --all
|
||||||
|
|
||||||
|
for remote in $(git remote); do
|
||||||
|
for branch in master develop; do
|
||||||
|
if ! git diff --quiet "${remote}/${branch}..${branch}"; then
|
||||||
|
printf 'Remote branch %s/%s not up to date, synchronize first!\n' "${remote}" "${branch}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
if ! git merge-base --is-ancestor master develop; then
|
||||||
|
printf '%s\n' 'Develop is not a straight descendant of master, rebase!' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
changes="$(git log --oneline master..develop | wc -l)"
|
||||||
|
if ((changes == 0)); then
|
||||||
|
printf '%s\n' 'No changes between master and develop?' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
just update-dependencies
|
||||||
|
|
||||||
|
just check
|
||||||
|
|
||||||
|
sed -i "0,/^version/{s/^version.*$/version = \"${new_version}\"/}" Cargo.toml
|
||||||
|
|
||||||
|
cargo update --package git-repo-manager --precise "${new_version}"
|
||||||
|
|
||||||
|
diff="$(git diff --numstat)"
|
||||||
|
if (($(printf '%s\n' "${diff}" | wc -l || true) != 2)); then
|
||||||
|
printf '%s\n' 'Weird changes detected, bailing' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! printf '%s\n' "${diff}" | grep -Pq '^1\s+1\s+Cargo.lock$'; then
|
||||||
|
printf '%s\n' 'Weird changes detected, bailing' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! printf '%s\n' "${diff}" | grep -Pq '^1\s+1\s+Cargo.toml$'; then
|
||||||
|
printf '%s\n' 'Weird changes detected, bailing' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git add Cargo.lock Cargo.toml
|
||||||
|
|
||||||
|
git commit -m "Release v${new_version}"
|
||||||
|
|
||||||
|
git switch master 2>/dev/null || { [[ -d "../master" ]] && cd "../master"; } || {
|
||||||
|
printf '%s\n' 'Could not change to master' >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
current_branch="$(git rev-parse --abbrev-ref HEAD)"
|
||||||
|
if [[ "${current_branch}" != "master" ]]; then
|
||||||
|
printf '%s\n' 'Looks like branch switching to master did not work' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git merge --no-ff --no-edit develop
|
||||||
|
git tag "v${new_version}"
|
||||||
|
|
||||||
|
for remote in $(git remote); do
|
||||||
|
while ! git push "${remote}" "v${new_version}" master; do
|
||||||
|
:
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
git switch develop 2>/dev/null || { [[ -d "../develop" ]] && cd "../develop"; } || {
|
||||||
|
printf '%s\n' 'Could not change to develop' >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
current_branch="$(git rev-parse --abbrev-ref HEAD)"
|
||||||
|
if [[ "${current_branch}" != "develop" ]]; then
|
||||||
|
printf '%s\n' 'Looks like branch switching to develop did not work' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git merge --ff-only master
|
||||||
|
|
||||||
|
for remote in $(git remote); do
|
||||||
|
while ! git push "${remote}" develop; do
|
||||||
|
:
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
cargo publish
|
||||||
|
|
||||||
|
printf 'Published %s successfully\n' "${new_version}"
|
||||||
|
exit 0
|
||||||
45
src/auth.rs
Normal file
45
src/auth.rs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
use std::process;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AuthToken(String);
|
||||||
|
|
||||||
|
impl AuthToken {
|
||||||
|
pub fn access(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_token_from_command(command: &str) -> Result<AuthToken, String> {
|
||||||
|
let output = process::Command::new("/usr/bin/env")
|
||||||
|
.arg("sh")
|
||||||
|
.arg("-c")
|
||||||
|
.arg(command)
|
||||||
|
.output()
|
||||||
|
.map_err(|error| format!("Failed to run token-command: {}", error))?;
|
||||||
|
|
||||||
|
let stderr = String::from_utf8(output.stderr).map_err(|error| error.to_string())?;
|
||||||
|
let stdout = String::from_utf8(output.stdout).map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
if !stderr.is_empty() {
|
||||||
|
return Err(format!("Token command failed: {}", stderr));
|
||||||
|
} else {
|
||||||
|
return Err(String::from("Token command failed."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !stderr.is_empty() {
|
||||||
|
return Err(format!("Token command produced stderr: {}", stderr));
|
||||||
|
}
|
||||||
|
|
||||||
|
if stdout.is_empty() {
|
||||||
|
return Err(String::from("Token command did not produce output"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let token = stdout
|
||||||
|
.split('\n')
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| String::from("Output did not contain any newline"))?;
|
||||||
|
|
||||||
|
Ok(AuthToken(token.to_string()))
|
||||||
|
}
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::process;
|
use std::process;
|
||||||
|
|
||||||
use crate::output::*;
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::{get_token_from_command, path_as_string, Remote, Repo, Tree};
|
use super::auth;
|
||||||
|
use super::output::*;
|
||||||
|
use super::path;
|
||||||
|
use super::provider;
|
||||||
|
use super::provider::Filter;
|
||||||
|
use super::provider::Provider;
|
||||||
|
use super::repo;
|
||||||
|
use super::tree;
|
||||||
|
|
||||||
use crate::provider;
|
pub type RemoteProvider = provider::RemoteProvider;
|
||||||
use crate::provider::Filter;
|
pub type RemoteType = repo::RemoteType;
|
||||||
use crate::provider::Provider;
|
|
||||||
|
|
||||||
pub type RemoteProvider = crate::provider::RemoteProvider;
|
|
||||||
pub type RemoteType = crate::repo::RemoteType;
|
|
||||||
|
|
||||||
fn worktree_setup_default() -> bool {
|
fn worktree_setup_default() -> bool {
|
||||||
false
|
false
|
||||||
@@ -52,6 +53,8 @@ pub struct ConfigProvider {
|
|||||||
|
|
||||||
pub worktree: Option<bool>,
|
pub worktree: Option<bool>,
|
||||||
pub init_worktree: Option<bool>,
|
pub init_worktree: Option<bool>,
|
||||||
|
|
||||||
|
pub remote_name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
@@ -64,7 +67,7 @@ pub struct RemoteConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RemoteConfig {
|
impl RemoteConfig {
|
||||||
pub fn from_remote(remote: Remote) -> Self {
|
pub fn from_remote(remote: repo::Remote) -> Self {
|
||||||
Self {
|
Self {
|
||||||
name: remote.name,
|
name: remote.name,
|
||||||
url: remote.url,
|
url: remote.url,
|
||||||
@@ -72,8 +75,8 @@ impl RemoteConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_remote(self) -> Remote {
|
pub fn into_remote(self) -> repo::Remote {
|
||||||
Remote {
|
repo::Remote {
|
||||||
name: self.name,
|
name: self.name,
|
||||||
url: self.url,
|
url: self.url,
|
||||||
remote_type: self.remote_type,
|
remote_type: self.remote_type,
|
||||||
@@ -93,7 +96,7 @@ pub struct RepoConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RepoConfig {
|
impl RepoConfig {
|
||||||
pub fn from_repo(repo: Repo) -> Self {
|
pub fn from_repo(repo: repo::Repo) -> Self {
|
||||||
Self {
|
Self {
|
||||||
name: repo.name,
|
name: repo.name,
|
||||||
worktree_setup: repo.worktree_setup,
|
worktree_setup: repo.worktree_setup,
|
||||||
@@ -103,14 +106,14 @@ impl RepoConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_repo(self) -> Repo {
|
pub fn into_repo(self) -> repo::Repo {
|
||||||
let (namespace, name) = if let Some((namespace, name)) = self.name.rsplit_once('/') {
|
let (namespace, name) = if let Some((namespace, name)) = self.name.rsplit_once('/') {
|
||||||
(Some(namespace.to_string()), name.to_string())
|
(Some(namespace.to_string()), name.to_string())
|
||||||
} else {
|
} else {
|
||||||
(None, self.name)
|
(None, self.name)
|
||||||
};
|
};
|
||||||
|
|
||||||
Repo {
|
repo::Repo {
|
||||||
name,
|
name,
|
||||||
namespace,
|
namespace,
|
||||||
worktree_setup: self.worktree_setup,
|
worktree_setup: self.worktree_setup,
|
||||||
@@ -133,7 +136,7 @@ impl ConfigTrees {
|
|||||||
ConfigTrees { trees: vec }
|
ConfigTrees { trees: vec }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_trees(vec: Vec<Tree>) -> Self {
|
pub fn from_trees(vec: Vec<tree::Tree>) -> Self {
|
||||||
ConfigTrees {
|
ConfigTrees {
|
||||||
trees: vec.into_iter().map(ConfigTree::from_tree).collect(),
|
trees: vec.into_iter().map(ConfigTree::from_tree).collect(),
|
||||||
}
|
}
|
||||||
@@ -157,7 +160,7 @@ impl Config {
|
|||||||
match self {
|
match self {
|
||||||
Config::ConfigTrees(config) => Ok(config.trees),
|
Config::ConfigTrees(config) => Ok(config.trees),
|
||||||
Config::ConfigProvider(config) => {
|
Config::ConfigProvider(config) => {
|
||||||
let token = match get_token_from_command(&config.token_command) {
|
let token = match auth::get_token_from_command(&config.token_command) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Getting token from command failed: {}", error));
|
print_error(&format!("Getting token from command failed: {}", error));
|
||||||
@@ -191,6 +194,7 @@ impl Config {
|
|||||||
.get_repos(
|
.get_repos(
|
||||||
config.worktree.unwrap_or(false),
|
config.worktree.unwrap_or(false),
|
||||||
config.force_ssh.unwrap_or(false),
|
config.force_ssh.unwrap_or(false),
|
||||||
|
config.remote_name,
|
||||||
)?
|
)?
|
||||||
}
|
}
|
||||||
RemoteProvider::Gitlab => {
|
RemoteProvider::Gitlab => {
|
||||||
@@ -204,6 +208,7 @@ impl Config {
|
|||||||
.get_repos(
|
.get_repos(
|
||||||
config.worktree.unwrap_or(false),
|
config.worktree.unwrap_or(false),
|
||||||
config.force_ssh.unwrap_or(false),
|
config.force_ssh.unwrap_or(false),
|
||||||
|
config.remote_name,
|
||||||
)?
|
)?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -217,9 +222,9 @@ impl Config {
|
|||||||
.collect();
|
.collect();
|
||||||
let tree = ConfigTree {
|
let tree = ConfigTree {
|
||||||
root: if let Some(namespace) = namespace {
|
root: if let Some(namespace) = namespace {
|
||||||
path_as_string(&Path::new(&config.root).join(namespace))
|
path::path_as_string(&Path::new(&config.root).join(namespace))
|
||||||
} else {
|
} else {
|
||||||
path_as_string(Path::new(&config.root))
|
path::path_as_string(Path::new(&config.root))
|
||||||
},
|
},
|
||||||
repos: Some(repos),
|
repos: Some(repos),
|
||||||
};
|
};
|
||||||
@@ -236,7 +241,7 @@ impl Config {
|
|||||||
|
|
||||||
pub fn normalize(&mut self) {
|
pub fn normalize(&mut self) {
|
||||||
if let Config::ConfigTrees(config) = self {
|
if let Config::ConfigTrees(config) = self {
|
||||||
let home = super::env_home().display().to_string();
|
let home = path::env_home().display().to_string();
|
||||||
for tree in &mut config.trees_mut().iter_mut() {
|
for tree in &mut config.trees_mut().iter_mut() {
|
||||||
if tree.root.starts_with(&home) {
|
if tree.root.starts_with(&home) {
|
||||||
// The tilde is not handled differently, it's just a normal path component for `Path`.
|
// The tilde is not handled differently, it's just a normal path component for `Path`.
|
||||||
@@ -275,14 +280,14 @@ pub struct ConfigTree {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ConfigTree {
|
impl ConfigTree {
|
||||||
pub fn from_repos(root: String, repos: Vec<Repo>) -> Self {
|
pub fn from_repos(root: String, repos: Vec<repo::Repo>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
root,
|
root,
|
||||||
repos: Some(repos.into_iter().map(RepoConfig::from_repo).collect()),
|
repos: Some(repos.into_iter().map(RepoConfig::from_repo).collect()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_tree(tree: Tree) -> Self {
|
pub fn from_tree(tree: tree::Tree) -> Self {
|
||||||
Self {
|
Self {
|
||||||
root: tree.root,
|
root: tree.root,
|
||||||
repos: Some(tree.repos.into_iter().map(RepoConfig::from_repo).collect()),
|
repos: Some(tree.repos.into_iter().map(RepoConfig::from_repo).collect()),
|
||||||
|
|||||||
@@ -103,6 +103,9 @@ pub struct FindRemoteArgs {
|
|||||||
#[clap(arg_enum, short, long, help = "Remote provider to use")]
|
#[clap(arg_enum, short, long, help = "Remote provider to use")]
|
||||||
pub provider: RemoteProvider,
|
pub provider: RemoteProvider,
|
||||||
|
|
||||||
|
#[clap(short, long, help = "Name of the remote to use")]
|
||||||
|
pub remote_name: Option<String>,
|
||||||
|
|
||||||
#[clap(
|
#[clap(
|
||||||
multiple_occurrences = true,
|
multiple_occurrences = true,
|
||||||
name = "user",
|
name = "user",
|
||||||
@@ -181,7 +184,7 @@ pub struct Config {
|
|||||||
pub init_worktree: String,
|
pub init_worktree: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type RemoteProvider = grm::provider::RemoteProvider;
|
pub type RemoteProvider = super::provider::RemoteProvider;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[clap()]
|
#[clap()]
|
||||||
@@ -189,6 +192,9 @@ pub struct SyncRemoteArgs {
|
|||||||
#[clap(arg_enum, short, long, help = "Remote provider to use")]
|
#[clap(arg_enum, short, long, help = "Remote provider to use")]
|
||||||
pub provider: RemoteProvider,
|
pub provider: RemoteProvider,
|
||||||
|
|
||||||
|
#[clap(short, long, help = "Name of the remote to use")]
|
||||||
|
pub remote_name: Option<String>,
|
||||||
|
|
||||||
#[clap(
|
#[clap(
|
||||||
multiple_occurrences = true,
|
multiple_occurrences = true,
|
||||||
name = "user",
|
name = "user",
|
||||||
|
|||||||
144
src/grm/main.rs
144
src/grm/main.rs
@@ -3,12 +3,17 @@ use std::process;
|
|||||||
|
|
||||||
mod cmd;
|
mod cmd;
|
||||||
|
|
||||||
|
use grm::auth;
|
||||||
use grm::config;
|
use grm::config;
|
||||||
|
use grm::find_in_tree;
|
||||||
use grm::output::*;
|
use grm::output::*;
|
||||||
use grm::path_as_string;
|
use grm::path;
|
||||||
use grm::provider;
|
use grm::provider;
|
||||||
use grm::provider::Provider;
|
use grm::provider::Provider;
|
||||||
use grm::repo;
|
use grm::repo;
|
||||||
|
use grm::table;
|
||||||
|
use grm::tree;
|
||||||
|
use grm::worktree;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let opts = cmd::parse();
|
let opts = cmd::parse();
|
||||||
@@ -24,7 +29,7 @@ fn main() {
|
|||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match grm::sync_trees(config, args.init_worktree == "true") {
|
match tree::sync_trees(config, args.init_worktree == "true") {
|
||||||
Ok(success) => {
|
Ok(success) => {
|
||||||
if !success {
|
if !success {
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
@@ -37,7 +42,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::SyncAction::Remote(args) => {
|
cmd::SyncAction::Remote(args) => {
|
||||||
let token = match grm::get_token_from_command(&args.token_command) {
|
let token = match auth::get_token_from_command(&args.token_command) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Getting token from command failed: {}", error));
|
print_error(&format!("Getting token from command failed: {}", error));
|
||||||
@@ -45,35 +50,39 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let filter = grm::provider::Filter::new(
|
let filter =
|
||||||
args.users,
|
provider::Filter::new(args.users, args.groups, args.owner, args.access);
|
||||||
args.groups,
|
|
||||||
args.owner,
|
|
||||||
args.access,
|
|
||||||
);
|
|
||||||
|
|
||||||
let worktree = args.worktree == "true";
|
let worktree = args.worktree == "true";
|
||||||
|
|
||||||
let repos = match args.provider {
|
let repos = match args.provider {
|
||||||
cmd::RemoteProvider::Github => {
|
cmd::RemoteProvider::Github => {
|
||||||
match grm::provider::Github::new(filter, token, args.api_url) {
|
match provider::Github::new(filter, token, args.api_url) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Error: {}", error));
|
print_error(&format!("Error: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.get_repos(worktree, args.force_ssh)
|
.get_repos(
|
||||||
|
worktree,
|
||||||
|
args.force_ssh,
|
||||||
|
args.remote_name,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
cmd::RemoteProvider::Gitlab => {
|
cmd::RemoteProvider::Gitlab => {
|
||||||
match grm::provider::Gitlab::new(filter, token, args.api_url) {
|
match provider::Gitlab::new(filter, token, args.api_url) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Error: {}", error));
|
print_error(&format!("Error: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.get_repos(worktree, args.force_ssh)
|
.get_repos(
|
||||||
|
worktree,
|
||||||
|
args.force_ssh,
|
||||||
|
args.remote_name,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,9 +92,9 @@ fn main() {
|
|||||||
|
|
||||||
for (namespace, repolist) in repos {
|
for (namespace, repolist) in repos {
|
||||||
let root = if let Some(namespace) = namespace {
|
let root = if let Some(namespace) = namespace {
|
||||||
path_as_string(&Path::new(&args.root).join(namespace))
|
path::path_as_string(&Path::new(&args.root).join(namespace))
|
||||||
} else {
|
} else {
|
||||||
path_as_string(Path::new(&args.root))
|
path::path_as_string(Path::new(&args.root))
|
||||||
};
|
};
|
||||||
|
|
||||||
let tree = config::ConfigTree::from_repos(root, repolist);
|
let tree = config::ConfigTree::from_repos(root, repolist);
|
||||||
@@ -94,7 +103,7 @@ fn main() {
|
|||||||
|
|
||||||
let config = config::Config::from_trees(trees);
|
let config = config::Config::from_trees(trees);
|
||||||
|
|
||||||
match grm::sync_trees(config, args.init_worktree == "true") {
|
match tree::sync_trees(config, args.init_worktree == "true") {
|
||||||
Ok(success) => {
|
Ok(success) => {
|
||||||
if !success {
|
if !success {
|
||||||
process::exit(1)
|
process::exit(1)
|
||||||
@@ -122,7 +131,7 @@ fn main() {
|
|||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match grm::table::get_status_table(config) {
|
match table::get_status_table(config) {
|
||||||
Ok((tables, errors)) => {
|
Ok((tables, errors)) => {
|
||||||
for table in tables {
|
for table in tables {
|
||||||
println!("{}", table);
|
println!("{}", table);
|
||||||
@@ -146,7 +155,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
match grm::table::show_single_repo_status(&dir) {
|
match table::show_single_repo_status(&dir) {
|
||||||
Ok((table, warnings)) => {
|
Ok((table, warnings)) => {
|
||||||
println!("{}", table);
|
println!("{}", table);
|
||||||
for warning in warnings {
|
for warning in warnings {
|
||||||
@@ -184,7 +193,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let (found_repos, warnings) = match grm::find_in_tree(&path) {
|
let (found_repos, warnings) = match find_in_tree(&path) {
|
||||||
Ok((repos, warnings)) => (repos, warnings),
|
Ok((repos, warnings)) => (repos, warnings),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&error);
|
print_error(&error);
|
||||||
@@ -192,7 +201,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let trees = grm::config::ConfigTrees::from_trees(vec![found_repos]);
|
let trees = config::ConfigTrees::from_trees(vec![found_repos]);
|
||||||
if trees.trees_ref().iter().all(|t| match &t.repos {
|
if trees.trees_ref().iter().all(|t| match &t.repos {
|
||||||
None => false,
|
None => false,
|
||||||
Some(r) => r.is_empty(),
|
Some(r) => r.is_empty(),
|
||||||
@@ -237,8 +246,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::FindAction::Config(args) => {
|
cmd::FindAction::Config(args) => {
|
||||||
let config: crate::config::ConfigProvider =
|
let config: config::ConfigProvider = match config::read_config(&args.config) {
|
||||||
match config::read_config(&args.config) {
|
|
||||||
Ok(config) => config,
|
Ok(config) => config,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&error);
|
print_error(&error);
|
||||||
@@ -246,7 +254,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let token = match grm::get_token_from_command(&config.token_command) {
|
let token = match auth::get_token_from_command(&config.token_command) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Getting token from command failed: {}", error));
|
print_error(&format!("Getting token from command failed: {}", error));
|
||||||
@@ -254,7 +262,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let filters = config.filters.unwrap_or(grm::config::ConfigProviderFilter {
|
let filters = config.filters.unwrap_or(config::ConfigProviderFilter {
|
||||||
access: Some(false),
|
access: Some(false),
|
||||||
owner: Some(false),
|
owner: Some(false),
|
||||||
users: Some(vec![]),
|
users: Some(vec![]),
|
||||||
@@ -280,6 +288,7 @@ fn main() {
|
|||||||
.get_repos(
|
.get_repos(
|
||||||
config.worktree.unwrap_or(false),
|
config.worktree.unwrap_or(false),
|
||||||
config.force_ssh.unwrap_or(false),
|
config.force_ssh.unwrap_or(false),
|
||||||
|
config.remote_name,
|
||||||
) {
|
) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -299,6 +308,7 @@ fn main() {
|
|||||||
.get_repos(
|
.get_repos(
|
||||||
config.worktree.unwrap_or(false),
|
config.worktree.unwrap_or(false),
|
||||||
config.force_ssh.unwrap_or(false),
|
config.force_ssh.unwrap_or(false),
|
||||||
|
config.remote_name,
|
||||||
) {
|
) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -314,14 +324,14 @@ fn main() {
|
|||||||
for (namespace, namespace_repos) in repos {
|
for (namespace, namespace_repos) in repos {
|
||||||
let tree = config::ConfigTree {
|
let tree = config::ConfigTree {
|
||||||
root: if let Some(namespace) = namespace {
|
root: if let Some(namespace) = namespace {
|
||||||
path_as_string(&Path::new(&config.root).join(namespace))
|
path::path_as_string(&Path::new(&config.root).join(namespace))
|
||||||
} else {
|
} else {
|
||||||
path_as_string(Path::new(&config.root))
|
path::path_as_string(Path::new(&config.root))
|
||||||
},
|
},
|
||||||
repos: Some(
|
repos: Some(
|
||||||
namespace_repos
|
namespace_repos
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(grm::config::RepoConfig::from_repo)
|
.map(config::RepoConfig::from_repo)
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
@@ -360,7 +370,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::FindAction::Remote(args) => {
|
cmd::FindAction::Remote(args) => {
|
||||||
let token = match grm::get_token_from_command(&args.token_command) {
|
let token = match auth::get_token_from_command(&args.token_command) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Getting token from command failed: {}", error));
|
print_error(&format!("Getting token from command failed: {}", error));
|
||||||
@@ -368,35 +378,39 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let filter = grm::provider::Filter::new(
|
let filter =
|
||||||
args.users,
|
provider::Filter::new(args.users, args.groups, args.owner, args.access);
|
||||||
args.groups,
|
|
||||||
args.owner,
|
|
||||||
args.access,
|
|
||||||
);
|
|
||||||
|
|
||||||
let worktree = args.worktree == "true";
|
let worktree = args.worktree == "true";
|
||||||
|
|
||||||
let repos = match args.provider {
|
let repos = match args.provider {
|
||||||
cmd::RemoteProvider::Github => {
|
cmd::RemoteProvider::Github => {
|
||||||
match grm::provider::Github::new(filter, token, args.api_url) {
|
match provider::Github::new(filter, token, args.api_url) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Error: {}", error));
|
print_error(&format!("Error: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.get_repos(worktree, args.force_ssh)
|
.get_repos(
|
||||||
|
worktree,
|
||||||
|
args.force_ssh,
|
||||||
|
args.remote_name,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
cmd::RemoteProvider::Gitlab => {
|
cmd::RemoteProvider::Gitlab => {
|
||||||
match grm::provider::Gitlab::new(filter, token, args.api_url) {
|
match provider::Gitlab::new(filter, token, args.api_url) {
|
||||||
Ok(provider) => provider,
|
Ok(provider) => provider,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Error: {}", error));
|
print_error(&format!("Error: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.get_repos(worktree, args.force_ssh)
|
.get_repos(
|
||||||
|
worktree,
|
||||||
|
args.force_ssh,
|
||||||
|
args.remote_name,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -410,14 +424,14 @@ fn main() {
|
|||||||
for (namespace, repolist) in repos {
|
for (namespace, repolist) in repos {
|
||||||
let tree = config::ConfigTree {
|
let tree = config::ConfigTree {
|
||||||
root: if let Some(namespace) = namespace {
|
root: if let Some(namespace) = namespace {
|
||||||
path_as_string(&Path::new(&args.root).join(namespace))
|
path::path_as_string(&Path::new(&args.root).join(namespace))
|
||||||
} else {
|
} else {
|
||||||
path_as_string(Path::new(&args.root))
|
path::path_as_string(Path::new(&args.root))
|
||||||
},
|
},
|
||||||
repos: Some(
|
repos: Some(
|
||||||
repolist
|
repolist
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(grm::config::RepoConfig::from_repo)
|
.map(config::RepoConfig::from_repo)
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
@@ -503,7 +517,13 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match grm::add_worktree(&cwd, name, subdirectory, track, action_args.no_track) {
|
match worktree::add_worktree(
|
||||||
|
&cwd,
|
||||||
|
name,
|
||||||
|
subdirectory,
|
||||||
|
track,
|
||||||
|
action_args.no_track,
|
||||||
|
) {
|
||||||
Ok(_) => print_success(&format!("Worktree {} created", &action_args.name)),
|
Ok(_) => print_success(&format!("Worktree {} created", &action_args.name)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
print_error(&format!("Error creating worktree: {}", error));
|
print_error(&format!("Error creating worktree: {}", error));
|
||||||
@@ -525,7 +545,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
print_error(&format!("Error opening repository: {}", error));
|
print_error(&format!("Error opening repository: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
});
|
});
|
||||||
@@ -539,17 +559,17 @@ fn main() {
|
|||||||
Ok(_) => print_success(&format!("Worktree {} deleted", &action_args.name)),
|
Ok(_) => print_success(&format!("Worktree {} deleted", &action_args.name)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
match error {
|
match error {
|
||||||
grm::WorktreeRemoveFailureReason::Error(msg) => {
|
repo::WorktreeRemoveFailureReason::Error(msg) => {
|
||||||
print_error(&msg);
|
print_error(&msg);
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
grm::WorktreeRemoveFailureReason::Changes(changes) => {
|
repo::WorktreeRemoveFailureReason::Changes(changes) => {
|
||||||
print_warning(&format!(
|
print_warning(&format!(
|
||||||
"Changes in worktree: {}. Refusing to delete",
|
"Changes in worktree: {}. Refusing to delete",
|
||||||
changes
|
changes
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
grm::WorktreeRemoveFailureReason::NotMerged(message) => {
|
repo::WorktreeRemoveFailureReason::NotMerged(message) => {
|
||||||
print_warning(&message);
|
print_warning(&message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -558,12 +578,12 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::WorktreeAction::Status(_args) => {
|
cmd::WorktreeAction::Status(_args) => {
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
print_error(&format!("Error opening repository: {}", error));
|
print_error(&format!("Error opening repository: {}", error));
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
match grm::table::get_worktree_status_table(&repo, &cwd) {
|
match table::get_worktree_status_table(&repo, &cwd) {
|
||||||
Ok((table, errors)) => {
|
Ok((table, errors)) => {
|
||||||
println!("{}", table);
|
println!("{}", table);
|
||||||
for error in errors {
|
for error in errors {
|
||||||
@@ -583,8 +603,8 @@ fn main() {
|
|||||||
// * Remove all files
|
// * Remove all files
|
||||||
// * Set `core.bare` to `true`
|
// * Set `core.bare` to `true`
|
||||||
|
|
||||||
let repo = grm::RepoHandle::open(&cwd, false).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, false).unwrap_or_else(|error| {
|
||||||
if error.kind == grm::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
print_error("Directory does not contain a git repository");
|
print_error("Directory does not contain a git repository");
|
||||||
} else {
|
} else {
|
||||||
print_error(&format!("Opening repository failed: {}", error));
|
print_error(&format!("Opening repository failed: {}", error));
|
||||||
@@ -611,8 +631,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::WorktreeAction::Clean(_args) => {
|
cmd::WorktreeAction::Clean(_args) => {
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
if error.kind == grm::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
print_error("Directory does not contain a git repository");
|
print_error("Directory does not contain a git repository");
|
||||||
} else {
|
} else {
|
||||||
print_error(&format!("Opening repository failed: {}", error));
|
print_error(&format!("Opening repository failed: {}", error));
|
||||||
@@ -645,8 +665,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd::WorktreeAction::Fetch(_args) => {
|
cmd::WorktreeAction::Fetch(_args) => {
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
if error.kind == grm::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
print_error("Directory does not contain a git repository");
|
print_error("Directory does not contain a git repository");
|
||||||
} else {
|
} else {
|
||||||
print_error(&format!("Opening repository failed: {}", error));
|
print_error(&format!("Opening repository failed: {}", error));
|
||||||
@@ -661,8 +681,8 @@ fn main() {
|
|||||||
print_success("Fetched from all remotes");
|
print_success("Fetched from all remotes");
|
||||||
}
|
}
|
||||||
cmd::WorktreeAction::Pull(args) => {
|
cmd::WorktreeAction::Pull(args) => {
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
if error.kind == grm::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
print_error("Directory does not contain a git repository");
|
print_error("Directory does not contain a git repository");
|
||||||
} else {
|
} else {
|
||||||
print_error(&format!("Opening repository failed: {}", error));
|
print_error(&format!("Opening repository failed: {}", error));
|
||||||
@@ -702,8 +722,8 @@ fn main() {
|
|||||||
print_error("There is no point in using --rebase without --pull");
|
print_error("There is no point in using --rebase without --pull");
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
let repo = grm::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
let repo = repo::RepoHandle::open(&cwd, true).unwrap_or_else(|error| {
|
||||||
if error.kind == grm::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
print_error("Directory does not contain a git repository");
|
print_error("Directory does not contain a git repository");
|
||||||
} else {
|
} else {
|
||||||
print_error(&format!("Opening repository failed: {}", error));
|
print_error(&format!("Opening repository failed: {}", error));
|
||||||
@@ -718,12 +738,8 @@ fn main() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let config =
|
let config = repo::read_worktree_root_config(&cwd).unwrap_or_else(|error| {
|
||||||
grm::repo::read_worktree_root_config(&cwd).unwrap_or_else(|error| {
|
print_error(&format!("Failed to read worktree configuration: {}", error));
|
||||||
print_error(&format!(
|
|
||||||
"Failed to read worktree configuration: {}",
|
|
||||||
error
|
|
||||||
));
|
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
595
src/lib.rs
595
src/lib.rs
@@ -1,423 +1,37 @@
|
|||||||
#![feature(io_error_more)]
|
#![feature(io_error_more)]
|
||||||
#![feature(const_option_ext)]
|
#![feature(const_option_ext)]
|
||||||
|
|
||||||
use std::fs;
|
use std::path::Path;
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::process;
|
|
||||||
|
|
||||||
|
pub mod auth;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod output;
|
pub mod output;
|
||||||
|
pub mod path;
|
||||||
pub mod provider;
|
pub mod provider;
|
||||||
pub mod repo;
|
pub mod repo;
|
||||||
pub mod table;
|
pub mod table;
|
||||||
|
pub mod tree;
|
||||||
|
pub mod worktree;
|
||||||
|
|
||||||
use config::Config;
|
|
||||||
use output::*;
|
|
||||||
|
|
||||||
use repo::{clone_repo, detect_remote_type, Remote, RemoteType};
|
|
||||||
|
|
||||||
pub use repo::{
|
|
||||||
RemoteTrackingStatus, Repo, RepoErrorKind, RepoHandle, WorktreeRemoveFailureReason,
|
|
||||||
};
|
|
||||||
|
|
||||||
const GIT_MAIN_WORKTREE_DIRECTORY: &str = ".git-main-working-tree";
|
|
||||||
const BRANCH_NAMESPACE_SEPARATOR: &str = "/";
|
const BRANCH_NAMESPACE_SEPARATOR: &str = "/";
|
||||||
|
|
||||||
const GIT_CONFIG_BARE_KEY: &str = "core.bare";
|
|
||||||
const GIT_CONFIG_PUSH_DEFAULT: &str = "push.default";
|
|
||||||
|
|
||||||
pub struct Tree {
|
|
||||||
root: String,
|
|
||||||
repos: Vec<Repo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn setup() {
|
|
||||||
std::env::set_var("HOME", "/home/test");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn check_expand_tilde() {
|
|
||||||
setup();
|
|
||||||
assert_eq!(
|
|
||||||
expand_path(Path::new("~/file")),
|
|
||||||
Path::new("/home/test/file")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn check_expand_invalid_tilde() {
|
|
||||||
setup();
|
|
||||||
assert_eq!(
|
|
||||||
expand_path(Path::new("/home/~/file")),
|
|
||||||
Path::new("/home/~/file")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn check_expand_home() {
|
|
||||||
setup();
|
|
||||||
assert_eq!(
|
|
||||||
expand_path(Path::new("$HOME/file")),
|
|
||||||
Path::new("/home/test/file")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
expand_path(Path::new("${HOME}/file")),
|
|
||||||
Path::new("/home/test/file")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn path_as_string(path: &Path) -> String {
|
|
||||||
path.to_path_buf().into_os_string().into_string().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn env_home() -> PathBuf {
|
|
||||||
match std::env::var("HOME") {
|
|
||||||
Ok(path) => Path::new(&path).to_path_buf(),
|
|
||||||
Err(e) => {
|
|
||||||
print_error(&format!("Unable to read HOME: {}", e));
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expand_path(path: &Path) -> PathBuf {
|
|
||||||
fn home_dir() -> Option<PathBuf> {
|
|
||||||
Some(env_home())
|
|
||||||
}
|
|
||||||
|
|
||||||
let expanded_path = match shellexpand::full_with_context(
|
|
||||||
&path_as_string(path),
|
|
||||||
home_dir,
|
|
||||||
|name| -> Result<Option<String>, &'static str> {
|
|
||||||
match name {
|
|
||||||
"HOME" => Ok(Some(path_as_string(home_dir().unwrap().as_path()))),
|
|
||||||
_ => Ok(None),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
Ok(std::borrow::Cow::Borrowed(path)) => path.to_owned(),
|
|
||||||
Ok(std::borrow::Cow::Owned(path)) => path,
|
|
||||||
Err(e) => {
|
|
||||||
print_error(&format!("Unable to expand root: {}", e));
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Path::new(&expanded_path).to_path_buf()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_token_from_command(command: &str) -> Result<String, String> {
|
|
||||||
let output = std::process::Command::new("/usr/bin/env")
|
|
||||||
.arg("sh")
|
|
||||||
.arg("-c")
|
|
||||||
.arg(command)
|
|
||||||
.output()
|
|
||||||
.map_err(|error| format!("Failed to run token-command: {}", error))?;
|
|
||||||
|
|
||||||
let stderr = String::from_utf8(output.stderr).map_err(|error| error.to_string())?;
|
|
||||||
let stdout = String::from_utf8(output.stdout).map_err(|error| error.to_string())?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
if !stderr.is_empty() {
|
|
||||||
return Err(format!("Token command failed: {}", stderr));
|
|
||||||
} else {
|
|
||||||
return Err(String::from("Token command failed."));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !stderr.is_empty() {
|
|
||||||
return Err(format!("Token command produced stderr: {}", stderr));
|
|
||||||
}
|
|
||||||
|
|
||||||
if stdout.is_empty() {
|
|
||||||
return Err(String::from("Token command did not produce output"));
|
|
||||||
}
|
|
||||||
|
|
||||||
let token = stdout
|
|
||||||
.split('\n')
|
|
||||||
.next()
|
|
||||||
.ok_or_else(|| String::from("Output did not contain any newline"))?;
|
|
||||||
|
|
||||||
Ok(token.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sync_repo(root_path: &Path, repo: &Repo, init_worktree: bool) -> Result<(), String> {
|
|
||||||
let repo_path = root_path.join(&repo.fullname());
|
|
||||||
let actual_git_directory = get_actual_git_directory(&repo_path, repo.worktree_setup);
|
|
||||||
|
|
||||||
let mut newly_created = false;
|
|
||||||
|
|
||||||
if repo_path.exists() {
|
|
||||||
if repo.worktree_setup && !actual_git_directory.exists() {
|
|
||||||
return Err(String::from(
|
|
||||||
"Repo already exists, but is not using a worktree setup",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
} else if matches!(&repo.remotes, None) || repo.remotes.as_ref().unwrap().is_empty() {
|
|
||||||
print_repo_action(
|
|
||||||
&repo.name,
|
|
||||||
"Repository does not have remotes configured, initializing new",
|
|
||||||
);
|
|
||||||
match RepoHandle::init(&repo_path, repo.worktree_setup) {
|
|
||||||
Ok(r) => {
|
|
||||||
print_repo_success(&repo.name, "Repository created");
|
|
||||||
Some(r)
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
return Err(format!("Repository failed during init: {}", e));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
let first = repo.remotes.as_ref().unwrap().first().unwrap();
|
|
||||||
|
|
||||||
match clone_repo(first, &repo_path, repo.worktree_setup) {
|
|
||||||
Ok(_) => {
|
|
||||||
print_repo_success(&repo.name, "Repository successfully cloned");
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
return Err(format!("Repository failed during clone: {}", e));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
newly_created = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let repo_handle = match RepoHandle::open(&repo_path, repo.worktree_setup) {
|
|
||||||
Ok(repo) => repo,
|
|
||||||
Err(error) => {
|
|
||||||
if !repo.worktree_setup && RepoHandle::open(&repo_path, true).is_ok() {
|
|
||||||
return Err(String::from(
|
|
||||||
"Repo already exists, but is using a worktree setup",
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
return Err(format!("Opening repository failed: {}", error));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if newly_created && repo.worktree_setup && init_worktree {
|
|
||||||
match repo_handle.default_branch() {
|
|
||||||
Ok(branch) => {
|
|
||||||
add_worktree(&repo_path, &branch.name()?, None, None, false)?;
|
|
||||||
}
|
|
||||||
Err(_error) => print_repo_error(
|
|
||||||
&repo.name,
|
|
||||||
"Could not determine default branch, skipping worktree initializtion",
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(remotes) = &repo.remotes {
|
|
||||||
let current_remotes: Vec<String> = repo_handle
|
|
||||||
.remotes()
|
|
||||||
.map_err(|error| format!("Repository failed during getting the remotes: {}", error))?;
|
|
||||||
|
|
||||||
for remote in remotes {
|
|
||||||
let current_remote = repo_handle.find_remote(&remote.name)?;
|
|
||||||
|
|
||||||
match current_remote {
|
|
||||||
Some(current_remote) => {
|
|
||||||
let current_url = current_remote.url();
|
|
||||||
|
|
||||||
if remote.url != current_url {
|
|
||||||
print_repo_action(
|
|
||||||
&repo.name,
|
|
||||||
&format!("Updating remote {} to \"{}\"", &remote.name, &remote.url),
|
|
||||||
);
|
|
||||||
if let Err(e) = repo_handle.remote_set_url(&remote.name, &remote.url) {
|
|
||||||
return Err(format!("Repository failed during setting of the remote URL for remote \"{}\": {}", &remote.name, e));
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
print_repo_action(
|
|
||||||
&repo.name,
|
|
||||||
&format!(
|
|
||||||
"Setting up new remote \"{}\" to \"{}\"",
|
|
||||||
&remote.name, &remote.url
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if let Err(e) = repo_handle.new_remote(&remote.name, &remote.url) {
|
|
||||||
return Err(format!(
|
|
||||||
"Repository failed during setting the remotes: {}",
|
|
||||||
e
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for current_remote in ¤t_remotes {
|
|
||||||
if !remotes.iter().any(|r| &r.name == current_remote) {
|
|
||||||
print_repo_action(
|
|
||||||
&repo.name,
|
|
||||||
&format!("Deleting remote \"{}\"", ¤t_remote,),
|
|
||||||
);
|
|
||||||
if let Err(e) = repo_handle.remote_delete(current_remote) {
|
|
||||||
return Err(format!(
|
|
||||||
"Repository failed during deleting remote \"{}\": {}",
|
|
||||||
¤t_remote, e
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_unmanaged_repos(
|
|
||||||
root_path: &Path,
|
|
||||||
managed_repos: &[Repo],
|
|
||||||
) -> Result<Vec<PathBuf>, String> {
|
|
||||||
let mut unmanaged_repos = Vec::new();
|
|
||||||
|
|
||||||
for repo_path in find_repo_paths(root_path)? {
|
|
||||||
if !managed_repos
|
|
||||||
.iter()
|
|
||||||
.any(|r| Path::new(root_path).join(r.fullname()) == repo_path)
|
|
||||||
{
|
|
||||||
unmanaged_repos.push(repo_path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(unmanaged_repos)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn sync_trees(config: Config, init_worktree: bool) -> Result<bool, String> {
|
|
||||||
let mut failures = false;
|
|
||||||
|
|
||||||
let mut unmanaged_repos_absolute_paths = vec![];
|
|
||||||
let mut managed_repos_absolute_paths = vec![];
|
|
||||||
|
|
||||||
let trees = config.trees()?;
|
|
||||||
|
|
||||||
for tree in trees {
|
|
||||||
let repos: Vec<Repo> = tree
|
|
||||||
.repos
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
|
||||||
.map(|repo| repo.into_repo())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let root_path = expand_path(Path::new(&tree.root));
|
|
||||||
|
|
||||||
for repo in &repos {
|
|
||||||
managed_repos_absolute_paths.push(root_path.join(repo.fullname()));
|
|
||||||
match sync_repo(&root_path, repo, init_worktree) {
|
|
||||||
Ok(_) => print_repo_success(&repo.name, "OK"),
|
|
||||||
Err(error) => {
|
|
||||||
print_repo_error(&repo.name, &error);
|
|
||||||
failures = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match find_unmanaged_repos(&root_path, &repos) {
|
|
||||||
Ok(repos) => {
|
|
||||||
unmanaged_repos_absolute_paths.extend(repos);
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
print_error(&format!("Error getting unmanaged repos: {}", error));
|
|
||||||
failures = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for unmanaged_repo_absolute_path in &unmanaged_repos_absolute_paths {
|
|
||||||
if managed_repos_absolute_paths
|
|
||||||
.iter()
|
|
||||||
.any(|managed_repo_absolute_path| {
|
|
||||||
managed_repo_absolute_path == unmanaged_repo_absolute_path
|
|
||||||
})
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
print_warning(&format!(
|
|
||||||
"Found unmanaged repository: \"{}\"",
|
|
||||||
path_as_string(unmanaged_repo_absolute_path)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(!failures)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Finds repositories recursively, returning their path
|
|
||||||
fn find_repo_paths(path: &Path) -> Result<Vec<PathBuf>, String> {
|
|
||||||
let mut repos = Vec::new();
|
|
||||||
|
|
||||||
let git_dir = path.join(".git");
|
|
||||||
let git_worktree = path.join(GIT_MAIN_WORKTREE_DIRECTORY);
|
|
||||||
|
|
||||||
if git_dir.exists() || git_worktree.exists() {
|
|
||||||
repos.push(path.to_path_buf());
|
|
||||||
} else {
|
|
||||||
match fs::read_dir(path) {
|
|
||||||
Ok(contents) => {
|
|
||||||
for content in contents {
|
|
||||||
match content {
|
|
||||||
Ok(entry) => {
|
|
||||||
let path = entry.path();
|
|
||||||
if path.is_symlink() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if path.is_dir() {
|
|
||||||
match find_repo_paths(&path) {
|
|
||||||
Ok(ref mut r) => repos.append(r),
|
|
||||||
Err(error) => return Err(error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
return Err(format!("Error accessing directory: {}", e));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
return Err(format!(
|
|
||||||
"Failed to open \"{}\": {}",
|
|
||||||
&path.display(),
|
|
||||||
match e.kind() {
|
|
||||||
std::io::ErrorKind::NotADirectory =>
|
|
||||||
String::from("directory expected, but path is not a directory"),
|
|
||||||
std::io::ErrorKind::NotFound => String::from("not found"),
|
|
||||||
_ => format!("{:?}", e.kind()),
|
|
||||||
}
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(repos)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_actual_git_directory(path: &Path, is_worktree: bool) -> PathBuf {
|
|
||||||
match is_worktree {
|
|
||||||
false => path.to_path_buf(),
|
|
||||||
true => path.join(GIT_MAIN_WORKTREE_DIRECTORY),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Find all git repositories under root, recursively
|
/// Find all git repositories under root, recursively
|
||||||
///
|
///
|
||||||
/// The bool in the return value specifies whether there is a repository
|
/// The bool in the return value specifies whether there is a repository
|
||||||
/// in root itself.
|
/// in root itself.
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, String> {
|
fn find_repos(root: &Path) -> Result<Option<(Vec<repo::Repo>, Vec<String>, bool)>, String> {
|
||||||
let mut repos: Vec<Repo> = Vec::new();
|
let mut repos: Vec<repo::Repo> = Vec::new();
|
||||||
let mut repo_in_root = false;
|
let mut repo_in_root = false;
|
||||||
let mut warnings = Vec::new();
|
let mut warnings = Vec::new();
|
||||||
|
|
||||||
for path in find_repo_paths(root)? {
|
for path in tree::find_repo_paths(root)? {
|
||||||
let is_worktree = RepoHandle::detect_worktree(&path);
|
let is_worktree = repo::RepoHandle::detect_worktree(&path);
|
||||||
if path == root {
|
if path == root {
|
||||||
repo_in_root = true;
|
repo_in_root = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
match RepoHandle::open(&path, is_worktree) {
|
match repo::RepoHandle::open(&path, is_worktree) {
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
warnings.push(format!(
|
warnings.push(format!(
|
||||||
"Error opening repo {}{}: {}",
|
"Error opening repo {}{}: {}",
|
||||||
@@ -436,32 +50,32 @@ fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, Str
|
|||||||
Err(error) => {
|
Err(error) => {
|
||||||
warnings.push(format!(
|
warnings.push(format!(
|
||||||
"{}: Error getting remotes: {}",
|
"{}: Error getting remotes: {}",
|
||||||
&path_as_string(&path),
|
&path::path_as_string(&path),
|
||||||
error
|
error
|
||||||
));
|
));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut results: Vec<Remote> = Vec::new();
|
let mut results: Vec<repo::Remote> = Vec::new();
|
||||||
for remote_name in remotes.iter() {
|
for remote_name in remotes.iter() {
|
||||||
match repo.find_remote(remote_name)? {
|
match repo.find_remote(remote_name)? {
|
||||||
Some(remote) => {
|
Some(remote) => {
|
||||||
let name = remote.name();
|
let name = remote.name();
|
||||||
let url = remote.url();
|
let url = remote.url();
|
||||||
let remote_type = match detect_remote_type(&url) {
|
let remote_type = match repo::detect_remote_type(&url) {
|
||||||
Some(t) => t,
|
Some(t) => t,
|
||||||
None => {
|
None => {
|
||||||
warnings.push(format!(
|
warnings.push(format!(
|
||||||
"{}: Could not detect remote type of \"{}\"",
|
"{}: Could not detect remote type of \"{}\"",
|
||||||
&path_as_string(&path),
|
&path::path_as_string(&path),
|
||||||
&url
|
&url
|
||||||
));
|
));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
results.push(Remote {
|
results.push(repo::Remote {
|
||||||
name,
|
name,
|
||||||
url,
|
url,
|
||||||
remote_type,
|
remote_type,
|
||||||
@@ -470,7 +84,7 @@ fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, Str
|
|||||||
None => {
|
None => {
|
||||||
warnings.push(format!(
|
warnings.push(format!(
|
||||||
"{}: Remote {} not found",
|
"{}: Remote {} not found",
|
||||||
&path_as_string(&path),
|
&path::path_as_string(&path),
|
||||||
remote_name
|
remote_name
|
||||||
));
|
));
|
||||||
continue;
|
continue;
|
||||||
@@ -483,7 +97,9 @@ fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, Str
|
|||||||
(
|
(
|
||||||
None,
|
None,
|
||||||
match &root.parent() {
|
match &root.parent() {
|
||||||
Some(parent) => path_as_string(path.strip_prefix(parent).unwrap()),
|
Some(parent) => {
|
||||||
|
path::path_as_string(path.strip_prefix(parent).unwrap())
|
||||||
|
}
|
||||||
None => {
|
None => {
|
||||||
warnings.push(String::from("Getting name of the search root failed. Do you have a git repository in \"/\"?"));
|
warnings.push(String::from("Getting name of the search root failed. Do you have a git repository in \"/\"?"));
|
||||||
continue;
|
continue;
|
||||||
@@ -495,15 +111,15 @@ fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, Str
|
|||||||
let namespace = name.parent().unwrap();
|
let namespace = name.parent().unwrap();
|
||||||
(
|
(
|
||||||
if namespace != Path::new("") {
|
if namespace != Path::new("") {
|
||||||
Some(path_as_string(namespace).to_string())
|
Some(path::path_as_string(namespace).to_string())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
path_as_string(name),
|
path::path_as_string(name),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
repos.push(Repo {
|
repos.push(repo::Repo {
|
||||||
name,
|
name,
|
||||||
namespace,
|
namespace,
|
||||||
remotes: Some(remotes),
|
remotes: Some(remotes),
|
||||||
@@ -515,10 +131,10 @@ fn find_repos(root: &Path) -> Result<Option<(Vec<Repo>, Vec<String>, bool)>, Str
|
|||||||
Ok(Some((repos, warnings, repo_in_root)))
|
Ok(Some((repos, warnings, repo_in_root)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_in_tree(path: &Path) -> Result<(Tree, Vec<String>), String> {
|
pub fn find_in_tree(path: &Path) -> Result<(tree::Tree, Vec<String>), String> {
|
||||||
let mut warnings = Vec::new();
|
let mut warnings = Vec::new();
|
||||||
|
|
||||||
let (repos, repo_in_root): (Vec<Repo>, bool) = match find_repos(path)? {
|
let (repos, repo_in_root): (Vec<repo::Repo>, bool) = match find_repos(path)? {
|
||||||
Some((vec, mut repo_warnings, repo_in_root)) => {
|
Some((vec, mut repo_warnings, repo_in_root)) => {
|
||||||
warnings.append(&mut repo_warnings);
|
warnings.append(&mut repo_warnings);
|
||||||
(vec, repo_in_root)
|
(vec, repo_in_root)
|
||||||
@@ -539,171 +155,10 @@ pub fn find_in_tree(path: &Path) -> Result<(Tree, Vec<String>), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok((
|
Ok((
|
||||||
Tree {
|
tree::Tree {
|
||||||
root: root.into_os_string().into_string().unwrap(),
|
root: root.into_os_string().into_string().unwrap(),
|
||||||
repos,
|
repos,
|
||||||
},
|
},
|
||||||
warnings,
|
warnings,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_worktree(
|
|
||||||
directory: &Path,
|
|
||||||
name: &str,
|
|
||||||
subdirectory: Option<&Path>,
|
|
||||||
track: Option<(&str, &str)>,
|
|
||||||
no_track: bool,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let repo = RepoHandle::open(directory, true).map_err(|error| match error.kind {
|
|
||||||
RepoErrorKind::NotFound => {
|
|
||||||
String::from("Current directory does not contain a worktree setup")
|
|
||||||
}
|
|
||||||
_ => format!("Error opening repo: {}", error),
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let config = repo::read_worktree_root_config(directory)?;
|
|
||||||
|
|
||||||
if repo.find_worktree(name).is_ok() {
|
|
||||||
return Err(format!("Worktree {} already exists", &name));
|
|
||||||
}
|
|
||||||
|
|
||||||
let path = match subdirectory {
|
|
||||||
Some(dir) => directory.join(dir).join(name),
|
|
||||||
None => directory.join(Path::new(name)),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut remote_branch_exists = false;
|
|
||||||
|
|
||||||
let default_checkout = || repo.default_branch()?.to_commit();
|
|
||||||
|
|
||||||
let checkout_commit;
|
|
||||||
if no_track {
|
|
||||||
checkout_commit = default_checkout()?;
|
|
||||||
} else {
|
|
||||||
match track {
|
|
||||||
Some((remote_name, remote_branch_name)) => {
|
|
||||||
let remote_branch = repo.find_remote_branch(remote_name, remote_branch_name);
|
|
||||||
match remote_branch {
|
|
||||||
Ok(branch) => {
|
|
||||||
remote_branch_exists = true;
|
|
||||||
checkout_commit = branch.to_commit()?;
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
remote_branch_exists = false;
|
|
||||||
checkout_commit = default_checkout()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => match &config {
|
|
||||||
None => checkout_commit = default_checkout()?,
|
|
||||||
Some(config) => match &config.track {
|
|
||||||
None => checkout_commit = default_checkout()?,
|
|
||||||
Some(track_config) => {
|
|
||||||
if track_config.default {
|
|
||||||
let remote_branch =
|
|
||||||
repo.find_remote_branch(&track_config.default_remote, name);
|
|
||||||
match remote_branch {
|
|
||||||
Ok(branch) => {
|
|
||||||
remote_branch_exists = true;
|
|
||||||
checkout_commit = branch.to_commit()?;
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
checkout_commit = default_checkout()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
checkout_commit = default_checkout()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut target_branch = match repo.find_local_branch(name) {
|
|
||||||
Ok(branchref) => branchref,
|
|
||||||
Err(_) => repo.create_branch(name, &checkout_commit)?,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn push(
|
|
||||||
remote: &mut repo::RemoteHandle,
|
|
||||||
branch_name: &str,
|
|
||||||
remote_branch_name: &str,
|
|
||||||
repo: &repo::RepoHandle,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
if !remote.is_pushable()? {
|
|
||||||
return Err(format!(
|
|
||||||
"Cannot push to non-pushable remote {}",
|
|
||||||
remote.url()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
remote.push(branch_name, remote_branch_name, repo)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !no_track {
|
|
||||||
if let Some((remote_name, remote_branch_name)) = track {
|
|
||||||
if remote_branch_exists {
|
|
||||||
target_branch.set_upstream(remote_name, remote_branch_name)?;
|
|
||||||
} else {
|
|
||||||
let mut remote = repo
|
|
||||||
.find_remote(remote_name)
|
|
||||||
.map_err(|error| format!("Error getting remote {}: {}", remote_name, error))?
|
|
||||||
.ok_or_else(|| format!("Remote {} not found", remote_name))?;
|
|
||||||
|
|
||||||
push(
|
|
||||||
&mut remote,
|
|
||||||
&target_branch.name()?,
|
|
||||||
remote_branch_name,
|
|
||||||
&repo,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
target_branch.set_upstream(remote_name, remote_branch_name)?;
|
|
||||||
}
|
|
||||||
} else if let Some(config) = config {
|
|
||||||
if let Some(track_config) = config.track {
|
|
||||||
if track_config.default {
|
|
||||||
let remote_name = track_config.default_remote;
|
|
||||||
if remote_branch_exists {
|
|
||||||
target_branch.set_upstream(&remote_name, name)?;
|
|
||||||
} else {
|
|
||||||
let remote_branch_name = match track_config.default_remote_prefix {
|
|
||||||
Some(prefix) => {
|
|
||||||
format!("{}{}{}", &prefix, BRANCH_NAMESPACE_SEPARATOR, &name)
|
|
||||||
}
|
|
||||||
None => name.to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut remote = repo
|
|
||||||
.find_remote(&remote_name)
|
|
||||||
.map_err(|error| {
|
|
||||||
format!("Error getting remote {}: {}", remote_name, error)
|
|
||||||
})?
|
|
||||||
.ok_or_else(|| format!("Remote {} not found", remote_name))?;
|
|
||||||
|
|
||||||
if !remote.is_pushable()? {
|
|
||||||
return Err(format!(
|
|
||||||
"Cannot push to non-pushable remote {}",
|
|
||||||
remote.url()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
push(
|
|
||||||
&mut remote,
|
|
||||||
&target_branch.name()?,
|
|
||||||
&remote_branch_name,
|
|
||||||
&repo,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
target_branch.set_upstream(&remote_name, &remote_branch_name)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(subdirectory) = subdirectory {
|
|
||||||
std::fs::create_dir_all(subdirectory).map_err(|error| error.to_string())?;
|
|
||||||
}
|
|
||||||
repo.new_worktree(name, &path, &target_branch)?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ pub fn print_repo_action(repo: &str, message: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn print_action(message: &str) {
|
pub fn print_action(message: &str) {
|
||||||
let stderr = Term::stderr();
|
let stdout = Term::stdout();
|
||||||
let mut style = Style::new().yellow();
|
let mut style = Style::new().yellow();
|
||||||
if stderr.is_term() {
|
if stdout.is_term() {
|
||||||
style = style.force_styling(true);
|
style = style.force_styling(true);
|
||||||
}
|
}
|
||||||
stderr
|
stdout
|
||||||
.write_line(&format!("[{}] {}", style.apply_to('\u{2699}'), &message))
|
.write_line(&format!("[{}] {}", style.apply_to('\u{2699}'), &message))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
@@ -46,13 +46,13 @@ pub fn print_repo_success(repo: &str, message: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn print_success(message: &str) {
|
pub fn print_success(message: &str) {
|
||||||
let stderr = Term::stderr();
|
let stdout = Term::stdout();
|
||||||
let mut style = Style::new().green();
|
let mut style = Style::new().green();
|
||||||
if stderr.is_term() {
|
if stdout.is_term() {
|
||||||
style = style.force_styling(true);
|
style = style.force_styling(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
stderr
|
stdout
|
||||||
.write_line(&format!("[{}] {}", style.apply_to('\u{2714}'), &message))
|
.write_line(&format!("[{}] {}", style.apply_to('\u{2714}'), &message))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
84
src/path.rs
Normal file
84
src/path.rs
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process;
|
||||||
|
|
||||||
|
use super::output::*;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn setup() {
|
||||||
|
std::env::set_var("HOME", "/home/test");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_expand_tilde() {
|
||||||
|
setup();
|
||||||
|
assert_eq!(
|
||||||
|
expand_path(Path::new("~/file")),
|
||||||
|
Path::new("/home/test/file")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_expand_invalid_tilde() {
|
||||||
|
setup();
|
||||||
|
assert_eq!(
|
||||||
|
expand_path(Path::new("/home/~/file")),
|
||||||
|
Path::new("/home/~/file")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_expand_home() {
|
||||||
|
setup();
|
||||||
|
assert_eq!(
|
||||||
|
expand_path(Path::new("$HOME/file")),
|
||||||
|
Path::new("/home/test/file")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
expand_path(Path::new("${HOME}/file")),
|
||||||
|
Path::new("/home/test/file")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn path_as_string(path: &Path) -> String {
|
||||||
|
path.to_path_buf().into_os_string().into_string().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn env_home() -> PathBuf {
|
||||||
|
match std::env::var("HOME") {
|
||||||
|
Ok(path) => Path::new(&path).to_path_buf(),
|
||||||
|
Err(e) => {
|
||||||
|
print_error(&format!("Unable to read HOME: {}", e));
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn expand_path(path: &Path) -> PathBuf {
|
||||||
|
fn home_dir() -> Option<PathBuf> {
|
||||||
|
Some(env_home())
|
||||||
|
}
|
||||||
|
|
||||||
|
let expanded_path = match shellexpand::full_with_context(
|
||||||
|
&path_as_string(path),
|
||||||
|
home_dir,
|
||||||
|
|name| -> Result<Option<String>, &'static str> {
|
||||||
|
match name {
|
||||||
|
"HOME" => Ok(Some(path_as_string(home_dir().unwrap().as_path()))),
|
||||||
|
_ => Ok(None),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Ok(std::borrow::Cow::Borrowed(path)) => path.to_owned(),
|
||||||
|
Ok(std::borrow::Cow::Owned(path)) => path,
|
||||||
|
Err(e) => {
|
||||||
|
print_error(&format!("Unable to expand root: {}", e));
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Path::new(&expanded_path).to_path_buf()
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::auth;
|
||||||
|
use super::escape;
|
||||||
use super::ApiErrorResponse;
|
use super::ApiErrorResponse;
|
||||||
use super::Filter;
|
use super::Filter;
|
||||||
use super::JsonError;
|
use super::JsonError;
|
||||||
use super::Project;
|
use super::Project;
|
||||||
use super::Provider;
|
use super::Provider;
|
||||||
use super::SecretToken;
|
|
||||||
|
|
||||||
const PROVIDER_NAME: &str = "github";
|
|
||||||
const ACCEPT_HEADER_JSON: &str = "application/vnd.github.v3+json";
|
const ACCEPT_HEADER_JSON: &str = "application/vnd.github.v3+json";
|
||||||
const GITHUB_API_BASEURL: &str =
|
const GITHUB_API_BASEURL: &str =
|
||||||
option_env!("GITHUB_API_BASEURL").unwrap_or("https://api.github.com");
|
option_env!("GITHUB_API_BASEURL").unwrap_or("https://api.github.com");
|
||||||
@@ -66,7 +66,7 @@ impl JsonError for GithubApiErrorResponse {
|
|||||||
|
|
||||||
pub struct Github {
|
pub struct Github {
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
secret_token: SecretToken,
|
secret_token: auth::AuthToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Provider for Github {
|
impl Provider for Github {
|
||||||
@@ -75,7 +75,7 @@ impl Provider for Github {
|
|||||||
|
|
||||||
fn new(
|
fn new(
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
secret_token: SecretToken,
|
secret_token: auth::AuthToken,
|
||||||
api_url_override: Option<String>,
|
api_url_override: Option<String>,
|
||||||
) -> Result<Self, String> {
|
) -> Result<Self, String> {
|
||||||
if api_url_override.is_some() {
|
if api_url_override.is_some() {
|
||||||
@@ -87,20 +87,16 @@ impl Provider for Github {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn name(&self) -> String {
|
fn filter(&self) -> &Filter {
|
||||||
String::from(PROVIDER_NAME)
|
&self.filter
|
||||||
}
|
}
|
||||||
|
|
||||||
fn filter(&self) -> Filter {
|
fn secret_token(&self) -> &auth::AuthToken {
|
||||||
self.filter.clone()
|
&self.secret_token
|
||||||
}
|
}
|
||||||
|
|
||||||
fn secret_token(&self) -> SecretToken {
|
fn auth_header_key() -> &'static str {
|
||||||
self.secret_token.clone()
|
"token"
|
||||||
}
|
|
||||||
|
|
||||||
fn auth_header_key() -> String {
|
|
||||||
"token".to_string()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user_projects(
|
fn get_user_projects(
|
||||||
@@ -108,7 +104,7 @@ impl Provider for Github {
|
|||||||
user: &str,
|
user: &str,
|
||||||
) -> Result<Vec<GithubProject>, ApiErrorResponse<GithubApiErrorResponse>> {
|
) -> Result<Vec<GithubProject>, ApiErrorResponse<GithubApiErrorResponse>> {
|
||||||
self.call_list(
|
self.call_list(
|
||||||
&format!("{GITHUB_API_BASEURL}/users/{user}/repos"),
|
&format!("{GITHUB_API_BASEURL}/users/{}/repos", escape(user)),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -118,7 +114,7 @@ impl Provider for Github {
|
|||||||
group: &str,
|
group: &str,
|
||||||
) -> Result<Vec<GithubProject>, ApiErrorResponse<GithubApiErrorResponse>> {
|
) -> Result<Vec<GithubProject>, ApiErrorResponse<GithubApiErrorResponse>> {
|
||||||
self.call_list(
|
self.call_list(
|
||||||
&format!("{GITHUB_API_BASEURL}/orgs/{group}/repos?type=all"),
|
&format!("{GITHUB_API_BASEURL}/orgs/{}/repos?type=all", escape(group)),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -135,8 +131,8 @@ impl Provider for Github {
|
|||||||
fn get_current_user(&self) -> Result<String, ApiErrorResponse<GithubApiErrorResponse>> {
|
fn get_current_user(&self) -> Result<String, ApiErrorResponse<GithubApiErrorResponse>> {
|
||||||
Ok(super::call::<GithubUser, GithubApiErrorResponse>(
|
Ok(super::call::<GithubUser, GithubApiErrorResponse>(
|
||||||
&format!("{GITHUB_API_BASEURL}/user"),
|
&format!("{GITHUB_API_BASEURL}/user"),
|
||||||
&Self::auth_header_key(),
|
Self::auth_header_key(),
|
||||||
&self.secret_token(),
|
self.secret_token(),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)?
|
)?
|
||||||
.username)
|
.username)
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::auth;
|
||||||
|
use super::escape;
|
||||||
use super::ApiErrorResponse;
|
use super::ApiErrorResponse;
|
||||||
use super::Filter;
|
use super::Filter;
|
||||||
use super::JsonError;
|
use super::JsonError;
|
||||||
use super::Project;
|
use super::Project;
|
||||||
use super::Provider;
|
use super::Provider;
|
||||||
use super::SecretToken;
|
|
||||||
|
|
||||||
const PROVIDER_NAME: &str = "gitlab";
|
|
||||||
const ACCEPT_HEADER_JSON: &str = "application/json";
|
const ACCEPT_HEADER_JSON: &str = "application/json";
|
||||||
const GITLAB_API_BASEURL: &str = option_env!("GITLAB_API_BASEURL").unwrap_or("https://gitlab.com");
|
const GITLAB_API_BASEURL: &str = option_env!("GITLAB_API_BASEURL").unwrap_or("https://gitlab.com");
|
||||||
|
|
||||||
@@ -56,13 +56,13 @@ impl Project for GitlabProject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn private(&self) -> bool {
|
fn private(&self) -> bool {
|
||||||
matches!(self.visibility, GitlabVisibility::Private)
|
!matches!(self.visibility, GitlabVisibility::Public)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct GitlabApiErrorResponse {
|
pub struct GitlabApiErrorResponse {
|
||||||
#[serde(alias = "error_description")]
|
#[serde(alias = "error_description", alias = "error")]
|
||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +74,7 @@ impl JsonError for GitlabApiErrorResponse {
|
|||||||
|
|
||||||
pub struct Gitlab {
|
pub struct Gitlab {
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
secret_token: SecretToken,
|
secret_token: auth::AuthToken,
|
||||||
api_url_override: Option<String>,
|
api_url_override: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ impl Provider for Gitlab {
|
|||||||
|
|
||||||
fn new(
|
fn new(
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
secret_token: SecretToken,
|
secret_token: auth::AuthToken,
|
||||||
api_url_override: Option<String>,
|
api_url_override: Option<String>,
|
||||||
) -> Result<Self, String> {
|
) -> Result<Self, String> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -104,20 +104,16 @@ impl Provider for Gitlab {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn name(&self) -> String {
|
fn filter(&self) -> &Filter {
|
||||||
String::from(PROVIDER_NAME)
|
&self.filter
|
||||||
}
|
}
|
||||||
|
|
||||||
fn filter(&self) -> Filter {
|
fn secret_token(&self) -> &auth::AuthToken {
|
||||||
self.filter.clone()
|
&self.secret_token
|
||||||
}
|
}
|
||||||
|
|
||||||
fn secret_token(&self) -> SecretToken {
|
fn auth_header_key() -> &'static str {
|
||||||
self.secret_token.clone()
|
"bearer"
|
||||||
}
|
|
||||||
|
|
||||||
fn auth_header_key() -> String {
|
|
||||||
"bearer".to_string()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user_projects(
|
fn get_user_projects(
|
||||||
@@ -125,7 +121,7 @@ impl Provider for Gitlab {
|
|||||||
user: &str,
|
user: &str,
|
||||||
) -> Result<Vec<GitlabProject>, ApiErrorResponse<GitlabApiErrorResponse>> {
|
) -> Result<Vec<GitlabProject>, ApiErrorResponse<GitlabApiErrorResponse>> {
|
||||||
self.call_list(
|
self.call_list(
|
||||||
&format!("{}/api/v4/users/{}/projects", self.api_url(), user),
|
&format!("{}/api/v4/users/{}/projects", self.api_url(), escape(user)),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -138,7 +134,7 @@ impl Provider for Gitlab {
|
|||||||
&format!(
|
&format!(
|
||||||
"{}/api/v4/groups/{}/projects?include_subgroups=true&archived=false",
|
"{}/api/v4/groups/{}/projects?include_subgroups=true&archived=false",
|
||||||
self.api_url(),
|
self.api_url(),
|
||||||
group
|
escape(group),
|
||||||
),
|
),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)
|
)
|
||||||
@@ -156,8 +152,8 @@ impl Provider for Gitlab {
|
|||||||
fn get_current_user(&self) -> Result<String, ApiErrorResponse<GitlabApiErrorResponse>> {
|
fn get_current_user(&self) -> Result<String, ApiErrorResponse<GitlabApiErrorResponse>> {
|
||||||
Ok(super::call::<GitlabUser, GitlabApiErrorResponse>(
|
Ok(super::call::<GitlabUser, GitlabApiErrorResponse>(
|
||||||
&format!("{}/api/v4/user", self.api_url()),
|
&format!("{}/api/v4/user", self.api_url()),
|
||||||
&Self::auth_header_key(),
|
Self::auth_header_key(),
|
||||||
&self.secret_token(),
|
self.secret_token(),
|
||||||
Some(ACCEPT_HEADER_JSON),
|
Some(ACCEPT_HEADER_JSON),
|
||||||
)?
|
)?
|
||||||
.username)
|
.username)
|
||||||
|
|||||||
@@ -9,10 +9,13 @@ pub mod gitlab;
|
|||||||
pub use github::Github;
|
pub use github::Github;
|
||||||
pub use gitlab::Gitlab;
|
pub use gitlab::Gitlab;
|
||||||
|
|
||||||
use crate::{Remote, RemoteType, Repo};
|
use super::auth;
|
||||||
|
use super::repo;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
const DEFAULT_REMOTE_NAME: &str = "origin";
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, clap::ArgEnum, Clone)]
|
#[derive(Debug, Deserialize, Serialize, clap::ArgEnum, Clone)]
|
||||||
pub enum RemoteProvider {
|
pub enum RemoteProvider {
|
||||||
#[serde(alias = "github", alias = "GitHub")]
|
#[serde(alias = "github", alias = "GitHub")]
|
||||||
@@ -28,16 +31,25 @@ enum ProjectResponse<T, U> {
|
|||||||
Failure(U),
|
Failure(U),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn escape(s: &str) -> String {
|
||||||
|
url_escape::encode_component(s).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
pub trait Project {
|
pub trait Project {
|
||||||
fn into_repo_config(self, provider_name: &str, worktree_setup: bool, force_ssh: bool) -> Repo
|
fn into_repo_config(
|
||||||
|
self,
|
||||||
|
provider_name: &str,
|
||||||
|
worktree_setup: bool,
|
||||||
|
force_ssh: bool,
|
||||||
|
) -> repo::Repo
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
{
|
{
|
||||||
Repo {
|
repo::Repo {
|
||||||
name: self.name(),
|
name: self.name(),
|
||||||
namespace: self.namespace(),
|
namespace: self.namespace(),
|
||||||
worktree_setup,
|
worktree_setup,
|
||||||
remotes: Some(vec![Remote {
|
remotes: Some(vec![repo::Remote {
|
||||||
name: String::from(provider_name),
|
name: String::from(provider_name),
|
||||||
url: if force_ssh || self.private() {
|
url: if force_ssh || self.private() {
|
||||||
self.ssh_url()
|
self.ssh_url()
|
||||||
@@ -45,9 +57,9 @@ pub trait Project {
|
|||||||
self.http_url()
|
self.http_url()
|
||||||
},
|
},
|
||||||
remote_type: if force_ssh || self.private() {
|
remote_type: if force_ssh || self.private() {
|
||||||
RemoteType::Ssh
|
repo::RemoteType::Ssh
|
||||||
} else {
|
} else {
|
||||||
RemoteType::Https
|
repo::RemoteType::Https
|
||||||
},
|
},
|
||||||
}]),
|
}]),
|
||||||
}
|
}
|
||||||
@@ -60,8 +72,6 @@ pub trait Project {
|
|||||||
fn private(&self) -> bool;
|
fn private(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
type SecretToken = String;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Filter {
|
pub struct Filter {
|
||||||
users: Vec<String>,
|
users: Vec<String>,
|
||||||
@@ -108,16 +118,15 @@ pub trait Provider {
|
|||||||
|
|
||||||
fn new(
|
fn new(
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
secret_token: SecretToken,
|
secret_token: auth::AuthToken,
|
||||||
api_url_override: Option<String>,
|
api_url_override: Option<String>,
|
||||||
) -> Result<Self, String>
|
) -> Result<Self, String>
|
||||||
where
|
where
|
||||||
Self: Sized;
|
Self: Sized;
|
||||||
|
|
||||||
fn name(&self) -> String;
|
fn filter(&self) -> &Filter;
|
||||||
fn filter(&self) -> Filter;
|
fn secret_token(&self) -> &auth::AuthToken;
|
||||||
fn secret_token(&self) -> SecretToken;
|
fn auth_header_key() -> &'static str;
|
||||||
fn auth_header_key() -> String;
|
|
||||||
|
|
||||||
fn get_user_projects(
|
fn get_user_projects(
|
||||||
&self,
|
&self,
|
||||||
@@ -158,7 +167,11 @@ pub trait Provider {
|
|||||||
.header("accept", accept_header.unwrap_or("application/json"))
|
.header("accept", accept_header.unwrap_or("application/json"))
|
||||||
.header(
|
.header(
|
||||||
"authorization",
|
"authorization",
|
||||||
format!("{} {}", Self::auth_header_key(), &self.secret_token()),
|
format!(
|
||||||
|
"{} {}",
|
||||||
|
Self::auth_header_key(),
|
||||||
|
&self.secret_token().access()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.body(())
|
.body(())
|
||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
@@ -201,7 +214,8 @@ pub trait Provider {
|
|||||||
&self,
|
&self,
|
||||||
worktree_setup: bool,
|
worktree_setup: bool,
|
||||||
force_ssh: bool,
|
force_ssh: bool,
|
||||||
) -> Result<HashMap<Option<String>, Vec<Repo>>, String> {
|
remote_name: Option<String>,
|
||||||
|
) -> Result<HashMap<Option<String>, Vec<repo::Repo>>, String> {
|
||||||
let mut repos = vec![];
|
let mut repos = vec![];
|
||||||
|
|
||||||
if self.filter().owner {
|
if self.filter().owner {
|
||||||
@@ -278,12 +292,14 @@ pub trait Provider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut ret: HashMap<Option<String>, Vec<Repo>> = HashMap::new();
|
let mut ret: HashMap<Option<String>, Vec<repo::Repo>> = HashMap::new();
|
||||||
|
|
||||||
|
let remote_name = remote_name.unwrap_or_else(|| DEFAULT_REMOTE_NAME.to_string());
|
||||||
|
|
||||||
for repo in repos {
|
for repo in repos {
|
||||||
let namespace = repo.namespace();
|
let namespace = repo.namespace();
|
||||||
|
|
||||||
let mut repo = repo.into_repo_config(&self.name(), worktree_setup, force_ssh);
|
let mut repo = repo.into_repo_config(&remote_name, worktree_setup, force_ssh);
|
||||||
|
|
||||||
// Namespace is already part of the hashmap key. I'm not too happy
|
// Namespace is already part of the hashmap key. I'm not too happy
|
||||||
// about the data exchange format here.
|
// about the data exchange format here.
|
||||||
@@ -299,7 +315,7 @@ pub trait Provider {
|
|||||||
fn call<T, U>(
|
fn call<T, U>(
|
||||||
uri: &str,
|
uri: &str,
|
||||||
auth_header_key: &str,
|
auth_header_key: &str,
|
||||||
secret_token: &str,
|
secret_token: &auth::AuthToken,
|
||||||
accept_header: Option<&str>,
|
accept_header: Option<&str>,
|
||||||
) -> Result<T, ApiErrorResponse<U>>
|
) -> Result<T, ApiErrorResponse<U>>
|
||||||
where
|
where
|
||||||
@@ -313,7 +329,7 @@ where
|
|||||||
.header("accept", accept_header.unwrap_or("application/json"))
|
.header("accept", accept_header.unwrap_or("application/json"))
|
||||||
.header(
|
.header(
|
||||||
"authorization",
|
"authorization",
|
||||||
format!("{} {}", &auth_header_key, &secret_token),
|
format!("{} {}", &auth_header_key, &secret_token.access()),
|
||||||
)
|
)
|
||||||
.body(())
|
.body(())
|
||||||
.map_err(|error| ApiErrorResponse::String(error.to_string()))?;
|
.map_err(|error| ApiErrorResponse::String(error.to_string()))?;
|
||||||
|
|||||||
169
src/repo.rs
169
src/repo.rs
@@ -3,9 +3,13 @@ use std::path::Path;
|
|||||||
|
|
||||||
use git2::Repository;
|
use git2::Repository;
|
||||||
|
|
||||||
use crate::output::*;
|
use super::output::*;
|
||||||
|
use super::path;
|
||||||
|
use super::worktree;
|
||||||
|
|
||||||
const WORKTREE_CONFIG_FILE_NAME: &str = "grm.toml";
|
const WORKTREE_CONFIG_FILE_NAME: &str = "grm.toml";
|
||||||
|
const GIT_CONFIG_BARE_KEY: &str = "core.bare";
|
||||||
|
const GIT_CONFIG_PUSH_DEFAULT: &str = "push.default";
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
@@ -506,7 +510,7 @@ impl RepoHandle {
|
|||||||
false => Repository::open,
|
false => Repository::open,
|
||||||
};
|
};
|
||||||
let path = match is_worktree {
|
let path = match is_worktree {
|
||||||
true => path.join(crate::GIT_MAIN_WORKTREE_DIRECTORY),
|
true => path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY),
|
||||||
false => path.to_path_buf(),
|
false => path.to_path_buf(),
|
||||||
};
|
};
|
||||||
match open_func(path) {
|
match open_func(path) {
|
||||||
@@ -655,6 +659,14 @@ impl RepoHandle {
|
|||||||
.collect::<Result<Vec<Branch>, String>>()
|
.collect::<Result<Vec<Branch>, String>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn remote_branches(&self) -> Result<Vec<Branch>, String> {
|
||||||
|
self.0
|
||||||
|
.branches(Some(git2::BranchType::Remote))
|
||||||
|
.map_err(convert_libgit2_error)?
|
||||||
|
.map(|branch| Ok(Branch(branch.map_err(convert_libgit2_error)?.0)))
|
||||||
|
.collect::<Result<Vec<Branch>, String>>()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn fetch(&self, remote_name: &str) -> Result<(), String> {
|
pub fn fetch(&self, remote_name: &str) -> Result<(), String> {
|
||||||
let mut remote = self
|
let mut remote = self
|
||||||
.0
|
.0
|
||||||
@@ -679,7 +691,7 @@ impl RepoHandle {
|
|||||||
pub fn init(path: &Path, is_worktree: bool) -> Result<Self, String> {
|
pub fn init(path: &Path, is_worktree: bool) -> Result<Self, String> {
|
||||||
let repo = match is_worktree {
|
let repo = match is_worktree {
|
||||||
false => Repository::init(path).map_err(convert_libgit2_error)?,
|
false => Repository::init(path).map_err(convert_libgit2_error)?,
|
||||||
true => Repository::init_bare(path.join(crate::GIT_MAIN_WORKTREE_DIRECTORY))
|
true => Repository::init_bare(path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY))
|
||||||
.map_err(convert_libgit2_error)?,
|
.map_err(convert_libgit2_error)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -742,8 +754,8 @@ impl RepoHandle {
|
|||||||
let mut config = self.config()?;
|
let mut config = self.config()?;
|
||||||
|
|
||||||
config
|
config
|
||||||
.set_bool(crate::GIT_CONFIG_BARE_KEY, value)
|
.set_bool(GIT_CONFIG_BARE_KEY, value)
|
||||||
.map_err(|error| format!("Could not set {}: {}", crate::GIT_CONFIG_BARE_KEY, error))
|
.map_err(|error| format!("Could not set {}: {}", GIT_CONFIG_BARE_KEY, error))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn convert_to_worktree(
|
pub fn convert_to_worktree(
|
||||||
@@ -766,7 +778,7 @@ impl RepoHandle {
|
|||||||
return Err(WorktreeConversionFailureReason::Ignored);
|
return Err(WorktreeConversionFailureReason::Ignored);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::fs::rename(".git", crate::GIT_MAIN_WORKTREE_DIRECTORY).map_err(|error| {
|
std::fs::rename(".git", worktree::GIT_MAIN_WORKTREE_DIRECTORY).map_err(|error| {
|
||||||
WorktreeConversionFailureReason::Error(format!(
|
WorktreeConversionFailureReason::Error(format!(
|
||||||
"Error moving .git directory: {}",
|
"Error moving .git directory: {}",
|
||||||
error
|
error
|
||||||
@@ -786,7 +798,7 @@ impl RepoHandle {
|
|||||||
Ok(entry) => {
|
Ok(entry) => {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
// unwrap is safe here, the path will ALWAYS have a file component
|
// unwrap is safe here, the path will ALWAYS have a file component
|
||||||
if path.file_name().unwrap() == crate::GIT_MAIN_WORKTREE_DIRECTORY {
|
if path.file_name().unwrap() == worktree::GIT_MAIN_WORKTREE_DIRECTORY {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if path.is_file() || path.is_symlink() {
|
if path.is_file() || path.is_symlink() {
|
||||||
@@ -835,18 +847,12 @@ impl RepoHandle {
|
|||||||
|
|
||||||
config
|
config
|
||||||
.set_str(
|
.set_str(
|
||||||
crate::GIT_CONFIG_PUSH_DEFAULT,
|
GIT_CONFIG_PUSH_DEFAULT,
|
||||||
match value {
|
match value {
|
||||||
GitPushDefaultSetting::Upstream => "upstream",
|
GitPushDefaultSetting::Upstream => "upstream",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.map_err(|error| {
|
.map_err(|error| format!("Could not set {}: {}", GIT_CONFIG_PUSH_DEFAULT, error))
|
||||||
format!(
|
|
||||||
"Could not set {}: {}",
|
|
||||||
crate::GIT_CONFIG_PUSH_DEFAULT,
|
|
||||||
error
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_untracked_files(&self, is_worktree: bool) -> Result<bool, String> {
|
pub fn has_untracked_files(&self, is_worktree: bool) -> Result<bool, String> {
|
||||||
@@ -1036,16 +1042,82 @@ impl RepoHandle {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn default_branch(&self) -> Result<Branch, String> {
|
pub fn get_remote_default_branch(&self, remote_name: &str) -> Result<Option<Branch>, String> {
|
||||||
match self.0.find_branch("main", git2::BranchType::Local) {
|
// libgit2's `git_remote_default_branch()` and `Remote::default_branch()`
|
||||||
Ok(branch) => Ok(Branch(branch)),
|
// need an actual connection to the remote, so they may fail.
|
||||||
Err(_) => match self.0.find_branch("master", git2::BranchType::Local) {
|
if let Some(mut remote) = self.find_remote(remote_name)? {
|
||||||
Ok(branch) => Ok(Branch(branch)),
|
if remote.connected() {
|
||||||
Err(_) => Err(String::from("Could not determine default branch")),
|
let remote = remote; // unmut
|
||||||
},
|
if let Ok(remote_default_branch) = remote.default_branch() {
|
||||||
|
return Ok(Some(self.find_local_branch(&remote_default_branch)?));
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Note that <remote>/HEAD only exists after a normal clone, there is no way to get the
|
||||||
|
// remote HEAD afterwards. So this is a "best effort" approach.
|
||||||
|
if let Ok(remote_head) = self.find_remote_branch(remote_name, "HEAD") {
|
||||||
|
if let Some(pointer_name) = remote_head.as_reference().symbolic_target() {
|
||||||
|
if let Some(local_branch_name) =
|
||||||
|
pointer_name.strip_prefix(&format!("refs/remotes/{}/", remote_name))
|
||||||
|
{
|
||||||
|
return Ok(Some(self.find_local_branch(local_branch_name)?));
|
||||||
|
} else {
|
||||||
|
eprintln!("Remote HEAD ({}) pointer is invalid", pointer_name);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("Remote HEAD does not point to a symbolic target");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn default_branch(&self) -> Result<Branch, String> {
|
||||||
|
// This is a bit of a guessing game.
|
||||||
|
//
|
||||||
|
// In the best case, there is only one remote. Then, we can check <remote>/HEAD to get the
|
||||||
|
// default remote branch.
|
||||||
|
//
|
||||||
|
// If there are multiple remotes, we first check whether they all have the same
|
||||||
|
// <remote>/HEAD branch. If yes, good! If not, we use whatever "origin" uses, if that
|
||||||
|
// exists. If it does not, there is no way to reliably get a remote default branch.
|
||||||
|
//
|
||||||
|
// In this case, we just try to guess a local branch from a list. If even that does not
|
||||||
|
// work, well, bad luck.
|
||||||
|
let remotes = self.remotes()?;
|
||||||
|
|
||||||
|
if remotes.len() == 1 {
|
||||||
|
let remote_name = &remotes[0];
|
||||||
|
if let Some(default_branch) = self.get_remote_default_branch(remote_name)? {
|
||||||
|
return Ok(default_branch);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let mut default_branches: Vec<Branch> = vec![];
|
||||||
|
for remote_name in remotes {
|
||||||
|
if let Some(default_branch) = self.get_remote_default_branch(&remote_name)? {
|
||||||
|
default_branches.push(default_branch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !default_branches.is_empty()
|
||||||
|
&& (default_branches.len() == 1
|
||||||
|
|| default_branches
|
||||||
|
.windows(2)
|
||||||
|
.all(|w| w[0].name() == w[1].name()))
|
||||||
|
{
|
||||||
|
return Ok(default_branches.remove(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for branch_name in &vec!["main", "master"] {
|
||||||
|
if let Ok(branch) = self.0.find_branch(branch_name, git2::BranchType::Local) {
|
||||||
|
return Ok(Branch(branch));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(String::from("Could not determine default branch"))
|
||||||
|
}
|
||||||
|
|
||||||
// Looks like there is no distinguishing between the error cases
|
// Looks like there is no distinguishing between the error cases
|
||||||
// "no such remote" and "failed to get remote for some reason".
|
// "no such remote" and "failed to get remote for some reason".
|
||||||
// May be a good idea to handle this explicitly, by returning a
|
// May be a good idea to handle this explicitly, by returning a
|
||||||
@@ -1105,10 +1177,10 @@ impl RepoHandle {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
if branch_name != name
|
if branch_name != name
|
||||||
&& !branch_name.ends_with(&format!("{}{}", crate::BRANCH_NAMESPACE_SEPARATOR, name))
|
&& !branch_name.ends_with(&format!("{}{}", super::BRANCH_NAMESPACE_SEPARATOR, name))
|
||||||
{
|
{
|
||||||
return Err(WorktreeRemoveFailureReason::Error(format!(
|
return Err(WorktreeRemoveFailureReason::Error(format!(
|
||||||
"Branch {} is checked out in worktree, this does not look correct",
|
"Branch \"{}\" is checked out in worktree, this does not look correct",
|
||||||
&branch_name
|
&branch_name
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
@@ -1275,7 +1347,7 @@ impl RepoHandle {
|
|||||||
|
|
||||||
let mut unmanaged_worktrees = Vec::new();
|
let mut unmanaged_worktrees = Vec::new();
|
||||||
for entry in std::fs::read_dir(&directory).map_err(|error| error.to_string())? {
|
for entry in std::fs::read_dir(&directory).map_err(|error| error.to_string())? {
|
||||||
let dirname = crate::path_as_string(
|
let dirname = path::path_as_string(
|
||||||
entry
|
entry
|
||||||
.map_err(|error| error.to_string())?
|
.map_err(|error| error.to_string())?
|
||||||
.path()
|
.path()
|
||||||
@@ -1308,7 +1380,7 @@ impl RepoHandle {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if dirname == crate::GIT_MAIN_WORKTREE_DIRECTORY {
|
if dirname == worktree::GIT_MAIN_WORKTREE_DIRECTORY {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if dirname == WORKTREE_CONFIG_FILE_NAME {
|
if dirname == WORKTREE_CONFIG_FILE_NAME {
|
||||||
@@ -1327,7 +1399,7 @@ impl RepoHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn detect_worktree(path: &Path) -> bool {
|
pub fn detect_worktree(path: &Path) -> bool {
|
||||||
path.join(crate::GIT_MAIN_WORKTREE_DIRECTORY).exists()
|
path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY).exists()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1396,6 +1468,15 @@ impl Branch<'_> {
|
|||||||
self.0.delete().map_err(convert_libgit2_error)
|
self.0.delete().map_err(convert_libgit2_error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn basename(&self) -> Result<String, String> {
|
||||||
|
let name = self.name()?;
|
||||||
|
if let Some((_prefix, basename)) = name.split_once('/') {
|
||||||
|
Ok(basename.to_string())
|
||||||
|
} else {
|
||||||
|
Ok(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// only used internally in this module, exposes libgit2 details
|
// only used internally in this module, exposes libgit2 details
|
||||||
fn as_reference(&self) -> &git2::Reference {
|
fn as_reference(&self) -> &git2::Reference {
|
||||||
self.0.get()
|
self.0.get()
|
||||||
@@ -1441,6 +1522,20 @@ impl RemoteHandle<'_> {
|
|||||||
.to_string()
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn connected(&mut self) -> bool {
|
||||||
|
self.0.connected()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn default_branch(&self) -> Result<String, String> {
|
||||||
|
Ok(self
|
||||||
|
.0
|
||||||
|
.default_branch()
|
||||||
|
.map_err(convert_libgit2_error)?
|
||||||
|
.as_str()
|
||||||
|
.expect("Remote branch name is not valid utf-8")
|
||||||
|
.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_pushable(&self) -> Result<bool, String> {
|
pub fn is_pushable(&self) -> Result<bool, String> {
|
||||||
let remote_type = detect_remote_type(self.0.url().expect("Remote name is not valid utf-8"))
|
let remote_type = detect_remote_type(self.0.url().expect("Remote name is not valid utf-8"))
|
||||||
.ok_or_else(|| String::from("Could not detect remote type"))?;
|
.ok_or_else(|| String::from("Could not detect remote type"))?;
|
||||||
@@ -1486,7 +1581,7 @@ pub fn clone_repo(
|
|||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let clone_target = match is_worktree {
|
let clone_target = match is_worktree {
|
||||||
false => path.to_path_buf(),
|
false => path.to_path_buf(),
|
||||||
true => path.join(crate::GIT_MAIN_WORKTREE_DIRECTORY),
|
true => path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY),
|
||||||
};
|
};
|
||||||
|
|
||||||
print_action(&format!(
|
print_action(&format!(
|
||||||
@@ -1531,6 +1626,24 @@ pub fn clone_repo(
|
|||||||
repo.rename_remote(&origin, &remote.name)?;
|
repo.rename_remote(&origin, &remote.name)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialize local branches. For all remote branches, we set up local
|
||||||
|
// tracking branches with the same name (just without the remote prefix).
|
||||||
|
for remote_branch in repo.remote_branches()? {
|
||||||
|
let local_branch_name = remote_branch.basename()?;
|
||||||
|
|
||||||
|
if repo.find_local_branch(&local_branch_name).is_ok() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore <remote>/HEAD, as this is not something we can check out
|
||||||
|
if local_branch_name == "HEAD" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut local_branch = repo.create_branch(&local_branch_name, &remote_branch.commit()?)?;
|
||||||
|
local_branch.set_upstream(&remote.name, &local_branch_name)?;
|
||||||
|
}
|
||||||
|
|
||||||
// If there is no head_branch, we most likely cloned an empty repository and
|
// If there is no head_branch, we most likely cloned an empty repository and
|
||||||
// there is no point in setting any upstreams.
|
// there is no point in setting any upstreams.
|
||||||
if let Ok(mut active_branch) = repo.head_branch() {
|
if let Ok(mut active_branch) = repo.head_branch() {
|
||||||
|
|||||||
38
src/table.rs
38
src/table.rs
@@ -1,4 +1,6 @@
|
|||||||
use crate::RepoHandle;
|
use super::config;
|
||||||
|
use super::path;
|
||||||
|
use super::repo;
|
||||||
|
|
||||||
use comfy_table::{Cell, Table};
|
use comfy_table::{Cell, Table};
|
||||||
|
|
||||||
@@ -21,7 +23,7 @@ fn add_table_header(table: &mut Table) {
|
|||||||
fn add_repo_status(
|
fn add_repo_status(
|
||||||
table: &mut Table,
|
table: &mut Table,
|
||||||
repo_name: &str,
|
repo_name: &str,
|
||||||
repo_handle: &crate::RepoHandle,
|
repo_handle: &repo::RepoHandle,
|
||||||
is_worktree: bool,
|
is_worktree: bool,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let repo_status = repo_handle.status(is_worktree)?;
|
let repo_status = repo_handle.status(is_worktree)?;
|
||||||
@@ -65,11 +67,11 @@ fn add_repo_status(
|
|||||||
" <{}>{}",
|
" <{}>{}",
|
||||||
remote_branch_name,
|
remote_branch_name,
|
||||||
&match remote_tracking_status {
|
&match remote_tracking_status {
|
||||||
crate::RemoteTrackingStatus::UpToDate =>
|
repo::RemoteTrackingStatus::UpToDate =>
|
||||||
String::from(" \u{2714}"),
|
String::from(" \u{2714}"),
|
||||||
crate::RemoteTrackingStatus::Ahead(d) => format!(" [+{}]", &d),
|
repo::RemoteTrackingStatus::Ahead(d) => format!(" [+{}]", &d),
|
||||||
crate::RemoteTrackingStatus::Behind(d) => format!(" [-{}]", &d),
|
repo::RemoteTrackingStatus::Behind(d) => format!(" [-{}]", &d),
|
||||||
crate::RemoteTrackingStatus::Diverged(d1, d2) =>
|
repo::RemoteTrackingStatus::Diverged(d1, d2) =>
|
||||||
format!(" [+{}/-{}]", &d1, &d2),
|
format!(" [+{}/-{}]", &d1, &d2),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -99,7 +101,7 @@ fn add_repo_status(
|
|||||||
|
|
||||||
// Don't return table, return a type that implements Display(?)
|
// Don't return table, return a type that implements Display(?)
|
||||||
pub fn get_worktree_status_table(
|
pub fn get_worktree_status_table(
|
||||||
repo: &crate::RepoHandle,
|
repo: &repo::RepoHandle,
|
||||||
directory: &Path,
|
directory: &Path,
|
||||||
) -> Result<(impl std::fmt::Display, Vec<String>), String> {
|
) -> Result<(impl std::fmt::Display, Vec<String>), String> {
|
||||||
let worktrees = repo.get_worktrees()?;
|
let worktrees = repo.get_worktrees()?;
|
||||||
@@ -111,7 +113,7 @@ pub fn get_worktree_status_table(
|
|||||||
for worktree in &worktrees {
|
for worktree in &worktrees {
|
||||||
let worktree_dir = &directory.join(&worktree.name());
|
let worktree_dir = &directory.join(&worktree.name());
|
||||||
if worktree_dir.exists() {
|
if worktree_dir.exists() {
|
||||||
let repo = match crate::RepoHandle::open(worktree_dir, false) {
|
let repo = match repo::RepoHandle::open(worktree_dir, false) {
|
||||||
Ok(repo) => repo,
|
Ok(repo) => repo,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
@@ -132,7 +134,7 @@ pub fn get_worktree_status_table(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for worktree in RepoHandle::find_unmanaged_worktrees(repo, directory)? {
|
for worktree in repo::RepoHandle::find_unmanaged_worktrees(repo, directory)? {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
"Found {}, which is not a valid worktree directory!",
|
"Found {}, which is not a valid worktree directory!",
|
||||||
&worktree
|
&worktree
|
||||||
@@ -141,13 +143,13 @@ pub fn get_worktree_status_table(
|
|||||||
Ok((table, errors))
|
Ok((table, errors))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_status_table(config: crate::Config) -> Result<(Vec<Table>, Vec<String>), String> {
|
pub fn get_status_table(config: config::Config) -> Result<(Vec<Table>, Vec<String>), String> {
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
let mut tables = Vec::new();
|
let mut tables = Vec::new();
|
||||||
for tree in config.trees()? {
|
for tree in config.trees()? {
|
||||||
let repos = tree.repos.unwrap_or_default();
|
let repos = tree.repos.unwrap_or_default();
|
||||||
|
|
||||||
let root_path = crate::expand_path(Path::new(&tree.root));
|
let root_path = path::expand_path(Path::new(&tree.root));
|
||||||
|
|
||||||
let mut table = Table::new();
|
let mut table = Table::new();
|
||||||
add_table_header(&mut table);
|
add_table_header(&mut table);
|
||||||
@@ -163,12 +165,12 @@ pub fn get_status_table(config: crate::Config) -> Result<(Vec<Table>, Vec<String
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let repo_handle = crate::RepoHandle::open(&repo_path, repo.worktree_setup);
|
let repo_handle = repo::RepoHandle::open(&repo_path, repo.worktree_setup);
|
||||||
|
|
||||||
let repo_handle = match repo_handle {
|
let repo_handle = match repo_handle {
|
||||||
Ok(repo) => repo,
|
Ok(repo) => repo,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
if error.kind == crate::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
"{}: No git repository found. Run sync?",
|
"{}: No git repository found. Run sync?",
|
||||||
&repo.name
|
&repo.name
|
||||||
@@ -206,8 +208,8 @@ fn add_worktree_table_header(table: &mut Table) {
|
|||||||
|
|
||||||
fn add_worktree_status(
|
fn add_worktree_status(
|
||||||
table: &mut Table,
|
table: &mut Table,
|
||||||
worktree: &crate::repo::Worktree,
|
worktree: &repo::Worktree,
|
||||||
repo: &crate::RepoHandle,
|
repo: &repo::RepoHandle,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let repo_status = repo.status(false)?;
|
let repo_status = repo.status(false)?;
|
||||||
|
|
||||||
@@ -272,13 +274,13 @@ pub fn show_single_repo_status(
|
|||||||
let mut table = Table::new();
|
let mut table = Table::new();
|
||||||
let mut warnings = Vec::new();
|
let mut warnings = Vec::new();
|
||||||
|
|
||||||
let is_worktree = crate::RepoHandle::detect_worktree(path);
|
let is_worktree = repo::RepoHandle::detect_worktree(path);
|
||||||
add_table_header(&mut table);
|
add_table_header(&mut table);
|
||||||
|
|
||||||
let repo_handle = crate::RepoHandle::open(path, is_worktree);
|
let repo_handle = repo::RepoHandle::open(path, is_worktree);
|
||||||
|
|
||||||
if let Err(error) = repo_handle {
|
if let Err(error) = repo_handle {
|
||||||
if error.kind == crate::RepoErrorKind::NotFound {
|
if error.kind == repo::RepoErrorKind::NotFound {
|
||||||
return Err(String::from("Directory is not a git directory"));
|
return Err(String::from("Directory is not a git directory"));
|
||||||
} else {
|
} else {
|
||||||
return Err(format!("Opening repository failed: {}", error));
|
return Err(format!("Opening repository failed: {}", error));
|
||||||
|
|||||||
296
src/tree.rs
Normal file
296
src/tree.rs
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use super::config;
|
||||||
|
use super::output::*;
|
||||||
|
use super::path;
|
||||||
|
use super::repo;
|
||||||
|
use super::worktree;
|
||||||
|
|
||||||
|
pub struct Tree {
|
||||||
|
pub root: String,
|
||||||
|
pub repos: Vec<repo::Repo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_unmanaged_repos(
|
||||||
|
root_path: &Path,
|
||||||
|
managed_repos: &[repo::Repo],
|
||||||
|
) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let mut unmanaged_repos = Vec::new();
|
||||||
|
|
||||||
|
for repo_path in find_repo_paths(root_path)? {
|
||||||
|
if !managed_repos
|
||||||
|
.iter()
|
||||||
|
.any(|r| Path::new(root_path).join(r.fullname()) == repo_path)
|
||||||
|
{
|
||||||
|
unmanaged_repos.push(repo_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(unmanaged_repos)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_trees(config: config::Config, init_worktree: bool) -> Result<bool, String> {
|
||||||
|
let mut failures = false;
|
||||||
|
|
||||||
|
let mut unmanaged_repos_absolute_paths = vec![];
|
||||||
|
let mut managed_repos_absolute_paths = vec![];
|
||||||
|
|
||||||
|
let trees = config.trees()?;
|
||||||
|
|
||||||
|
for tree in trees {
|
||||||
|
let repos: Vec<repo::Repo> = tree
|
||||||
|
.repos
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(|repo| repo.into_repo())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let root_path = path::expand_path(Path::new(&tree.root));
|
||||||
|
|
||||||
|
for repo in &repos {
|
||||||
|
managed_repos_absolute_paths.push(root_path.join(repo.fullname()));
|
||||||
|
match sync_repo(&root_path, repo, init_worktree) {
|
||||||
|
Ok(_) => print_repo_success(&repo.name, "OK"),
|
||||||
|
Err(error) => {
|
||||||
|
print_repo_error(&repo.name, &error);
|
||||||
|
failures = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match find_unmanaged_repos(&root_path, &repos) {
|
||||||
|
Ok(repos) => {
|
||||||
|
unmanaged_repos_absolute_paths.extend(repos);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
print_error(&format!("Error getting unmanaged repos: {}", error));
|
||||||
|
failures = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for unmanaged_repo_absolute_path in &unmanaged_repos_absolute_paths {
|
||||||
|
if managed_repos_absolute_paths
|
||||||
|
.iter()
|
||||||
|
.any(|managed_repo_absolute_path| {
|
||||||
|
managed_repo_absolute_path == unmanaged_repo_absolute_path
|
||||||
|
})
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
print_warning(&format!(
|
||||||
|
"Found unmanaged repository: \"{}\"",
|
||||||
|
path::path_as_string(unmanaged_repo_absolute_path)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(!failures)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds repositories recursively, returning their path
|
||||||
|
pub fn find_repo_paths(path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let mut repos = Vec::new();
|
||||||
|
|
||||||
|
let git_dir = path.join(".git");
|
||||||
|
let git_worktree = path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY);
|
||||||
|
|
||||||
|
if git_dir.exists() || git_worktree.exists() {
|
||||||
|
repos.push(path.to_path_buf());
|
||||||
|
} else {
|
||||||
|
match fs::read_dir(path) {
|
||||||
|
Ok(contents) => {
|
||||||
|
for content in contents {
|
||||||
|
match content {
|
||||||
|
Ok(entry) => {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_symlink() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if path.is_dir() {
|
||||||
|
match find_repo_paths(&path) {
|
||||||
|
Ok(ref mut r) => repos.append(r),
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(format!("Error accessing directory: {}", e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(format!(
|
||||||
|
"Failed to open \"{}\": {}",
|
||||||
|
&path.display(),
|
||||||
|
match e.kind() {
|
||||||
|
std::io::ErrorKind::NotADirectory =>
|
||||||
|
String::from("directory expected, but path is not a directory"),
|
||||||
|
std::io::ErrorKind::NotFound => String::from("not found"),
|
||||||
|
_ => format!("{:?}", e.kind()),
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(repos)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_repo(root_path: &Path, repo: &repo::Repo, init_worktree: bool) -> Result<(), String> {
|
||||||
|
let repo_path = root_path.join(&repo.fullname());
|
||||||
|
let actual_git_directory = get_actual_git_directory(&repo_path, repo.worktree_setup);
|
||||||
|
|
||||||
|
let mut newly_created = false;
|
||||||
|
|
||||||
|
// Syncing a repository can have a few different flows, depending on the repository
|
||||||
|
// that is to be cloned and the local directory:
|
||||||
|
//
|
||||||
|
// * If the local directory already exists, we have to make sure that it matches the
|
||||||
|
// worktree configuration, as there is no way to convert. If the sync is supposed
|
||||||
|
// to be worktree-aware, but the local directory is not, we abort. Note that we could
|
||||||
|
// also automatically convert here. In any case, the other direction (converting a
|
||||||
|
// worktree repository to non-worktree) cannot work, as we'd have to throw away the
|
||||||
|
// worktrees.
|
||||||
|
//
|
||||||
|
// * If the local directory does not yet exist, we have to actually do something ;). If
|
||||||
|
// no remote is specified, we just initialize a new repository (git init) and are done.
|
||||||
|
//
|
||||||
|
// If there are (potentially multiple) remotes configured, we have to clone. We assume
|
||||||
|
// that the first remote is the canonical one that we do the first clone from. After
|
||||||
|
// cloning, we just add the other remotes as usual (as if they were added to the config
|
||||||
|
// afterwards)
|
||||||
|
//
|
||||||
|
// Branch handling:
|
||||||
|
//
|
||||||
|
// Handling the branches on checkout is a bit magic. For minimum surprises, we just set
|
||||||
|
// up local tracking branches for all remote branches.
|
||||||
|
if repo_path.exists()
|
||||||
|
&& repo_path
|
||||||
|
.read_dir()
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
|
.next()
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
if repo.worktree_setup && !actual_git_directory.exists() {
|
||||||
|
return Err(String::from(
|
||||||
|
"Repo already exists, but is not using a worktree setup",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
} else if matches!(&repo.remotes, None) || repo.remotes.as_ref().unwrap().is_empty() {
|
||||||
|
print_repo_action(
|
||||||
|
&repo.name,
|
||||||
|
"Repository does not have remotes configured, initializing new",
|
||||||
|
);
|
||||||
|
match repo::RepoHandle::init(&repo_path, repo.worktree_setup) {
|
||||||
|
Ok(r) => {
|
||||||
|
print_repo_success(&repo.name, "Repository created");
|
||||||
|
Some(r)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(format!("Repository failed during init: {}", e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
let first = repo.remotes.as_ref().unwrap().first().unwrap();
|
||||||
|
|
||||||
|
match repo::clone_repo(first, &repo_path, repo.worktree_setup) {
|
||||||
|
Ok(_) => {
|
||||||
|
print_repo_success(&repo.name, "Repository successfully cloned");
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(format!("Repository failed during clone: {}", e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
newly_created = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let repo_handle = match repo::RepoHandle::open(&repo_path, repo.worktree_setup) {
|
||||||
|
Ok(repo) => repo,
|
||||||
|
Err(error) => {
|
||||||
|
if !repo.worktree_setup && repo::RepoHandle::open(&repo_path, true).is_ok() {
|
||||||
|
return Err(String::from(
|
||||||
|
"Repo already exists, but is using a worktree setup",
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
return Err(format!("Opening repository failed: {}", error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if newly_created && repo.worktree_setup && init_worktree {
|
||||||
|
match repo_handle.default_branch() {
|
||||||
|
Ok(branch) => {
|
||||||
|
worktree::add_worktree(&repo_path, &branch.name()?, None, None, false)?;
|
||||||
|
}
|
||||||
|
Err(_error) => print_repo_error(
|
||||||
|
&repo.name,
|
||||||
|
"Could not determine default branch, skipping worktree initializtion",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(remotes) = &repo.remotes {
|
||||||
|
let current_remotes: Vec<String> = repo_handle
|
||||||
|
.remotes()
|
||||||
|
.map_err(|error| format!("Repository failed during getting the remotes: {}", error))?;
|
||||||
|
|
||||||
|
for remote in remotes {
|
||||||
|
let current_remote = repo_handle.find_remote(&remote.name)?;
|
||||||
|
|
||||||
|
match current_remote {
|
||||||
|
Some(current_remote) => {
|
||||||
|
let current_url = current_remote.url();
|
||||||
|
|
||||||
|
if remote.url != current_url {
|
||||||
|
print_repo_action(
|
||||||
|
&repo.name,
|
||||||
|
&format!("Updating remote {} to \"{}\"", &remote.name, &remote.url),
|
||||||
|
);
|
||||||
|
if let Err(e) = repo_handle.remote_set_url(&remote.name, &remote.url) {
|
||||||
|
return Err(format!("Repository failed during setting of the remote URL for remote \"{}\": {}", &remote.name, e));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
print_repo_action(
|
||||||
|
&repo.name,
|
||||||
|
&format!(
|
||||||
|
"Setting up new remote \"{}\" to \"{}\"",
|
||||||
|
&remote.name, &remote.url
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if let Err(e) = repo_handle.new_remote(&remote.name, &remote.url) {
|
||||||
|
return Err(format!(
|
||||||
|
"Repository failed during setting the remotes: {}",
|
||||||
|
e
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for current_remote in ¤t_remotes {
|
||||||
|
if !remotes.iter().any(|r| &r.name == current_remote) {
|
||||||
|
print_repo_action(
|
||||||
|
&repo.name,
|
||||||
|
&format!("Deleting remote \"{}\"", ¤t_remote,),
|
||||||
|
);
|
||||||
|
if let Err(e) = repo_handle.remote_delete(current_remote) {
|
||||||
|
return Err(format!(
|
||||||
|
"Repository failed during deleting remote \"{}\": {}",
|
||||||
|
¤t_remote, e
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_actual_git_directory(path: &Path, is_worktree: bool) -> PathBuf {
|
||||||
|
match is_worktree {
|
||||||
|
false => path.to_path_buf(),
|
||||||
|
true => path.join(worktree::GIT_MAIN_WORKTREE_DIRECTORY),
|
||||||
|
}
|
||||||
|
}
|
||||||
202
src/worktree.rs
Normal file
202
src/worktree.rs
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::output::*;
|
||||||
|
use super::repo;
|
||||||
|
|
||||||
|
pub const GIT_MAIN_WORKTREE_DIRECTORY: &str = ".git-main-working-tree";
|
||||||
|
|
||||||
|
// The logic about the base branch and the tracking branch is as follows:
|
||||||
|
//
|
||||||
|
// * If a branch with the same name does not exist and no track is given, use the default
|
||||||
|
// branch
|
||||||
|
//
|
||||||
|
// * If a branch with the same name exists and no track is given, use that
|
||||||
|
//
|
||||||
|
// * If a branch with the same name does not exist and track is given, use the
|
||||||
|
// local branch that tracks that branch
|
||||||
|
//
|
||||||
|
// * If a branch with the same name exists and track is given, use the locally
|
||||||
|
// existing branch. If the locally existing branch is not the local branch to
|
||||||
|
// the remote tracking branch, issue a warning
|
||||||
|
pub fn add_worktree(
|
||||||
|
directory: &Path,
|
||||||
|
name: &str,
|
||||||
|
subdirectory: Option<&Path>,
|
||||||
|
track: Option<(&str, &str)>,
|
||||||
|
no_track: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let repo = repo::RepoHandle::open(directory, true).map_err(|error| match error.kind {
|
||||||
|
repo::RepoErrorKind::NotFound => {
|
||||||
|
String::from("Current directory does not contain a worktree setup")
|
||||||
|
}
|
||||||
|
_ => format!("Error opening repo: {}", error),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let config = repo::read_worktree_root_config(directory)?;
|
||||||
|
|
||||||
|
if repo.find_worktree(name).is_ok() {
|
||||||
|
return Err(format!("Worktree {} already exists", &name));
|
||||||
|
}
|
||||||
|
|
||||||
|
let path = match subdirectory {
|
||||||
|
Some(dir) => directory.join(dir).join(name),
|
||||||
|
None => directory.join(Path::new(name)),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut remote_branch_exists = false;
|
||||||
|
|
||||||
|
let mut target_branch = match repo.find_local_branch(name) {
|
||||||
|
Ok(branchref) => {
|
||||||
|
if !no_track {
|
||||||
|
if let Some((remote_name, remote_branch_name)) = track {
|
||||||
|
let remote_branch = repo.find_remote_branch(remote_name, remote_branch_name);
|
||||||
|
if let Ok(remote_branch) = remote_branch {
|
||||||
|
remote_branch_exists = true;
|
||||||
|
if let Ok(local_upstream_branch) = branchref.upstream() {
|
||||||
|
if remote_branch.name()? != local_upstream_branch.name()? {
|
||||||
|
print_warning(&format!(
|
||||||
|
"You specified a tracking branch ({}/{}) for an existing branch ({}), but \
|
||||||
|
it differs from the current upstream ({}). Will keep current upstream"
|
||||||
|
, remote_name, remote_branch_name, branchref.name()?, local_upstream_branch.name()?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
branchref
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
let default_checkout = || repo.default_branch()?.to_commit();
|
||||||
|
|
||||||
|
let checkout_commit;
|
||||||
|
|
||||||
|
if no_track {
|
||||||
|
checkout_commit = default_checkout()?;
|
||||||
|
} else {
|
||||||
|
match track {
|
||||||
|
Some((remote_name, remote_branch_name)) => {
|
||||||
|
let remote_branch =
|
||||||
|
repo.find_remote_branch(remote_name, remote_branch_name);
|
||||||
|
match remote_branch {
|
||||||
|
Ok(branch) => {
|
||||||
|
remote_branch_exists = true;
|
||||||
|
checkout_commit = branch.to_commit()?;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
remote_branch_exists = false;
|
||||||
|
checkout_commit = default_checkout()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => match &config {
|
||||||
|
None => checkout_commit = default_checkout()?,
|
||||||
|
Some(config) => match &config.track {
|
||||||
|
None => checkout_commit = default_checkout()?,
|
||||||
|
Some(track_config) => {
|
||||||
|
if track_config.default {
|
||||||
|
let remote_branch =
|
||||||
|
repo.find_remote_branch(&track_config.default_remote, name);
|
||||||
|
match remote_branch {
|
||||||
|
Ok(branch) => {
|
||||||
|
remote_branch_exists = true;
|
||||||
|
checkout_commit = branch.to_commit()?;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
checkout_commit = default_checkout()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
checkout_commit = default_checkout()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
repo.create_branch(name, &checkout_commit)?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fn push(
|
||||||
|
remote: &mut repo::RemoteHandle,
|
||||||
|
branch_name: &str,
|
||||||
|
remote_branch_name: &str,
|
||||||
|
repo: &repo::RepoHandle,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if !remote.is_pushable()? {
|
||||||
|
return Err(format!(
|
||||||
|
"Cannot push to non-pushable remote {}",
|
||||||
|
remote.url()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
remote.push(branch_name, remote_branch_name, repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !no_track {
|
||||||
|
if let Some((remote_name, remote_branch_name)) = track {
|
||||||
|
if remote_branch_exists {
|
||||||
|
target_branch.set_upstream(remote_name, remote_branch_name)?;
|
||||||
|
} else {
|
||||||
|
let mut remote = repo
|
||||||
|
.find_remote(remote_name)
|
||||||
|
.map_err(|error| format!("Error getting remote {}: {}", remote_name, error))?
|
||||||
|
.ok_or_else(|| format!("Remote {} not found", remote_name))?;
|
||||||
|
|
||||||
|
push(
|
||||||
|
&mut remote,
|
||||||
|
&target_branch.name()?,
|
||||||
|
remote_branch_name,
|
||||||
|
&repo,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
target_branch.set_upstream(remote_name, remote_branch_name)?;
|
||||||
|
}
|
||||||
|
} else if let Some(config) = config {
|
||||||
|
if let Some(track_config) = config.track {
|
||||||
|
if track_config.default {
|
||||||
|
let remote_name = track_config.default_remote;
|
||||||
|
if remote_branch_exists {
|
||||||
|
target_branch.set_upstream(&remote_name, name)?;
|
||||||
|
} else {
|
||||||
|
let remote_branch_name = match track_config.default_remote_prefix {
|
||||||
|
Some(prefix) => {
|
||||||
|
format!("{}{}{}", &prefix, super::BRANCH_NAMESPACE_SEPARATOR, &name)
|
||||||
|
}
|
||||||
|
None => name.to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut remote = repo
|
||||||
|
.find_remote(&remote_name)
|
||||||
|
.map_err(|error| {
|
||||||
|
format!("Error getting remote {}: {}", remote_name, error)
|
||||||
|
})?
|
||||||
|
.ok_or_else(|| format!("Remote {} not found", remote_name))?;
|
||||||
|
|
||||||
|
if !remote.is_pushable()? {
|
||||||
|
return Err(format!(
|
||||||
|
"Cannot push to non-pushable remote {}",
|
||||||
|
remote.url()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
push(
|
||||||
|
&mut remote,
|
||||||
|
&target_branch.name()?,
|
||||||
|
&remote_branch_name,
|
||||||
|
&repo,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
target_branch.set_upstream(&remote_name, &remote_branch_name)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(subdirectory) = subdirectory {
|
||||||
|
std::fs::create_dir_all(subdirectory).map_err(|error| error.to_string())?;
|
||||||
|
}
|
||||||
|
repo.new_worktree(name, &path, &target_branch)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user