]> njoseph.me Git - babashka-scripts.git/blame - scripts/git.clj
Shift from standalone scripts to babashka tasks
[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
9(def default-root ".")
10
11(defn- has-git-repo
12 [dir]
13 (first (filter #(= ".git" %)
14 (map #(.getName %)
15 (filter #(.isDirectory %) (.listFiles (io/file dir)))))))
16
17(defn- list-dirs
18 [root]
19 (filter #(has-git-repo %)
20 (filter #(.isDirectory %) (.listFiles (io/file root)))))
21
22(defn- git-pull [dir]
23 (p/process ["git" "-C" dir "pull" "--rebase"]))
24
25(defn git-pull-all
26 "Runs `git-pull` on all the git repositories in a directory"
27 [root]
28 (let [dirs (list-dirs root)
29 pulls (->> root
30 list-dirs
31 (map git-pull)
32 doall)
33 outputs (map #(->> %
34 p/check
35 :out
36 slurp)
37 pulls)]
38 ;; Print corresponding directory name when pulling
39 ;; Skip printing already up to date repos
40 (doseq [[dir out] (filter #(not (.contains (second %) "is up to date."))
41 (map vector dirs outputs))]
42 (println (str dir "\n" out)))))
43
44
45(defn git-pull-rebase-branch
46 "Do git pull and rebase branch with master"
47 [dir]
48 (let [current-branch (str/trim (run-cmd ["git" "branch" "--show-current"]))]
49 (git-pull dir)
50 (when (not (contains? #{"master" "main"} current-branch))
51 (run! print
52 (map run-cmd
53 '[["git" "checkout" "master"]
54 ["git" "pull" "--rebase"]
55 ["git" "checkout" "-"]
56 ["git" "rebase" "master"]])))))