Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Converting Clojure File to YAML

Tags:

yaml

clojure

How would you convert a clojure source file to YAML? I have used the clj-yaml library to do it in the interactive REPL, but I'd like to automate this, so I can pass in an input file and specify an output, ie:

clj2yaml input.clj > output.yml 
like image 205
Zach Dennis Avatar asked May 27 '11 14:05

Zach Dennis


2 Answers

As I understand it you need help to read and write the files?! See slurp and spit. For a real example of reading a YAML config file and parsing it with clj-yaml, see pswincom.gateway.config.

And here's an implementation of a simple clojure tool to do the convertion:

(ns sample
    (:require [clj-yaml.core :as yaml]))

(->> (slurp (nth *command-line-args* 0))
     read-string ; converts the file content to a clojure datastructure
     yaml/generate-string
     (spit (nth *command-line-args* 1)))

(On Windows) I can create a batch file called clj2yaml.bat to make it easy to use. It assumes the needed jar-files are located in the current directory. I'm just a novice when it comes to this kind of execution, so a better script is quite likely possible, but here it is:

java.exe -cp .\clojure-1.2.0.jar;.\clojure-contrib-1.2.0.jar;.\clj-yaml-0.3.0-20101010.033133-1.jar;.\snakeyaml-1.5.jar clojure.main sample.clj %*

I can now execute clj2yaml foo.clj foo.yaml to create the yaml file.

like image 119
Torbjørn Avatar answered Sep 29 '22 15:09

Torbjørn


You already know how to code a clojure converter, you now just need to package it as a standalone application, and possibly create a sh script that just invokes your class.

As an alternative, here's a neat way to do it, if you're on a *nix environment:

#^:shebang '[
exec java -cp "$HOME/src/clj/clojure/clojure.jar" clojure.lang.Script "$0" -- "$@"
]
(your code here)
like image 23
skuro Avatar answered Sep 29 '22 16:09

skuro