Removed untyped contructor from ComponentRegistration and add a protected setter.
[castle.git] / Experiments / Generator / src / app / ArgumentParser.boo
blob2a7fdefd1c1361fcac827b7cd1fc786f2717ec23
1 namespace Generator
3 import System
4 import System.Reflection
5 import Generator.Extentions
7 class ArgumentParser():
8 [Property(Target)] _target
10 def constructor(target):
11 _target = target
13 def GetUsage() as string:
14 return string.Join(' ', GetArgumentsNames()) + " [options]"
16 def GetHelp() as string:
17 usage = "Arguments:"
18 for arg in GetArguments():
19 usage += "\n ${arg.Name.PadRight(15)} ${arg.Description}"
20 usage += "\nOptions:"
21 for arg in GetOptions():
22 usage += "\n -${arg.ShortName}, --${arg.LongName.PadRight(9)} ${arg.Description}"
23 return usage
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
30 if option != null:
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}")
35 elif arg != null:
36 i = 0
37 while i < len(argv)-1 and (argv[i] as string).StartsWith('-'):
38 i++
39 if i < len(argv):
40 field.SetValue(_target, argv[i])
41 argv.Remove(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) == ""):
49 return false
50 return true
52 private def GetArguments() as (ArgumentAttribute):
53 args = []
54 for field in GetTargetFields():
55 arg = Attribute.GetCustomAttribute(field, ArgumentAttribute) as ArgumentAttribute
56 if arg != null:
57 arg.Name = field.Name.ToClassName()
58 args.Add(arg)
60 return args.ToArray(ArgumentAttribute)
62 private def GetOptions() as (OptionAttribute):
63 args = []
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):
71 args = []
73 for field in GetTargetFields():
74 arg = Attribute.GetCustomAttribute(field, ArgumentAttribute) as ArgumentAttribute
75 if arg != null:
76 if arg.Optional:
77 args.Add("[${field.Name.ToClassName()}]")
78 else:
79 args.Add(field.Name.ToClassName())
81 return args.ToArray(string)
83 private def GetTargetFields():
84 return _target.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)