71 lines
2.6 KiB
Hy
71 lines
2.6 KiB
Hy
;; -*- coding: utf-8 -*-
|
|
;;
|
|
;; Copyright 2019 Fabien Bourgeois <fabien@yaltik.com>
|
|
;;
|
|
;; This program is free software: you can redistribute it and/or modify
|
|
;; it under the terms of the GNU Affero General Public License as
|
|
;; published by the Free Software Foundation, either version 3 of the
|
|
;; License, or (at your option) any later version.
|
|
;;
|
|
;; This program is distributed in the hope that it will be useful,
|
|
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
;; GNU Affero General Public License for more details.
|
|
;;
|
|
;; You should have received a copy of the GNU Affero General Public License
|
|
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
" XML helpers and macros "
|
|
|
|
(import [xml.etree.ElementTree :as ET])
|
|
|
|
;; Helpers
|
|
|
|
(defn xmlroot [tree]
|
|
"Special process for root XML Node"
|
|
(setv rootel (.Element ET (get tree "tag") (get tree "attrs"))
|
|
children (get tree "children"))
|
|
(if children (xmlchild rootel children))
|
|
(return rootel))
|
|
|
|
(defn xmlchild [parent children]
|
|
"Handling of children (ie non root) XML Nodes with/o text and subchildren
|
|
(recursive)"
|
|
(for [child children]
|
|
(if (string? child)
|
|
(setv (. parent text) child)
|
|
(do
|
|
(setv attrs (dfor [k v] (.items (get child "attrs")) [(str k) (str v)]))
|
|
(setv new_parent (.SubElement ET parent (get child "tag") attrs))
|
|
(setv subchildren (get child "children"))
|
|
(if subchildren (xmlchild new_parent subchildren))))))
|
|
|
|
(defn xmln [tag &optional attrs children]
|
|
"XMLNode with optional attributes or children, defaults according to second
|
|
argument type or empty dict and list"
|
|
(if (and attrs (not children))
|
|
(if (instance? list attrs)
|
|
(do (setv children attrs) (setv attrs {}))))
|
|
{"tag" tag "attrs" (or attrs {}) "children" (or children [])})
|
|
|
|
;; Macros
|
|
|
|
(defmacro if-python2 [python2-form python3-form]
|
|
"If running on python2, execute python2-form, else, execute python3-form"
|
|
(import sys)
|
|
(if (< (get sys.version_info 0) 3)
|
|
python2-form
|
|
python3-form))
|
|
|
|
(defmacro/g! xml-write [filename tree]
|
|
"Write XML file according to filename and given tree"
|
|
`(do
|
|
(import [os [path]]
|
|
[xml.etree.ElementTree :as ET])
|
|
(if-python2
|
|
(setv ~g!output-xml (.tostring ET ~tree))
|
|
(setv ~g!output-xml (.decode (.tostring ET ~tree) "utf-8")))
|
|
(setv ~g!output-path (.dirname path (.abspath path __file__))
|
|
~g!fpath (+ ~g!output-path "/" ~filename))
|
|
(with [f (open ~g!fpath "w")] (.write f ~g!output-xml))))
|