xenodium · 2022-07-11 06:07
xenodium · 2022-07-11 06:10
https://xenodium.com/emacs-dwim-shell-command-multi-language/
Another usage of `dwim-shell-command-on-marked-files`, this time in non-shell languages.
Python
(defun dwim-shell-command-csv-to-json-via-python ()
"Convert csv file to json (via Python)."
(interactive)
(dwim-shell-command-on-marked-files
"Convert csv file to json (via Python)."
"
import csv
import json
text = json.dumps({ \"values\": list(csv.reader(open('<<f>>')))})
fpath = '<<fne>>.json'
with open(fpath , 'w') as f:
f.write(text)"
:shell-util "python"
:shell-args "-c"))
Swift
(defun dwim-shell-command-csv-to-json-via-swift ()
"Convert csv file to json (via Swift)."
(interactive)
(dwim-shell-command-on-marked-files
"Convert csv file to json (via Swift)."
"
import Foundation
import TabularData
let filePath = \"<<f>>\"
print(\"reading \\(filePath)\")
let content = try String(contentsOfFile: filePath).trimmingCharacters(in: .whitespacesAndNewlines)
let parsedCSV = content.components(separatedBy: CSVWritingOptions().newline).map{
$0.components(separatedBy: \",\")
}
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode([\"value\": parsedCSV])
let json = String(data: jsonData, encoding: String.Encoding.utf8)
let outURL = URL(fileURLWithPath:\"<<fne>>.json\")
try json!.write(to: outURL, atomically: true, encoding: String.Encoding.utf8)
print(\"wrote \\(outURL)\")"
:shell-pipe "swift -"))
jigarthanda-paal · 2022-07-11 12:56
Interesting! I think it should be possible to do this in lisp as well...
xenodium · 2022-07-11 18:04
You mean solve csv to json in elisp? Or integrating some other lisp (Common Lisp?) like shown for python and swift? Either way, yes ;)
jigarthanda-paal · 2022-07-11 18:15
Yeah the former.
xenodium · 2022-07-11 18:51
Ah yeah. The csv -> json conversion was more of a sample problem. We can solve it in elisp (and I typically do), but sometimes it's quicker to just use an existing snippet one already has in a different language.
Multi-language brings convenience when you also inherit the other DWIM support from \`dwim-shell-command-on-marked-files\`.
divinedominion · 2022-07-13 07:05
Also thanks for the accidental demo of `TabularData`. Didn't look into the new API just yet :)
xenodium · 2022-07-13 08:07
👍 that was my first time using the tabular data Swift API, and didn’t quite use it other than a constant :)
varsderk · 2022-07-13 23:17
A little off-topic, but what font is that?
xenodium · 2022-07-14 04:42
https://www.jetbrains.com/lp/mono/