unixify v2
[babashka-scripts.git] / lib.clj
CommitLineData
1770a260 1; Common utility functions used by scripts
ead73d37 2; Unlike the functions in utils.clj, these are not directly useful
f1d839f5 3
67d5a15a
JN
4(ns lib
5 (:require [babashka.process :as p]
6 [org.httpkit.client :as http]
7 [clojure.java.io :as io]
ead73d37 8 [clojure.string :as str])
67d5a15a 9 (:import [java.nio.file Files FileSystems CopyOption StandardCopyOption]))
fbc08850
JN
10
11(defn run-cmd
12 [command]
13 (->> command
14 p/process
15 :out
16 slurp))
9da8be80 17
f1d839f5
JN
18(defn extract-file-from-zip
19 [zip-file-name source destination]
20 (let [zip-file (io/file zip-file-name)
f1d839f5
JN
21 dest (io/file destination)
22 fs (FileSystems/newFileSystem (.toPath zip-file) nil)
23 file-in-zip (.getPath fs source (into-array String []))]
0b0f2aa3
JN
24 (Files/copy file-in-zip
25 (.toPath dest)
f1d839f5
JN
26 (into-array CopyOption [StandardCopyOption/REPLACE_EXISTING]))))
27
0b0f2aa3
JN
28(defn expand-home
29 [s]
f1d839f5 30 (if (.startsWith s "~")
ead73d37 31 (str/replace-first s "~" (System/getProperty "user.home"))
f1d839f5 32 s))
9da8be80
JN
33
34(defn download-binary
35 [url destination]
36 (io/copy (:body @(http/get url)) (io/file destination)))
76cc62f0
JN
37
38(defn unixify
ead73d37
JN
39 "Make a function `f` behave like a UNIX shell command.
40
41 Examples:
42
43 # Multiple arguments
44 $ install-deb url1 url2 url3
45
46 # Read from file with one url on each line
47 $ install-deb `cat urls.txt`
48
49 # Piping from another process
50 $ ls | install-deb # Note: install-deb doesn't work with ls
51 "
76cc62f0
JN
52 [f]
53 (when (= *file* (System/getProperty "babashka.file"))
ead73d37
JN
54 (if (> (.available System/in) 0)
55 (->> (slurp *in*)
56 (str/split-lines)
30bd2f34 57 (filter seq)
ead73d37
JN
58 (run! f))
59 (->> (vec *command-line-args*)
60 (map #(str/split % #" "))
61 (flatten)
30bd2f34 62 (run! f)))))