]> njoseph.me Git - babashka-scripts.git/blame - scripts/git.clj
git: Fix function git-pull-rebase
[babashka-scripts.git] / scripts / git.clj
CommitLineData
ec37ad05
JN
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
ec37ad05
JN
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
e1035b9f 20(defn- git-pull [dir] (p/process ["git" "-C" dir "pull" "--rebase"]))
ec37ad05
JN
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)
e1035b9f 34 pulls)]
ec37ad05
JN
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."))
e1035b9f 38 (map vector dirs outputs))]
ec37ad05
JN
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]
e1035b9f 45 (run-cmd ["git" "pull" "--rebase"])
ec37ad05 46 (let [current-branch (str/trim (run-cmd ["git" "branch" "--show-current"]))]
ec37ad05
JN
47 (when (not (contains? #{"master" "main"} current-branch))
48 (run! print
49 (map run-cmd
e1035b9f
JN
50 [["git" "checkout" "master"] ["git" "pull" "--rebase"]
51 ["git" "checkout" current-branch] ["git" "rebase" "master"]])))))