Skip to content

Instantly share code, notes, and snippets.

@jesse-c
Created September 6, 2022 09:29
Show Gist options
  • Save jesse-c/ac596d873407872718ac1eec223d7229 to your computer and use it in GitHub Desktop.
Save jesse-c/ac596d873407872718ac1eec223d7229 to your computer and use it in GitHub Desktop.
using babashka for my Git worktree workflow
#!/usr/bin/env bb
(require '[babashka.fs :as fs]
'[babashka.process :as process])
; Get the final path name
(defn get-final-path-name []
(.toString (.getName (fs/cwd) (- (.getNameCount (fs/cwd)) 1))))
; Get the matching group that may have a worktree-type name
;
; Example: ["empty-b", "b"]
(defn get-worktree []
(re-matches #".*-([a-z])$" (get-final-path-name)))
; Build the Git branch name
(defn build-branch [worktree]
(str "empty-" (last (worktree))))
; Ignore the returned Process and return success
;
; Example: {:proc #object[java.lang.ProcessImpl 0x7ddf9484 "Process[pid=65208, exitValue=0]"], :exit 0, :in #object[java.lang.ProcessImpl$ProcessPipeOutputStream 0x51719cc7 "java.lang.ProcessImpl$ProcessPipeOutputStream@51719cc7"], :out "", :err #object[java.lang.ProcessImpl$ProcessPipeInputStream 0x2efa8fb7 "java.lang.ProcessImpl$ProcessPipeInputStream@2efa8fb7"], :prev nil, :cmd ["git" "sw" "empty-b"]}
(defn return [_process]
"Switched branch")
; Switch to the found Git branch
(defn switch-branch [branch]
(-> (process/process ["git" "sw" branch] {:out :string})
(process/check)
(return)))
(defn run []
(let [worktree get-worktree]
(if (= (count (worktree)) 2)
(switch-branch (build-branch worktree))
(System/exit 1))))
(run)
@shaharz
Copy link

shaharz commented Sep 7, 2022

It's been a while since I last wrote Clojure but something like this seems a bit more idiomatic (unformatted and untested):

#!/usr/bin/env bb

(require '[babashka.fs :as fs]
         '[babashka.process :as process])

(defn switch-branch [branch]
    (-> (process/process ["git" "sw" branch] {:out :string}) (process/check)))

(let [worktree (->> (fs/cwd) (fs/file-name) (re-matches #".*-([a-z])$"))]
    (when (= (count worktree) 2)
        (->> (last worktree) (str "empty-") (switch-branch))))

You could also break things apart into a let as I mentioned if you feel like binding an intermediate value to a name makes things more readable.

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