Skip to content

Commit

Permalink
handle hex values, fix bugs when positional arg is a float/int
Browse files Browse the repository at this point in the history
  • Loading branch information
eriknyquist committed Oct 13, 2023
1 parent 0f88851 commit c14307c
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 2 deletions.
23 changes: 21 additions & 2 deletions duckargs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class CmdlineOpt(object):
Represents a single option / flag / positional argument parsed from command line arguments
"""

positional_count = 0

# Return values for add_arg
SUCCESS = 0
SUCCESS_AND_FULL = 1
Expand Down Expand Up @@ -69,10 +71,17 @@ def finalize(self):

if self.value is None:
return

try:
intval = int(self.value)
except ValueError:
pass
if (len(self.value) >= 3) and (self.value[:2].lower() == "0x"):
try:
intval = int(self.value, 16)
except ValueError:
pass
else:
self.type = ArgType.INT
else:
self.type = ArgType.INT

Expand Down Expand Up @@ -163,7 +172,16 @@ def generate_code(self):
funcargs += f", type={self.type}"

elif self.is_positional():
funcargs = f"'{self.value}'"
if self.value.isidentifier():
funcargs = f"'{self.value}'"
else:
varname = f"positional_arg{CmdlineOpt.positional_count}"
funcargs = f"'{varname}'"
self.var_name = varname
CmdlineOpt.positional_count += 1

if self.type is not ArgType.STRING:
funcargs += f", type={self.type}"
else:
raise RuntimeError('Invalid options provided')

Expand Down Expand Up @@ -264,4 +282,5 @@ def generate_python_code(argv=sys.argv):
processed_args = process_args(argv)
optlines = " " + "\n ".join([o.generate_code() for o in processed_args])
printlines = " " + "\n ".join([f"print(args.{o.var_name})" for o in processed_args])
CmdlineOpt.positional_count = 0
return PYTHON_TEMPLATE.format(' '.join(argv[1:]), optlines, printlines)
1 change: 1 addition & 0 deletions tests/test_data/hex/args.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
duckargs -f --fff 0xabc -q 0x --test ox2
19 changes: 19 additions & 0 deletions tests/test_data/hex/expected_python.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -f --fff 0xabc -q 0x --test ox2

import argparse

def main():
parser = argparse.ArgumentParser(description='A command-line program generated by duckargs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('-f', '--fff', default=0xabc, type=int, help='an int value')
parser.add_argument('-q', default='0x', help='a string')
parser.add_argument('--test', default='ox2', help='a string')
args = parser.parse_args()

print(args.fff)
print(args.q)
print(args.test)

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions tests/test_data/positional_values/args.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
duckargs 0x 0x123 2.3 hello -r --ra FILE
23 changes: 23 additions & 0 deletions tests/test_data/positional_values/expected_python.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 0x 0x123 2.3 hello -r --ra FILE

import argparse

def main():
parser = argparse.ArgumentParser(description='A command-line program generated by duckargs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('positional_arg0', help='a string')
parser.add_argument('positional_arg1', type=int, help='an int value')
parser.add_argument('positional_arg2', type=float, help='a float value')
parser.add_argument('hello', help='a string')
parser.add_argument('-r', '--ra', default=None, type=argparse.FileType(), help='a filename')
args = parser.parse_args()

print(args.positional_arg0)
print(args.positional_arg1)
print(args.positional_arg2)
print(args.hello)
print(args.ra)

if __name__ == "__main__":
main()
6 changes: 6 additions & 0 deletions tests/test_duckargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ def test_many_opts(self):
def test_choices(self):
self._run_test("choices")

def test_hex(self):
self._run_test("hex")

def test_positional_values(self):
self._run_test("positional_values")

def test_duplicate_names(self):
self.assertRaises(ValueError, generate_python_code, ['duckargs', '-a', '-a'])
self.assertRaises(ValueError, generate_python_code, ['duckargs', '-a', '-b', '-a'])
Expand Down

0 comments on commit c14307c

Please sign in to comment.