Skip to content

Instantly share code, notes, and snippets.

@KGOH
Last active February 29, 2024 12:12
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save KGOH/50c0f66022fea2ac173518a143238058 to your computer and use it in GitHub Desktop.
Save KGOH/50c0f66022fea2ac173518a143238058 to your computer and use it in GitHub Desktop.
convert.clj -- babashka edn/json/yaml to edn/json/yaml converter
#!/usr/bin/env bb
;; convert.clj -- babashka edn/json/yaml to edn/json/yaml converter
;; Author: github.com/KGOH/
;; Source: gist.github.com/KGOH/50c0f66022fea2ac173518a143238058
;; Version: 2020.4
; Usage example:
; In Emacs: i.imgur.com/TIEDmga.mp4
; $ convert.clj edn <<< '{"foo": "bar"}'
; {:foo "bar"}
; $ convert.clj yaml <<< '{:foo "bar"}'
; {foo: "bar"}
; Emacs:
; (defun try-convert (out)
; (shell-command-on-region
; (region-beginning) (region-end)
; (format "convert.clj %s " out)
; nil "REPLACE" nil t))
; (defun convert-to-edn () (interactive) (try-convert "edn"))
; (defun convert-to-json () (interactive) (try-convert "json"))
; (defun convert-to-yaml () (interactive) (try-convert "yaml"))
; And my spacemacs keybindings:
; (spacemacs/set-leader-keys
; "oe" 'convert-to-edn
; "oj" 'convert-to-json
; "oy" 'convert-to-yaml)
(ns converter
(:require [clojure.string :as str]
[clojure.java.io :as io]
[clojure.pprint :as pprint]
[clojure.edn :as edn]
[cheshire.core :as json]
[clojure.walk :as walk]
[clj-yaml.core :as yaml]))
(def vectorify
"clj-yaml.core/parse-string returns lists instead of vectors"
(partial walk/postwalk #(cond-> % (sequential? %) vec)))
(defn try-convert [out s]
(let [parsers [(comp vectorify yaml/parse-string) edn/read-string]
out-convert (case out
:edn #(with-out-str (pprint/pprint %))
:json #(json/generate-string % {:pretty true})
:yaml yaml/generate-string
(constantly nil))]
(some->> parsers
(keep (fn [parser] (try (parser s) (catch Exception _))))
first
out-convert)))
(let [[out] *command-line-args*
[l :as s] (->> (io/reader *in*) line-seq)
pad (->> l (take-while #{\space}) str/join)]
(print (or (cond-> (some->> s (str/join \newline) (try-convert (keyword out)) str/trim)
(seq pad) (some->> str/split-lines (map (partial str pad)) (str/join \newline)))
s)))
@KGOH
Copy link
Author

KGOH commented Jun 5, 2020

TODO:

Done:

  • Padding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment