Fork me on GitHub
#babashka
<
2022-06-04
>
perpen13:06:23

I want to run a subprocess, and handle stdout and stderr differently. I came up with:

(defn run-handling-lines
  "Runs the command, passing each stdout/stderr line to the relevant handler.
   Returns the process exit code."
  [command handle-stdout handle-stderr]

  (let [proc (p/process command {:shutdown p/destroy-tree})
        reader->channel (fn [r]
                          (let [c (chan)]
                            (start-thread #(binding [*in* r]
                                             (loop [line (read-line)]
                                               (when (not (nil? line))
                                                 (>!! c line)
                                                 (recur (read-line))))
                                             (>!! c :exit)))
                            c))]

    (with-open [reader-stdout (io/reader (:out proc))
                reader-stderr (io/reader (:err proc))]
       (let [stdout-chan (reader->channel reader-stdout)
             stderr-chan (reader->channel reader-stderr)]
         (loop []
           (let [[line c] (alts!! [stdout-chan stderr-chan])
                 handler (condp = c
                           stdout-chan handle-stdout
                           stderr-chan handle-stderr)]
             (when (not= line :exit)
               (spy line)
               (handler line)
               (recur))))))
    (:exit @proc)))
But it feels really complicated for what it does, am I missing on some obvious clj or bb mechanism?

borkdude15:06:56

I think that's a reasonable approach. Usually I write a loop and a future which reads from those streams with read-line

perpen16:06:37

Thanks @U04V15CAJ, I'll look into futures.

orestis17:06:22

Perhaps a naive question, but say I want to manage my static blog with netlify, using babashka. How does that work? Do I setup a script that downloads babashka from somewhere? Run the script locally and commit the results directly to git, letting Netlify just publish a pre-built site?

borkdude18:06:41

Maybe @U8WFYMFRU can say something about this, I haven't got much netlify experience

eccentric J18:06:02

Hey there was experimenting with this. Currently I experimented with using node babashka to implement a few tasks to build static files then can publish them to netlify. You could also have netlify build on git push or use an action

eccentric J18:06:42

Same could be done with babashka. I chose nbb since there is a huge library of modern frontend tools to leverage in static site building.

orestis05:06:11

Well yes but how do you get the babashka binary to netlify? I guess you get nbb via npm which is straightforward

eccentric J04:06:27

Bash script to download the static binaries?

eccentric J05:06:18

Could also self-publish an npm package with just the babashka binary or use gh packages