66 lines
2.7 KiB
Hy
66 lines
2.7 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])
|
|
|
|
(defn xmlroot [tree]
|
|
"Special process for root XML Node"
|
|
(setv root (first tree))
|
|
(setv rootel (.Element ET (get root "tag") (get root "attrs")))
|
|
(setv children (get root "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 [c children]
|
|
(if (string? c)
|
|
(setv (. parent text) c)
|
|
(do
|
|
(setv attrs (dfor [k v] (.items (get c "attrs")) [k (str v)]))
|
|
(setv new_parent (.SubElement ET parent (get c "tag") attrs))
|
|
(setv subchildren (get c "children"))
|
|
(if subchildren (xmlchild new_parent subchildren))))))
|
|
|
|
(defmacro xmlnc [&rest args]
|
|
"XMLNode with default children, not attributes"
|
|
(cond [(= (len args) 1) (setv tag (first args) attrs {} children [])]
|
|
[(= (len args) 2) (setv tag (first args) attrs {} children (last args))]
|
|
[(= (len args) 3) (setv tag (first args) attrs (get args 1) children (last args))])
|
|
`{"tag" ~tag "attrs" ~attrs "children" ~children})
|
|
|
|
(defmacro xmlna [&rest args]
|
|
"XMLNode with default attributes, not children"
|
|
(cond [(= (len args) 1) (setv tag (first args) attrs {} children [])]
|
|
[(= (len args) 2) (setv tag (first args) attrs (last args) children [])]
|
|
[(= (len args) 3) (setv tag (first args) attrs (get args 1) children (last args))])
|
|
`{"tag" ~tag "attrs" ~attrs "children" ~children})
|
|
|
|
(defmacro xmlnt [&rest args]
|
|
"XMLNode with no child but maybe some text"
|
|
(cond [(= (len args) 1) (setv tag (first args) attrs {} text "")]
|
|
[(= (len args) 2) (setv tag (first args) attrs {} text (last args))]
|
|
[(= (len args) 3) (setv tag (first args) attrs (get args 1) text (last args))])
|
|
`(xmln ~tag ~attrs [~text]))
|
|
|
|
(defmacro xmlr [&rest args]
|
|
"XML Root node"
|
|
(setv expr `(xmlnc ~@args)) `(xmlroot [~expr]))
|