Merge pull request #1882 from redraiment/fix-issue-1875

Fixes #1875: parse-args requires values to be representable as Hy models
This commit is contained in:
Kodi Arfer 2020-03-31 11:02:59 -04:00 committed by GitHub
commit 02e6a0c6dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 24 additions and 4 deletions

View File

@ -97,3 +97,4 @@
* Adam Porter <adam@alphapapa.net>
* Gábor Lipták <gliptak@gmail.com>
* Raymund MARTINEZ <zhaqenl@protonmail.com>
* Zepeng Zhang <redraiment@gmail.com>

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]))