Skip to content

Instantly share code, notes, and snippets.

@xavierchow
Last active February 21, 2025 14:12
Show Gist options
  • Save xavierchow/06cf91cd2b347cc869b069b884088480 to your computer and use it in GitHub Desktop.
Save xavierchow/06cf91cd2b347cc869b069b884088480 to your computer and use it in GitHub Desktop.
babashka script to remove outdated git branch
#! /usr/bin/env bb
(require '[babashka.process :refer [shell]])
(require '[clojure.string :refer [includes? split-lines trim]])
(require '[babashka.cli :as cli])
(def cli-options {:main {:default "main" :alias :m :desc "the main branch name" }
:help {:coerce :boolean}})
(def cli-opt (cli/parse-opts *command-line-args* {:spec cli-options}))
(defn lazy-contains? [col key]
(boolean (some #(= % key) col)))
(defn behind? [target main]
( -> (shell {:out :string } (format "git log %s..%s" main target)) :out empty?))
(defn not_head [n]
(not (includes? n "HEAD")))
(defn git_rm [branch]
(shell {:out :string } (format "git branch -d %s" branch))
(println (format "Branch: [%s] has been removed" branch)))
(def locals (->> (shell {:out :string } "git branch") :out split-lines))
(def normalized (->> locals (map #(if (includes? % "*") (subs % (count "* ")) %))))
(if (not (lazy-contains? normalized (:main cli-opt)))
(println (format "Branch [%s] does not exit" (:main cli-opt) ))
(let [remotes_fullname ( -> (shell {:out :string } "git branch -r") :out split-lines )
remote_branches (->> remotes_fullname (filter not_head) (map #(subs (trim %) (count "origin/"))))
local_candidates (filter #(not (includes? % "*")) locals)
to_remove (filter #(and (not (lazy-contains? remote_branches %)) (behind? % (:main cli-opt))) (map #(trim %) local_candidates))
]
(doseq [to_rm to_remove]
(git_rm to_rm) )))
@xavierchow
Copy link
Author

need to check if the main branch exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment