Skip to content

Commit 93a2a5f

Browse files
committed
Implement the optparser to the genattrib
1 parent fe44515 commit 93a2a5f

File tree

1 file changed

+115
-93
lines changed

1 file changed

+115
-93
lines changed

about_code_tool/genattrib.py

Lines changed: 115 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -30,21 +30,48 @@
3030
import fnmatch
3131
import getopt
3232
import httplib
33+
import logging
34+
import optparse
3335
import posixpath
3436
import socket
3537
import string
3638
import sys
3739
import urlparse
40+
3841
from collections import namedtuple
3942
from datetime import datetime
4043
from email.parser import HeaderParser
4144
from os import listdir, walk
4245
from os.path import exists, dirname, join, abspath, isdir, basename, normpath
4346
from StringIO import StringIO
47+
48+
49+
logger = logging.getLogger(__name__)
50+
handler = logging.StreamHandler()
51+
handler.setLevel(logging.CRITICAL)
52+
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
53+
logger.addHandler(handler)
54+
55+
4456
__version__ = '0.9.0'
4557

46-
# see http://dejacode.org
47-
__about_spec_version__ = '0.8.0'
58+
__about_spec_version__ = '0.8.0' # See http://dejacode.org
59+
60+
__copyright__ = """
61+
Copyright (c) 2013-2014 nexB Inc. All rights reserved.
62+
63+
Licensed under the Apache License, Version 2.0 (the "License");
64+
you may not use this file except in compliance with the License.
65+
You may obtain a copy of the License at
66+
67+
http://www.apache.org/licenses/LICENSE-2.0
68+
69+
Unless required by applicable law or agreed to in writing, software
70+
distributed under the License is distributed on an "AS IS" BASIS,
71+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72+
See the License for the specific language governing permissions and
73+
limitations under the License.
74+
"""
4875

4976
def component_subset_to_sublist(input_path):
5077
sublist = []
@@ -55,86 +82,39 @@ def component_subset_to_sublist(input_path):
5582

5683
return sublist
5784

