]> njoseph.me Git - babashka-scripts.git/blob - scripts/git.clj
370b3158af02ba81a2289a02b00e42f96cee349c
[babashka-scripts.git] / scripts / git.clj
1 (ns git
2 (:require [babashka.process :as p]
3 [clojure.java.io :as io]
4 [clojure.string :as str]
5 [lib :refer [run-cmd]]))
6
7 ; Utilities for git operations
8
9 (defn- has-git-repo
10 [dir]
11 (first (filter #(= ".git" %)
12 (map #(.getName %)
13 (filter #(.isDirectory %) (.listFiles (io/file dir)))))))
14
15 (defn- list-dirs
16 [root]
17 (filter #(has-git-repo %)
18 (filter #(.isDirectory %) (.listFiles (io/file root)))))
19
20 (defn- git-pull [dir] (p/process ["git" "-C" dir "pull" "--rebase"]))
21
22 (defn git-pull-all
23 "Runs `git-pull` on all the git repositories in a directory"
24 [root]
25 (let [dirs (list-dirs root)
26 pulls (->> root
27 list-dirs
28 (map git-pull)
29 doall)
30 outputs (map #(->> %
31 p/check
32 :out
33 slurp)
34 pulls)]
35 ;; Print corresponding directory name when pulling
36 ;; Skip printing already up to date repos
37 (doseq [[dir out] (filter #(not (.contains (second %) "is up to date."))
38 (map vector dirs outputs))]
39 (println (str dir "\n" out)))))
40
41
42 (defn git-pull-rebase-branch
43 "Do git pull and rebase branch with master"
44 [dir]
45 (run-cmd ["git" "pull" "--rebase"])
46 (let [current-branch (str/trim (run-cmd ["git" "branch" "--show-current"]))]
47 (when (not (contains? #{"master" "main"} current-branch))
48 (run! print
49 (map run-cmd
50 [["git" "checkout" "master"] ["git" "pull" "--rebase"]
51 ["git" "checkout" current-branch] ["git" "rebase" "master"]])))))