4 import System
.Reflection
5 import Generator
.Extentions
7 class ArgumentParser():
8 [Property(Target
)] _target
10 def constructor(target
):
13 def GetUsage() as string
:
14 return string
.Join(' ', GetArgumentsNames()) + " [options]"
16 def GetHelp() as string
:
18 for arg
in GetArguments():
19 usage
+= "\n ${arg.Name.PadRight(15)} ${arg.Description}"
21 for arg
in GetOptions():
22 usage
+= "\n -${arg.ShortName}, --${arg.LongName.PadRight(9)} ${arg.Description}"
25 def SetArguments(argvParam
as (string
)) as (string
):
26 argv
= List(argvParam
)
27 for field
in GetTargetFields():
28 arg
= Attribute
.GetCustomAttribute(field
, ArgumentAttribute
)
29 option
= Attribute
.GetCustomAttribute(field
, OptionAttribute
) as OptionAttribute
31 if ("-${option.ShortName}" in argvParam
or "--${option.LongName}" in argvParam
):
32 field
.SetValue(_target
, true)
33 argv
.Remove("-${option.ShortName}")
34 argv
.Remove("--${option.LongName}")
37 while i
< len(argv
)-1 and (argv
[i
] as string
).StartsWith('-'):
40 field
.SetValue(_target
, argv
[i
])
43 return argv
.ToArray(string
)
45 def IsValid() as bool
:
46 for field
in GetTargetFields():
47 arg
= Attribute
.GetCustomAttribute(field
, ArgumentAttribute
) as ArgumentAttribute
48 if arg
!= null and not arg
.Optional
and (field
.GetValue(_target
) == null or field
.GetValue(_target
) == ""):
52 private def GetArguments() as (ArgumentAttribute
):
54 for field
in GetTargetFields():
55 arg
= Attribute
.GetCustomAttribute(field
, ArgumentAttribute
) as ArgumentAttribute
57 arg
.Name
= field
.Name
.ToClassName()
60 return args
.ToArray(ArgumentAttribute
)
62 private def GetOptions() as (OptionAttribute
):
64 for field
in GetTargetFields():
65 arg
= Attribute
.GetCustomAttribute(field
, OptionAttribute
) as OptionAttribute
66 args
.Add(arg
) if arg
!= null
68 return args
.ToArray(OptionAttribute
)
70 private def GetArgumentsNames() as (string
):
73 for field
in GetTargetFields():
74 arg
= Attribute
.GetCustomAttribute(field
, ArgumentAttribute
) as ArgumentAttribute
77 args
.Add("[${field.Name.ToClassName()}]")
79 args
.Add(field
.Name
.ToClassName())
81 return args
.ToArray(string
)
83 private def GetTargetFields():
84 return _target
.GetType().GetFields(BindingFlags
.Instance | BindingFlags
.NonPublic
)