2 from __future__
import with_statement
27 null
= open(os
.devnull
, 'r+')
28 parser
= argparse
.ArgumentParser(description
= 'Basis of my python scripts.')
31 def dieCleanly(level
= None):
32 """Exit the application with proper cleanup."""
34 #TODO: perform application cleanup
39 #exit with appropriate value
40 if level
== LOG_FATAL
:
45 def message(level
, msg
):
47 """Print a message to a certain debug level"""
50 if level
<= arguments
.logLevel
or level
== LOG_ALWAYS
:
53 # if logfile is open print to it instead
54 if arguments
.logFile
== "-":
56 elif level
<= LOG_WARN
:
59 retval
= msgPrefixes
[int(level
+ 0.5)] + msg
63 if level
<= LOG_FATAL
:
68 def printUsage(msg
= None):
71 message(LOG_FATAL
, msg
+ parser
.get_usage())
72 message(LOG_ALWAYS
, usage
)
73 dieCleanly(LOG_ALWAYS
)
76 global parser
, arguments
77 parser
.add_argument('-l', '--log-file',
78 metavar
= 'FILE', dest
= 'logFile',
79 help = 'Specify a log to receive all messages.')
80 parser
.add_argument('-q', '--quiet',
82 help = 'Decrease verbosity.')
83 parser
.add_argument('-v', '--verbose',
85 help = 'Increase verbosity.')
86 parser
.add_argument('-a', '--append-to-spec',
88 help = 'Replace the changlog in the specified spec file with our content.')
89 parser
.add_argument('-d', '--debian-release',
91 help = 'Output a debian changelog with this version used in the first entry.')
92 parser
.add_argument('-b', '--build',
94 help = 'Specify a build number to override the most recent entry.')
95 parser
.add_argument('--arg-file',
97 help = 'Specify a file that lists arguments to parse one set per line.')
98 parser
.add_argument('-o', '--output',
100 help = 'Where to put the output.')
101 arguments
= parser
.parse_args()
102 arguments
.logLevel
= LOG_NORMAL
;
103 if arguments
.verbose
:
104 arguments
.logLevel
+= arguments
.verbose
106 arguments
.logLevel
-= arguments
.quiet
107 if arguments
.logLevel
<= LOG_FATAL
:
108 arguments
.logLevel
= LOG_FATAL
109 if arguments
.logFile
== '-':
110 arguments
.logFile
= None
113 # open the log file if specified
114 if arguments
.logFile
!= None:
115 sys
.log
= open(arguments
.logFile
, "a", 1)
116 arguments
.logFile
= "-"
122 with
open(os
.path
.join(sys
.path
[0], 'ChangeLog')) as input:
129 if 'message' in entry
:
131 entries
.append(entry
)
134 entry
['message'] += line
138 parts
= list(map(lambda a
: a
.strip(), line
.split(':', 1)))
140 if parts
[0].lower() == 'version':
141 entry
['version'] = parts
[1].strip()
142 elif parts
[0].lower() == 'author':
143 entry
['author'] = parts
[1].strip()
144 elif parts
[0].lower() == 'when':
146 #Tue, 21 Aug 2012 20:01:44 -0600
148 entry
['whenIsShort'] = False
150 entry
['when'] = datetime
.datetime
.strptime(parts
[1], '%a %b %d %Y')
151 entry
['whenIsShort'] = True
154 entry
['when'] = datetime
.datetime
.strptime(parts
[1].rsplit(None, 1)[0],
155 '%a, %d %b %Y %H:%M:%S')
157 raise Exception('Failed to parse date string: %s' % parts
[1])
158 entry
['whenText'] = parts
[1]
159 elif parts
[0].lower() == 'debian':
160 debs
= list(map(lambda a
: a
.strip(), parts
[1].split(',')))
162 raise Exception('Debian entry should look like: rel, bld: %s' % parts
[1])
163 entry
['debianRel'] = debs
[0]
164 entry
['debianBld'] = debs
[1]
165 elif parts
[0].lower() == 'fedora':
166 entry
['fedoraBld'] = parts
[1]
167 elif parts
[0].lower() == 'message':
168 entry
['message'] = ''
170 raise Exception('Unknown field: %s' % parts
[0])
171 elif line
.startswith('END'):
174 raise Exception('Unparsed line: %s' % line
)
179 output
= open(args
.output
, 'w')
181 if args
.append_to_spec
and args
.debian_release
:
182 message(LOG_FATAL
, 'Either write a spec file or a debian changelog.\n')
183 elif args
.append_to_spec
:
184 # pass the spec through until we reach the changlog
185 with
open(args
.append_to_spec
) as input:
188 if line
.strip().lower() == '%changelog':
193 for entry
in entries
:
197 entry
['fedoraBld'] = args
.build
200 entry
['whenShort'] = entry
['when'].strftime('%a %b %d %Y')
202 for line
in entry
['message'].splitlines():
203 if not line
.startswith(' * '):
204 raise Exception('Unrecognized message format: %s' % line
)
206 lines
.append(line
.strip()[2:])
207 text
= ('- ' + ', '.join(lines
)).replace('\t', ' ')
213 if wrapAt
>= len(text
):
214 wrapped
.append(text
.strip())
218 while text
[at
] != ' ':
221 raise Exception('Cannot wrap text: %s' % text
)
222 wrapped
.append(text
[:at
].strip())
223 text
= ' ' + text
[at
:]
224 entry
['oneWrapped'] = '\n '.join(wrapped
)
226 output
.write("""* %(whenShort)s %(author)s %(version)s-%(fedoraBld)s
230 elif args
.debian_release
:
233 for entry
in entries
:
235 # override some fields of the first entry
236 if args
.debian_release
:
238 entry
['debianRel'] = args
.debian_release
241 entry
['debianBld'] = args
.build
244 if entry
['whenIsShort']:
245 entry
['longWhen'] = entry
['when'].strftime('%a, %d %b %Y %H:%M:%S -0500')
247 entry
['longWhen'] = entry
['whenText']
248 output
.write("""iguanair (%(version)s-%(debianRel)s) %(debianRel)s; urgency=low
251 -- %(author)s %(longWhen)s
255 message(LOG_FATAL
, 'Either write a spec file or a debian changelog: %s\n' % arguments
)
257 if output
!= sys
.stdout
:
261 if arguments
.arg_file
:
262 with
open(arguments
.arg_file
) as input:
263 for line
in map(lambda a
: a
.strip(), input):
264 execute(parser
.parse_args(line
.split()))