├── .changes ├── 0.2.1.md ├── 0.2.2.md ├── 0.3.0.md ├── header.tpl.md └── unreleased │ └── .gitkeep ├── .changie.yaml ├── .github └── workflows │ ├── build.yml │ └── changelog-check.yml ├── .gitignore ├── .markdownlint.yml ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── RELEASE_CHECK_LIST.md ├── ci ├── build-app ├── create-archive ├── run-static-checks ├── run-tests └── upload-build ├── create-demo-repository ├── src ├── app.rs ├── appui.rs ├── batchappui.rs ├── cliargs.rs ├── git.rs ├── interactiveappui.rs ├── lib.rs ├── main.rs └── tui.rs ├── tasks.py └── tests └── integ.rs /.changes/0.2.1.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.2.1 - 2021-05-25 4 | 5 | ### Changed 6 | 7 | - Internal: code is more Rust-like now (#4). 8 | - Internal: CI now checks formatting and runs clippy linter. 9 | 10 | ### Fixed 11 | 12 | - git-bonsai no longer fails when a branch is checked out in a separate worktree. Worktree branches are just ignored (#5). 13 | 14 | ## 0.2.0 - 2020-03-29 15 | 16 | ### Added 17 | 18 | - Added a --no-fetch option. 19 | - Implemented removal of identical branches. 20 | - Added integration tests. 21 | - The CI now builds git-bonsai on Windows and macOS. 22 | 23 | ### Changed 24 | 25 | - Improved README. 26 | 27 | ## 0.1.0 - 2020-03-22 28 | 29 | First release. 30 | -------------------------------------------------------------------------------- /.changes/0.2.2.md: -------------------------------------------------------------------------------- 1 | ## 0.2.2 - 2022-07-22 2 | 3 | ### Added 4 | 5 | - Make it possible to configure protected branches, using `git config`. See `git-bonsai --help` for details. 6 | -------------------------------------------------------------------------------- /.changes/0.3.0.md: -------------------------------------------------------------------------------- 1 | ## 0.3.0 - 2022-11-13 2 | 3 | ### Changed 4 | 5 | - Git Bonsai now detects the default branch and always considers it protected. 6 | -------------------------------------------------------------------------------- /.changes/header.tpl.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | -------------------------------------------------------------------------------- /.changes/unreleased/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateau/git-bonsai/9c0d25ce6b3234d41b51f77e330db5b7e7e5142a/.changes/unreleased/.gitkeep -------------------------------------------------------------------------------- /.changie.yaml: -------------------------------------------------------------------------------- 1 | changesDir: .changes 2 | unreleasedDir: unreleased 3 | headerPath: header.tpl.md 4 | versionHeaderPath: "" 5 | changelogPath: CHANGELOG.md 6 | versionExt: md 7 | versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}' 8 | kindFormat: '### {{.Kind}}' 9 | changeFormat: '- {{.Body}}' 10 | kinds: 11 | - label: Added 12 | - label: Changed 13 | - label: Removed 14 | - label: Fixed 15 | newlines: 16 | afterChangelogHeader: 1 17 | beforeChangelogVersion: 1 18 | endOfVersion: 1 19 | beforeKind: 1 20 | afterKind: 1 21 | afterChange: 1 22 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | tags: 9 | workflow_dispatch: 10 | 11 | jobs: 12 | lint: 13 | runs-on: ubuntu-20.04 14 | steps: 15 | - uses: actions/checkout@v3 16 | 17 | - name: Install stable toolchain 18 | uses: actions-rs/toolchain@v1 19 | with: 20 | toolchain: stable 21 | override: true 22 | 23 | - name: Run static checks 24 | run: ci/run-static-checks 25 | 26 | build: 27 | strategy: 28 | fail-fast: false 29 | matrix: 30 | os: 31 | - ubuntu-20.04 32 | - macos-12 33 | - windows-2019 34 | 35 | runs-on: ${{ matrix.os }} 36 | 37 | defaults: 38 | run: 39 | shell: bash 40 | 41 | steps: 42 | - uses: actions/checkout@v3 43 | with: 44 | # Use `fetch-depth: 0` otherwise `git describe` does not see valid 45 | # tags, causing ci/create-archive to create snapshot archives. This 46 | # also requires the "Fix actions/checkout bug" step below to work. 47 | fetch-depth: 0 48 | 49 | # See https://github.com/actions/checkout/issues/290#issuecomment-680260080 50 | - name: Fix actions/checkout bug 51 | run: git fetch --force --tags 52 | 53 | - name: Build 54 | run: ci/build-app 55 | 56 | - name: Run tests 57 | run: ci/run-tests 58 | 59 | - name: Create archive 60 | run: ci/create-archive 61 | 62 | - name: Upload artifacts 63 | uses: actions/upload-artifact@v3 64 | with: 65 | name: artifacts 66 | path: | 67 | artifacts/*.bz2 68 | 69 | server-upload: 70 | needs: build 71 | runs-on: ubuntu-20.04 72 | if: github.ref == 'refs/heads/master' 73 | 74 | steps: 75 | - uses: actions/checkout@v3 76 | 77 | - name: Download artifacts 78 | uses: actions/download-artifact@v3 79 | with: 80 | name: artifacts 81 | path: artifacts 82 | 83 | - name: Upload to builds.agateau.com 84 | run: ci/upload-build git-bonsai artifacts/*.bz2 85 | env: 86 | UPLOAD_USERNAME: ${{ secrets.UPLOAD_USERNAME }} 87 | UPLOAD_PRIVATE_KEY: ${{ secrets.UPLOAD_PRIVATE_KEY }} 88 | UPLOAD_HOSTNAME: ${{ secrets.UPLOAD_HOSTNAME }} 89 | -------------------------------------------------------------------------------- /.github/workflows/changelog-check.yml: -------------------------------------------------------------------------------- 1 | name: Require change fragment 2 | 3 | on: 4 | pull_request: 5 | types: 6 | # On by default if you specify no types. 7 | - "opened" 8 | - "reopened" 9 | - "synchronize" 10 | # For `skip-changelog` only. 11 | - "labeled" 12 | - "unlabeled" 13 | 14 | jobs: 15 | check-changelog: 16 | runs-on: ubuntu-20.04 17 | steps: 18 | - name: "Check for changelog entry" 19 | uses: brettcannon/check-for-changed-files@v1.1.0 20 | with: 21 | file-pattern: | 22 | .changes/unreleased/*.yaml 23 | CHANGELOG.md 24 | skip-label: "skip-changelog" 25 | failure-message: "Missing a changelog file in ${file-pattern}; please add one or apply the ${skip-label} label to the pull request" 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | /artifacts 4 | /demo 5 | -------------------------------------------------------------------------------- /.markdownlint.yml: -------------------------------------------------------------------------------- 1 | default: true 2 | ul-indent: 3 | indent: 4 4 | 5 | # Enforcing fenced code-blo-style is disabled for now because it reports the 6 | # yaml content of the gallery:: plugin as indented code-blocks 7 | #code-block-style: false 8 | code-block-style: 9 | style: fenced 10 | fenced-code-language: false 11 | 12 | line_length: false 13 | 14 | # Disable this because of .changes file entries 15 | first-line-h1: false 16 | 17 | # Disable this becauase of CHANGELOG.md 18 | no-duplicate-heading: false 19 | #no-trailing-punctuation: false 20 | #no-inline-html: false 21 | #commands-show-output: false 22 | # Disable this because in some articles `_` is used for image captions 23 | #no-emphasis-as-heading: false 24 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.3.0 6 | hooks: 7 | - id: trailing-whitespace 8 | - id: end-of-file-fixer 9 | - id: check-yaml 10 | - id: check-added-large-files 11 | - repo: https://github.com/doublify/pre-commit-rust 12 | rev: v1.0 13 | hooks: 14 | - id: fmt 15 | - id: clippy 16 | - id: cargo-check 17 | stages: [push] 18 | - repo: https://github.com/igorshubovych/markdownlint-cli 19 | rev: v0.32.2 20 | hooks: 21 | - id: markdownlint-fix 22 | args: [] 23 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.3.0 - 2022-11-13 4 | 5 | ### Changed 6 | 7 | - Git Bonsai now detects the default branch and always considers it protected. 8 | 9 | ## 0.2.2 - 2022-07-22 10 | 11 | ### Added 12 | 13 | - Make it possible to configure protected branches, using `git config`. See `git-bonsai --help` for details. 14 | 15 | ## 0.2.1 - 2021-05-25 16 | 17 | ### Changed 18 | 19 | - Internal: code is more Rust-like now (#4). 20 | - Internal: CI now checks formatting and runs clippy linter. 21 | 22 | ### Fixed 23 | 24 | - git-bonsai no longer fails when a branch is checked out in a separate worktree. Worktree branches are just ignored (#5). 25 | 26 | ## 0.2.0 - 2020-03-29 27 | 28 | ### Added 29 | 30 | - Added a --no-fetch option. 31 | - Implemented removal of identical branches. 32 | - Added integration tests. 33 | - The CI now builds git-bonsai on Windows and macOS. 34 | 35 | ### Changed 36 | 37 | - Improved README. 38 | 39 | ## 0.1.0 - 2020-03-22 40 | 41 | First release. 42 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aho-corasick" 7 | version = "0.7.18" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 10 | dependencies = [ 11 | "memchr", 12 | ] 13 | 14 | [[package]] 15 | name = "ansi_term" 16 | version = "0.11.0" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 19 | dependencies = [ 20 | "winapi", 21 | ] 22 | 23 | [[package]] 24 | name = "assert_fs" 25 | version = "1.0.7" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "cf09bb72e00da477c2596865e8873227e2196d263cca35414048875dbbeea1be" 28 | dependencies = [ 29 | "doc-comment", 30 | "globwalk", 31 | "predicates", 32 | "predicates-core", 33 | "predicates-tree", 34 | "tempfile", 35 | ] 36 | 37 | [[package]] 38 | name = "atty" 39 | version = "0.2.14" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 42 | dependencies = [ 43 | "hermit-abi", 44 | "libc", 45 | "winapi", 46 | ] 47 | 48 | [[package]] 49 | name = "autocfg" 50 | version = "1.0.0" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" 53 | 54 | [[package]] 55 | name = "bitflags" 56 | version = "1.2.1" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 59 | 60 | [[package]] 61 | name = "bstr" 62 | version = "0.2.15" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | checksum = "a40b47ad93e1a5404e6c18dec46b628214fee441c70f4ab5d6942142cc268a3d" 65 | dependencies = [ 66 | "memchr", 67 | ] 68 | 69 | [[package]] 70 | name = "c2-chacha" 71 | version = "0.2.3" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "214238caa1bf3a496ec3392968969cab8549f96ff30652c9e56885329315f6bb" 74 | dependencies = [ 75 | "ppv-lite86", 76 | ] 77 | 78 | [[package]] 79 | name = "cfg-if" 80 | version = "0.1.10" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 83 | 84 | [[package]] 85 | name = "claim" 86 | version = "0.5.0" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "f81099d6bb72e1df6d50bb2347224b666a670912bb7f06dbe867a4a070ab3ce8" 89 | dependencies = [ 90 | "autocfg", 91 | ] 92 | 93 | [[package]] 94 | name = "clap" 95 | version = "2.33.0" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" 98 | dependencies = [ 99 | "ansi_term", 100 | "atty", 101 | "bitflags", 102 | "strsim", 103 | "textwrap", 104 | "unicode-width", 105 | "vec_map", 106 | ] 107 | 108 | [[package]] 109 | name = "console" 110 | version = "0.15.0" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "a28b32d32ca44b70c3e4acd7db1babf555fa026e385fb95f18028f88848b3c31" 113 | dependencies = [ 114 | "encode_unicode", 115 | "libc", 116 | "once_cell", 117 | "regex", 118 | "terminal_size", 119 | "unicode-width", 120 | "winapi", 121 | ] 122 | 123 | [[package]] 124 | name = "crossbeam-channel" 125 | version = "0.4.2" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061" 128 | dependencies = [ 129 | "crossbeam-utils", 130 | "maybe-uninit", 131 | ] 132 | 133 | [[package]] 134 | name = "crossbeam-utils" 135 | version = "0.7.2" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" 138 | dependencies = [ 139 | "autocfg", 140 | "cfg-if", 141 | "lazy_static", 142 | ] 143 | 144 | [[package]] 145 | name = "dialoguer" 146 | version = "0.10.1" 147 | source = "registry+https://github.com/rust-lang/crates.io-index" 148 | checksum = "d8c8ae48e400addc32a8710c8d62d55cb84249a7d58ac4cd959daecfbaddc545" 149 | dependencies = [ 150 | "console", 151 | "tempfile", 152 | "zeroize", 153 | ] 154 | 155 | [[package]] 156 | name = "difflib" 157 | version = "0.4.0" 158 | source = "registry+https://github.com/rust-lang/crates.io-index" 159 | checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" 160 | 161 | [[package]] 162 | name = "doc-comment" 163 | version = "0.3.1" 164 | source = "registry+https://github.com/rust-lang/crates.io-index" 165 | checksum = "923dea538cea0aa3025e8685b20d6ee21ef99c4f77e954a30febbaac5ec73a97" 166 | 167 | [[package]] 168 | name = "either" 169 | version = "1.6.1" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" 172 | 173 | [[package]] 174 | name = "encode_unicode" 175 | version = "0.3.6" 176 | source = "registry+https://github.com/rust-lang/crates.io-index" 177 | checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" 178 | 179 | [[package]] 180 | name = "float-cmp" 181 | version = "0.9.0" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" 184 | dependencies = [ 185 | "num-traits", 186 | ] 187 | 188 | [[package]] 189 | name = "fnv" 190 | version = "1.0.6" 191 | source = "registry+https://github.com/rust-lang/crates.io-index" 192 | checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" 193 | 194 | [[package]] 195 | name = "getrandom" 196 | version = "0.1.14" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb" 199 | dependencies = [ 200 | "cfg-if", 201 | "libc", 202 | "wasi", 203 | ] 204 | 205 | [[package]] 206 | name = "git-bonsai" 207 | version = "0.3.0" 208 | dependencies = [ 209 | "assert_fs", 210 | "claim", 211 | "console", 212 | "dialoguer", 213 | "predicates", 214 | "structopt", 215 | ] 216 | 217 | [[package]] 218 | name = "globset" 219 | version = "0.4.4" 220 | source = "registry+https://github.com/rust-lang/crates.io-index" 221 | checksum = "925aa2cac82d8834e2b2a4415b6f6879757fb5c0928fc445ae76461a12eed8f2" 222 | dependencies = [ 223 | "aho-corasick", 224 | "bstr", 225 | "fnv", 226 | "log", 227 | "regex", 228 | ] 229 | 230 | [[package]] 231 | name = "globwalk" 232 | version = "0.8.1" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "93e3af942408868f6934a7b85134a3230832b9977cf66125df2f9edcfce4ddcc" 235 | dependencies = [ 236 | "bitflags", 237 | "ignore", 238 | "walkdir", 239 | ] 240 | 241 | [[package]] 242 | name = "heck" 243 | version = "0.3.1" 244 | source = "registry+https://github.com/rust-lang/crates.io-index" 245 | checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" 246 | dependencies = [ 247 | "unicode-segmentation", 248 | ] 249 | 250 | [[package]] 251 | name = "hermit-abi" 252 | version = "0.1.8" 253 | source = "registry+https://github.com/rust-lang/crates.io-index" 254 | checksum = "1010591b26bbfe835e9faeabeb11866061cc7dcebffd56ad7d0942d0e61aefd8" 255 | dependencies = [ 256 | "libc", 257 | ] 258 | 259 | [[package]] 260 | name = "ignore" 261 | version = "0.4.11" 262 | source = "registry+https://github.com/rust-lang/crates.io-index" 263 | checksum = "522daefc3b69036f80c7d2990b28ff9e0471c683bad05ca258e0a01dd22c5a1e" 264 | dependencies = [ 265 | "crossbeam-channel", 266 | "globset", 267 | "lazy_static", 268 | "log", 269 | "memchr", 270 | "regex", 271 | "same-file", 272 | "thread_local", 273 | "walkdir", 274 | "winapi-util", 275 | ] 276 | 277 | [[package]] 278 | name = "itertools" 279 | version = "0.10.3" 280 | source = "registry+https://github.com/rust-lang/crates.io-index" 281 | checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" 282 | dependencies = [ 283 | "either", 284 | ] 285 | 286 | [[package]] 287 | name = "lazy_static" 288 | version = "1.4.0" 289 | source = "registry+https://github.com/rust-lang/crates.io-index" 290 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 291 | 292 | [[package]] 293 | name = "libc" 294 | version = "0.2.67" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | checksum = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" 297 | 298 | [[package]] 299 | name = "log" 300 | version = "0.4.8" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" 303 | dependencies = [ 304 | "cfg-if", 305 | ] 306 | 307 | [[package]] 308 | name = "maybe-uninit" 309 | version = "2.0.0" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" 312 | 313 | [[package]] 314 | name = "memchr" 315 | version = "2.5.0" 316 | source = "registry+https://github.com/rust-lang/crates.io-index" 317 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 318 | 319 | [[package]] 320 | name = "normalize-line-endings" 321 | version = "0.3.0" 322 | source = "registry+https://github.com/rust-lang/crates.io-index" 323 | checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" 324 | 325 | [[package]] 326 | name = "num-traits" 327 | version = "0.2.11" 328 | source = "registry+https://github.com/rust-lang/crates.io-index" 329 | checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" 330 | dependencies = [ 331 | "autocfg", 332 | ] 333 | 334 | [[package]] 335 | name = "once_cell" 336 | version = "1.12.0" 337 | source = "registry+https://github.com/rust-lang/crates.io-index" 338 | checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" 339 | 340 | [[package]] 341 | name = "ppv-lite86" 342 | version = "0.2.6" 343 | source = "registry+https://github.com/rust-lang/crates.io-index" 344 | checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" 345 | 346 | [[package]] 347 | name = "predicates" 348 | version = "2.1.1" 349 | source = "registry+https://github.com/rust-lang/crates.io-index" 350 | checksum = "a5aab5be6e4732b473071984b3164dbbfb7a3674d30ea5ff44410b6bcd960c3c" 351 | dependencies = [ 352 | "difflib", 353 | "float-cmp", 354 | "itertools", 355 | "normalize-line-endings", 356 | "predicates-core", 357 | "regex", 358 | ] 359 | 360 | [[package]] 361 | name = "predicates-core" 362 | version = "1.0.0" 363 | source = "registry+https://github.com/rust-lang/crates.io-index" 364 | checksum = "06075c3a3e92559ff8929e7a280684489ea27fe44805174c3ebd9328dcb37178" 365 | 366 | [[package]] 367 | name = "predicates-tree" 368 | version = "1.0.0" 369 | source = "registry+https://github.com/rust-lang/crates.io-index" 370 | checksum = "8e63c4859013b38a76eca2414c64911fba30def9e3202ac461a2d22831220124" 371 | dependencies = [ 372 | "predicates-core", 373 | "treeline", 374 | ] 375 | 376 | [[package]] 377 | name = "proc-macro-error" 378 | version = "1.0.4" 379 | source = "registry+https://github.com/rust-lang/crates.io-index" 380 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 381 | dependencies = [ 382 | "proc-macro-error-attr", 383 | "proc-macro2", 384 | "quote", 385 | "syn", 386 | "version_check", 387 | ] 388 | 389 | [[package]] 390 | name = "proc-macro-error-attr" 391 | version = "1.0.4" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 394 | dependencies = [ 395 | "proc-macro2", 396 | "quote", 397 | "version_check", 398 | ] 399 | 400 | [[package]] 401 | name = "proc-macro2" 402 | version = "1.0.24" 403 | source = "registry+https://github.com/rust-lang/crates.io-index" 404 | checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" 405 | dependencies = [ 406 | "unicode-xid", 407 | ] 408 | 409 | [[package]] 410 | name = "quote" 411 | version = "1.0.9" 412 | source = "registry+https://github.com/rust-lang/crates.io-index" 413 | checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" 414 | dependencies = [ 415 | "proc-macro2", 416 | ] 417 | 418 | [[package]] 419 | name = "rand" 420 | version = "0.7.3" 421 | source = "registry+https://github.com/rust-lang/crates.io-index" 422 | checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" 423 | dependencies = [ 424 | "getrandom", 425 | "libc", 426 | "rand_chacha", 427 | "rand_core", 428 | "rand_hc", 429 | ] 430 | 431 | [[package]] 432 | name = "rand_chacha" 433 | version = "0.2.1" 434 | source = "registry+https://github.com/rust-lang/crates.io-index" 435 | checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" 436 | dependencies = [ 437 | "c2-chacha", 438 | "rand_core", 439 | ] 440 | 441 | [[package]] 442 | name = "rand_core" 443 | version = "0.5.1" 444 | source = "registry+https://github.com/rust-lang/crates.io-index" 445 | checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" 446 | dependencies = [ 447 | "getrandom", 448 | ] 449 | 450 | [[package]] 451 | name = "rand_hc" 452 | version = "0.2.0" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" 455 | dependencies = [ 456 | "rand_core", 457 | ] 458 | 459 | [[package]] 460 | name = "redox_syscall" 461 | version = "0.1.56" 462 | source = "registry+https://github.com/rust-lang/crates.io-index" 463 | checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" 464 | 465 | [[package]] 466 | name = "regex" 467 | version = "1.5.6" 468 | source = "registry+https://github.com/rust-lang/crates.io-index" 469 | checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" 470 | dependencies = [ 471 | "aho-corasick", 472 | "memchr", 473 | "regex-syntax", 474 | ] 475 | 476 | [[package]] 477 | name = "regex-syntax" 478 | version = "0.6.26" 479 | source = "registry+https://github.com/rust-lang/crates.io-index" 480 | checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" 481 | 482 | [[package]] 483 | name = "remove_dir_all" 484 | version = "0.5.2" 485 | source = "registry+https://github.com/rust-lang/crates.io-index" 486 | checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" 487 | dependencies = [ 488 | "winapi", 489 | ] 490 | 491 | [[package]] 492 | name = "same-file" 493 | version = "1.0.6" 494 | source = "registry+https://github.com/rust-lang/crates.io-index" 495 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 496 | dependencies = [ 497 | "winapi-util", 498 | ] 499 | 500 | [[package]] 501 | name = "strsim" 502 | version = "0.8.0" 503 | source = "registry+https://github.com/rust-lang/crates.io-index" 504 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 505 | 506 | [[package]] 507 | name = "structopt" 508 | version = "0.3.26" 509 | source = "registry+https://github.com/rust-lang/crates.io-index" 510 | checksum = "0c6b5c64445ba8094a6ab0c3cd2ad323e07171012d9c98b0b15651daf1787a10" 511 | dependencies = [ 512 | "clap", 513 | "lazy_static", 514 | "structopt-derive", 515 | ] 516 | 517 | [[package]] 518 | name = "structopt-derive" 519 | version = "0.4.18" 520 | source = "registry+https://github.com/rust-lang/crates.io-index" 521 | checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0" 522 | dependencies = [ 523 | "heck", 524 | "proc-macro-error", 525 | "proc-macro2", 526 | "quote", 527 | "syn", 528 | ] 529 | 530 | [[package]] 531 | name = "syn" 532 | version = "1.0.63" 533 | source = "registry+https://github.com/rust-lang/crates.io-index" 534 | checksum = "8fd9bc7ccc2688b3344c2f48b9b546648b25ce0b20fc717ee7fa7981a8ca9717" 535 | dependencies = [ 536 | "proc-macro2", 537 | "quote", 538 | "unicode-xid", 539 | ] 540 | 541 | [[package]] 542 | name = "tempfile" 543 | version = "3.1.0" 544 | source = "registry+https://github.com/rust-lang/crates.io-index" 545 | checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" 546 | dependencies = [ 547 | "cfg-if", 548 | "libc", 549 | "rand", 550 | "redox_syscall", 551 | "remove_dir_all", 552 | "winapi", 553 | ] 554 | 555 | [[package]] 556 | name = "terminal_size" 557 | version = "0.1.17" 558 | source = "registry+https://github.com/rust-lang/crates.io-index" 559 | checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" 560 | dependencies = [ 561 | "libc", 562 | "winapi", 563 | ] 564 | 565 | [[package]] 566 | name = "textwrap" 567 | version = "0.11.0" 568 | source = "registry+https://github.com/rust-lang/crates.io-index" 569 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 570 | dependencies = [ 571 | "unicode-width", 572 | ] 573 | 574 | [[package]] 575 | name = "thread_local" 576 | version = "1.0.1" 577 | source = "registry+https://github.com/rust-lang/crates.io-index" 578 | checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" 579 | dependencies = [ 580 | "lazy_static", 581 | ] 582 | 583 | [[package]] 584 | name = "treeline" 585 | version = "0.1.0" 586 | source = "registry+https://github.com/rust-lang/crates.io-index" 587 | checksum = "a7f741b240f1a48843f9b8e0444fb55fb2a4ff67293b50a9179dfd5ea67f8d41" 588 | 589 | [[package]] 590 | name = "unicode-segmentation" 591 | version = "1.6.0" 592 | source = "registry+https://github.com/rust-lang/crates.io-index" 593 | checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0" 594 | 595 | [[package]] 596 | name = "unicode-width" 597 | version = "0.1.7" 598 | source = "registry+https://github.com/rust-lang/crates.io-index" 599 | checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" 600 | 601 | [[package]] 602 | name = "unicode-xid" 603 | version = "0.2.1" 604 | source = "registry+https://github.com/rust-lang/crates.io-index" 605 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 606 | 607 | [[package]] 608 | name = "vec_map" 609 | version = "0.8.1" 610 | source = "registry+https://github.com/rust-lang/crates.io-index" 611 | checksum = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" 612 | 613 | [[package]] 614 | name = "version_check" 615 | version = "0.9.2" 616 | source = "registry+https://github.com/rust-lang/crates.io-index" 617 | checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" 618 | 619 | [[package]] 620 | name = "walkdir" 621 | version = "2.3.1" 622 | source = "registry+https://github.com/rust-lang/crates.io-index" 623 | checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" 624 | dependencies = [ 625 | "same-file", 626 | "winapi", 627 | "winapi-util", 628 | ] 629 | 630 | [[package]] 631 | name = "wasi" 632 | version = "0.9.0+wasi-snapshot-preview1" 633 | source = "registry+https://github.com/rust-lang/crates.io-index" 634 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 635 | 636 | [[package]] 637 | name = "winapi" 638 | version = "0.3.8" 639 | source = "registry+https://github.com/rust-lang/crates.io-index" 640 | checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" 641 | dependencies = [ 642 | "winapi-i686-pc-windows-gnu", 643 | "winapi-x86_64-pc-windows-gnu", 644 | ] 645 | 646 | [[package]] 647 | name = "winapi-i686-pc-windows-gnu" 648 | version = "0.4.0" 649 | source = "registry+https://github.com/rust-lang/crates.io-index" 650 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 651 | 652 | [[package]] 653 | name = "winapi-util" 654 | version = "0.1.3" 655 | source = "registry+https://github.com/rust-lang/crates.io-index" 656 | checksum = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" 657 | dependencies = [ 658 | "winapi", 659 | ] 660 | 661 | [[package]] 662 | name = "winapi-x86_64-pc-windows-gnu" 663 | version = "0.4.0" 664 | source = "registry+https://github.com/rust-lang/crates.io-index" 665 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 666 | 667 | [[package]] 668 | name = "zeroize" 669 | version = "1.5.5" 670 | source = "registry+https://github.com/rust-lang/crates.io-index" 671 | checksum = "94693807d016b2f2d2e14420eb3bfcca689311ff775dcf113d74ea624b7cdf07" 672 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "git-bonsai" 3 | version = "0.3.1-alpha.1" 4 | authors = ["Aurélien Gâteau "] 5 | edition = "2018" 6 | description = "Command-line tool to clean the branches of your git garden" 7 | documentation = "https://github.com/agateau/git-bonsai" 8 | readme = "README.md" 9 | homepage = "https://github.com/agateau/git-bonsai" 10 | repository = "https://github.com/agateau/git-bonsai" 11 | license = "GPL-3.0+" 12 | keywords = ["git", "clean"] 13 | categories = ["command-line-utilities", "development-tools"] 14 | 15 | [dependencies] 16 | structopt = "0.3.26" 17 | dialoguer = "0.10.1" 18 | console = "0.15.0" 19 | 20 | [dev-dependencies] 21 | assert_fs = "1.0.7" 22 | predicates = "2.1.1" 23 | claim = "0.5.0" 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Git Bonsai 2 | 3 | Git Bonsai is a command-line tool to help you tend the branches of your git garden. 4 | 5 | ## Usage 6 | 7 | Just run `git bonsai` in a git repository checkout. 8 | 9 | ## What does it do? 10 | 11 | Git Bonsai does the following: 12 | 13 | 1. Fetches remote changes. 14 | 15 | 2. Iterates on all your local tracking branches and update them to their remote counterparts. 16 | 17 | 3. Lists branches which can be safely deleted and lets you select the ones to delete. 18 | 19 | ## Is it safe? 20 | 21 | Git Bonsai takes several precautions to ensure it does not delete anything precious: 22 | 23 | 1. It refuses to run if there are any uncommitted changes. This includes unknown files. 24 | 25 | 2. It always prompt you before deleting any branch, and explains why this branch is safe to remove. 26 | 27 | 3. It refuses to delete a branch if it is not contained in another branch. 28 | 29 | 4. Git Bonsai never touches the remote repository. 30 | 31 | ## Demo 32 | 33 | Here is an example repository: 34 | 35 | ``` 36 | $ git log --oneline --all --graph 37 | 38 | * b87566d (duplicate2, duplicate1) Create duplicate1 39 | * e02d47e (HEAD -> master) Merging topic1 40 | |\ 41 | | * 020b54c (topic1) Merging topic1-1 42 | | |\ 43 | | | * cd060dc (topic1-1) Create topic1-1 44 | | |/ 45 | | * f356524 Create topic1 46 | |/ 47 | | * 85a9880 (topic2) Create topic2 48 | |/ 49 | * 0f209d0 Init 50 | ``` 51 | 52 | (You can create this repository with the `create-demo-repository` script) 53 | 54 | `topic1` and `topic1-1` branches can be safely deleted. `topic2` cannot. One of `duplicate1` and `duplicate2` can also be deleted, but not both. 55 | 56 | Let's run Git Bonsai: 57 | 58 | ``` 59 | $ git bonsai 60 | Info: Fetching changes 61 | These branches point to the same commit, but no other branch contains this 62 | commit, so you can delete all of them but one. 63 | 64 | Select branches to delete: 65 | > [x] duplicate1 66 | [x] duplicate2 67 | ``` 68 | 69 | I press `Space` to uncheck `duplicate1`, then `Enter` to continue. 70 | 71 | ``` 72 | Info: Deleting duplicate2 73 | Select branches to delete: 74 | > [x] topic1, contained in: 75 | - master 76 | - duplicate1 77 | 78 | [x] topic1-1, contained in: 79 | - topic1 80 | - duplicate1 81 | - master 82 | ``` 83 | 84 | Looks good to me, so I press `Enter`. 85 | 86 | ``` 87 | Info: Deleting topic1 88 | Info: Deleting topic1-1 89 | ``` 90 | 91 | Let's look at the repository now: 92 | 93 | ``` 94 | $ git log --oneline --all --graph 95 | 96 | * 0dfd179 (duplicate1) Create duplicate1 97 | * 5d06a2d (HEAD -> master) Merging topic1 98 | |\ 99 | | * 6a3b1de Merging topic1-1 100 | | |\ 101 | | | * 7671947 Create topic1-1 102 | | |/ 103 | | * c328fee Create topic1 104 | |/ 105 | | * 1616d9e (topic2) Create topic2 106 | |/ 107 | * 71913d9 Init 108 | ``` 109 | 110 | ## Installation 111 | 112 | ### Stable version 113 | 114 | The easiest way to install is to download an archive from the [release page][release], unpack it and copy the `git-bonsai` binary in a directory in `$PATH`. 115 | 116 | [release]: https://github.com/agateau/git-bonsai/releases 117 | 118 | ### Git snapshots 119 | 120 | Snapshots from the master branch are available from [builds.agateau.com/git-bonsai](https://builds.agateau.com/git-bonsai). 121 | 122 | ## Configuration 123 | 124 | ### Protected branches 125 | 126 | Git Bonsai considers branches called `main` and `master` as protected. You can add other protected branches using `git config --add git-bonsai protected-branches `. 127 | 128 | ## Building it 129 | 130 | Git Bonsai is written in [Rust][]. To build it, install Rust and then run: 131 | 132 | ``` 133 | cargo install git-bonsai 134 | ``` 135 | 136 | [Rust]: https://www.rust-lang.org 137 | 138 | ## Debugging 139 | 140 | If you define the `GB_DEBUG` environment variable, Git Bonsai will print all the git commands it runs. 141 | 142 | ## Why yet another git cleaning tool? 143 | 144 | I created Git Bonsai because I wanted a tool like this but also as a way to learn Rust. There definitely are similar tools, probably more capable, and the Rust code probably needs work, pull requests are welcome! 145 | -------------------------------------------------------------------------------- /RELEASE_CHECK_LIST.md: -------------------------------------------------------------------------------- 1 | ## Prepare 2 | 3 | - [ ] Setup 4 | 5 | ``` 6 | pip install invoke 7 | export VERSION= 8 | ``` 9 | 10 | - [ ] Prepare 11 | 12 | ``` 13 | invoke prepare-release 14 | ``` 15 | 16 | ## Tag 17 | 18 | - [ ] Wait for CI to be happy 19 | 20 | - [ ] Create tag 21 | 22 | ``` 23 | invoke tag 24 | ``` 25 | 26 | ## Publish 27 | 28 | ``` 29 | invoke download-artifacts 30 | invoke publish 31 | ``` 32 | 33 | ## Post publish 34 | 35 | - [ ] Bump version to x.y.z+1-alpha.1 36 | 37 | ``` 38 | VERSION= invoke update-version 39 | ``` 40 | 41 | - [ ] Write blog post 42 | -------------------------------------------------------------------------------- /ci/build-app: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | cargo build --verbose --release 4 | -------------------------------------------------------------------------------- /ci/create-archive: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | init_system() { 5 | ARCH=$(uname -m) 6 | 7 | local out 8 | out=$(uname) 9 | 10 | case "$out" in 11 | Linux) 12 | OS_NAME=linux 13 | EXE_NAME=$APP_NAME 14 | ;; 15 | Darwin) 16 | OS_NAME=macos 17 | EXE_NAME=$APP_NAME 18 | ;; 19 | MINGW*|MSYS*) 20 | OS_NAME=windows 21 | EXE_NAME=$APP_NAME.exe 22 | ;; 23 | *) 24 | echo "error: unknown OS. uname printed '$out'" 25 | exit 1 26 | ;; 27 | esac 28 | } 29 | 30 | init_checksum_cmd() { 31 | CHECKSUM_CMD=$(which sha512sum 2> /dev/null || true) 32 | if [ -n "$CHECKSUM_CMD" ] ; then 33 | return 34 | fi 35 | local openssl_cmd=$(which openssl 2> /dev/null || true) 36 | if [ -n "$openssl_cmd" ] ; then 37 | CHECKSUM_CMD="$openssl_cmd sha512 -r" 38 | return 39 | fi 40 | die "Neither sha512sum nor openssl are installed, can't compute sha512 sum" 41 | } 42 | 43 | cd $(dirname $0)/.. 44 | 45 | APP_NAME=git-bonsai 46 | DATA_FILES="README.md CHANGELOG.md LICENSE" 47 | 48 | init_system 49 | init_checksum_cmd 50 | echo "Checksum command: $CHECKSUM_CMD" 51 | 52 | define_version() { 53 | local describe=$(git describe) 54 | echo "git describe: $describe" 55 | case "$describe" in 56 | *-*-g*) 57 | echo "Building a snapshot" 58 | VERSION=${describe//-*/}+$(git show --no-patch --format=%cd-%h --date=format:%Y%m%dT%H%M%S) 59 | ;; 60 | *) 61 | echo "Building from a tag" 62 | VERSION=$describe 63 | ;; 64 | esac 65 | echo "VERSION=$VERSION" 66 | } 67 | 68 | define_version 69 | 70 | ARTIFACTS_DIR=$PWD/artifacts 71 | ARCHIVE_DIR=$APP_NAME-$VERSION 72 | ARCHIVE_NAME=$APP_NAME-$VERSION-$ARCH-$OS_NAME.tar.bz2 73 | 74 | rm -rf $ARTIFACTS_DIR 75 | mkdir -p $ARTIFACTS_DIR/$ARCHIVE_DIR 76 | 77 | echo "Copying and stripping binary" 78 | cp target/release/$EXE_NAME $ARTIFACTS_DIR/$ARCHIVE_DIR 79 | strip $ARTIFACTS_DIR/$ARCHIVE_DIR/$EXE_NAME 80 | 81 | echo "Copying data files" 82 | cp $DATA_FILES $ARTIFACTS_DIR/$ARCHIVE_DIR 83 | 84 | echo "Creating archive $ARTIFACTS_DIR/$ARCHIVE_NAME" 85 | cd $ARTIFACTS_DIR 86 | tar -cjvf $ARCHIVE_NAME $ARCHIVE_DIR 87 | 88 | echo "Computing checksum" 89 | $CHECKSUM_CMD $ARCHIVE_NAME 90 | -------------------------------------------------------------------------------- /ci/run-static-checks: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | pipx run pre-commit run --all 4 | -------------------------------------------------------------------------------- /ci/run-tests: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | export RUST_BACKTRACE=1 4 | cargo test --verbose 5 | -------------------------------------------------------------------------------- /ci/upload-build: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | PROGNAME=$(basename $0) 5 | 6 | die() { 7 | echo "$PROGNAME: $*" >&2 8 | exit 1 9 | } 10 | 11 | # Check $1 is defined and not empty 12 | check_var() { 13 | local name=$1 14 | if ! env | grep -q "^$name=..*" ; then 15 | die "Environment variable $name is not set or is empty" 16 | fi 17 | } 18 | 19 | usage() { 20 | if [ "$*" != "" ] ; then 21 | echo "Error: $*" 22 | echo 23 | fi 24 | 25 | cat << EOF 26 | Usage: $PROGNAME [OPTION ...] [build_file...] 27 | 28 | Uploads build artifacts to a server using scp. 29 | 30 | Files are upload to builds//. 31 | 32 | Expects the following environment variables to be set: 33 | - UPLOAD_USERNAME 34 | - UPLOAD_PRIVATE_KEY 35 | - UPLOAD_HOSTNAME 36 | 37 | Options: 38 | -h, --help display this usage message and exit 39 | EOF 40 | 41 | exit 1 42 | } 43 | 44 | project="" 45 | build_files="" 46 | while [ $# -gt 0 ] ; do 47 | case "$1" in 48 | -h|--help) 49 | usage 50 | ;; 51 | -*) 52 | usage "Unknown option '$1'" 53 | ;; 54 | *) 55 | if [ -z "$project" ] ; then 56 | project="$1" 57 | else 58 | build_files="$build_files $1" 59 | fi 60 | ;; 61 | esac 62 | shift 63 | done 64 | 65 | if [ -z "$build_files" ] ; then 66 | usage "Not enough arguments" 67 | fi 68 | 69 | check_var UPLOAD_USERNAME 70 | check_var UPLOAD_PRIVATE_KEY 71 | check_var UPLOAD_HOSTNAME 72 | 73 | echo "Uploading" 74 | eval $(ssh-agent) 75 | echo "$UPLOAD_PRIVATE_KEY" | ssh-add - 76 | scp -o "StrictHostKeyChecking off" $build_files "$UPLOAD_USERNAME@$UPLOAD_HOSTNAME:builds/$project/" 77 | -------------------------------------------------------------------------------- /create-demo-repository: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | create_branch() { 5 | local base=$1 6 | local branch=$2 7 | git checkout -b $branch $base 8 | touch $branch 9 | git add $branch 10 | git commit $branch -m "Create $branch" 11 | } 12 | 13 | merge() { 14 | local branch=$1 15 | git merge --no-ff "$branch" -m "Merging $branch" 16 | } 17 | 18 | rm -rf demo 19 | mkdir demo 20 | cd demo 21 | 22 | git init 23 | touch README 24 | git add README 25 | git commit -m "Init" README 26 | 27 | create_branch master topic1 28 | create_branch topic1 topic1-1 29 | create_branch master topic2 30 | 31 | git checkout topic1 32 | merge topic1-1 33 | 34 | git checkout master 35 | merge topic1 36 | 37 | # Create two branches pointing to the same commit 38 | create_branch master duplicate1 39 | git branch duplicate2 40 | git checkout master 41 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use std::collections::{HashMap, HashSet}; 20 | use std::convert::From; 21 | use std::fmt; 22 | use std::path::PathBuf; 23 | 24 | use crate::appui::{AppUi, BranchToDeleteInfo}; 25 | use crate::batchappui::BatchAppUi; 26 | use crate::cliargs::CliArgs; 27 | use crate::git::{BranchRestorer, GitError, Repository}; 28 | use crate::interactiveappui::InteractiveAppUi; 29 | 30 | pub static DEFAULT_BRANCH_CONFIG_KEY: &str = "git-bonsai.default-branch"; 31 | 32 | #[derive(Debug, PartialEq, Eq)] 33 | pub enum AppError { 34 | Git(GitError), 35 | UnsafeDelete, 36 | InterruptedByUser, 37 | } 38 | 39 | impl From for AppError { 40 | fn from(error: GitError) -> Self { 41 | AppError::Git(error) 42 | } 43 | } 44 | 45 | impl fmt::Display for AppError { 46 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 47 | match self { 48 | AppError::Git(error) => error.fmt(f), 49 | AppError::UnsafeDelete => { 50 | write!(f, "This branch cannot be deleted safely") 51 | } 52 | AppError::InterruptedByUser => { 53 | write!(f, "Interrupted") 54 | } 55 | } 56 | } 57 | } 58 | 59 | pub struct App { 60 | repo: Repository, 61 | protected_branches: HashSet, 62 | ui: Box, 63 | fetch: bool, 64 | } 65 | 66 | impl App { 67 | pub fn new(args: &CliArgs, ui: Box, repo_dir: &str) -> App { 68 | let repo = Repository::new(&PathBuf::from(repo_dir)); 69 | 70 | let mut branches: HashSet = HashSet::new(); 71 | for branch in repo 72 | .get_config_keys("git-bonsai.protected-branches") 73 | .unwrap() 74 | { 75 | branches.insert(branch.to_string()); 76 | } 77 | for branch in &args.excluded { 78 | branches.insert(branch.to_string()); 79 | } 80 | App { 81 | repo, 82 | protected_branches: branches, 83 | ui, 84 | fetch: !args.no_fetch, 85 | } 86 | } 87 | 88 | // Used by test code 89 | #[allow(dead_code)] 90 | pub fn get_protected_branches(&self) -> HashSet { 91 | self.protected_branches.clone() 92 | } 93 | 94 | pub fn is_working_tree_clean(&self) -> bool { 95 | if self.repo.get_current_branch().is_none() { 96 | self.ui.log_error("No current branch"); 97 | return false; 98 | } 99 | match self.repo.has_changes() { 100 | Ok(has_changes) => { 101 | if has_changes { 102 | self.ui 103 | .log_error("Can't work in a tree with uncommitted changes"); 104 | return false; 105 | } 106 | true 107 | } 108 | Err(_) => { 109 | self.ui.log_error("Failed to get working tree status"); 110 | false 111 | } 112 | } 113 | } 114 | 115 | /// Ask git the name of the default branch, and store the result in git config. If we can't 116 | /// find it using git, fallback to asking the user. 117 | pub fn find_default_branch_from_git(&self) -> Result { 118 | self.ui.log_info("Determining repository default branch"); 119 | let branch = match self.repo.find_default_branch() { 120 | Ok(x) => x, 121 | Err(err) => { 122 | self.ui.log_error(&format!( 123 | "Can't determine default branch: {}", 124 | &err.to_string() 125 | )); 126 | return self.find_default_branch_from_user(); 127 | } 128 | }; 129 | self.repo 130 | .set_config_key(DEFAULT_BRANCH_CONFIG_KEY, &branch)?; 131 | self.ui.log_info(&format!("Default branch is {}", branch)); 132 | Ok(branch) 133 | } 134 | 135 | /// Ask the user the name of the default branch, and store the result in git config 136 | pub fn find_default_branch_from_user(&self) -> Result { 137 | let branch = match self.ui.select_default_branch(&self.repo.list_branches()?) { 138 | Some(x) => x, 139 | None => { 140 | return Err(AppError::InterruptedByUser); 141 | } 142 | }; 143 | self.repo 144 | .set_config_key(DEFAULT_BRANCH_CONFIG_KEY, &branch)?; 145 | Ok(branch) 146 | } 147 | 148 | /// Return the default branch stored in git config, if any 149 | pub fn get_default_branch(&self) -> Result, AppError> { 150 | match self.repo.get_config_keys(DEFAULT_BRANCH_CONFIG_KEY) { 151 | Ok(values) => Ok(if values.len() != 1 { 152 | None 153 | } else { 154 | Some(values[0].clone()) 155 | }), 156 | Err(x) => Err(AppError::Git(x)), 157 | } 158 | } 159 | 160 | pub fn fetch_changes(&self) -> Result<(), AppError> { 161 | self.ui.log_info("Fetching changes"); 162 | self.repo.fetch()?; 163 | Ok(()) 164 | } 165 | 166 | pub fn update_tracking_branches(&self) -> Result<(), AppError> { 167 | let branches = match self.repo.list_tracking_branches() { 168 | Ok(x) => x, 169 | Err(x) => { 170 | self.ui.log_error("Failed to list tracking branches"); 171 | return Err(AppError::Git(x)); 172 | } 173 | }; 174 | 175 | let _restorer = BranchRestorer::new(&self.repo); 176 | for branch in branches { 177 | self.ui.log_info(&format!("Updating {}", branch)); 178 | if let Err(x) = self.repo.checkout(&branch) { 179 | self.ui.log_error("Failed to checkout branch"); 180 | return Err(AppError::Git(x)); 181 | } 182 | if let Err(_x) = self.repo.update_branch() { 183 | self.ui.log_warning("Failed to update branch"); 184 | // This is not wrong, it can happen if the branches have diverged 185 | // let's continue 186 | } 187 | } 188 | Ok(()) 189 | } 190 | pub fn remove_merged_branches(&self) -> Result<(), AppError> { 191 | let to_delete = self.get_deletable_branches()?; 192 | 193 | if to_delete.is_empty() { 194 | self.ui.log_info("No deletable branches"); 195 | return Ok(()); 196 | } 197 | 198 | let selected_branches = self.ui.select_branches_to_delete(&to_delete); 199 | if selected_branches.is_empty() { 200 | return Ok(()); 201 | } 202 | 203 | let branch_names: Vec = selected_branches 204 | .iter() 205 | .map(|x| x.name.to_string()) 206 | .collect(); 207 | self.delete_branches(&branch_names[..])?; 208 | Ok(()) 209 | } 210 | 211 | /// Delete the specified branches, takes care of checking out another branch if we are deleting 212 | /// the current one 213 | fn delete_branches(&self, branches: &[String]) -> Result<(), AppError> { 214 | let current_branch = self.repo.get_current_branch().unwrap(); 215 | 216 | let mut current_branch_deleted = false; 217 | let default_branch = self.get_default_branch().unwrap().unwrap(); 218 | 219 | match self.repo.checkout(&default_branch) { 220 | Ok(()) => (), 221 | Err(x) => { 222 | let msg = format!("Failed to switch to default branch '{}'", default_branch); 223 | self.ui.log_error(&msg); 224 | return Err(AppError::Git(x)); 225 | } 226 | } 227 | 228 | for branch in branches { 229 | self.ui.log_info(&format!("Deleting {}", branch)); 230 | 231 | if self.safe_delete_branch(branch).is_err() { 232 | self.ui.log_warning("Failed to delete branch"); 233 | } else if *branch == current_branch { 234 | current_branch_deleted = true; 235 | } 236 | } 237 | 238 | if !current_branch_deleted { 239 | self.repo.checkout(¤t_branch)?; 240 | } 241 | Ok(()) 242 | } 243 | 244 | fn get_deletable_branches(&self) -> Result, AppError> { 245 | let deletable_branches: Vec = match self.repo.list_branches() { 246 | Ok(x) => x, 247 | Err(x) => { 248 | self.ui.log_error("Failed to list branches"); 249 | return Err(AppError::Git(x)); 250 | } 251 | } 252 | .iter() 253 | .filter(|&x| !self.protected_branches.contains(x)) 254 | .map(|branch| { 255 | let contained_in: HashSet = match self.repo.list_branches_containing(branch) { 256 | Ok(x) => x, 257 | Err(_x) => { 258 | self.ui 259 | .log_error(&format!("Failed to list branches containing {}", branch)); 260 | [].to_vec() 261 | } 262 | } 263 | .iter() 264 | .filter(|&x| x != branch) 265 | .cloned() 266 | .collect(); 267 | 268 | BranchToDeleteInfo { 269 | name: branch.to_string(), 270 | contained_in, 271 | } 272 | }) 273 | .filter(|x| !x.contained_in.is_empty()) 274 | .collect(); 275 | 276 | Ok(deletable_branches) 277 | } 278 | 279 | fn is_sha1_contained_in_another_branch( 280 | &self, 281 | sha1: &str, 282 | branches: &HashSet, 283 | ) -> Result { 284 | for branch in self.repo.list_branches_containing(sha1).unwrap() { 285 | if !branches.contains(&branch) { 286 | return Ok(true); 287 | } 288 | } 289 | Ok(false) 290 | } 291 | 292 | pub fn do_delete_identical_branches( 293 | &self, 294 | sha1: &str, 295 | branch_set: &HashSet, 296 | ) -> Result<(), AppError> { 297 | let unprotected_branch_set: HashSet<_> = 298 | branch_set.difference(&self.protected_branches).collect(); 299 | if !self 300 | .is_sha1_contained_in_another_branch(sha1, branch_set) 301 | .unwrap() 302 | { 303 | let contains_protected_branches = unprotected_branch_set.len() < branch_set.len(); 304 | let branches: Vec = unprotected_branch_set 305 | .iter() 306 | .map(|x| x.to_string()) 307 | .collect(); 308 | if !contains_protected_branches { 309 | let selected_branches: Vec = self 310 | .ui 311 | .select_identical_branches_to_delete_keep_one(&branches) 312 | .iter() 313 | .map(|x| x.to_string()) 314 | .collect(); 315 | self.delete_branches(&selected_branches)?; 316 | return Ok(()); 317 | } 318 | } 319 | if unprotected_branch_set.is_empty() { 320 | // Aliases are only protected branches, do nothing 321 | return Ok(()); 322 | } 323 | let branches: Vec = unprotected_branch_set 324 | .iter() 325 | .map(|x| x.to_string()) 326 | .collect(); 327 | let selected_branches: Vec<_> = self 328 | .ui 329 | .select_identical_branches_to_delete(&branches) 330 | .iter() 331 | .map(|x| x.to_string()) 332 | .collect(); 333 | self.delete_branches(&selected_branches)?; 334 | Ok(()) 335 | } 336 | 337 | pub fn delete_identical_branches(&self) -> Result<(), AppError> { 338 | // Create a hashmap sha1 => set(branches) 339 | let mut branches_for_sha1: HashMap> = HashMap::new(); 340 | 341 | match self.repo.list_branches_with_sha1s() { 342 | Ok(x) => x, 343 | Err(x) => { 344 | self.ui.log_error("Failed to list branches"); 345 | return Err(AppError::Git(x)); 346 | } 347 | } 348 | .iter() 349 | .for_each(|(branch, sha1)| { 350 | let branch_set = branches_for_sha1 351 | .entry(sha1.to_string()) 352 | .or_insert_with(HashSet::::new); 353 | branch_set.insert(branch.to_string()); 354 | }); 355 | 356 | // Delete identical branches if there are more than one for the same sha1 357 | for (sha1, branch_set) in branches_for_sha1 { 358 | if branch_set.len() == 1 { 359 | continue; 360 | } 361 | if let Err(x) = self.do_delete_identical_branches(&sha1, &branch_set) { 362 | self.ui.log_error("Failed to list branches"); 363 | return Err(x); 364 | } 365 | } 366 | 367 | Ok(()) 368 | } 369 | 370 | pub fn safe_delete_branch(&self, branch: &str) -> Result<(), AppError> { 371 | // A branch is only safe to delete if at least another branch contains it 372 | let contained_in = self.repo.list_branches_containing(branch).unwrap(); 373 | if contained_in.len() < 2 { 374 | self.ui.log_error(&format!( 375 | "Not deleting {}, no other branches contain it", 376 | branch 377 | )); 378 | return Err(AppError::UnsafeDelete); 379 | } 380 | self.repo.delete_branch(branch)?; 381 | Ok(()) 382 | } 383 | 384 | pub fn add_default_branch_to_protected_branches(&mut self) -> Result<(), AppError> { 385 | let default_branch = match self.get_default_branch()? { 386 | Some(x) => x, 387 | None => { 388 | if self.fetch { 389 | self.find_default_branch_from_git()? 390 | } else { 391 | self.find_default_branch_from_user()? 392 | } 393 | } 394 | }; 395 | self.protected_branches.insert(default_branch); 396 | Ok(()) 397 | } 398 | 399 | pub fn run(&mut self) -> Result<(), AppError> { 400 | self.add_default_branch_to_protected_branches()?; 401 | if self.fetch { 402 | self.fetch_changes()?; 403 | } 404 | 405 | self.update_tracking_branches()?; 406 | self.delete_identical_branches()?; 407 | self.remove_merged_branches()?; 408 | Ok(()) 409 | } 410 | } 411 | 412 | pub fn run(args: CliArgs, dir: &str) -> i32 { 413 | let ui: Box = match args.yes { 414 | false => Box::new(InteractiveAppUi {}), 415 | true => Box::new(BatchAppUi {}), 416 | }; 417 | let mut app = App::new(&args, ui, dir); 418 | 419 | if !app.is_working_tree_clean() { 420 | return 1; 421 | } 422 | 423 | match app.run() { 424 | Ok(()) => 0, 425 | Err(_) => 1, 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /src/appui.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | /** 20 | * This module provides a "high-level" interface for the UI 21 | */ 22 | use std::collections::HashSet; 23 | 24 | #[derive(Clone, Debug)] 25 | pub struct BranchToDeleteInfo { 26 | pub name: String, 27 | pub contained_in: HashSet, 28 | } 29 | 30 | pub trait AppUi { 31 | fn log_info(&self, msg: &str); 32 | fn log_warning(&self, msg: &str); 33 | fn log_error(&self, msg: &str); 34 | 35 | fn select_branches_to_delete( 36 | &self, 37 | branch_infos: &[BranchToDeleteInfo], 38 | ) -> Vec; 39 | 40 | fn select_identical_branches_to_delete(&self, branches: &[String]) -> Vec; 41 | 42 | fn select_identical_branches_to_delete_keep_one(&self, branches: &[String]) -> Vec; 43 | 44 | fn select_default_branch(&self, branches: &[String]) -> Option; 45 | } 46 | -------------------------------------------------------------------------------- /src/batchappui.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use crate::appui::{AppUi, BranchToDeleteInfo}; 20 | use crate::tui; 21 | 22 | pub struct BatchAppUi; 23 | 24 | impl AppUi for BatchAppUi { 25 | fn log_info(&self, msg: &str) { 26 | tui::log_info(msg); 27 | } 28 | 29 | fn log_warning(&self, msg: &str) { 30 | tui::log_warning(msg); 31 | } 32 | 33 | fn log_error(&self, msg: &str) { 34 | tui::log_error(msg); 35 | } 36 | 37 | fn select_branches_to_delete( 38 | &self, 39 | branch_infos: &[BranchToDeleteInfo], 40 | ) -> Vec { 41 | branch_infos.to_vec() 42 | } 43 | 44 | fn select_identical_branches_to_delete(&self, branches: &[String]) -> Vec { 45 | branches.to_vec() 46 | } 47 | 48 | fn select_identical_branches_to_delete_keep_one(&self, branches: &[String]) -> Vec { 49 | let mut to_delete = branches.to_vec(); 50 | to_delete.sort(); 51 | to_delete.remove(0); 52 | to_delete 53 | } 54 | 55 | fn select_default_branch(&self, _branches: &[String]) -> Option { 56 | None 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/cliargs.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use structopt::StructOpt; 20 | 21 | #[derive(StructOpt)] 22 | /// Keep a git repository clean and tidy. 23 | /// 24 | /// Branches can be declared as protected from suppression using `git config --add 25 | /// git-bonsai.protected-branches `. 26 | pub struct CliArgs { 27 | /// Other branches to protect from suppression. 28 | #[structopt(short = "x", long)] 29 | pub excluded: Vec, 30 | 31 | /// Do not fetch changes 32 | #[structopt(long = "no-fetch")] 33 | pub no_fetch: bool, 34 | 35 | /// Do not ask for confirmation 36 | #[structopt(short = "y", long = "yes")] 37 | pub yes: bool, 38 | } 39 | -------------------------------------------------------------------------------- /src/git.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use std::env; 20 | use std::fmt; 21 | use std::fs::File; 22 | use std::path::{Path, PathBuf}; 23 | use std::process::Command; 24 | 25 | // Define this environment variable to print all executed git commands to stderr 26 | const GIT_BONSAI_DEBUG: &str = "GB_DEBUG"; 27 | 28 | // If a branch is checked out in a separate worktree, then `git branch` prefixes it with this 29 | // string 30 | const WORKTREE_BRANCH_PREFIX: &str = "+ "; 31 | 32 | #[derive(Debug, PartialEq, Eq)] 33 | pub enum GitError { 34 | FailedToRunGit, 35 | CommandFailed { exit_code: i32 }, 36 | TerminatedBySignal, 37 | UnexpectedOutput(String), 38 | } 39 | 40 | impl fmt::Display for GitError { 41 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 42 | match self { 43 | GitError::FailedToRunGit => { 44 | write!(f, "Failed to run git") 45 | } 46 | GitError::CommandFailed { exit_code: e } => { 47 | write!(f, "Command exited with code {}", e) 48 | } 49 | GitError::TerminatedBySignal => { 50 | write!(f, "Terminated by signal") 51 | } 52 | GitError::UnexpectedOutput(message) => { 53 | write!(f, "UnexpectedOutput: {}", message) 54 | } 55 | } 56 | } 57 | } 58 | 59 | /** 60 | * Restores the current git branch when dropped 61 | * Assumes we are on a real branch 62 | */ 63 | pub struct BranchRestorer<'a> { 64 | repository: &'a Repository, 65 | branch: String, 66 | } 67 | 68 | impl BranchRestorer<'_> { 69 | pub fn new(repo: &Repository) -> BranchRestorer { 70 | let current_branch = repo.get_current_branch().expect("Can't get current branch"); 71 | BranchRestorer { 72 | repository: repo, 73 | branch: current_branch, 74 | } 75 | } 76 | } 77 | 78 | impl Drop for BranchRestorer<'_> { 79 | fn drop(&mut self) { 80 | if let Err(_x) = self.repository.checkout(&self.branch) { 81 | println!("Failed to restore original branch {}", self.branch); 82 | } 83 | } 84 | } 85 | 86 | pub struct Repository { 87 | pub path: PathBuf, 88 | } 89 | 90 | impl Repository { 91 | pub fn new(path: &Path) -> Repository { 92 | Repository { 93 | path: path.to_path_buf(), 94 | } 95 | } 96 | 97 | #[allow(dead_code)] 98 | pub fn clone(path: &Path, url: &str) -> Result { 99 | let repo = Repository::new(path); 100 | repo.git("clone", &[url, path.to_str().unwrap()])?; 101 | Ok(repo) 102 | } 103 | 104 | pub fn git(&self, subcommand: &str, args: &[&str]) -> Result { 105 | let mut cmd = Command::new("git"); 106 | cmd.current_dir(&self.path); 107 | cmd.env("LANG", "C"); 108 | cmd.arg(subcommand); 109 | for arg in args { 110 | cmd.arg(arg); 111 | } 112 | if env::var(GIT_BONSAI_DEBUG).is_ok() { 113 | eprintln!( 114 | "DEBUG: pwd={}: git {} {}", 115 | self.path.to_str().unwrap(), 116 | subcommand, 117 | args.join(" ") 118 | ); 119 | } 120 | let output = match cmd.output() { 121 | Ok(x) => x, 122 | Err(_x) => { 123 | println!("Failed to execute process"); 124 | return Err(GitError::FailedToRunGit); 125 | } 126 | }; 127 | if !output.status.success() { 128 | // TODO: store error message in GitError 129 | println!( 130 | "{}", 131 | String::from_utf8(output.stderr).expect("Failed to decode command stderr") 132 | ); 133 | return match output.status.code() { 134 | Some(code) => Err(GitError::CommandFailed { exit_code: code }), 135 | None => Err(GitError::TerminatedBySignal), 136 | }; 137 | } 138 | let out = String::from_utf8(output.stdout).expect("Failed to decode command stdout"); 139 | Ok(out) 140 | } 141 | 142 | pub fn fetch(&self) -> Result<(), GitError> { 143 | self.git("fetch", &["--prune"])?; 144 | Ok(()) 145 | } 146 | 147 | /// Reads config keys defined with `git config --add ` 148 | pub fn get_config_keys(&self, key: &str) -> Result, GitError> { 149 | let stdout = match self.git("config", &["--get-all", key]) { 150 | Ok(x) => x, 151 | Err(x) => match x { 152 | GitError::CommandFailed { exit_code: 1 } => { 153 | // Happens when reading a non-existing key 154 | return Ok([].to_vec()); 155 | } 156 | x => { 157 | return Err(x); 158 | } 159 | }, 160 | }; 161 | 162 | let values: Vec = stdout.lines().map(|x| x.into()).collect(); 163 | Ok(values) 164 | } 165 | 166 | pub fn set_config_key(&self, key: &str, value: &str) -> Result<(), GitError> { 167 | self.git("config", &[key, value])?; 168 | Ok(()) 169 | } 170 | 171 | pub fn find_default_branch(&self) -> Result { 172 | let stdout = self.git("ls-remote", &["--symref", "origin", "HEAD"])?; 173 | /* Output looks like this: 174 | * 175 | * ref: refs/heads/master\tHEAD 176 | * 960389f1c69e8b9c3fe06d29866d0d193375a6cb\tHEAD 177 | * 178 | * We want to extra "master" from the first line 179 | */ 180 | let line = stdout.lines().next().ok_or_else(|| { 181 | GitError::UnexpectedOutput("ls-remote returned an empty string".to_string()) 182 | })?; 183 | 184 | let line = line 185 | .strip_prefix("ref: refs/heads/") 186 | .ok_or_else(|| GitError::UnexpectedOutput("missing prefix".to_string()))?; 187 | 188 | let line = line 189 | .strip_suffix("\tHEAD") 190 | .ok_or_else(|| GitError::UnexpectedOutput("missing suffix".to_string()))?; 191 | 192 | Ok(line.to_string()) 193 | } 194 | 195 | pub fn list_branches(&self) -> Result, GitError> { 196 | self.list_branches_internal(&[]) 197 | } 198 | 199 | pub fn list_branches_with_sha1s(&self) -> Result, GitError> { 200 | let mut list: Vec<(String, String)> = Vec::new(); 201 | 202 | let lines = self.list_branches_internal(&["-v"])?; 203 | 204 | for line in lines { 205 | let mut it = line.split_whitespace(); 206 | let branch = it.next().unwrap().to_string(); 207 | let sha1 = it.next().unwrap().to_string(); 208 | list.push((branch, sha1)); 209 | } 210 | Ok(list) 211 | } 212 | 213 | fn list_branches_internal(&self, args: &[&str]) -> Result, GitError> { 214 | let mut branches: Vec = Vec::new(); 215 | 216 | let stdout = self.git("branch", args)?; 217 | 218 | for line in stdout.lines() { 219 | if line.starts_with(WORKTREE_BRANCH_PREFIX) { 220 | continue; 221 | } 222 | let branch = line.get(2..).expect("Invalid branch name"); 223 | branches.push(branch.to_string()); 224 | } 225 | Ok(branches) 226 | } 227 | 228 | pub fn list_branches_containing(&self, commit: &str) -> Result, GitError> { 229 | self.list_branches_internal(&["--contains", commit]) 230 | } 231 | 232 | pub fn list_tracking_branches(&self) -> Result, GitError> { 233 | let mut branches: Vec = Vec::new(); 234 | 235 | let lines = self.list_branches_internal(&["-vv"])?; 236 | 237 | for line in lines { 238 | if line.contains("[origin/") && !line.contains(": gone]") { 239 | let branch = line.split(' ').next(); 240 | branches.push(branch.unwrap().to_string()); 241 | } 242 | } 243 | Ok(branches) 244 | } 245 | 246 | pub fn checkout(&self, branch: &str) -> Result<(), GitError> { 247 | self.git("checkout", &[branch])?; 248 | Ok(()) 249 | } 250 | 251 | pub fn delete_branch(&self, branch: &str) -> Result<(), GitError> { 252 | self.git("branch", &["-D", branch])?; 253 | Ok(()) 254 | } 255 | 256 | pub fn get_current_branch(&self) -> Option { 257 | let stdout = self.git("branch", &[]); 258 | if stdout.is_err() { 259 | return None; 260 | } 261 | for line in stdout.unwrap().lines() { 262 | if line.starts_with('*') { 263 | return Some(line[2..].to_string()); 264 | } 265 | } 266 | None 267 | } 268 | 269 | pub fn update_branch(&self) -> Result<(), GitError> { 270 | let out = self.git("merge", &["--ff-only"])?; 271 | println!("{}", out); 272 | Ok(()) 273 | } 274 | 275 | pub fn has_changes(&self) -> Result { 276 | let out = self.git("status", &["--short"])?; 277 | Ok(!out.is_empty()) 278 | } 279 | 280 | #[allow(dead_code)] 281 | pub fn get_current_sha1(&self) -> Result { 282 | let out = self.git("show", &["--no-patch", "--oneline"])?; 283 | let sha1 = out.split(' ').next().unwrap().to_string(); 284 | Ok(sha1) 285 | } 286 | } 287 | 288 | // Used by test code 289 | #[allow(dead_code)] 290 | pub fn create_test_repository(path: &Path) -> Repository { 291 | let repo = Repository::new(path); 292 | 293 | repo.git("init", &[]).expect("init failed"); 294 | repo.git("config", &["user.name", "test"]) 295 | .expect("setting username failed"); 296 | repo.git("config", &["user.email", "test@example.com"]) 297 | .expect("setting email failed"); 298 | 299 | // Create a file so that we have more than the start commit 300 | File::create(path.join("f")).unwrap(); 301 | repo.git("add", &["."]).expect("add failed"); 302 | repo.git("commit", &["-m", "init"]).expect("commit failed"); 303 | 304 | repo 305 | } 306 | 307 | #[cfg(test)] 308 | mod tests { 309 | extern crate assert_fs; 310 | 311 | use super::*; 312 | use std::fs; 313 | 314 | #[test] 315 | fn get_current_branch() { 316 | let dir = assert_fs::TempDir::new().unwrap(); 317 | let repo = create_test_repository(dir.path()); 318 | assert_eq!(repo.get_current_branch().unwrap(), "master"); 319 | 320 | repo.git("checkout", &["-b", "test"]) 321 | .expect("create branch failed"); 322 | assert_eq!(repo.get_current_branch().unwrap(), "test"); 323 | } 324 | 325 | #[test] 326 | fn delete_branch() { 327 | // GIVEN a repository with a test branch containing unique content 328 | let dir = assert_fs::TempDir::new().unwrap(); 329 | let repo = create_test_repository(dir.path()); 330 | assert_eq!(repo.get_current_branch().unwrap(), "master"); 331 | 332 | repo.git("checkout", &["-b", "test"]).unwrap(); 333 | File::create(dir.path().join("test")).unwrap(); 334 | repo.git("add", &["test"]).unwrap(); 335 | repo.git("commit", &["-m", &format!("Create file")]) 336 | .unwrap(); 337 | 338 | repo.checkout("master").unwrap(); 339 | 340 | // WHEN I call delete_branch 341 | let result = repo.delete_branch("test"); 342 | 343 | // THEN the branch is deleted 344 | assert_eq!(result, Ok(())); 345 | 346 | // AND only the master branch remains 347 | assert_eq!(repo.list_branches().unwrap(), &["master"]); 348 | } 349 | 350 | #[test] 351 | fn list_branches_with_sha1s() { 352 | // GIVEN a repository with two branches 353 | let dir = assert_fs::TempDir::new().unwrap(); 354 | let repo = create_test_repository(dir.path()); 355 | 356 | repo.git("checkout", &["-b", "test"]).unwrap(); 357 | File::create(dir.path().join("test")).unwrap(); 358 | repo.git("add", &["test"]).unwrap(); 359 | repo.git("commit", &["-m", &format!("Create file")]) 360 | .unwrap(); 361 | 362 | // WHEN I list branches with sha1 363 | let branches_with_sha1 = repo.list_branches_with_sha1s().unwrap(); 364 | 365 | // THEN the list contains two entries 366 | assert_eq!(branches_with_sha1.len(), 2); 367 | 368 | // AND when switching to each branch, the current sha1 is the expected one 369 | for (branch, sha1) in branches_with_sha1 { 370 | repo.git("checkout", &[&branch]).unwrap(); 371 | assert_eq!(repo.get_current_sha1().unwrap(), sha1); 372 | } 373 | } 374 | 375 | #[test] 376 | fn list_branches_skip_worktree_branches() { 377 | // GIVEN a source repository with two branches 378 | let tmp_dir = assert_fs::TempDir::new().unwrap(); 379 | 380 | let source_path = tmp_dir.path().join("source"); 381 | fs::create_dir_all(&source_path).unwrap(); 382 | let source_repo = create_test_repository(&source_path); 383 | source_repo.git("branch", &["topic1"]).unwrap(); 384 | 385 | // AND a clone of this repository 386 | let clone_path = tmp_dir.path().join("clone"); 387 | fs::create_dir_all(&clone_path).unwrap(); 388 | let clone_repo = Repository::clone(&clone_path, &source_path.to_str().unwrap()).unwrap(); 389 | 390 | // with the topic1 branch checked-out in a separate worktree 391 | let worktree_dir = assert_fs::TempDir::new().unwrap(); 392 | let worktree_path_str = worktree_dir.path().to_str().unwrap(); 393 | clone_repo 394 | .git("worktree", &["add", worktree_path_str, "topic1"]) 395 | .unwrap(); 396 | 397 | // WHEN I list branches 398 | let branches = clone_repo.list_branches().unwrap(); 399 | 400 | // THEN it does not list worktree branches 401 | assert_eq!(branches.len(), 1); 402 | assert_eq!(branches, &["master"]); 403 | } 404 | 405 | #[test] 406 | fn find_default_branch_happy_path() { 407 | // GIVEN a source repository 408 | let tmp_dir = assert_fs::TempDir::new().unwrap(); 409 | let source_path = tmp_dir.path().join("source"); 410 | fs::create_dir_all(&source_path).unwrap(); 411 | create_test_repository(&source_path); 412 | 413 | // AND a clone of this repository 414 | let clone_path = tmp_dir.path().join("clone"); 415 | fs::create_dir_all(&clone_path).unwrap(); 416 | let clone_repo = Repository::clone(&clone_path, &source_path.to_str().unwrap()).unwrap(); 417 | 418 | // WHEN I call find_default_branch() on the clone 419 | let branch = clone_repo.find_default_branch(); 420 | 421 | // THEN it finds the default branch name 422 | assert_eq!(branch, Ok("master".to_string())); 423 | } 424 | 425 | #[test] 426 | fn find_default_branch_no_remote() { 427 | // GIVEN a repository without a remote 428 | let tmp_dir = assert_fs::TempDir::new().unwrap(); 429 | let repo = create_test_repository(&tmp_dir.path()); 430 | 431 | // WHEN I call find_default_branch() 432 | let branch = repo.find_default_branch(); 433 | 434 | // THEN it fails 435 | assert_eq!(branch, Err(GitError::CommandFailed { exit_code: 128 })); 436 | } 437 | } 438 | -------------------------------------------------------------------------------- /src/interactiveappui.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use crate::appui::{AppUi, BranchToDeleteInfo}; 20 | use crate::tui; 21 | 22 | pub struct InteractiveAppUi; 23 | 24 | fn format_branch_info(branch_info: &BranchToDeleteInfo) -> String { 25 | let container_str = branch_info 26 | .contained_in 27 | .iter() 28 | .map(|x| format!(" - {}", x)) 29 | .collect::>() 30 | .join("\n"); 31 | 32 | format!("{}, contained in:\n{} \n", branch_info.name, container_str) 33 | } 34 | 35 | impl AppUi for InteractiveAppUi { 36 | fn log_info(&self, msg: &str) { 37 | tui::log_info(msg); 38 | } 39 | 40 | fn log_warning(&self, msg: &str) { 41 | tui::log_warning(msg); 42 | } 43 | 44 | fn log_error(&self, msg: &str) { 45 | tui::log_error(msg); 46 | } 47 | 48 | fn select_branches_to_delete( 49 | &self, 50 | branch_infos: &[BranchToDeleteInfo], 51 | ) -> Vec { 52 | let select_items: Vec = branch_infos 53 | .iter() 54 | .map(format_branch_info) 55 | .collect::>(); 56 | 57 | let selections = tui::select("Select branches to delete", &select_items); 58 | 59 | selections 60 | .iter() 61 | .map(|&x| branch_infos[x].clone()) 62 | .collect::>() 63 | } 64 | 65 | fn select_identical_branches_to_delete(&self, branches: &[String]) -> Vec { 66 | let mut items = branches.to_vec(); 67 | items.sort(); 68 | 69 | let selections = tui::select( 70 | "These branches point to the same commit, which is contained in another branch,\ 71 | so it is safe to delete them all.\n\ 72 | Select branches to delete", 73 | &items, 74 | ); 75 | 76 | selections 77 | .iter() 78 | .map(|&x| items[x].clone()) 79 | .collect::>() 80 | } 81 | 82 | fn select_identical_branches_to_delete_keep_one(&self, branches: &[String]) -> Vec { 83 | let mut items = branches.to_vec(); 84 | items.sort(); 85 | 86 | let mut selections: Vec; 87 | println!( 88 | "These branches point to the same commit, but no other branch contains this commit, \ 89 | so you can delete all of them but one.\n" 90 | ); 91 | loop { 92 | selections = tui::select("Select branches to delete", &items); 93 | if selections.len() == items.len() { 94 | self.log_error("You must leave at least one branch unchecked."); 95 | } else { 96 | break; 97 | } 98 | } 99 | selections 100 | .iter() 101 | .map(|&x| items[x].clone()) 102 | .collect::>() 103 | } 104 | 105 | fn select_default_branch(&self, branches: &[String]) -> Option { 106 | let mut items = branches.to_vec(); 107 | items.sort(); 108 | 109 | tui::select_one("Select the branch to use as the default branch", &items) 110 | .map(|x| items[x].clone()) 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | pub mod app; 20 | pub mod appui; 21 | pub mod batchappui; 22 | pub mod cliargs; 23 | pub mod git; 24 | pub mod interactiveappui; 25 | pub mod tui; 26 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | use structopt::StructOpt; 20 | 21 | mod app; 22 | mod appui; 23 | mod batchappui; 24 | mod cliargs; 25 | mod git; 26 | mod interactiveappui; 27 | mod tui; 28 | 29 | use cliargs::CliArgs; 30 | 31 | fn main() { 32 | let args = CliArgs::from_args(); 33 | ::std::process::exit(app::run(args, ".")); 34 | } 35 | -------------------------------------------------------------------------------- /src/tui.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | 20 | /** 21 | * This module contains "low-level" primitives to implement a text-based UI 22 | */ 23 | use console::style; 24 | 25 | use dialoguer::{MultiSelect, Select}; 26 | 27 | pub fn log_warning(msg: &str) { 28 | println!("{}", style(format!("Warning: {}", msg)).yellow()); 29 | } 30 | 31 | pub fn log_error(msg: &str) { 32 | println!("{}", style(format!("Error: {}", msg)).red()); 33 | } 34 | 35 | pub fn log_info(msg: &str) { 36 | println!("{}", style(format!("Info: {}", msg)).blue()); 37 | } 38 | 39 | pub fn select(msg: &str, items: &[String]) -> Vec { 40 | let checked_items: Vec<(String, bool)> = items.iter().map(|x| (x.clone(), true)).collect(); 41 | 42 | MultiSelect::new() 43 | .with_prompt(msg) 44 | .items_checked(&checked_items[..]) 45 | .interact() 46 | .unwrap() 47 | } 48 | 49 | pub fn select_one(msg: &str, items: &[String]) -> Option { 50 | Select::new() 51 | .with_prompt(msg) 52 | .items(items) 53 | .default(0) 54 | .interact_opt() 55 | .unwrap() 56 | } 57 | -------------------------------------------------------------------------------- /tasks.py: -------------------------------------------------------------------------------- 1 | """ 2 | SPDX-FileCopyrightText: 2022 Aurélien Gâteau 3 | 4 | SPDX-License-Identifier: GPL-3.0-or-later 5 | 6 | A set of tasks to simplify the release process. See RELEASE_CHECK_LIST.md 7 | for details. 8 | """ 9 | 10 | import os 11 | import re 12 | import shutil 13 | import sys 14 | 15 | from pathlib import Path 16 | from typing import List 17 | 18 | from invoke import task, run 19 | 20 | 21 | ARTIFACTS_DIR = Path("artifacts") 22 | 23 | MAIN_BRANCH = "master" 24 | 25 | def get_version(): 26 | return os.environ["VERSION"] 27 | 28 | 29 | def erun(*args, **kwargs): 30 | """Like run, but with echo on""" 31 | kwargs["echo"] = True 32 | return run(*args, **kwargs) 33 | 34 | 35 | def cerun(c, *args, **kwargs): 36 | """Like Context.run, but with echo on""" 37 | kwargs["echo"] = True 38 | return c.run(*args, **kwargs) 39 | 40 | 41 | def ask(msg: str) -> str: 42 | """Show a message, wait for input and returns it""" 43 | print(msg, end=" ") 44 | return input() 45 | 46 | 47 | def is_ok(msg: str) -> bool: 48 | """Show a message, append (y/n) and return True if user select y or Y""" 49 | answer = ask(f"{msg} (y/n)").lower() 50 | return answer == "y" 51 | 52 | 53 | @task 54 | def create_pr(c): 55 | """Create a pull-request and mark it as auto-mergeable""" 56 | result = cerun(c, "gh pr create --fill", warn=True) 57 | if not result: 58 | sys.exit(1) 59 | cerun(c, f"gh pr merge --auto -dm") 60 | 61 | 62 | @task 63 | def update_version(c): 64 | version = get_version() 65 | path = Path("Cargo.toml") 66 | text = path.read_text() 67 | text, count = re.subn(r"^version = .*", f"version = \"{version}\"", text, 68 | flags=re.MULTILINE) 69 | assert count == 0 or count == 1 70 | path.write_text(text) 71 | 72 | 73 | @task 74 | def prepare_release(c): 75 | version = get_version() 76 | run(f"gh issue list -m {version}", pty=True) 77 | run("gh pr list", pty=True) 78 | if not is_ok("Continue?"): 79 | sys.exit(1) 80 | 81 | erun(f"git checkout {MAIN_BRANCH}") 82 | erun("git pull") 83 | erun("git status -s") 84 | if not is_ok("Continue?"): 85 | sys.exit(1) 86 | 87 | prepare_release2(c) 88 | 89 | 90 | @task 91 | def prepare_release2(c): 92 | version = get_version() 93 | erun("git checkout -b prep-release") 94 | 95 | update_version(c) 96 | 97 | erun(f"changie batch {version}") 98 | print(f"Review/edit changelog (.changes/{version}.md)") 99 | if not is_ok("Looks good?"): 100 | sys.exit(1) 101 | erun("changie merge") 102 | print("Review CHANGELOG.md") 103 | 104 | if not is_ok("Looks good?"): 105 | sys.exit(1) 106 | 107 | prepare_release3(c) 108 | 109 | 110 | @task 111 | def prepare_release3(c): 112 | version = get_version() 113 | # Rebuild to ensure Cargo.lock is updated 114 | erun("cargo build") 115 | erun("git add Cargo.toml Cargo.lock CHANGELOG.md .changes") 116 | 117 | erun("cargo publish --dry-run") 118 | 119 | erun(f"git commit -m 'Prepare {version}'") 120 | erun("git push -u origin prep-release") 121 | create_pr(c) 122 | 123 | 124 | @task 125 | def tag(c): 126 | version = get_version() 127 | erun(f"git checkout {MAIN_BRANCH}") 128 | erun("git pull") 129 | changes_file = Path(".changes") / f"{version}.md" 130 | if not changes_file.exists(): 131 | print(f"{changes_file} does not exist, check previous PR has been merged") 132 | sys.exit(1) 133 | if not is_ok("Create tag?"): 134 | sys.exit(1) 135 | 136 | erun(f"git tag -a {version} -m 'Releasing version {version}'") 137 | 138 | erun("git push") 139 | erun("git push --tags") 140 | 141 | 142 | def get_artifact_list() -> List[Path]: 143 | assert ARTIFACTS_DIR.exists() 144 | return list(ARTIFACTS_DIR.glob("*.tar.bz2")) 145 | 146 | 147 | @task 148 | def download_artifacts(c): 149 | if ARTIFACTS_DIR.exists(): 150 | shutil.rmtree(ARTIFACTS_DIR) 151 | ARTIFACTS_DIR.mkdir() 152 | erun(f"gh run download --dir {ARTIFACTS_DIR}", pty=True) 153 | 154 | 155 | @task 156 | def publish(c): 157 | version = get_version() 158 | files_str = " ".join(str(x) for x in get_artifact_list()) 159 | erun(f"gh release create {version} -F.changes/{version}.md {files_str}") 160 | erun("cargo publish") 161 | -------------------------------------------------------------------------------- /tests/integ.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Aurélien Gâteau 3 | * 4 | * This file is part of git-bonsai. 5 | * 6 | * Git-bonsai is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) 9 | * any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 | * more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along with 17 | * this program. If not, see . 18 | */ 19 | #[cfg(test)] 20 | mod integ { 21 | extern crate assert_fs; 22 | extern crate claim; 23 | extern crate git_bonsai; 24 | 25 | use std::collections::HashSet; 26 | use std::fs::File; 27 | use structopt::StructOpt; 28 | 29 | use assert_fs::prelude::*; 30 | use claim::*; 31 | use predicates::prelude::*; 32 | 33 | use git_bonsai::app::{self, App, AppError, DEFAULT_BRANCH_CONFIG_KEY}; 34 | use git_bonsai::batchappui::BatchAppUi; 35 | use git_bonsai::cliargs::CliArgs; 36 | use git_bonsai::git::create_test_repository; 37 | use git_bonsai::git::Repository; 38 | 39 | fn create_repository() -> (assert_fs::TempDir, Repository) { 40 | let dir = assert_fs::TempDir::new().unwrap(); 41 | let repo = create_test_repository(dir.path()); 42 | repo.set_config_key(DEFAULT_BRANCH_CONFIG_KEY, "master") 43 | .unwrap(); 44 | (dir, repo) 45 | } 46 | 47 | fn clone_repository(url: &str) -> (assert_fs::TempDir, Repository) { 48 | let dir = assert_fs::TempDir::new().unwrap(); 49 | let repo = Repository::clone(dir.path(), &url).unwrap(); 50 | (dir, repo) 51 | } 52 | 53 | fn create_branch(repo: &Repository, name: &str) { 54 | repo.git("checkout", &["-b", name]).unwrap(); 55 | create_and_commit_file(&repo, name); 56 | } 57 | 58 | fn create_and_commit_file(repo: &Repository, name: &str) { 59 | File::create(repo.path.join(name)).unwrap(); 60 | repo.git("add", &[name]).unwrap(); 61 | repo.git("commit", &["-m", &format!("Create file {}", name)]) 62 | .unwrap(); 63 | } 64 | 65 | fn merge_branch(repo: &Repository, name: &str) { 66 | repo.git("merge", &["--no-ff", name, "-m", "Merging branch"]) 67 | .unwrap(); 68 | } 69 | 70 | fn run_git_bonsai(cwd: &str, argv: &[&str]) -> i32 { 71 | let mut full_argv = vec!["git-bonsai"]; 72 | full_argv.extend(argv); 73 | let args = CliArgs::from_iter(full_argv); 74 | app::run(args, &cwd) 75 | } 76 | 77 | fn create_app(cwd: &str, argv: &[&str]) -> App { 78 | let mut full_argv = vec!["git-bonsai"]; 79 | full_argv.extend(argv); 80 | let ui = Box::new(BatchAppUi {}); 81 | let args = CliArgs::from_iter(full_argv); 82 | App::new(&args, ui, &cwd) 83 | } 84 | 85 | macro_rules! assert_branches_eq { 86 | ($repo:expr, $expected_branches:expr) => { 87 | let branches = $repo.list_branches().unwrap(); 88 | assert_eq!(branches, $expected_branches); 89 | }; 90 | } 91 | 92 | #[test] 93 | fn no_op() { 94 | // GIVEN a repository with a single branch 95 | let (dir, _repo) = create_repository(); 96 | let path_str = dir.path().to_str().unwrap(); 97 | 98 | // WHEN git-bonsai runs 99 | let result = run_git_bonsai(&path_str, &["-y"]); 100 | 101 | // THEN it succeeds 102 | assert_eq!(result, 0); 103 | } 104 | 105 | #[test] 106 | fn delete_merged_branch() { 107 | // GIVEN a repository with two topic branches, topic1 and topic2 108 | let (dir, repo) = create_repository(); 109 | let path_str = dir.path().to_str().unwrap(); 110 | create_branch(&repo, "topic1"); 111 | create_branch(&repo, "topic2"); 112 | // AND topic1 has been merged in master 113 | repo.checkout("master").unwrap(); 114 | merge_branch(&repo, "topic1"); 115 | 116 | assert_branches_eq!(&repo, &["master", "topic1", "topic2"]); 117 | 118 | // WHEN git-bonsai runs 119 | { 120 | let app = create_app(&path_str, &[]); 121 | assert_ok!(app.remove_merged_branches()); 122 | } 123 | 124 | // THEN only the topic1 branch has been removed 125 | assert_branches_eq!(&repo, &["master", "topic2"]); 126 | } 127 | 128 | #[test] 129 | fn skip_protected_branch() { 130 | // GIVEN a repository with a protected, merged branch: "protected" 131 | let (dir, repo) = create_repository(); 132 | let path_str = dir.path().to_str().unwrap(); 133 | create_branch(&repo, "protected"); 134 | repo.checkout("master").unwrap(); 135 | merge_branch(&repo, "protected"); 136 | 137 | assert_branches_eq!(&repo, &["master", "protected"]); 138 | 139 | // WHEN git-bonsai runs with "-x protected" 140 | { 141 | let app = create_app(&path_str, &["-x", "protected"]); 142 | assert_ok!(app.remove_merged_branches()); 143 | } 144 | 145 | // THEN the protected branch is still there 146 | assert_branches_eq!(&repo, &["master", "protected"]); 147 | 148 | // WHEN git-bonsai runs without "-x protected" 149 | { 150 | let app = create_app(&path_str, &[]); 151 | assert_ok!(app.remove_merged_branches()); 152 | } 153 | 154 | // THEN the protected branch is gone 155 | assert_branches_eq!(&repo, &["master"]); 156 | } 157 | 158 | #[test] 159 | fn update_branch() { 160 | // GIVEN a source repository 161 | let (source_dir, source_repo) = create_repository(); 162 | 163 | // AND a clone of it 164 | let (clone_dir, _clone_repo) = clone_repository(source_dir.path().to_str().unwrap()); 165 | let clone_dir_str = clone_dir.path().to_str().unwrap(); 166 | 167 | // AND a new commit in the source repository 168 | create_and_commit_file(&source_repo, "new"); 169 | 170 | // WHEN git-bonsai runs in the clone 171 | let result = run_git_bonsai(&clone_dir_str, &["-y"]); 172 | assert_eq!(result, 0); 173 | 174 | // THEN the clone repository now contains the new commit 175 | clone_dir.child("new").assert(predicate::path::exists()); 176 | } 177 | 178 | #[test] 179 | fn identical_sha1_no_other_branch() { 180 | // GIVEN a repository with three branches pointing to the same sha1, contained in no other 181 | // branch 182 | let (dir, repo) = create_repository(); 183 | let path_str = dir.path().to_str().unwrap(); 184 | create_branch(&repo, "topic1"); 185 | repo.git("branch", &["topic2", "topic1"]).unwrap(); 186 | repo.git("branch", &["topic3", "topic1"]).unwrap(); 187 | 188 | // WHEN git-bonsai runs 189 | let app = create_app(&path_str, &[]); 190 | assert_ok!(app.delete_identical_branches()); 191 | 192 | // THEN only the first topic branch remains 193 | assert_branches_eq!(&repo, &["master", "topic1"]); 194 | } 195 | 196 | #[test] 197 | fn identical_sha1_contained_in_master() { 198 | // GIVEN a repository with two branches pointing to the same sha1, contained in the master 199 | // branch 200 | let (dir, repo) = create_repository(); 201 | let path_str = dir.path().to_str().unwrap(); 202 | repo.git("branch", &["topic1"]).unwrap(); 203 | repo.git("branch", &["topic2"]).unwrap(); 204 | 205 | // WHEN git-bonsai runs 206 | let app = create_app(&path_str, &[]); 207 | assert_ok!(app.delete_identical_branches()); 208 | 209 | // THEN only the master branch remains 210 | assert_branches_eq!(&repo, &["master"]); 211 | } 212 | 213 | #[test] 214 | fn skip_worktree_branches() { 215 | // GIVEN a source repository with two branches 216 | let (source_dir, source_repo) = create_repository(); 217 | create_branch(&source_repo, "topic1"); 218 | source_repo.checkout("master").unwrap(); 219 | 220 | // AND a clone of this repository 221 | let (clone_dir, clone_repo) = clone_repository(source_dir.path().to_str().unwrap()); 222 | let clone_path_str = clone_dir.path().to_str().unwrap(); 223 | 224 | // with the topic1 branch checked-out in a separate worktree 225 | let worktree_dir = assert_fs::TempDir::new().unwrap(); 226 | let worktree_path_str = worktree_dir.path().to_str().unwrap(); 227 | clone_repo 228 | .git("worktree", &["add", worktree_path_str, "topic1"]) 229 | .unwrap(); 230 | 231 | let worktree_repo = Repository::new(worktree_dir.path()); 232 | worktree_repo.checkout("topic1").unwrap(); 233 | 234 | // WHEN git-bonsai updates the branches of the clone 235 | // THEN it does not fail 236 | let app = create_app(&clone_path_str, &[]); 237 | assert_ok!(app.update_tracking_branches()); 238 | } 239 | 240 | #[test] 241 | fn safe_delete_branch() { 242 | // GIVEN a repository with a test branch equals to master 243 | let (dir, repo) = create_repository(); 244 | repo.git("branch", &["test"]).unwrap(); 245 | repo.checkout("master").unwrap(); 246 | 247 | // WHEN I call safe_delete_branch 248 | let app = create_app(&dir.path().to_str().unwrap(), &[]); 249 | let result = app.safe_delete_branch("test"); 250 | 251 | // THEN it succeeds 252 | assert_eq!(result, Ok(())); 253 | 254 | // AND only the master branch remains 255 | assert_eq!(repo.list_branches().unwrap(), &["master"]); 256 | } 257 | 258 | #[test] 259 | fn cant_delete_unique_branch() { 260 | // GIVEN a repository with a test branch containing unique content 261 | let (dir, repo) = create_repository(); 262 | create_branch(&repo, "test"); 263 | repo.checkout("master").unwrap(); 264 | 265 | // WHEN I call safe_delete_branch 266 | let app = create_app(&dir.path().to_str().unwrap(), &[]); 267 | let result = app.safe_delete_branch("test"); 268 | 269 | // THEN it fails 270 | assert_eq!(result, Err(AppError::UnsafeDelete)); 271 | 272 | // AND the test branch still exists 273 | assert_eq!(repo.list_branches().unwrap(), &["master", "test"]); 274 | } 275 | 276 | #[test] 277 | fn test_protected_branches_from_git_config() { 278 | // GIVEN a repository with protected branches declared in git-config 279 | let (dir, repo) = create_repository(); 280 | create_branch(&repo, "test"); 281 | repo.checkout("master").unwrap(); 282 | repo.git( 283 | "config", 284 | &["--add", "git-bonsai.protected-branches", "custom1"], 285 | ) 286 | .unwrap(); 287 | repo.git( 288 | "config", 289 | &["--add", "git-bonsai.protected-branches", "custom2"], 290 | ) 291 | .unwrap(); 292 | 293 | // WHEN app is instantiated 294 | let mut app = create_app(&dir.path().to_str().unwrap(), &[]); 295 | app.add_default_branch_to_protected_branches().unwrap(); 296 | 297 | // THEN app.protected_branches contains all protected branches 298 | let expected_branches: HashSet = ["custom1", "custom2", "master"] 299 | .iter() 300 | .map(|x| x.to_string()) 301 | .collect(); 302 | assert_eq!(app.get_protected_branches(), expected_branches); 303 | } 304 | } 305 | --------------------------------------------------------------------------------