Debian Codegraph @

pyqi/commands/make_optparse.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/python3
2
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, The BiPy Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
•11
12 from operator import attrgetter
13 from pyqi.core.command import (Command, CommandIn, CommandOut,
14 ParameterCollection)
15 from pyqi.commands.code_header_generator import CodeHeaderGenerator
16
17 __credits__ = ["Daniel McDonald", "Jai Ram Rideout", "Greg Caporaso",
18 "Doug Wendel"]
19
20 header_format = """from pyqi.core.interfaces.optparse import (OptparseUsageExample,
21 OptparseOption, OptparseResult)
22 from pyqi.core.command import (make_command_in_collection_lookup_f,
23 make_command_out_collection_lookup_f)
24 from %(command_module)s import CommandConstructor
25
26 # If you need access to input or output handlers provided by pyqi, consider
27 # importing from the following modules:
28 # pyqi.core.interfaces.optparse.input_handler
29 # pyqi.core.interfaces.optparse.output_handler
30 # pyqi.interfaces.optparse.input_handler
31 # pyqi.interfaces.optparse.output_handler
32
33 # Convenience function for looking up parameters by name.
34 cmd_in_lookup = make_command_in_collection_lookup_f(CommandConstructor)
35 cmd_out_lookup = make_command_out_collection_lookup_f(CommandConstructor)
36
37 # Examples of how the command can be used from the command line using an
38 # optparse interface.
39 usage_examples = [
40 OptparseUsageExample(ShortDesc="A short single sentence description of the example",
41 LongDesc="A longer, more detailed description",
42 Ex="%%prog --foo --bar some_file")
43 ]
44
45 # inputs map command line arguments and values onto Parameters. It is possible
46 # to define options here that do not exist as parameters, e.g., an output file.
47 inputs = [
48 # An example option that has a direct relationship with a Parameter.
49 # OptparseOption(Parameter=cmd_in_lookup('name_of_a_command_in'),
50 # Type='existing_filepath', # the optparse type of input
51 # Action='store', # the optparse action
52 # Handler=None, # Apply a function to the input value to convert it into the type expected by Parameter.DataType
53 # ShortName='n', # a parameter short name, can be None
54 # # Name='foo', # implied by Parameter.Name. Can be overwritten here if desired
55 # # Required=False, # implied by Parameter.Required. Can be promoted by setting True
56 # # Help='help', # implied by Parameter.Description. Can be overwritten here if desired
57 # # Default=None, # implied by Parameter.Default. Can be overwritten here if desired
58 # # DefaultDescription=None, # implied by Parameter.DefaultDescription. Can be overwritten here if desired
59 # convert_to_dashed_name=True), # whether the Name (either implied by Parameter or defined above) should have underscores converted to dashes when displayed to the user
60 #
61 # An example option that does not have an associated Parameter.
62 # OptparseOption(Parameter=None,
63 # Type='new_filepath',
64 # Action='store',
65 # Handler=None, # we don't need a Handler because this option isn't being converted into a format that a Parameter expects
66 # ShortName='o',
67 # Name='output-fp',
68 # Required=True,
69 # Help='output filepath')
70
71 %(input_fmt)s]
72
73 # outputs map result keys to output options and handlers. It is not necessary
74 # to supply an associated option, but if you do, it must be an option from the
75 # inputs list (above).
76 outputs = [
77 # An example option that maps to a CommandIn.
78 # OptparseResult(Parameter=cmd_out_lookup('name_of_a_command_out'),
79 # Handler=write_string, # a function applied to the output of the Command
80 # # the name of the option (defined in inputs, above), whose
81 # # value will be made available to Handler. This name
82 # # can be either an underscored or dashed version of the
83 # # option name (e.g., 'output_fp' or 'output-fp')
84 # InputName='output-fp'),
85 #
86 # An example option that does not map to a CommandIn.
87 # OptparseResult(Parameter=cmd_out_lookup('some_other_result'),
88 # Handler=print_string)
89
90 %(output_fmt)s]"""
91
92 # Fill out by Parameter, and comment out some of the most common stuff.
93 input_format = """ OptparseOption(Parameter=cmd_in_lookup('%(name)s'),
94 Type=%(datatype)s,
95 Action='%(action)s', # default is 'store', change if desired
96 Handler=None, # must be defined if desired
97 ShortName=None, # must be defined if desired
98 # Name='%(name)s', # implied by Parameter
99 # Required=%(required)s, # implied by Parameter
100 # Help='%(help)s', # implied by Parameter
101 %(default_block)s),
102 """
103
104 output_format = """ OptparseResult(Parameter=cmd_out_lookup('%(name)s'),
105 Handler=None, # must be defined
106 InputName=None), # define if tying to an OptparseOption
107 """
108
109 default_block_format = """# Default=%(default)s, # implied by Parameter
110 # DefaultDescription=%(default_description)s, # implied by Parameter"""
111
112 class MakeOptparse(CodeHeaderGenerator):
113 BriefDescription = "Consume a Command, stub out an optparse configuration"
114 LongDescription = """Construct and stub out the basic optparse configuration for a given Command. This template provides comments and examples of what to fill in."""
115
116 CommandIns = ParameterCollection(
117 CodeHeaderGenerator.CommandIns.Parameters + [
118 CommandIn(Name='command', DataType=Command,
119 Description='an existing Command', Required=True),
120 CommandIn(Name='command_module', DataType=str,
121 Description='the Command source module', Required=True)
122 ]
123 )
124
125 CommandOuts = ParameterCollection([
126 CommandOut(Name='result', DataType=list,
127 Description='The resulting template configuration')
128 ])
129
130 def run(self, **kwargs):
131 code_header_lines = super(MakeOptparse, self).run(
132 author=kwargs['author'], email=kwargs['email'],
133 license=kwargs['license'], copyright=kwargs['copyright'],
134 version=kwargs['version'], credits=kwargs['credits'])['result']
135
136 result_lines = code_header_lines
137
138 # construct inputs based off of CommandIns
139 cmdin_formatted = []
•140 for cmdin in sorted(list(kwargs['command'].CommandIns.values()),
141 key=attrgetter('Name')):
142 if cmdin.Required:
143 default_block = ''
144 else:
145 default_fmt = {
146 'default': repr(cmdin.Default),
147 'default_description': repr(cmdin.DefaultDescription)
148 }
149 default_block = default_block_format % default_fmt
150
151 if cmdin.DataType is bool:
152 action = 'store_true'
153 data_type = None
154 else:
155 action = 'store'
156 data_type = cmdin.DataType
157
158 fmt = {'name':cmdin.Name,
159 'datatype':getattr(data_type, '__name__', None),
160 'action':action, 'required':str(cmdin.Required),
161 'help':cmdin.Description, 'default_block':default_block}
162 cmdin_formatted.append(input_format % fmt)
163
164 cmdout_formatted = []
•165 for cmdin in sorted(list(kwargs['command'].CommandOuts.values()),
166 key=attrgetter('Name')):
167 fmt = {'name':cmdin.Name}
168 cmdout_formatted.append(output_format % fmt)
169
170
171 cmdin_formatted = ''.join(cmdin_formatted)
172 cmdout_formatted = ''.join(cmdout_formatted)
173 header_fmt = {'command_module':kwargs['command_module'],
174 'input_fmt': cmdin_formatted,
175 'output_fmt':cmdout_formatted}
176
177 result_lines.extend((header_format % header_fmt).split('\n'))
178 return {'result': result_lines}
179
180 CommandConstructor = MakeOptparse