GTG

Merge lp:~jml/gtg/better-lint-checking into lp:~gtg/gtg/old-trunk

Proposed by Jonathan Lange
Status: Merged
Merged at revision: not available
Proposed branch: lp:~jml/gtg/better-lint-checking
Merge into: lp:~gtg/gtg/old-trunk
Diff against target: None lines
To merge this branch: bzr merge lp:~jml/gtg/better-lint-checking
Reviewer Review Type Date Requested Status
Gtg developers Pending
Review via email: mp+8680@code.launchpad.net
To post a comment you must log in.
Revision history for this message
Jonathan Lange (jml) wrote :

This branch tries to improve both the way that lint checking is done and also how well we do at those lint checks.

Most of the size of the branch is made up from adding pep8.py to scripts. It's an MIT licensed script, and should be OK to distribute with this GPLv3 app.

The next biggest change is making dbuswrapper use 4 space indentation, like every other Python module in the known universe :)

Another interesting change is removing the '_' hack to __builtins__ and instead requiring scripts to import _ from GTG. This change, together with removal of '*' imports and a few other tweaks means that pyflakes returns a clean bill of health. Note that * imports make pyflakes less useful, since with them it can't detect unrecognized names.

I've also got rid of some tabs and replaced them with spaces.

The most interesting change is that 'make lint' now runs pyflakes and pep8 checks on the code base. Although I've updated codecheck.sh so that the sillier warnings are now disabled, I think that 'make lint' should become the standard way of doing a lint check.

lp:~jml/gtg/better-lint-checking updated
278. By Jonathan Lange

Remove codecheck.sh -- let's use 'make lint' instead.

279. By Jonathan Lange

Later version of PEP 8. Drop the warning filters

280. By Jonathan Lange

