-
-
Save refset/5dfe93883d0024572eadfd62619389da to your computer and use it in GitHub Desktop.
convert.clj -- babashka edn/json/yaml to edn/json/yaml converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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.3 | |
; 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) | |
(< 0 (count pad)) | |
(->> str/split-lines (map (partial str pad)) (str/join \newline))) | |
s))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment