autopep8'ed

pull/309/head
William Ting 10 years ago
parent f23727ed0f
commit 581b8d9617

@ -70,21 +70,21 @@ def set_defaults():
if is_osx(): if is_osx():
data_home = os.path.join( data_home = os.path.join(
os.path.expanduser('~'), os.path.expanduser('~'),
'Library', 'Library',
'autojump') 'autojump')
elif is_windows(): elif is_windows():
data_home = os.path.join( data_home = os.path.join(
os.getenv('APPDATA'), os.getenv('APPDATA'),
'autojump') 'autojump')
else: else:
data_home = os.getenv( data_home = os.getenv(
'XDG_DATA_HOME', 'XDG_DATA_HOME',
os.path.join( os.path.join(
os.path.expanduser('~'), os.path.expanduser('~'),
'.local', '.local',
'share', 'share',
'autojump')) 'autojump'))
config['data_path'] = os.path.join(data_home, 'autojump.txt') config['data_path'] = os.path.join(data_home, 'autojump.txt')
config['backup_path'] = os.path.join(data_home, 'autojump.txt.bak') config['backup_path'] = os.path.join(data_home, 'autojump.txt.bak')
@ -94,35 +94,35 @@ def set_defaults():
def parse_arguments(): def parse_arguments():
parser = ArgumentParser( parser = ArgumentParser(
description='Automatically jump to directory passed as an \ description='Automatically jump to directory passed as an \
argument.', argument.',
epilog="Please see autojump(1) man pages for full documentation.") epilog="Please see autojump(1) man pages for full documentation.")
parser.add_argument( parser.add_argument(
'directory', metavar='DIRECTORY', nargs='*', default='', 'directory', metavar='DIRECTORY', nargs='*', default='',
help='directory to jump to') help='directory to jump to')
parser.add_argument( parser.add_argument(
'-a', '--add', metavar='DIRECTORY', '-a', '--add', metavar='DIRECTORY',
help='add path') help='add path')
parser.add_argument( parser.add_argument(
'-i', '--increase', metavar='WEIGHT', nargs='?', type=int, '-i', '--increase', metavar='WEIGHT', nargs='?', type=int,
const=10, default=False, const=10, default=False,
help='increase current directory weight') help='increase current directory weight')
parser.add_argument( parser.add_argument(
'-d', '--decrease', metavar='WEIGHT', nargs='?', type=int, '-d', '--decrease', metavar='WEIGHT', nargs='?', type=int,
const=15, default=False, const=15, default=False,
help='decrease current directory weight') help='decrease current directory weight')
parser.add_argument( parser.add_argument(
'--complete', action="store_true", default=False, '--complete', action="store_true", default=False,
help='used for tab completion') help='used for tab completion')
parser.add_argument( parser.add_argument(
'--purge', action="store_true", default=False, '--purge', action="store_true", default=False,
help='remove non-existent paths from database') help='remove non-existent paths from database')
parser.add_argument( parser.add_argument(
'-s', '--stat', action="store_true", default=False, '-s', '--stat', action="store_true", default=False,
help='show database entries and their key weights') help='show database entries and their key weights')
parser.add_argument( parser.add_argument(
'-v', '--version', action="version", version="%(prog)s v" + '-v', '--version', action="version", version="%(prog)s v" +
VERSION, help='show version information') VERSION, help='show version information')
return parser.parse_args() return parser.parse_args()
@ -180,16 +180,16 @@ def find_matches(entries, needles, check_entries=True):
path_exists = lambda _: True path_exists = lambda _: True
data = sorted( data = sorted(
entries, entries,
key=attrgetter('weight'), key=attrgetter('weight'),
reverse=True) reverse=True)
return ifilter( return ifilter(
lambda entry: not is_cwd(entry) and path_exists(entry), lambda entry: not is_cwd(entry) and path_exists(entry),
chain( chain(
match_consecutive(needles, data, ignore_case), match_consecutive(needles, data, ignore_case),
match_fuzzy(needles, data, ignore_case), match_fuzzy(needles, data, ignore_case),
match_anywhere(needles, data, ignore_case))) match_anywhere(needles, data, ignore_case)))
def handle_tab_completion(needle, entries): def handle_tab_completion(needle, entries):
@ -205,20 +205,20 @@ def handle_tab_completion(needle, entries):
elif tab_needle: elif tab_needle:
# found partial tab completion entry # found partial tab completion entry
print_tab_menu( print_tab_menu(
tab_needle, tab_needle,
take(TAB_ENTRIES_COUNT, find_matches( take(TAB_ENTRIES_COUNT, find_matches(
entries, entries,
[tab_needle], [tab_needle],
check_entries=False)), check_entries=False)),
TAB_SEPARATOR) TAB_SEPARATOR)
else: else:
print_tab_menu( print_tab_menu(
needle, needle,
take(TAB_ENTRIES_COUNT, find_matches( take(TAB_ENTRIES_COUNT, find_matches(
entries, entries,
[needle], [needle],
check_entries=False)), check_entries=False)),
TAB_SEPARATOR) TAB_SEPARATOR)
def match_anywhere(needles, haystack, ignore_case=False): def match_anywhere(needles, haystack, ignore_case=False):
@ -241,9 +241,9 @@ def match_anywhere(needles, haystack, ignore_case=False):
regex_needle = '.*' + '.*'.join(needles).replace('\\', '\\\\') + '.*' regex_needle = '.*' + '.*'.join(needles).replace('\\', '\\\\') + '.*'
regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE
found = lambda haystack: re.search( found = lambda haystack: re.search(
regex_needle, regex_needle,
haystack.path, haystack.path,
flags=regex_flags) flags=regex_flags)
return ifilter(found, haystack) return ifilter(found, haystack)
@ -285,9 +285,9 @@ def match_consecutive(needles, haystack, ignore_case=False):
regex_needle = regex_one_sep.join(needles).replace('\\', '\\\\') + regex_no_sep_end # noqa regex_needle = regex_one_sep.join(needles).replace('\\', '\\\\') + regex_no_sep_end # noqa
regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE
found = lambda entry: re.search( found = lambda entry: re.search(
regex_needle, regex_needle,
entry.path, entry.path,
flags=regex_flags) flags=regex_flags)
return ifilter(found, haystack) return ifilter(found, haystack)
@ -317,13 +317,13 @@ def match_fuzzy(needles, haystack, ignore_case=False):
if ignore_case: if ignore_case:
needle = last(needles).lower() needle = last(needles).lower()
match_percent = lambda entry: SequenceMatcher( match_percent = lambda entry: SequenceMatcher(
a=needle, a=needle,
b=end_dir(entry.path.lower())).ratio() b=end_dir(entry.path.lower())).ratio()
else: else:
needle = last(needles) needle = last(needles)
match_percent = lambda entry: SequenceMatcher( match_percent = lambda entry: SequenceMatcher(
a=needle, a=needle,
b=end_dir(entry.path)).ratio() b=end_dir(entry.path)).ratio()
meets_threshold = lambda entry: match_percent(entry) >= \ meets_threshold = lambda entry: match_percent(entry) >= \
FUZZY_MATCH_THRESHOLD FUZZY_MATCH_THRESHOLD
return ifilter(meets_threshold, haystack) return ifilter(meets_threshold, haystack)
@ -345,7 +345,7 @@ def print_stats(data, data_path):
try: try:
print_local( print_local(
"%.2f:\t current directory weight" % data.get(os.getcwdu(), 0)) "%.2f:\t current directory weight" % data.get(os.getcwdu(), 0))
except OSError: except OSError:
# current directory no longer exists # current directory no longer exists
pass pass
@ -361,8 +361,8 @@ def main(args): # noqa
save(config, first(add_path(load(config), args.add))) save(config, first(add_path(load(config), args.add)))
elif args.complete: elif args.complete:
handle_tab_completion( handle_tab_completion(
needle=first(chain(sanitize(args.directory), [''])), needle=first(chain(sanitize(args.directory), [''])),
entries=entriefy(load(config))) entries=entriefy(load(config)))
elif args.decrease: elif args.decrease:
data, entry = decrease_path(load(config), get_pwd(), args.decrease) data, entry = decrease_path(load(config), get_pwd(), args.decrease)
save(config, data) save(config, data)
@ -382,9 +382,9 @@ def main(args): # noqa
# Return best match. # Return best match.
entries = entriefy(load(config)) entries = entriefy(load(config))
print_local(first(chain( print_local(first(chain(
imap(attrgetter('path'), find_matches(entries, [''])), imap(attrgetter('path'), find_matches(entries, [''])),
# always return a path to calling shell functions # always return a path to calling shell functions
['.']))) ['.'])))
else: else:
entries = entriefy(load(config)) entries = entriefy(load(config))
needles = sanitize(args.directory) needles = sanitize(args.directory)
@ -401,14 +401,14 @@ def main(args): # noqa
elif tab_index: elif tab_index:
get_ith_path = lambda i, iterable: last(take(i, iterable)).path get_ith_path = lambda i, iterable: last(take(i, iterable)).path
print_local( print_local(
get_ith_path( get_ith_path(
tab_index, tab_index,
find_matches(entries, [tab_needle]))) find_matches(entries, [tab_needle])))
else: else:
print_local(first(chain( print_local(first(chain(
imap(attrgetter('path'), find_matches(entries, needles)), imap(attrgetter('path'), find_matches(entries, needles)),
# always return a path to calling shell functions # always return a path to calling shell functions
['.']))) ['.'])))
return 0 return 0

@ -107,8 +107,7 @@ try:
except NameError: except NameError:
# for python < 2.4 compatibility: # for python < 2.4 compatibility:
def sorted(iterable, reverse=False): def sorted(iterable, reverse=False):
result = list(iterable) result = sorted(iterable)
result.sort()
if reverse: if reverse:
result.reverse() result.reverse()
return result return result
@ -131,7 +130,9 @@ _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
# Utility functions and classes # Utility functions and classes
# ============================= # =============================
class _AttributeHolder(object): class _AttributeHolder(object):
"""Abstract base class that provides __repr__. """Abstract base class that provides __repr__.
The __repr__ method returns a string in the format:: The __repr__ method returns a string in the format::
@ -167,6 +168,7 @@ def _ensure_value(namespace, name, value):
# =============== # ===============
class HelpFormatter(object): class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings. """Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods Only the name of this class is considered a public API. All the methods
@ -640,13 +642,14 @@ class HelpFormatter(object):
def _fill_text(self, text, width, indent): def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip() text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent, return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent) subsequent_indent=indent)
def _get_help_string(self, action): def _get_help_string(self, action):
return action.help return action.help
class RawDescriptionHelpFormatter(HelpFormatter): class RawDescriptionHelpFormatter(HelpFormatter):
"""Help message formatter which retains any formatting in descriptions. """Help message formatter which retains any formatting in descriptions.
Only the name of this class is considered a public API. All the methods Only the name of this class is considered a public API. All the methods
@ -658,6 +661,7 @@ class RawDescriptionHelpFormatter(HelpFormatter):
class RawTextHelpFormatter(RawDescriptionHelpFormatter): class RawTextHelpFormatter(RawDescriptionHelpFormatter):
"""Help message formatter which retains formatting of all help text. """Help message formatter which retains formatting of all help text.
Only the name of this class is considered a public API. All the methods Only the name of this class is considered a public API. All the methods
@ -669,6 +673,7 @@ class RawTextHelpFormatter(RawDescriptionHelpFormatter):
class ArgumentDefaultsHelpFormatter(HelpFormatter): class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""Help message formatter which adds default values to argument help. """Help message formatter which adds default values to argument help.
Only the name of this class is considered a public API. All the methods Only the name of this class is considered a public API. All the methods
@ -693,7 +698,7 @@ def _get_action_name(argument):
if argument is None: if argument is None:
return None return None
elif argument.option_strings: elif argument.option_strings:
return '/'.join(argument.option_strings) return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS): elif argument.metavar not in (None, SUPPRESS):
return argument.metavar return argument.metavar
elif argument.dest not in (None, SUPPRESS): elif argument.dest not in (None, SUPPRESS):
@ -703,6 +708,7 @@ def _get_action_name(argument):
class ArgumentError(Exception): class ArgumentError(Exception):
"""An error from creating or using an argument (optional or positional). """An error from creating or using an argument (optional or positional).
The string value of this exception is the message, augmented with The string value of this exception is the message, augmented with
@ -723,6 +729,7 @@ class ArgumentError(Exception):
class ArgumentTypeError(Exception): class ArgumentTypeError(Exception):
"""An error from trying to convert a command line string to a type.""" """An error from trying to convert a command line string to a type."""
pass pass
@ -732,6 +739,7 @@ class ArgumentTypeError(Exception):
# ============== # ==============
class Action(_AttributeHolder): class Action(_AttributeHolder):
"""Information about how to convert command line strings to Python objects. """Information about how to convert command line strings to Python objects.
Action objects are used by an ArgumentParser to represent the information Action objects are used by an ArgumentParser to represent the information
@ -1109,7 +1117,8 @@ class _SubParsersAction(Action):
# parse all the remaining options into the namespace # parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top # store any unrecognized options on the object, so that the top
# level parser can decide what to do with them # level parser can decide what to do with them
namespace, arg_strings = parser.parse_known_args(arg_strings, namespace) namespace, arg_strings = parser.parse_known_args(
arg_strings, namespace)
if arg_strings: if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
@ -1120,6 +1129,7 @@ class _SubParsersAction(Action):
# ============== # ==============
class FileType(object): class FileType(object):
"""Factory for creating file object types """Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the Instances of FileType are typically passed as type= arguments to the
@ -1162,7 +1172,9 @@ class FileType(object):
# Optional and Positional Parsing # Optional and Positional Parsing
# =========================== # ===========================
class Namespace(_AttributeHolder): class Namespace(_AttributeHolder):
"""Simple object for storing attributes. """Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple Implements equality by attribute names and values, and provides a simple
@ -1264,7 +1276,6 @@ class _ActionsContainer(object):
return action.default return action.default
return self._defaults.get(dest, None) return self._defaults.get(dest, None)
# ======================= # =======================
# Adding argument actions # Adding argument actions
# ======================= # =======================
@ -1536,6 +1547,7 @@ class _MutuallyExclusiveGroup(_ArgumentGroup):
class ArgumentParser(_AttributeHolder, _ActionsContainer): class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects. """Object for parsing command line strings into Python objects.
Keyword Arguments: Keyword Arguments:
@ -1611,12 +1623,12 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
default_prefix = prefix_chars[0] default_prefix = prefix_chars[0]
if self.add_help: if self.add_help:
self.add_argument( self.add_argument(
default_prefix+'h', default_prefix*2+'help', default_prefix + 'h', default_prefix * 2 + 'help',
action='help', default=SUPPRESS, action='help', default=SUPPRESS,
help=_('show this help message and exit')) help=_('show this help message and exit'))
if self.version: if self.version:
self.add_argument( self.add_argument(
default_prefix+'v', default_prefix*2+'version', default_prefix + 'v', default_prefix * 2 + 'version',
action='version', default=SUPPRESS, action='version', default=SUPPRESS,
version=self.version, version=self.version,
help=_("show program's version number and exit")) help=_("show program's version number and exit"))
@ -2075,8 +2087,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
# if multiple actions match, the option string was ambiguous # if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1: if len(option_tuples) > 1:
options = ', '.join([option_string options = ', '.join(
for action, option_string, explicit_arg in option_tuples]) [option_string for action, option_string, explicit_arg in option_tuples])
tup = arg_string, options tup = arg_string, options
self.error(_('ambiguous option: %s could match %s') % tup) self.error(_('ambiguous option: %s could match %s') % tup)

@ -51,10 +51,10 @@ def entriefy(data):
def load(config): def load(config):
"""Returns a dictonary (key=path, value=weight) loaded from data file.""" """Returns a dictonary (key=path, value=weight) loaded from data file."""
xdg_aj_home = os.path.join( xdg_aj_home = os.path.join(
os.path.expanduser('~'), os.path.expanduser('~'),
'.local', '.local',
'share', 'share',
'autojump') 'autojump')
if is_osx() and os.path.exists(xdg_aj_home): if is_osx() and os.path.exists(xdg_aj_home):
migrate_osx_xdg_data(config) migrate_osx_xdg_data(config)
@ -76,9 +76,9 @@ def load(config):
'r', encoding='utf-8', 'r', encoding='utf-8',
errors='replace') as f: errors='replace') as f:
return dict( return dict(
imap( imap(
tupleize, tupleize,
ifilter(correct_length, imap(parse, f)))) ifilter(correct_length, imap(parse, f))))
except (IOError, EOFError): except (IOError, EOFError):
return load_backup(config) return load_backup(config)

@ -56,8 +56,8 @@ def get_tab_entry_info(entry, separator):
match_needle = re.search(r'(.*?)' + separator, entry) match_needle = re.search(r'(.*?)' + separator, entry)
match_index = re.search(separator + r'([0-9]{1})', entry) match_index = re.search(separator + r'([0-9]{1})', entry)
match_path = re.search( match_path = re.search(
separator + r'[0-9]{1}' + separator + r'(.*)', separator + r'[0-9]{1}' + separator + r'(.*)',
entry) entry)
if match_needle: if match_needle:
needle = match_needle.group(1) needle = match_needle.group(1)

@ -138,7 +138,7 @@ def test_get_index():
def test_get_path(): def test_get_path():
assert get_tab_entry_info('foo__3__/foo/bar', '__') \ assert get_tab_entry_info('foo__3__/foo/bar', '__') \
== ('foo', 3, '/foo/bar') == ('foo', 3, '/foo/bar')
def test_get_none(): def test_get_none():

@ -26,24 +26,24 @@ def parse_arguments():
default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink') default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')
parser = ArgumentParser( parser = ArgumentParser(
description='Uninstalls autojump.') description='Uninstalls autojump.')
parser.add_argument( parser.add_argument(
'-n', '--dryrun', action="store_true", default=False, '-n', '--dryrun', action="store_true", default=False,
help='simulate installation') help='simulate installation')
parser.add_argument( parser.add_argument(
'-u', '--userdata', action="store_true", default=False, '-u', '--userdata', action="store_true", default=False,
help='delete user data') help='delete user data')
parser.add_argument( parser.add_argument(
'-d', '--destdir', metavar='DIR', '-d', '--destdir', metavar='DIR',
help='custom destdir') help='custom destdir')
parser.add_argument( parser.add_argument(
'-p', '--prefix', metavar='DIR', default='', '-p', '--prefix', metavar='DIR', default='',
help='custom prefix') help='custom prefix')
parser.add_argument( parser.add_argument(
'-z', '--zshshare', metavar='DIR', default='functions', '-z', '--zshshare', metavar='DIR', default='functions',
help='custom zshshare') help='custom zshshare')
parser.add_argument( parser.add_argument(
'-c', '--clinkdir', metavar='DIR', default=default_clink_dir) '-c', '--clinkdir', metavar='DIR', default=default_clink_dir)
return parser.parse_args() return parser.parse_args()
@ -125,21 +125,21 @@ def remove_system_installation(dryrun=False):
def remove_user_data(dryrun=False): def remove_user_data(dryrun=False):
if platform.system() == 'Darwin': if platform.system() == 'Darwin':
data_home = os.path.join( data_home = os.path.join(
os.path.expanduser('~'), os.path.expanduser('~'),
'Library', 'Library',
'autojump') 'autojump')
elif platform.system() == 'Windows': elif platform.system() == 'Windows':
data_home = os.path.join( data_home = os.path.join(
os.getenv('APPDATA'), os.getenv('APPDATA'),
'autojump') 'autojump')
else: else:
data_home = os.getenv( data_home = os.getenv(
'XDG_DATA_HOME', 'XDG_DATA_HOME',
os.path.join( os.path.join(
os.path.expanduser('~'), os.path.expanduser('~'),
'.local', '.local',
'share', 'share',
'autojump')) 'autojump'))
if os.path.exists(data_home): if os.path.exists(data_home):
print("\nFound user data...") print("\nFound user data...")
@ -149,7 +149,7 @@ def remove_user_data(dryrun=False):
def remove_user_installation(dryrun=False): def remove_user_installation(dryrun=False):
if platform.system() == 'Windows': if platform.system() == 'Windows':
default_destdir = os.path.join(os.getenv('LOCALAPPDATA', ''), default_destdir = os.path.join(os.getenv('LOCALAPPDATA', ''),
'autojump') 'autojump')
clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink') clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')
else: else:
default_destdir = os.path.join(os.path.expanduser("~"), '.autojump') default_destdir = os.path.join(os.path.expanduser("~"), '.autojump')

Loading…
Cancel
Save