58-
def syntax():
59-
print("""
60-
Syntax:
61-
genattrib.py [Options] [Input] [Output] [Component List]
85+
USAGE_SYNTAX = """\
6286
Input can be a file or directory.
6387
Output of rendered template must be a file (e.g. .html).
6488
Component List must be a .csv file which has at least an "about_resource" column.
65-
""")
66-
67-
68-
def option_usage():
69-
print("""
70-
Options:
71-
--overwrite Overwrites the output file if it exists
72-
-v,--version Display current version, license notice, and copyright notice
73-
-h,--help Display help
74-
--verbosity <arg> Print more or less verbose messages while processing ABOUT files
75-
<arg>
76-
0 - Do not print any warning or error messages, just a total count (default)
77-
1 - Print error messages
78-
2 - Print error and warning messages
79-
""")
80-
81-
82-
def version():
83-
print("""
84-
ABOUT CODE: Version: %s
85-
Copyright (c) 2013 nexB Inc. All rights reserved.
86-
http://dejacode.org
87-
Licensed under the Apache License, Version 2.0 (the "License");
88-
you may not use this file except in compliance with the License.
89-
You may obtain a copy of the License at
90-
http://www.apache.org/licenses/LICENSE-2.0
91-
Unless required by applicable law or agreed to in writing,
92-
software distributed under the License is distributed on an "AS IS" BASIS,
93-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
94-
See the License for the specific language governing permissions and limitations
95-
under the License.""" % __version__)
96-
97-
98-
def main(args, opts):
99-
overwrite = False
100-
opt_arg_num = '0'
101-
for opt, opt_arg in opts:
102-
invalid_opt = True
103-
if opt in ('-h', '--help'):
104-
syntax()
105-
option_usage()
106-
sys.exit(0)
107-
108-
if opt in ('-v', '--version'):
109-
version()
110-
sys.exit(0)
111-
112-
if opt in ('--verbosity'):
113-
invalid_opt = False
114-
valid_opt_args = ['0', '1', '2']
115-
if not opt_arg or not opt_arg in valid_opt_args:
116-
print("Invalid option argument.")
117-
option_usage()
118-
sys.exit(errno.EINVAL)
119-
else:
120-
opt_arg_num = opt_arg
121-
122-
if opt in ('--overwrite'):
123-
invalid_opt = False
124-
overwrite = True
125-
126-
if invalid_opt:
127-
assert False, 'Unsupported option.'
128-
129-
if len(args) < 2:
130-
print('Input and output parameters are mandatory.')
131-
syntax()
132-
option_usage()
133-
sys.exit(errno.EINVAL)
134-
135-
input_path = args[0]
136-
output_path = args[1]
137-
component_subset_path = None if len(args) < 3 else args[2]
89+
"""
90+
91+
VERBOSITY_HELP = """\
92+
Print more or fewer verbose messages while processing ABOUT files
93+
0 - Do not print any warning or error messages, just a total count (default)
94+
1 - Print error messages
95+
2 - Print error and warning messages
96+
"""
97+
98+
99+
def main(parser, options, args):
100+
overwrite = options.overwrite
101+
verbosity = options.verbosity
102+
103+
if options.version:
104+
print('ABOUT tool {0}\n{1}'.format(__version__, __copyright__))
105+
sys.exit(0)
106+
107+
if verbosity == 1:
108+
handler.setLevel(logging.ERROR)
109+
elif verbosity >= 2:
110+
handler.setLevel(logging.WARNING)
111+
112+
if not len(args) == 3:
113+
print('Path for input, output and component list are required.\n')
114+
parser.print_help()
115+
sys.exit(errno.EEXIST)
116+
117+
input_path, output_path, component_subset_path = args
138118

139119
# TODO: need more path normalization (normpath, expanduser)
140120
# input_path = abspath(input_path)
@@ -147,23 +127,23 @@ def main(args, opts):
147127

148128
if not exists(input_path):
149129
print('Input path does not exist.')
150-
option_usage()
130+
parser.print_help()
151131
sys.exit(errno.EEXIST)
152132

153133
if isdir(output_path):
154134
print('Output must be a file, not a directory.')
155-
option_usage()
135+
parser.print_help()
156136
sys.exit(errno.EISDIR)
157137

158138
if exists(output_path) and not overwrite:
159139
print('Output file already exists. Select a different file name or use '
160140
'the --overwrite option.')
161-
option_usage()
141+
parser.print_help()
162142
sys.exit(errno.EEXIST)
163143

164144
if component_subset_path and not exists(component_subset_path):
165145
print('Component Subset path does not exist.')
166-
option_usage()
146+
parser.print_help()
167147
sys.exit(errno.EEXIST)
168148

169149
if not exists(output_path) or (exists(output_path) and overwrite):
@@ -178,14 +158,56 @@ def main(args, opts):
178158
assert False, "Unsupported option(s)."
179159

180160

161+
def get_parser():
162+
class MyFormatter(optparse.IndentedHelpFormatter):
163+
def _format_text(self, text):
164+
"""
165+
Overridden to allow description to be printed without
166+
modification
167+
"""
168+
return text
169+
170+
def format_option(self, option):
171+
"""
172+
Overridden to allow options help text to be printed without
173+
modification
174+
"""
175+
result = []
176+
opts = self.option_strings[option]
177+
opt_width = self.help_position - self.current_indent - 2
178+
if len(opts) > opt_width:
179+
opts = "%*s%s\n" % (self.current_indent, "", opts)
180+
indent_first = self.help_position
181+
else: # start help on same line as opts
182+
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
183+
indent_first = 0
184+
result.append(opts)
185+
if option.help:
186+
help_text = self.expand_default(option)
187+
help_lines = help_text.split('\n')
188+
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
189+
result.extend(["%*s%s\n" % (self.help_position, "", line)
190+
for line in help_lines[1:]])
191+
elif opts[-1] != "\n":
192+
result.append("\n")
193+
return "".join(result)
194+
195+
parser = optparse.OptionParser(
196+
usage='%prog [options] input_path output_path component_list',
197+
description=USAGE_SYNTAX,
198+
add_help_option=False,
199+
formatter=MyFormatter(),
200+
)
201+
parser.add_option("-h", "--help", action="help", help="Display help")
202+
parser.add_option("-v", "--version", action="store_true",
203+
help='Display current version, license notice, and copyright notice')
204+
parser.add_option('--overwrite', action='store_true',
205+
help='Overwrites the output file if it exists')
206+
parser.add_option('--verbosity', type=int, help=VERBOSITY_HELP)
207+
return parser
208+
209+
181210
if __name__ == "__main__":
182-
longopts = ['help', 'version', 'overwrite', 'verbosity=']
183-
try:
184-
opts, args = getopt.getopt(sys.argv[1:], 'hv', longopts)
185-
except Exception as e:
186-
print(repr(e))
187-
syntax()
188-
option_usage()
189-
sys.exit(errno.EINVAL)
190-
191-
main(args, opts)
211+
parser = get_parser()
212+
options, args = parser.parse_args()
213+
main(parser, options, args)

0 commit comments

Comments
 (0)