Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
  • 2 commits
  • 2 files changed
  • 0 commit comments
  • 1 contributor
Showing with 76 additions and 115 deletions.
  1. +42 −80 todo.py
  2. +34 −35 utils/pep8.py
View
122 todo.py
@@ -109,9 +109,7 @@ def todo_padding(include_done=False):
def iter_todos(include_done=False):
- """
- Opens the file in read-only mode, and returns an iterator for the todos.
- """
+ """Opens the file in read-only mode; returns an iterator for the todos."""
files = [CONFIG["TODO_FILE"]]
if not os.path.isfile(files[0]):
return
@@ -139,20 +137,16 @@ def separate_line(number):
def rewrite_file(fd, lines):
- """
- Simple wrapper for three lines used all too frequently.
- Sets the access position to the beginning of the file, truncates the
- file's length to 0 and then writes all the lines to the file.
- """
+ """Simple wrapper for three lines used all too frequently. Sets the access
+ position to the beginning of the file, truncates the file's length to 0 and
+ then writes all the lines to the file. """
fd.seek(0, 0)
fd.truncate(0)
fd.writelines(lines)
def rewrite_and_post(line_no, old_line, new_line, lines):
- """
- Wraps the following code used frequently in post-production functions.
- """
+ """Wrapper for frequently used semantics for "post-production"."""
with open(CONFIG["TODO_FILE"], "w") as fd:
rewrite_file(fd, lines)
post_success(line_no, old_line, new_line)
@@ -168,9 +162,7 @@ def usage_decorator(func):
def _git_err(g):
- """
- Print any errors that result from GitPython and exit.
- """
+ """Print any errors that result from GitPython and exit."""
if g.stderr:
print(g.stderr)
else:
@@ -179,9 +171,7 @@ def _git_err(g):
def _git_pull():
- """
- Pull any commits that exist on the remote to the local repository.
- """
+ """Equivalent to running git pull on the command line."""
try:
print(CONFIG["GIT"].pull())
except git.exc.GitCommandError as g:
@@ -189,9 +179,7 @@ def _git_pull():
def _git_push():
- """
- Push commits made locally to the remote.
- """
+ """Push commits made locally to the remote."""
try:
s = CONFIG["GIT"].push()
except git.exc.GitCommandError as g:
@@ -203,10 +191,8 @@ def _git_push():
def _git_status():
- """
- Print the status of the local repository if the version of git is 1.7
- or later.
- """
+ """Print the status of the local repository if the version of git is 1.7
+ or later."""
if CONFIG["GIT"].version_info >= (1, 7, 3):
print(CONFIG["GIT"].status())
else:
@@ -214,17 +200,14 @@ def _git_status():
def _git_log():
- """
- Print the two latest commits in the local repository's log.
- """
+ """Print the two latest commits in the local repository's log."""
print(CONFIG["GIT"].log("-5", "--oneline"))
def _git_commit(files, message):
- """
- Make a commit to the git repository.
- * files should be a list like ['file_a', 'file_b'] or ['-a']
- """
+ """Make a commit to the git repository.
+
+ files -- should be an iterable like ['file_a', 'file_b'] or ['-a']"""
if len(message) > 49:
message = concat([message[:45], "...\n\n", message])
try:
@@ -236,12 +219,11 @@ def _git_commit(files, message):
def prompt(*args, **kwargs):
- """
- Sanitize input collected with raw_input().
+ """Sanitize input collected with raw_input().
Prevents someone from entering 'y\' to attempt to break the program.
- args can be any collection of strings that require formatting.
- kwargs will collect the tokens and values.
+ args -- can be any collection of strings that require formatting.
+ kwargs -- will collect the tokens and values.
"""
args = list(args) # [a for a in args]
args.append(' ')
@@ -269,10 +251,8 @@ def test_separated(removed, lines, line_no):
### Configuration Functions
def _iter_actual_lines_(config_file):
- """
- Return only the actual lines of the config file. This skips commented or
- blank lines.
- """
+ """Return only the actual lines of the config file. This skips commented or
+ blank lines."""
skip_re = re.compile('^\s*(#|$)')
with open(config_file, 'r') as f:
@@ -282,9 +262,7 @@ def _iter_actual_lines_(config_file):
def get_config(config_name="", dir_name=""):
- """
- Read the config file
- """
+ """Read the config file"""
if config_name:
CONFIG["TODOTXT_CFG_FILE"] = config_name
if dir_name:
@@ -358,9 +336,7 @@ def git_functions():
global repo_config
def repo_config():
- """
- Help the user configure their git repository.
- """
+ """Help the user configure their git repository."""
from os import getenv
g = CONFIG["GIT"]
# local configuration
@@ -426,13 +402,9 @@ def __while_prompt__(prompt_str, error_string):
def default_config():
- """
- Set up the default configuration file.
- """
+ """Set up the default configuration file."""
def touch(filename):
- """
- Create files if they aren't already there.
- """
+ """Create files if they aren't already there."""
open(filename, "w").close()
if not os.path.exists(CONFIG["TODO_DIR"]):
@@ -514,11 +486,9 @@ def touch(filename):
@usage('\tadd | a "Item to do +project @context #{yyyy-mm-dd}"',
concat(["\t\tAdds 'Item to do +project @context #{yyyy-mm-dd}'",
"to your todo.txt"], ' '), "\t\tfile.",
- "\t\t+project, @context, #{yyyy-mm-dd} are optional")
+ "\t\t+project, @context, #{yyyy-mm-dd} are optional\n")
def add_todo(args):
- """
- Add a new item to the list of things todo.
- """
+ """Add a new item to the list of things todo."""
if str(args) == args:
line = args
elif len(args) >= 1:
@@ -545,10 +515,12 @@ def add_todo(args):
_git_commit([CONFIG["TODO_FILE"]], s)
+@usage('\taddm "First item to do +project @context #{yyyy-mm-dd}',
+ "\t\tSecond item to do +project @context #{yyyy-mm-dd}",
+ "\t\t...", "\t\tLast item to do +project @context #{yyyy-mm-dd}",
+ "\t\tAdds each line as a separate item to your todo.txt file.\n")
def addm_todo(args):
- """
- Add new items to the list of things todo.
- """
+ """Add new items to the list of things todo."""
if str(args) == args:
lines = args
else:
@@ -559,10 +531,11 @@ def addm_todo(args):
### Start do/del functions
+@usage("\tdo NUMBER",
+ "\t\tMarks item with corresponding number as done and moves it to",
+ "\t\tyour done.txt file.\n")
def do_todo(line):
- """
- Mark an item on a specified line as done.
- """
+ """Mark an item on a specified line as done."""
if not line.isdigit():
print("Usage: {0} do item#".format(CONFIG["TODO_PY"]))
else:
@@ -591,9 +564,7 @@ def do_todo(line):
def delete_todo(line):
- """
- Delete an item without marking it as done.
- """
+ """Delete an item without marking it as done."""
if not line.isdigit():
print("Usage: {0} (del|rm) item#".format(CONFIG["TODO_PY"]))
else:
@@ -640,6 +611,8 @@ def post_success(item_no, old_line, new_line):
_git_commit([CONFIG["TODO_FILE"]], print_str)
+@usage('\tappend | app NUMBER "text to append"',
+ '\t\tAppend "text to append" to item NUMBER.\n')
def append_todo(args):
"""
Append text to the item specified.
@@ -683,6 +656,8 @@ def prioritize_todo(args):
post_error('pri', 'NUMBER', 'capital letter in [A-X]')
+@usage("\tdepri | dp NUMBER",
+ "\t\tRemove the priority of the item on line NUMBER.\n")
def de_prioritize_todo(number):
"""
Remove priority markings from the beginning of the line if they're there.
@@ -735,22 +710,9 @@ def cmd_help():
print("")
print(concat(["Usage:", CONFIG["TODO_PY"], "command [arg(s)]"], " "))
print(add_todo.__usage__)
- print('\taddm "First item to do +project @context #{yyyy-mm-dd}')
- print("\t\tSecond item to do +project @context #{yyyy-mm-dd}")
- print("\t\t...")
- print("\t\tLast item to do +project @context #{yyyy-mm-dd}")
- print("\t\tAdds each line as a separate item to your todo.txt file.")
- print("")
- print('\tappend | app NUMBER "text to append"')
- print('\t\tAppend "text to append" to item NUMBER.')
- print("")
- print("\tdepri | dp NUMBER")
- print("\t\tRemove the priority of the item on line NUMBER.")
- print("")
- print("\tdo NUMBER")
- print("\t\tMarks item with corresponding number as done and moves it to")
- print("\t\tyour done.txt file.")
- print("")
+ print(addm_todo.__usage__)
+ print(append_todo.__usage__)
+ print(do_todo.__usage__)
print("\tlist | ls")
print("\t\tLists all items in your todo.txt file sorted by priority.")
print("")
View
69 utils/pep8.py
@@ -92,7 +92,7 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number)
"""
-__version__ = '0.5.1dev'
+__version__ = '1.0.1'
import os
import sys
@@ -115,6 +115,7 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number)
INDENT_REGEX = re.compile(r'([ \t]*)')
RAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*(,)')
+RERAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,\s*\w+\s*,\s*\w+')
SELFTEST_REGEX = re.compile(r'(Okay|[EW]\d{3}):\s(.*)')
ERRORCODE_REGEX = re.compile(r'[EW]\d{3}')
DOCSTRING_REGEX = re.compile(r'u?r?["\']')
@@ -123,6 +124,7 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number)
EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
WHITESPACE_AROUND_NAMED_PARAMETER_REGEX = \
re.compile(r'[()]|\s=[^=]|[^=!<>]=\s')
+LAMBDA_REGEX = re.compile(r'\blambda\b')
WHITESPACE = ' \t'
@@ -242,16 +244,17 @@ def maximum_line_length(physical_line):
"""
line = physical_line.rstrip()
length = len(line)
- if length > MAX_LINE_LENGTH:
+ if length > options.max_line_length:
try:
# The line could contain multi-byte characters
if not hasattr(line, 'decode'): # Python 3
line = line.encode('latin-1')
length = len(line.decode('utf-8'))
- except UnicodeDecodeError:
+ except UnicodeError:
pass
- if length > MAX_LINE_LENGTH:
- return MAX_LINE_LENGTH, "E501 line too long (%d characters)" % length
+ if length > options.max_line_length:
+ return options.max_line_length, \
+ "E501 line too long (%d characters)" % length
##############################################################################
@@ -656,7 +659,7 @@ def compound_statements(logical_line):
before = line[:found]
if (before.count('{') <= before.count('}') and # {'a': 1} (dict)
before.count('[') <= before.count(']') and # [1:2] (slice)
- not re.search(r'\blambda\b', before)): # lambda x: x
+ not LAMBDA_REGEX.search(before)): # lambda x: x
return found, "E701 multiple statements on one line (colon)"
found = line.find(';')
if -1 < found:
@@ -687,7 +690,7 @@ def python_3000_raise_comma(logical_line):
form will be removed in Python 3000.
"""
match = RAISE_COMMA_REGEX.match(logical_line)
- if match:
+ if match and not RERAISE_COMMA_REGEX.match(logical_line):
return match.start(1), "W602 deprecated form of raising exception"
@@ -781,13 +784,6 @@ def mute_string(text):
return text[:start] + 'x' * (end - start) + text[end:]
-def message(text):
- """Print a message."""
- # print >> sys.stderr, options.prog + ': ' + text
- # print >> sys.stderr, text
- print(text)
-
-
##############################################################################
# Framework to run all checks
##############################################################################
@@ -996,7 +992,7 @@ def report_error(self, line_number, offset, text, check):
if ignore_code(code):
return
if options.quiet == 1 and not self.file_errors:
- message(self.filename)
+ print(self.filename)
if code in options.counters:
options.counters[code] += 1
else:
@@ -1007,15 +1003,15 @@ def report_error(self, line_number, offset, text, check):
return
self.file_errors += 1
if options.counters[code] == 1 or options.repeat:
- message("%s:%s:%d: %s" %
- (self.filename, self.line_offset + line_number,
- offset + 1, text))
+ print("%s:%s:%d: %s" %
+ (self.filename, self.line_offset + line_number,
+ offset + 1, text))
if options.show_source:
line = self.lines[line_number - 1]
- message(line.rstrip())
- message(' ' * offset + '^')
+ print(line.rstrip())
+ print(' ' * offset + '^')
if options.show_pep8:
- message(check.__doc__.lstrip('\n').rstrip())
+ print(check.__doc__.lstrip('\n').rstrip())
def input_file(filename):
@@ -1023,7 +1019,7 @@ def input_file(filename):
Run all checks on a Python source file.
"""
if options.verbose:
- message('checking ' + filename)
+ print('checking ' + filename)
errors = Checker(filename).check_all()
@@ -1038,15 +1034,12 @@ def input_dir(dirname, runner=None):
runner = input_file
for root, dirs, files in os.walk(dirname):
if options.verbose:
- message('directory ' + root)
+ print('directory ' + root)
options.counters['directories'] += 1
dirs.sort()
- excluded_dirs = []
- for subdir in dirs:
+ for subdir in dirs[:]:
if excluded(subdir):
- excluded_dirs.append(subdir)
- for subdir in excluded_dirs:
- dirs.remove(subdir)
+ dirs.remove(subdir)
files.sort()
for filename in files:
if filename_match(filename) and not excluded(filename):
@@ -1149,8 +1142,8 @@ def print_benchmark(elapsed):
print('%-7.2f %s' % (elapsed, 'seconds elapsed'))
for key in BENCHMARK_KEYS:
print('%-7d %s per second (%d total)' % (
- options.counters[key] / elapsed, key,
- options.counters[key]))
+ options.counters[key] / elapsed, key,
+ options.counters[key]))
def run_tests(filename):
@@ -1190,9 +1183,9 @@ def run_tests(filename):
for code in codes:
if not options.counters.get(code):
errors += 1
- message('%s: error %s not found' % (label, code))
+ print('%s: error %s not found' % (label, code))
if options.verbose and not errors:
- message('%s: passed (%s)' % (label, ' '.join(codes)))
+ print('%s: passed (%s)' % (label, ' '.join(codes)))
# Keep showing errors for multiple tests
reset_counters()
# output the real line numbers
@@ -1264,8 +1257,10 @@ def process_options(arglist=None):
help="print status messages, or debug with -vv")
parser.add_option('-q', '--quiet', default=0, action='count',
help="report only file names, or nothing with -qq")
- parser.add_option('-r', '--repeat', action='store_true',
- help="show all occurrences of the same error")
+ parser.add_option('-r', '--repeat', default=True, action='store_true',
+ help="(obsolete) show all occurrences of the same error")
+ parser.add_option('--first', action='store_false', dest='repeat',
+ help="show first occurrence of each error")
parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE,
help="exclude files or directories which match these "
"comma separated patterns (default: %s)" %
@@ -1292,6 +1287,10 @@ def process_options(arglist=None):
help="measure processing speed")
parser.add_option('--testsuite', metavar='dir',
help="run regression tests from dir")
+ parser.add_option('--max-line-length', type='int', metavar='n',
+ default=MAX_LINE_LENGTH,
+ help="set maximum allowed line length (default: %d)" %
+ MAX_LINE_LENGTH)
parser.add_option('--doctest', action='store_true',
help="run doctest on myself")
options, args = parser.parse_args(arglist)
@@ -1314,7 +1313,7 @@ def process_options(arglist=None):
elif options.select:
# Ignore all checks which are not explicitly selected
options.ignore = ['']
- elif options.testsuite or options.doctest:
+ elif options.testsuite or options.doctest or not DEFAULT_IGNORE:
# For doctest and testsuite, all checks are required
options.ignore = []
else:

No commit comments for this range

Something went wrong with that request. Please try again.