Update comments in Makefile.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'GTG/__init__.py'
2--- GTG/__init__.py 2009-07-12 22:05:07 +0000
3+++ GTG/__init__.py 2009-07-13 10:22:44 +0000
4@@ -96,8 +96,8 @@
5 translation = gettext.translation(GETTEXT_DOMAIN, LOCALE_PATH,
6 languages=languages_used,
7 fallback=True)
8-import __builtin__
9-__builtin__._ = translation.gettext
10+
11+_ = translation.gettext
12
13 #GTG directories setup
14 if not os.path.isdir( os.path.join(LOCAL_ROOTDIR,'data') ) :
15
16=== modified file 'GTG/backends/localfile.py'
17--- GTG/backends/localfile.py 2009-04-02 22:03:26 +0000
18+++ GTG/backends/localfile.py 2009-07-13 09:20:43 +0000
19@@ -21,7 +21,7 @@
20 #Localfile is a read/write backend that will store your tasks in an XML file
21 #This file will be in your $XDG_DATA_DIR/gtg folder.
22
23-import os,shutil
24+import os
25 import uuid
26
27 from GTG.core import CoreConfig
28
29=== modified file 'GTG/core/__init__.py'
30--- GTG/core/__init__.py 2009-06-18 08:56:33 +0000
31+++ GTG/core/__init__.py 2009-07-13 10:26:28 +0000
32@@ -45,11 +45,10 @@
33
34 #=== IMPORT ====================================================================
35 import os
36-from xdg.BaseDirectory import *
37+from xdg.BaseDirectory import xdg_data_home, xdg_config_home
38 from GTG.tools import cleanxml
39 from configobj import ConfigObj
40
41-import GTG
42 from GTG.core import firstrun_tasks
43
44 class CoreConfig:
45
46=== modified file 'GTG/core/dbuswrapper.py'
47--- GTG/core/dbuswrapper.py 2009-07-09 20:03:12 +0000
48+++ GTG/core/dbuswrapper.py 2009-07-13 09:13:22 +0000
49@@ -1,120 +1,133 @@
50-import gobject, dbus.glib, dbus, dbus.service
51+import dbus
52+import dbus.glib
53+import dbus.service
54+
55
56 BUSNAME = "org.GTG"
57
58 def dsanitize(data):
59- # Clean up a dict so that it can be transmitted through D-Bus
60- for k, v in data.items():
61- # Manually specify an arbitrary content type for empty Python arrays
62- # because D-Bus can't handle the type conversion for empty arrays
63- if not v and isinstance(v, list):
64- data[k] = dbus.Array([], "s")
65- # D-Bus has no concept of a null or empty value so we have to convert None
66- # types to something else. I use an empty string because it has the same
67- # behavior as None in a Python conditional expression
68- elif v == None:
69- data[k] = ""
70-
71- return data
72+ # Clean up a dict so that it can be transmitted through D-Bus
73+ for k, v in data.items():
74+ # Manually specify an arbitrary content type for empty Python arrays
75+ # because D-Bus can't handle the type conversion for empty arrays
76+ if not v and isinstance(v, list):
77+ data[k] = dbus.Array([], "s")
78+ # D-Bus has no concept of a null or empty value so we have to convert
79+ # None types to something else. I use an empty string because it has
80+ # the same behavior as None in a Python conditional expression
81+ elif v == None:
82+ data[k] = ""
83+
84+ return data
85+
86
87 def task_to_dict(task):
88- # Translate a task object into a D-Bus dictionary
89- return dbus.Dictionary(dsanitize({
90- "id": task.get_id(),
91- "status": task.get_status(),
92- "title": task.get_title(),
93- "duedate": task.get_due_date(),
94- "startdate": task.get_start_date(),
95- "donedate": task.get_closed_date(),
96- "tags": task.get_tags_name(),
97- "text": task.get_text(),
98- "subtask": task.get_subtasks_tid(),
99- }), signature="sv")
100+ # Translate a task object into a D-Bus dictionary
101+ return dbus.Dictionary(dsanitize({
102+ "id": task.get_id(),
103+ "status": task.get_status(),
104+ "title": task.get_title(),
105+ "duedate": task.get_due_date(),
106+ "startdate": task.get_start_date(),
107+ "donedate": task.get_closed_date(),
108+ "tags": task.get_tags_name(),
109+ "text": task.get_text(),
110+ "subtask": task.get_subtasks_tid(),
111+ }), signature="sv")
112+
113
114 class DBusTaskWrapper(dbus.service.Object):
115- # D-Bus service object that exposes GTG's task store to third-party apps
116- def __init__(self, req, ui):
117- # Attach the object to D-Bus
118- self.bus = dbus.SessionBus()
119- bus_name = dbus.service.BusName(BUSNAME, bus=self.bus)
120- dbus.service.Object.__init__(self, bus_name, "/org/GTG")
121- self.req = req
122- self.ui = ui
123-
124- @dbus.service.method(BUSNAME)
125- def get_task_ids(self):
126- # Retrieve a list of task ID values
127- return self.req.get_tasks_list(status=["Active", "Done"], started_only=False)
128-
129- @dbus.service.method(BUSNAME)
130- def get_task(self, tid):
131- # Retrieve a specific task by ID and return the data
132- return task_to_dict(self.req.get_task(tid))
133-
134- @dbus.service.method(BUSNAME)
135- def get_tasks(self):
136- # Retrieve a list of task data dicts
137- return [self.get_task(id) for id in self.get_task_ids()]
138-
139- @dbus.service.method(BUSNAME, in_signature="asasbb")
140- def get_task_ids_filtered(self, tags, status, started_only, is_root):
141- # Retrieve a list of task IDs filtered by specified parameters
142- ids = self.req.get_tasks_list(tags, status, False, started_only, is_root)
143- # If there are no matching tasks, return an empty D-Bus array
144- return ids if ids else dbus.Array([], "s")
145-
146- @dbus.service.method(BUSNAME, in_signature="asasbb")
147- def get_tasks_filtered(self, tags, status, started_only, is_root):
148- # Retrieve a list of task data discts filtered by specificed parameters
149- tasks = self.get_task_ids_filtered(tags, status, started_only, is_root)
150- # If no tasks match the filter, return an empty D-Bus array
151- return [self.get_task(id) for id in tasks] if tasks else dbus.Array([], "s")
152-
153- @dbus.service.method(BUSNAME)
154- def has_task(self, tid):
155- return self.req.has_task(tid)
156-
157- @dbus.service.method(BUSNAME)
158- def delete_task(self, tid):
159- self.req.delete_task(tid)
160-
161- @dbus.service.method(BUSNAME, in_signature="sssssassas")
162- def new_task(self, status, title, duedate, startdate, donedate, tags, text, subtasks):
163- # Generate a new task object and return the task data as a dict
164- nt = self.req.new_task()
165- for sub in subtasks: nt.add_subtask(sub)
166- for tag in tags: nt.add_tag(tag)
167- nt.set_status(status, donedate=donedate)
168- nt.set_title(title)
169- nt.set_due_date(duedate)
170- nt.set_start_date(startdate)
171- nt.set_text(text)
172- return task_to_dict(nt)
173-
174- @dbus.service.method(BUSNAME)
175- def modify_task(self, tid, task_data):
176- # Apply supplied task data to the task object with the specified ID
177- task = self.req.get_task(tid)
178- task.set_status(task_data["status"], donedate=task_data["donedate"])
179- task.set_title(task_data["title"])
180- task.set_due_date(task_data["duedate"])
181- task.set_start_date(task_data["startdate"])
182- task.set_text(task_data["text"])
183-
184- for tag in task_data["tags"]: task.add_tag(tag)
185- for sub in task_data["subtask"]: task.add_subtask(sub)
186- return task_to_dict(task)
187-
188- @dbus.service.method(BUSNAME)
189- def open_task_editor(self, tid):
190- self.ui.open_task(tid)
191-
192- @dbus.service.method(BUSNAME)
193- def hide_task_browser(self):
194- self.ui.window.hide()
195-
196- @dbus.service.method(BUSNAME)
197- def show_task_browser(self):
198- self.ui.window.present()
199- self.ui.window.move(self.ui.priv["window_xpos"], self.ui.priv["window_ypos"])
200-
201+
202+ # D-Bus service object that exposes GTG's task store to third-party apps
203+ def __init__(self, req, ui):
204+ # Attach the object to D-Bus
205+ self.bus = dbus.SessionBus()
206+ bus_name = dbus.service.BusName(BUSNAME, bus=self.bus)
207+ dbus.service.Object.__init__(self, bus_name, "/org/GTG")
208+ self.req = req
209+ self.ui = ui
210+
211+ @dbus.service.method(BUSNAME)
212+ def get_task_ids(self):
213+ # Retrieve a list of task ID values
214+ return self.req.get_tasks_list(
215+ status=["Active", "Done"], started_only=False)
216+
217+ @dbus.service.method(BUSNAME)
218+ def get_task(self, tid):
219+ # Retrieve a specific task by ID and return the data
220+ return task_to_dict(self.req.get_task(tid))
221+
222+ @dbus.service.method(BUSNAME)
223+ def get_tasks(self):
224+ # Retrieve a list of task data dicts
225+ return [self.get_task(id) for id in self.get_task_ids()]
226+
227+ @dbus.service.method(BUSNAME, in_signature="asasbb")
228+ def get_task_ids_filtered(self, tags, status, started_only, is_root):
229+ # Retrieve a list of task IDs filtered by specified parameters
230+ ids = self.req.get_tasks_list(
231+ tags, status, False, started_only, is_root)
232+ # If there are no matching tasks, return an empty D-Bus array
233+ return ids if ids else dbus.Array([], "s")
234+
235+ @dbus.service.method(BUSNAME, in_signature="asasbb")
236+ def get_tasks_filtered(self, tags, status, started_only, is_root):
237+ # Retrieve a list of task data discts filtered by specificed parameters
238+ tasks = self.get_task_ids_filtered(
239+ tags, status, started_only, is_root)
240+ # If no tasks match the filter, return an empty D-Bus array
241+ if tasks:
242+ return [self.get_task(id) for id in tasks]
243+ else:
244+ return dbus.Array([], "s")
245+
246+ @dbus.service.method(BUSNAME)
247+ def has_task(self, tid):
248+ return self.req.has_task(tid)
249+
250+ @dbus.service.method(BUSNAME)
251+ def delete_task(self, tid):
252+ self.req.delete_task(tid)
253+
254+ @dbus.service.method(BUSNAME, in_signature="sssssassas")
255+ def new_task(self, status, title, duedate, startdate, donedate, tags,
256+ text, subtasks):
257+ # Generate a new task object and return the task data as a dict
258+ nt = self.req.new_task()
259+ for sub in subtasks: nt.add_subtask(sub)
260+ for tag in tags: nt.add_tag(tag)
261+ nt.set_status(status, donedate=donedate)
262+ nt.set_title(title)
263+ nt.set_due_date(duedate)
264+ nt.set_start_date(startdate)
265+ nt.set_text(text)
266+ return task_to_dict(nt)
267+
268+ @dbus.service.method(BUSNAME)
269+ def modify_task(self, tid, task_data):
270+ # Apply supplied task data to the task object with the specified ID
271+ task = self.req.get_task(tid)
272+ task.set_status(task_data["status"], donedate=task_data["donedate"])
273+ task.set_title(task_data["title"])
274+ task.set_due_date(task_data["duedate"])
275+ task.set_start_date(task_data["startdate"])
276+ task.set_text(task_data["text"])
277+
278+ for tag in task_data["tags"]: task.add_tag(tag)
279+ for sub in task_data["subtask"]: task.add_subtask(sub)
280+ return task_to_dict(task)
281+
282+ @dbus.service.method(BUSNAME)
283+ def open_task_editor(self, tid):
284+ self.ui.open_task(tid)
285+
286+ @dbus.service.method(BUSNAME)
287+ def hide_task_browser(self):
288+ self.ui.window.hide()
289+
290+ @dbus.service.method(BUSNAME)
291+ def show_task_browser(self):
292+ self.ui.window.present()
293+ self.ui.window.move(
294+ self.ui.priv["window_xpos"], self.ui.priv["window_ypos"])
295
296=== modified file 'GTG/core/firstrun_tasks.py'
297--- GTG/core/firstrun_tasks.py 2009-06-18 08:37:25 +0000
298+++ GTG/core/firstrun_tasks.py 2009-07-13 10:22:44 +0000
299@@ -1,3 +1,4 @@
300+from GTG import _
301 from GTG.tools import cleanxml
302
303 def populate():
304
305=== modified file 'GTG/core/requester.py'
306--- GTG/core/requester.py 2009-07-13 08:57:44 +0000
307+++ GTG/core/requester.py 2009-07-13 10:26:28 +0000
308@@ -18,7 +18,7 @@
309 # -----------------------------------------------------------------------------
310
311
312-from GTG.tools.listes import *
313+from GTG.tools.listes import returnlist
314
315 #Requester is a pure View object. It will not do anything but it will
316 #be used by any Interface to handle the requests to the datastore
317
318=== modified file 'GTG/core/task.py'
319--- GTG/core/task.py 2009-07-13 08:57:44 +0000
320+++ GTG/core/task.py 2009-07-13 10:26:28 +0000
321@@ -20,8 +20,10 @@
322 from datetime import date
323 import xml.dom.minidom
324
325-from GTG.tools.dates import *
326-from GTG.tools.listes import *
327+from GTG import _
328+from GTG.tools.dates import strtodate
329+from GTG.tools.listes import returnlist
330+
331
332 #This class represent a task in GTG.
333 #You should never create a Task directly. Use the datastore.new_task() function.
334
335=== modified file 'GTG/gtg.py'
336--- GTG/gtg.py 2009-07-09 08:31:53 +0000
337+++ GTG/gtg.py 2009-07-13 10:22:44 +0000
338@@ -46,6 +46,7 @@
339 import sys, os
340
341 #our own imports
342+from GTG import _
343 from GTG.taskbrowser.browser import TaskBrowser
344 from GTG.core.datastore import DataStore
345 from GTG.core.dbuswrapper import DBusTaskWrapper
346
347=== modified file 'GTG/taskbrowser/__init__.py'
348--- GTG/taskbrowser/__init__.py 2009-04-03 15:00:18 +0000
349+++ GTG/taskbrowser/__init__.py 2009-07-13 10:22:44 +0000
350@@ -22,6 +22,8 @@
351 #simple, HIG compliant and well integrated with Gnome.
352 import os
353
354+from GTG import _
355+
356 class GnomeConfig :
357 current_rep = os.path.dirname(os.path.abspath(__file__))
358 GLADE_FILE = os.path.join(current_rep,"taskbrowser.glade")
359
360=== modified file 'GTG/taskbrowser/browser.py'
361--- GTG/taskbrowser/browser.py 2009-07-13 02:40:17 +0000
362+++ GTG/taskbrowser/browser.py 2009-07-13 10:41:18 +0000
363@@ -1,4 +1,5 @@
364 # -*- coding: utf-8 -*-
365+# pylint: disable-msg=W0201
366 # -----------------------------------------------------------------------------
367 # Gettings Things Gnome! - a personnal organizer for the GNOME desktop
368 # Copyright (c) 2008-2009 - Lionel Dricot & Bertrand Rousseau
369@@ -33,6 +34,7 @@
370
371 #our own imports
372 import GTG
373+from GTG import _
374 from GTG.taskeditor.editor import TaskEditor
375 from GTG.taskbrowser.CellRendererTags import CellRendererTags
376 from GTG.taskbrowser import GnomeConfig
377@@ -507,15 +509,15 @@
378 }
379 wTree.signal_autoconnect(dic)
380 window = wTree.get_widget("ColorChooser")
381- # Get previous color
382+ # Get previous color
383 tags,notag_only = self.get_selected_tags() #pylint: disable-msg=W0612
384 if len(tags) == 1:
385- color = tags[0].get_attribute("color")
386- if color != None:
387- colorspec = gtk.gdk.Color(color)
388- colorsel = window.colorsel
389- colorsel.set_previous_color(colorspec)
390- colorsel.set_current_color(colorspec)
391+ color = tags[0].get_attribute("color")
392+ if color != None:
393+ colorspec = gtk.gdk.Color(color)
394+ colorsel = window.colorsel
395+ colorsel.set_previous_color(colorspec)
396+ colorsel.set_current_color(colorspec)
397 window.show()
398
399 def on_color_response(self,widget,response) :
400@@ -653,7 +655,7 @@
401 return False
402 year,month,day = splited_date
403 try :
404- date = datetime.date(int(year),int(month),int(day))
405+ datetime.date(int(year),int(month),int(day))
406 except ValueError :
407 return False
408 else :
409
410=== modified file 'GTG/taskeditor/__init__.py'
411--- GTG/taskeditor/__init__.py 2009-06-10 13:17:47 +0000
412+++ GTG/taskeditor/__init__.py 2009-07-13 10:22:44 +0000
413@@ -20,6 +20,8 @@
414
415 import os
416
417+from GTG import _
418+
419 class GnomeConfig :
420 current_rep = os.path.dirname(os.path.abspath(__file__))
421 GLADE_FILE = os.path.join(current_rep,"taskeditor.glade")
422
423=== modified file 'GTG/taskeditor/editor.py'
424--- GTG/taskeditor/editor.py 2009-06-10 13:17:47 +0000
425+++ GTG/taskeditor/editor.py 2009-07-13 10:41:18 +0000
426@@ -26,18 +26,19 @@
427 import time
428 from datetime import date
429
430+from GTG import _
431 from GTG.taskeditor import GnomeConfig
432 from GTG.tools import dates
433 from GTG.taskeditor.taskview import TaskView
434 try:
435 import pygtk
436 pygtk.require("2.0")
437-except:
438+except: # pylint: disable-msg=W0702
439 sys.exit(1)
440 try:
441 import gtk
442 from gtk import gdk
443-except:
444+except: # pylint: disable-msg=W0702
445 sys.exit(1)
446
447 date_separator = "/"
448
449=== modified file 'GTG/taskeditor/taskview.py'
450--- GTG/taskeditor/taskview.py 2009-06-04 19:59:15 +0000
451+++ GTG/taskeditor/taskview.py 2009-07-13 09:20:43 +0000
452@@ -909,11 +909,11 @@
453 for ta in itera.get_toggled_tags(False) :
454 if ta.get_data('is_subtask') :
455 subtask_nbr = ta.get_data('child')
456-
457+
458 #New line : the user pressed enter !
459 #If the line begins with "-", it's a new subtask !
460 if tex == '\n' :
461- insert_point = self.buff.create_mark("insert_point",itera,True)
462+ self.buff.create_mark("insert_point", itera, True)
463 #First, we close tag tags.
464 #If we are at the end of a tag, we look for closed tags
465 closed_tag = None
466@@ -923,7 +923,6 @@
467 #Or maybe we are in the middle of a tag
468 else :
469 list_stag = itera.get_tags()
470- stag = None
471 for t in list_stag :
472 if t.get_data('is_tag') :
473 closed_tag = t.get_data('tagname')
474@@ -984,17 +983,15 @@
475 self.buff.create_mark(anchor,itera,True)
476 self.buff.create_mark("/%s"%anchor,itera,False)
477 self.insert_sigid = self.buff.connect('insert-text', self._insert_at_cursor)
478- self.keypress_sigid = self.connect('key_press_event', self._keypress)
479+ self.connect('key_press_event', self._keypress)
480 self.modified_sigid = self.buff.connect("changed" , self.modified)
481
482 def _keypress(self, widget, event):
483 # Check for Ctrl-Return/Enter
484 if event.state & gtk.gdk.CONTROL_MASK and event.keyval in (gtk.keysyms.Return, gtk.keysyms.KP_Enter):
485- buff = self.buff
486+ buff = self.buff
487 cursor_mark = buff.get_insert()
488 cursor_iter = buff.get_iter_at_mark(cursor_mark)
489- table = buff.get_tag_table()
490-
491 local_start = cursor_iter.copy()
492
493 for tag in local_start.get_tags():
494@@ -1005,7 +1002,7 @@
495 self.open_task(anchor)
496 elif typ == "http" :
497 openurl.openurl(anchor)
498-
499+
500 return True
501
502 #Deindent the current line of one level
503
504=== added file 'Makefile'
505--- Makefile 1970-01-01 00:00:00 +0000
506+++ Makefile 2009-07-13 10:59:58 +0000
507@@ -0,0 +1,13 @@
508+
509+pyflakes:
510+ pyflakes GTG
511+
512+# Ignoring E301 "One blank line between things within a class", since it
513+# triggers false positives for normal decorator syntax.
514+pep8:
515+ find . -name '*.py' -print0 | xargs -0 ./scripts/pep8.py --ignore=E301
516+ find . -name '*.py' -print0 | xargs -0 ./scripts/pep8.py --ignore=E301 --repeat | wc -l
517+
518+lint: pyflakes pep8
519+
520+.PHONY: lint pyflakes pep8
521
522=== modified file 'scripts/codecheck.sh'
523--- scripts/codecheck.sh 2009-03-31 11:04:14 +0000
524+++ scripts/codecheck.sh 2009-07-13 10:41:18 +0000
525@@ -37,7 +37,7 @@
526 #I0011 : Locally disabling. We don't care if we disabled locally
527
528 #pylint argument :
529-disabled="C0324,C0103,C0301,C0111,R0914,R0903,R0915,R0904,R0912,R0201,R0913,C0323,R0902,W0102,W0232,W0105,C0321,W0401,W0142,I0011"
530+disabled="C0324,C0103,C0301,C0111,R0914,R0903,R0915,R0904,R0912,R0201,R0913,C0323,R0902,W0102,W0232,W0105,C0321,W0401,W0142,I0011,C0302,W0613,W0511,W0622,R0911"
531 args="--rcfile=/dev/null --include-ids=y --reports=n"
532 #grepped_out="Locally disabling"
533 #pylint doesn't recognize gettext _()
534@@ -49,8 +49,7 @@
535
536 echo "Running pyflakes"
537 echo "#################"
538-#pyflakes triggers a false positive with import * and with gettext _()
539-pyflakes GTG|grep -v "import \*"|grep -v "undefined name '_'"
540+pyflakes GTG
541
542 echo "Running pylint"
543 echo "#################"
544@@ -61,3 +60,8 @@
545 pylint --rcfile=/dev/null --include-ids=y --reports=n --disable-msg=$disabled $i |grep -v "$grepped_out"
546 fi
547 done
548+
549+
550+echo "Running pep8"
551+echo "############"
552+find . -name '*.py' -print0 | xargs -0 ./scripts/pep8.py
553
554=== added file 'scripts/pep8.py'
555--- scripts/pep8.py 1970-01-01 00:00:00 +0000
556+++ scripts/pep8.py 2009-07-13 10:12:30 +0000
557@@ -0,0 +1,773 @@
558+#!/usr/bin/python
559+# pep8.py - Check Python source code formatting, according to PEP 8
560+# Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org>
561+#
562+# Permission is hereby granted, free of charge, to any person
563+# obtaining a copy of this software and associated documentation files
564+# (the "Software"), to deal in the Software without restriction,
565+# including without limitation the rights to use, copy, modify, merge,
566+# publish, distribute, sublicense, and/or sell copies of the Software,
567+# and to permit persons to whom the Software is furnished to do so,
568+# subject to the following conditions:
569+#
570+# The above copyright notice and this permission notice shall be
571+# included in all copies or substantial portions of the Software.
572+#
573+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
574+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
575+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
576+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
577+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
578+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
579+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
580+# SOFTWARE.
581+
582+"""
583+Check Python source code formatting, according to PEP 8:
584+http://www.python.org/dev/peps/pep-0008/
585+
586+For usage and a list of options, try this:
587+$ python pep8.py -h
588+
589+This program and its regression test suite live here:
590+http://svn.browsershots.org/trunk/devtools/pep8/
591+http://trac.browsershots.org/browser/trunk/devtools/pep8/
592+
593+Groups of errors and warnings:
594+E errors
595+W warnings
596+100 indentation
597+200 whitespace
598+300 blank lines
599+400 imports
600+500 line length
601+600 deprecation
602+
603+You can add checks to this program by writing plugins. Each plugin is
604+a simple function that is called for each line of source code, either
605+physical or logical.
606+
607+Physical line:
608+- Raw line of text from the input file.
609+
610+Logical line:
611+- Multi-line statements converted to a single line.
612+- Stripped left and right.
613+- Contents of strings replaced with 'xxx' of same length.
614+- Comments removed.
615+
616+The check function requests physical or logical lines by the name of
617+the first argument:
618+
619+def maximum_line_length(physical_line)
620+def extraneous_whitespace(logical_line)
621+def indentation(logical_line, indent_level, state)
622+
623+The last example above demonstrates how check plugins can request
624+additional information with extra arguments. All attributes of the
625+Checker object are available. Some examples:
626+
627+lines: a list of the raw lines from the input file
628+tokens: the tokens that contribute to this logical line
629+state: dictionary for passing information across lines
630+indent_level: indentation (with tabs expanded to multiples of 8)
631+
632+The docstring of each check function shall be the relevant part of
633+text from PEP 8. It is printed if the user enables --show-pep8.
634+
635+"""
636+
637+import os
638+import sys
639+import re
640+import time
641+import inspect
642+import tokenize
643+from optparse import OptionParser
644+from keyword import iskeyword
645+from fnmatch import fnmatch
646+
647+__version__ = '0.2.0'
648+__revision__ = '$Rev: 930 $'
649+
650+default_exclude = '.svn,CVS,*.pyc,*.pyo'
651+
652+indent_match = re.compile(r'([ \t]*)').match
653+raise_comma_match = re.compile(r'raise\s+\w+\s*(,)').match
654+
655+operators = """
656++ - * / % ^ & | = < > >> <<
657++= -= *= /= %= ^= &= |= == <= >= >>= <<=
658+!= <> :
659+in is or not and
660+""".split()
661+
662+options = None
663+args = None
664+
665+
666+##############################################################################
667+# Plugins (check functions) for physical lines
668+##############################################################################
669+
670+
671+def tabs_or_spaces(physical_line, state):
672+ """
673+ Never mix tabs and spaces.
674+
675+ The most popular way of indenting Python is with spaces only. The
676+ second-most popular way is with tabs only. Code indented with a mixture
677+ of tabs and spaces should be converted to using spaces exclusively. When
678+ invoking the Python command line interpreter with the -t option, it issues
679+ warnings about code that illegally mixes tabs and spaces. When using -tt
680+ these warnings become errors. These options are highly recommended!
681+ """
682+ indent = indent_match(physical_line).group(1)
683+ if not indent:
684+ return
685+ if 'indent_char' in state:
686+ indent_char = state['indent_char']
687+ else:
688+ indent_char = indent[0]
689+ state['indent_char'] = indent_char
690+ for offset, char in enumerate(indent):
691+ if char != indent_char:
692+ return offset, "E101 indentation contains mixed spaces and tabs"
693+
694+
695+def tabs_obsolete(physical_line):
696+ """
697+ For new projects, spaces-only are strongly recommended over tabs. Most
698+ editors have features that make this easy to do.
699+ """
700+ indent = indent_match(physical_line).group(1)
701+ if indent.count('\t'):
702+ return indent.index('\t'), "W191 indentation contains tabs"
703+
704+
705+def trailing_whitespace(physical_line):
706+ """
707+ JCR: Trailing whitespace is superfluous.
708+ """
709+ physical_line = physical_line.rstrip('\n') # chr(10), newline
710+ physical_line = physical_line.rstrip('\r') # chr(13), carriage return
711+ physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
712+ stripped = physical_line.rstrip()
713+ if physical_line != stripped:
714+ return len(stripped), "W291 trailing whitespace"
715+
716+
717+def maximum_line_length(physical_line):
718+ """
719+ Limit all lines to a maximum of 79 characters.
720+
721+ There are still many devices around that are limited to 80 character
722+ lines; plus, limiting windows to 80 characters makes it possible to have
723+ several windows side-by-side. The default wrapping on such devices looks
724+ ugly. Therefore, please limit all lines to a maximum of 79 characters.
725+ For flowing long blocks of text (docstrings or comments), limiting the
726+ length to 72 characters is recommended.
727+ """
728+ length = len(physical_line.rstrip())
729+ if length > 79:
730+ return 79, "E501 line too long (%d characters)" % length
731+
732+
733+##############################################################################
734+# Plugins (check functions) for logical lines
735+##############################################################################
736+
737+
738+def blank_lines(logical_line, state, indent_level):
739+ """
740+ Separate top-level function and class definitions with two blank lines.
741+
742+ Method definitions inside a class are separated by a single blank line.
743+
744+ Extra blank lines may be used (sparingly) to separate groups of related
745+ functions. Blank lines may be omitted between a bunch of related
746+ one-liners (e.g. a set of dummy implementations).
747+
748+ Use blank lines in functions, sparingly, to indicate logical sections.
749+ """
750+ line = logical_line
751+ blank_lines = state.get('blank_lines', 0)
752+ if line.startswith('def '):
753+ if indent_level > 0 and blank_lines != 1:
754+ return 0, "E301 expected 1 blank line, found %d" % blank_lines
755+ if indent_level == 0 and blank_lines != 2:
756+ return 0, "E302 expected 2 blank lines, found %d" % blank_lines
757+ if blank_lines > 2:
758+ return 0, "E303 too many blank lines (%d)" % blank_lines
759+
760+
761+def extraneous_whitespace(logical_line):
762+ """
763+ Avoid extraneous whitespace in the following situations:
764+
765+ - Immediately inside parentheses, brackets or braces.
766+
767+ - Immediately before a comma, semicolon, or colon.
768+ """
769+ line = logical_line
770+ for char in '([{':
771+ found = line.find(char + ' ')
772+ if found > -1:
773+ return found + 1, "E201 whitespace after '%s'" % char
774+ for char in '}])':
775+ found = line.find(' ' + char)
776+ if found > -1 and line[found - 1] != ',':
777+ return found, "E202 whitespace before '%s'" % char
778+ for char in ',;:':
779+ found = line.find(' ' + char)
780+ if found > -1:
781+ return found, "E203 whitespace before '%s'" % char
782+
783+
784+def indentation(logical_line, indent_level, state):
785+ """
786+ Use 4 spaces per indentation level.
787+
788+ For really old code that you don't want to mess up, you can continue to
789+ use 8-space tabs.
790+ """
791+ line = logical_line
792+ previous_level = state.get('indent_level', 0)
793+ indent_expect = state.get('indent_expect', False)
794+ state['indent_expect'] = line.rstrip('#').rstrip().endswith(':')
795+ indent_char = state.get('indent_char', ' ')
796+ state['indent_level'] = indent_level
797+ if indent_char == ' ' and indent_level % 4:
798+ return 0, "E111 indentation is not a multiple of four"
799+ if indent_expect and indent_level <= previous_level:
800+ return 0, "E112 expected an indented block"
801+ if not indent_expect and indent_level > previous_level:
802+ return 0, "E113 unexpected indentation"
803+
804+
805+def whitespace_before_parameters(logical_line, tokens):
806+ """
807+ Avoid extraneous whitespace in the following situations:
808+
809+ - Immediately before the open parenthesis that starts the argument
810+ list of a function call.
811+
812+ - Immediately before the open parenthesis that starts an indexing or
813+ slicing.
814+ """
815+ prev_type = tokens[0][0]
816+ prev_text = tokens[0][1]
817+ prev_end = tokens[0][3]
818+ for index in range(1, len(tokens)):
819+ token_type, text, start, end, line = tokens[index]
820+ if (token_type == tokenize.OP and
821+ text in '([' and
822+ start != prev_end and
823+ prev_type == tokenize.NAME and
824+ (index < 2 or tokens[index - 2][1] != 'class') and
825+ (not iskeyword(prev_text))):
826+ return prev_end, "E211 whitespace before '%s'" % text
827+ prev_type = token_type
828+ prev_text = text
829+ prev_end = end
830+
831+
832+def whitespace_around_operator(logical_line):
833+ """
834+ Avoid extraneous whitespace in the following situations:
835+
836+ - More than one space around an assignment (or other) operator to
837+ align it with another.
838+ """
839+ line = logical_line
840+ for operator in operators:
841+ found = line.find(' ' + operator)
842+ if found > -1:
843+ return found, "E221 multiple spaces before operator"
844+ found = line.find('\t' + operator)
845+ if found > -1:
846+ return found, "E222 tab before operator"
847+
848+
849+def imports_on_separate_lines(logical_line):
850+ """
851+ Imports should usually be on separate lines.
852+ """
853+ line = logical_line
854+ if line.startswith('import '):
855+ found = line.find(',')
856+ if found > -1:
857+ return found, "E401 multiple imports on one line"
858+
859+
860+def python_3000_has_key(logical_line):
861+ """
862+ The {}.has_key() method will be removed in the future version of
863+ Python. Use the 'in' operation instead, like:
864+ d = {"a": 1, "b": 2}
865+ if "b" in d:
866+ print d["b"]
867+ """
868+ pos = logical_line.find('.has_key(')
869+ if pos > -1:
870+ return pos, "W601 .has_key() is deprecated, use 'in'"
871+
872+
873+def python_3000_raise_comma(logical_line):
874+ """
875+ When raising an exception, use "raise ValueError('message')"
876+ instead of the older form "raise ValueError, 'message'".
877+
878+ The paren-using form is preferred because when the exception arguments
879+ are long or include string formatting, you don't need to use line
880+ continuation characters thanks to the containing parentheses. The older
881+ form will be removed in Python 3000.
882+ """
883+ match = raise_comma_match(logical_line)
884+ if match:
885+ return match.start(1), "W602 deprecated form of raising exception"
886+
887+
888+##############################################################################
889+# Helper functions
890+##############################################################################
891+
892+
893+def expand_indent(line):
894+ """
895+ Return the amount of indentation.
896+ Tabs are expanded to the next multiple of 8.
897+
898+ >>> expand_indent(' ')
899+ 4
900+ >>> expand_indent('\\t')
901+ 8
902+ >>> expand_indent(' \\t')
903+ 8
904+ >>> expand_indent(' \\t')
905+ 8
906+ >>> expand_indent(' \\t')
907+ 16
908+ """
909+ result = 0
910+ for char in line:
911+ if char == '\t':
912+ result = result / 8 * 8 + 8
913+ elif char == ' ':
914+ result += 1
915+ else:
916+ break
917+ return result
918+
919+
920+##############################################################################
921+# Framework to run all checks
922+##############################################################################
923+
924+
925+def message(text):
926+ """Print a message."""
927+ # print >> sys.stderr, options.prog + ': ' + text
928+ # print >> sys.stderr, text
929+ print text
930+
931+
932+def find_checks(argument_name):
933+ """
934+ Find all globally visible functions where the first argument name
935+ starts with argument_name.
936+ """
937+ checks = []
938+ function_type = type(find_checks)
939+ for name, function in globals().iteritems():
940+ if type(function) is function_type:
941+ args = inspect.getargspec(function)[0]
942+ if len(args) >= 1 and args[0].startswith(argument_name):
943+ checks.append((name, function, args))
944+ checks.sort()
945+ return checks
946+
947+
948+def mute_string(text):
949+ """
950+ Replace contents with 'xxx' to prevent syntax matching.
951+
952+ >>> mute_string('"abc"')
953+ '"xxx"'
954+ >>> mute_string("'''abc'''")
955+ "'''xxx'''"
956+ >>> mute_string("r'abc'")
957+ "r'xxx'"
958+ """
959+ start = 1
960+ end = len(text) - 1
961+ # String modifiers (e.g. u or r)
962+ if text.endswith('"'):
963+ start += text.index('"')
964+ elif text.endswith("'"):
965+ start += text.index("'")
966+ # Triple quotes
967+ if text.endswith('"""') or text.endswith("'''"):
968+ start += 2
969+ end -= 2
970+ return text[:start] + 'x' * (end - start) + text[end:]
971+
972+
973+class Checker:
974+ """
975+ Load a Python source file, tokenize it, check coding style.
976+ """
977+
978+ def __init__(self, filename):
979+ self.filename = filename
980+ self.lines = file(filename).readlines()
981+ self.physical_checks = find_checks('physical_line')
982+ self.logical_checks = find_checks('logical_line')
983+ options.counters['physical lines'] = \
984+ options.counters.get('physical lines', 0) + len(self.lines)
985+
986+ def readline(self):
987+ """
988+ Get the next line from the input buffer.
989+ """
990+ self.line_number += 1
991+ if self.line_number > len(self.lines):
992+ return ''
993+ return self.lines[self.line_number - 1]
994+
995+ def readline_check_physical(self):
996+ """
997+ Check and return the next physical line. This method can be
998+ used to feed tokenize.generate_tokens.
999+ """
1000+ line = self.readline()
1001+ self.check_physical(line)
1002+ return line
1003+
1004+ def run_check(self, check, argument_names):
1005+ """
1006+ Run a check plugin.
1007+ """
1008+ arguments = []
1009+ for name in argument_names:
1010+ arguments.append(getattr(self, name))
1011+ return check(*arguments)
1012+
1013+ def check_physical(self, line):
1014+ """
1015+ Run all physical checks on a raw input line.
1016+ """
1017+ self.physical_line = line
1018+ for name, check, argument_names in self.physical_checks:
1019+ result = self.run_check(check, argument_names)
1020+ if result is not None:
1021+ offset, text = result
1022+ self.report_error(self.line_number, offset, text, check)
1023+
1024+ def build_tokens_line(self):
1025+ """
1026+ Build a logical line from tokens.
1027+ """
1028+ self.mapping = []
1029+ logical = []
1030+ length = 0
1031+ previous = None
1032+ for token in self.tokens:
1033+ token_type, text = token[0:2]
1034+ if token_type in (tokenize.COMMENT, tokenize.NL,
1035+ tokenize.INDENT, tokenize.DEDENT,
1036+ tokenize.NEWLINE):
1037+ continue
1038+ if token_type == tokenize.STRING:
1039+ text = mute_string(text)
1040+ if previous:
1041+ end_line, end = previous[3]
1042+ start_line, start = token[2]
1043+ if end_line != start_line: # different row
1044+ if self.lines[end_line - 1][end - 1] not in '{[(':
1045+ logical.append(' ')
1046+ length += 1
1047+ elif end != start: # different column
1048+ fill = self.lines[end_line - 1][end:start]
1049+ logical.append(fill)
1050+ length += len(fill)
1051+ self.mapping.append((length, token))
1052+ logical.append(text)
1053+ length += len(text)
1054+ previous = token
1055+ self.logical_line = ''.join(logical)
1056+
1057+ def check_logical(self):
1058+ """
1059+ Build a line from tokens and run all logical checks on it.
1060+ """
1061+ options.counters['logical lines'] = \
1062+ options.counters.get('logical lines', 0) + 1
1063+ self.build_tokens_line()
1064+ first_line = self.lines[self.mapping[0][1][2][0] - 1]
1065+ indent = first_line[:self.mapping[0][1][2][1]]
1066+ self.indent_level = expand_indent(indent)
1067+ if options.verbose >= 2:
1068+ print self.logical_line[:80].rstrip()
1069+ for name, check, argument_names in self.logical_checks:
1070+ if options.verbose >= 3:
1071+ print ' ', name
1072+ result = self.run_check(check, argument_names)
1073+ if result is not None:
1074+ offset, text = result
1075+ if type(offset) is tuple:
1076+ original_number, original_offset = offset
1077+ else:
1078+ for token_offset, token in self.mapping:
1079+ if offset >= token_offset:
1080+ original_number = token[2][0]
1081+ original_offset = (token[2][1]
1082+ + offset - token_offset)
1083+ self.report_error(original_number, original_offset,
1084+ text, check)
1085+
1086+ def check_all(self):
1087+ """
1088+ Run all checks on the input file.
1089+ """
1090+ self.file_errors = 0
1091+ self.line_number = 0
1092+ self.state = {'blank_lines': 0}
1093+ self.tokens = []
1094+ parens = 0
1095+ for token in tokenize.generate_tokens(self.readline_check_physical):
1096+ # print tokenize.tok_name[token[0]], repr(token)
1097+ self.tokens.append(token)
1098+ token_type, text = token[0:2]
1099+ if token_type == tokenize.OP and text in '([{':
1100+ parens += 1
1101+ if token_type == tokenize.OP and text in '}])':
1102+ parens -= 1
1103+ if token_type == tokenize.NEWLINE and not parens:
1104+ self.check_logical()
1105+ self.state['blank_lines'] = 0
1106+ self.tokens = []
1107+ if token_type == tokenize.NL and len(self.tokens) == 1:
1108+ self.state['blank_lines'] += 1
1109+ self.tokens = []
1110+ return self.file_errors
1111+
1112+ def report_error(self, line_number, offset, text, check):
1113+ """
1114+ Report an error, according to options.
1115+ """
1116+ if options.quiet == 1 and not self.file_errors:
1117+ message(self.filename)
1118+ self.file_errors += 1
1119+ code = text[:4]
1120+ options.counters[code] = options.counters.get(code, 0) + 1
1121+ options.messages[code] = text[5:]
1122+ if options.quiet:
1123+ return
1124+ if options.testsuite:
1125+ base = os.path.basename(self.filename)[:4]
1126+ if base == code:
1127+ return
1128+ if base[0] == 'E' and code[0] == 'W':
1129+ return
1130+ if ignore_code(code):
1131+ return
1132+ if options.counters[code] == 1 or options.repeat:
1133+ message("%s:%s:%d: %s" %
1134+ (self.filename, line_number, offset + 1, text))
1135+ if options.show_source:
1136+ line = self.lines[line_number - 1]
1137+ message(line.rstrip())
1138+ message(' ' * offset + '^')
1139+ if options.show_pep8:
1140+ message(check.__doc__.lstrip('\n').rstrip())
1141+
1142+
1143+def input_file(filename):
1144+ """
1145+ Run all checks on a Python source file.
1146+ """
1147+ if excluded(filename) or not filename_match(filename):
1148+ return {}
1149+ if options.verbose:
1150+ message('checking ' + filename)
1151+ options.counters['files'] = options.counters.get('files', 0) + 1
1152+ errors = Checker(filename).check_all()
1153+ if options.testsuite and not errors:
1154+ message("%s: %s" % (filename, "no errors found"))
1155+
1156+
1157+def input_dir(dirname):
1158+ """
1159+ Check all Python source files in this directory and all subdirectories.
1160+ """
1161+ dirname = dirname.rstrip('/')
1162+ if excluded(dirname):
1163+ return
1164+ for root, dirs, files in os.walk(dirname):
1165+ if options.verbose:
1166+ message('directory ' + root)
1167+ options.counters['directories'] = \
1168+ options.counters.get('directories', 0) + 1
1169+ dirs.sort()
1170+ for subdir in dirs:
1171+ if excluded(subdir):
1172+ dirs.remove(subdir)
1173+ files.sort()
1174+ for filename in files:
1175+ input_file(os.path.join(root, filename))
1176+
1177+
1178+def excluded(filename):
1179+ """
1180+ Check if options.exclude contains a pattern that matches filename.
1181+ """
1182+ for pattern in options.exclude:
1183+ if fnmatch(filename, pattern):
1184+ return True
1185+
1186+
1187+def filename_match(filename):
1188+ """
1189+ Check if options.filename contains a pattern that matches filename.
1190+ If options.filename is unspecified, this always returns True.
1191+ """
1192+ if not options.filename:
1193+ return True
1194+ for pattern in options.filename:
1195+ if fnmatch(filename, pattern):
1196+ return True
1197+
1198+
1199+def ignore_code(code):
1200+ """
1201+ Check if options.ignore contains a prefix of the error code.
1202+ """
1203+ for ignore in options.ignore:
1204+ if code.startswith(ignore):
1205+ return True
1206+
1207+
1208+def get_error_statistics():
1209+ """Get error statistics."""
1210+ return get_statistics("E")
1211+
1212+
1213+def get_warning_statistics():
1214+ """Get warning statistics."""
1215+ return get_statistics("W")
1216+
1217+
1218+def get_statistics(prefix=''):
1219+ """
1220+ Get statistics for message codes that start with the prefix.
1221+
1222+ prefix='' matches all errors and warnings
1223+ prefix='E' matches all errors
1224+ prefix='W' matches all warnings
1225+ prefix='E4' matches all errors that have to do with imports
1226+ """
1227+ stats = []
1228+ keys = options.messages.keys()
1229+ keys.sort()
1230+ for key in keys:
1231+ if key.startswith(prefix):
1232+ stats.append('%-7s %s %s' %
1233+ (options.counters[key], key, options.messages[key]))
1234+ return stats
1235+
1236+
1237+def print_statistics(prefix=''):
1238+ """Print overall statistics (number of errors and warnings)."""
1239+ for line in get_statistics(prefix):
1240+ print line
1241+
1242+
1243+def print_benchmark(elapsed):
1244+ """
1245+ Print benchmark numbers.
1246+ """
1247+ print '%-7.2f %s' % (elapsed, 'seconds elapsed')
1248+ keys = ['directories', 'files',
1249+ 'logical lines', 'physical lines']
1250+ for key in keys:
1251+ if key in options.counters:
1252+ print '%-7d %s per second (%d total)' % (
1253+ options.counters[key] / elapsed, key,
1254+ options.counters[key])
1255+
1256+
1257+def process_options(arglist=None):
1258+ """
1259+ Process options passed either via arglist or via command line args.
1260+ """
1261+ global options, args
1262+ usage = "%prog [options] input ..."
1263+ parser = OptionParser(usage)
1264+ parser.add_option('-v', '--verbose', default=0, action='count',
1265+ help="print status messages, or debug with -vv")
1266+ parser.add_option('-q', '--quiet', default=0, action='count',
1267+ help="report only file names, or nothing with -qq")
1268+ parser.add_option('--exclude', metavar='patterns', default=default_exclude,
1269+ help="skip matches (default %s)" % default_exclude)
1270+ parser.add_option('--filename', metavar='patterns',
1271+ help="only check matching files (e.g. *.py)")
1272+ parser.add_option('--ignore', metavar='errors', default='',
1273+ help="skip errors and warnings (e.g. E4,W)")
1274+ parser.add_option('--repeat', action='store_true',
1275+ help="show all occurrences of the same error")
1276+ parser.add_option('--show-source', action='store_true',
1277+ help="show source code for each error")
1278+ parser.add_option('--show-pep8', action='store_true',
1279+ help="show text of PEP 8 for each error")
1280+ parser.add_option('--statistics', action='store_true',
1281+ help="count errors and warnings")
1282+ parser.add_option('--benchmark', action='store_true',
1283+ help="measure processing speed")
1284+ parser.add_option('--testsuite', metavar='dir',
1285+ help="run regression tests from dir")
1286+ parser.add_option('--doctest', action='store_true',
1287+ help="run doctest on myself")
1288+ options, args = parser.parse_args(arglist)
1289+ if options.testsuite:
1290+ args.append(options.testsuite)
1291+ if len(args) == 0:
1292+ parser.error('input not specified')
1293+ options.prog = os.path.basename(sys.argv[0])
1294+ options.exclude = options.exclude.split(',')
1295+ for index in range(len(options.exclude)):
1296+ options.exclude[index] = options.exclude[index].rstrip('/')
1297+ if options.filename:
1298+ options.filename = options.filename.split(',')
1299+ if options.ignore:
1300+ options.ignore = options.ignore.split(',')
1301+ else:
1302+ options.ignore = []
1303+ options.counters = {}
1304+ options.messages = {}
1305+
1306+ return options, args
1307+
1308+def _main():
1309+ """
1310+ Parse options and run checks on Python source.
1311+ """
1312+ options, args = process_options()
1313+ if options.doctest:
1314+ import doctest
1315+ return doctest.testmod()
1316+ start_time = time.time()
1317+ for path in args:
1318+ if os.path.isdir(path):
1319+ input_dir(path)
1320+ else:
1321+ input_file(path)
1322+ elapsed = time.time() - start_time
1323+ if options.statistics:
1324+ print_statistics()
1325+ if options.benchmark:
1326+ print_benchmark(elapsed)
1327+
1328+
1329+if __name__ == '__main__':
1330+ _main()
1331
1332=== modified file 'setup.py'
1333--- setup.py 2009-07-04 13:31:04 +0000
1334+++ setup.py 2009-07-13 09:13:22 +0000
1335@@ -43,7 +43,7 @@
1336 if file.endswith(".png") or file.endswith(".svg"):
1337 dirList.append(os.path.join(root,file))
1338 if len(dirList)!=0:
1339- newroot = root.replace("data/","")
1340+ newroot = root.replace("data/","")
1341 fileList.append( (os.path.join(DATA_DIR,newroot),dirList) )
1342 return fileList
1343

Subscribers

People subscribed via source and target branches

to status/vote changes: