unixify v2
[babashka-scripts.git] / lib.clj
1 ; Common utility functions used by scripts
2 ; Unlike the functions in utils.clj, these are not directly useful
3
4 (ns lib
5 (:require [babashka.process :as p]
6 [org.httpkit.client :as http]
7 [clojure.java.io :as io]
8 [clojure.string :as str])
9 (:import [java.nio.file Files FileSystems CopyOption StandardCopyOption]))
10
11 (defn run-cmd
12 [command]
13 (->> command
14 p/process
15 :out
16 slurp))
17
18 (defn extract-file-from-zip
19 [zip-file-name source destination]
20 (let [zip-file (io/file zip-file-name)
21 dest (io/file destination)
22 fs (FileSystems/newFileSystem (.toPath zip-file) nil)
23 file-in-zip (.getPath fs source (into-array String []))]
24 (Files/copy file-in-zip
25 (.toPath dest)
26 (into-array CopyOption [StandardCopyOption/REPLACE_EXISTING]))))
27
28 (defn expand-home
29 [s]
30 (if (.startsWith s "~")
31 (str/replace-first s "~" (System/getProperty "user.home"))
32 s))
33
34 (defn download-binary
35 [url destination]
36 (io/copy (:body @(http/get url)) (io/file destination)))
37
38 (defn unixify
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 "
52 [f]
53 (when (= *file* (System/getProperty "babashka.file"))
54 (if (> (.available System/in) 0)
55 (->> (slurp *in*)
56 (str/split-lines)
57 (filter seq)
58 (run! f))
59 (->> (vec *command-line-args*)
60 (map #(str/split % #" "))
61 (flatten)
62 (run! f)))))