Fixes #1875: parse-args requires values to be representable as Hy models

* Update argument spec parse logic of parse-args function.
* Update test case of parse-args function.
* Update document of parse-args function.
* Describe the change in NEWS file.
This commit is contained in:
redraiment 2020-03-15 14:39:21 +08:00 committed by Kodi Arfer
parent 1112472f00
commit 2b40dea54d
4 changed files with 23 additions and 4 deletions

View File

@ -1,5 +1,13 @@
.. default-role:: code
Unreleased
==============================
Other Breaking Changes
------------------------------
* `parse-args` is no longer implemented with `eval`; so e.g. you should
now say `:type int` instead of `:type 'int`.
0.18.0
==============================

View File

@ -804,7 +804,7 @@ may be a list of keyword arguments to pass to the
.. code-block:: hy
=> (parse-args [["strings" :nargs "+" :help "Strings"]
["-n" "--numbers" :action "append" :type 'int :help "Numbers"]]
["-n" "--numbers" :action "append" :type int :help "Numbers"]]
["a" "b" "-n" "1" "-n" "2"]
:description "Parse strings and numbers from args")
Namespace(numbers=[1, 2], strings=['a', 'b'])

View File

@ -401,7 +401,17 @@ constructor."
(import argparse)
(setv parser (argparse.ArgumentParser #** parser-args))
(for [arg spec]
(eval `(.add-argument parser ~@arg)))
(setv positional-arguments []
keyword-arguments []
value-of-keyword? False)
(for [item arg]
(if value-of-keyword?
(.append (get keyword-arguments -1) item)
(if (keyword? item)
(.append keyword-arguments [(name item)])
(.append positional-arguments item)))
(setv value-of-keyword? (and (not value-of-keyword?) (keyword? item))))
(parser.add-argument #* positional-arguments #** (dict keyword-arguments)))
(.parse-args parser args))
(setv EXPORTS

View File

@ -480,9 +480,10 @@ result['y in globals'] = 'y' in globals()")
(defn test-parse-args []
"NATIVE: testing the parse-args function"
; https://github.com/hylang/hy/issues/1875
(setv parsed-args (parse-args [["strings" :nargs "+" :help "Strings"]
["-n" "--numbers" :action "append" :type 'int :help "Numbers"]]
["a" "b" "-n" "1" "-n" "2"]
["-n" :action "append" :type int :help "Numbers" "--numbers"]]
["a" "b" "-n" "1" "--numbers" "2"]
:description "Parse strings and numbers from args"))
(assert-equal parsed-args.strings ["a" "b"])
(assert-equal parsed-args.numbers [1 2]))