utils: Install deb from GitHub. Reduce scripts.
[babashka-scripts.git] / utils.clj
1 (ns utils
2 (:require [clojure.string :as str]
3 [clojure.java.io :as io]
4 [cheshire.core :as json]
5 [org.httpkit.client :as http]
6 [lib :refer [download-binary run-cmd]]))
7
8 (defn git-pull-rebase-branch
9 "Do git pull and rebase branch with master"
10 []
11 (let [current-branch (str/trim (run-cmd ["git" "branch" "--show-current"]))]
12 (print (run-cmd ["git" "pull" "--rebase"]))
13 (when (not (contains? #{"master" "main"} current-branch))
14 (run! print
15 (map run-cmd
16 '[["git" "checkout" "master"] ["git" "pull" "--rebase"]
17 ["git" "checkout" "-"] ["git" "rebase" "master"]])))))
18
19 (defn run-seq
20 "Run a sequence of shell commands on a sequence of arguments.
21
22 Examples:
23
24 1. Play and delete each video from a folder
25 ls | bb -i '(run-seq [\"mpv\" \"rm\"] *input*)'
26 "
27 [commands arguments]
28 (doseq [argument arguments
29 command commands]
30 (println (run-cmd [command argument]))))
31
32 (defn install-deb
33 "Install a Debian package given a direct URL to the .deb file."
34 [url]
35 (println "Downloading deb package...")
36 (download-binary url "package.deb")
37 (println "Installing...")
38 (println (run-cmd ["sudo" "apt" "install" "./package.deb"]))
39 (println "Cleaning up..")
40 (io/delete-file "package.deb")
41 (println "Done."))
42
43 (defn install-deb-from-GitHub
44 "Install a Debian package given a GitHub URL."
45 [url]
46
47 (assert (.contains url "github.com"))
48
49 (letfn [(extract-GitHub-author-project
50 ;; Extracts a string like author/project from URL.
51 [url]
52 (str/join "/" (subvec (str/split url #"/") 3)))
53 (make-api-url ;; just some string interpolation
54 [author-project]
55 (str "https://api.github.com/repos/"
56 author-project
57 "/releases/latest"))
58 (get-assets ;; Download list of assets from GitHub
59 [api-url]
60 (:assets (json/parse-string
61 (:body @(http/get api-url)) true)))
62 (find-url-to-deb ;; Find Debian package URL from assets
63 [assets]
64 (some #(if (str/ends-with? % "deb") %)
65 (map #(:browser_download_url %) assets)))]
66
67 (let [author-project (extract-GitHub-author-project url)
68 api-url (make-api-url author-project)
69 assets (get-assets api-url)
70 deb-url (find-url-to-deb assets)]
71 ;; Download and install Debian package
72 (install-deb deb-url))))