1
0
mirror of https://github.com/wting/autojump synced 2024-10-27 20:34:07 +00:00

Run pre-commit on repo.

This commit is contained in:
William Ting 2016-04-28 23:33:04 -07:00
parent e57956cc1c
commit d529790278
7 changed files with 92 additions and 83 deletions

View File

@ -1,5 +1,5 @@
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
# flake8: noqa # flake8: noqa
"""Command-line parsing library """Command-line parsing library

View File

@ -2,26 +2,27 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
from codecs import open
from collections import namedtuple
import os import os
import shutil import shutil
import sys import sys
from codecs import open
from collections import namedtuple
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from time import time from time import time
from autojump_utils import create_dir
from autojump_utils import is_osx
from autojump_utils import is_python3
from autojump_utils import move_file
from autojump_utils import unico
if sys.version_info[0] == 3: if sys.version_info[0] == 3:
ifilter = filter ifilter = filter
imap = map imap = map
else: else:
from itertools import ifilter from itertools import ifilter # noqa
from itertools import imap from itertools import imap # noqa
from autojump_utils import create_dir
from autojump_utils import unico
from autojump_utils import is_osx
from autojump_utils import is_python3
from autojump_utils import move_file
BACKUP_THRESHOLD = 24 * 60 * 60 BACKUP_THRESHOLD = 24 * 60 * 60
@ -95,7 +96,7 @@ def migrate_osx_xdg_data(config):
Older versions incorrectly used Linux XDG_DATA_HOME paths on OS X. This Older versions incorrectly used Linux XDG_DATA_HOME paths on OS X. This
migrates autojump files from ~/.local/share/autojump to ~/Library/autojump migrates autojump files from ~/.local/share/autojump to ~/Library/autojump
""" """
assert is_osx(), "This function should only be run on OS X." assert is_osx(), 'This function should only be run on OS X.'
xdg_data_home = os.path.join(os.path.expanduser('~'), '.local', 'share') xdg_data_home = os.path.join(os.path.expanduser('~'), '.local', 'share')
xdg_aj_home = os.path.join(xdg_data_home, 'autojump') xdg_aj_home = os.path.join(xdg_data_home, 'autojump')
@ -125,12 +126,12 @@ def save(config, data):
with open(temp.name, 'w', encoding='utf-8', errors='replace') as f: with open(temp.name, 'w', encoding='utf-8', errors='replace') as f:
for path, weight in data.items(): for path, weight in data.items():
f.write(unico("%s\t%s\n" % (weight, path))) f.write(unico('%s\t%s\n' % (weight, path)))
f.flush() f.flush()
os.fsync(f) os.fsync(f)
except IOError as ex: except IOError as ex:
print("Error saving autojump data (disk full?)" % ex, file=sys.stderr) print('Error saving autojump data (disk full?)' % ex, file=sys.stderr)
sys.exit(1) sys.exit(1)
# move temp_file -> autojump.txt # move temp_file -> autojump.txt

View File

@ -1,16 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
import errno import errno
from itertools import islice
import os import os
import platform import platform
import re import re
import shutil import shutil
import sys import sys
import unicodedata import unicodedata
from itertools import islice
if sys.version_info[0] == 3: if sys.version_info[0] == 3:
imap = map imap = map
@ -75,7 +74,7 @@ def get_pwd():
try: try:
return os.getcwdu() return os.getcwdu()
except OSError: except OSError:
print("Current directory no longer exists.", file=sys.stderr) print('Current directory no longer exists.', file=sys.stderr)
raise raise
@ -141,7 +140,7 @@ def move_file(src, dst):
def print_entry(entry): def print_entry(entry):
print_local("%.1f:\t%s" % (entry.weight, entry.path)) print_local('%.1f:\t%s' % (entry.weight, entry.path))
def print_local(string): def print_local(string):

View File

@ -8,13 +8,13 @@ import shutil
import sys import sys
sys.path.append('bin') sys.path.append('bin')
from autojump_argparse import ArgumentParser from autojump_argparse import ArgumentParser # noqa
SUPPORTED_SHELLS = ('bash', 'zsh', 'fish', 'tcsh') SUPPORTED_SHELLS = ('bash', 'zsh', 'fish', 'tcsh')
def cp(src, dest, dryrun=False): def cp(src, dest, dryrun=False):
print("copying file: %s -> %s" % (src, dest)) print('copying file: %s -> %s' % (src, dest))
if not dryrun: if not dryrun:
shutil.copy(src, dest) shutil.copy(src, dest)
@ -24,18 +24,18 @@ def get_shell():
def mkdir(path, dryrun=False): def mkdir(path, dryrun=False):
print("creating directory:", path) print('creating directory:', path)
if not dryrun and not os.path.exists(path): if not dryrun and not os.path.exists(path):
os.makedirs(path) os.makedirs(path)
def modify_autojump_sh(etc_dir, share_dir, dryrun=False): def modify_autojump_sh(etc_dir, share_dir, dryrun=False):
"""Append custom installation path to autojump.sh""" """Append custom installation path to autojump.sh"""
custom_install = "\ custom_install = '\
\n# check custom install \ \n# check custom install \
\nif [ -s %s/autojump.${shell} ]; then \ \nif [ -s %s/autojump.${shell} ]; then \
\n source %s/autojump.${shell} \ \n source %s/autojump.${shell} \
\nfi\n" % (share_dir, share_dir) \nfi\n' % (share_dir, share_dir)
with open(os.path.join(etc_dir, 'autojump.sh'), 'a') as f: with open(os.path.join(etc_dir, 'autojump.sh'), 'a') as f:
f.write(custom_install) f.write(custom_install)
@ -44,8 +44,8 @@ def modify_autojump_sh(etc_dir, share_dir, dryrun=False):
def modify_autojump_lua(clink_dir, bin_dir, dryrun=False): def modify_autojump_lua(clink_dir, bin_dir, dryrun=False):
"""Prepend custom AUTOJUMP_BIN_DIR definition to autojump.lua""" """Prepend custom AUTOJUMP_BIN_DIR definition to autojump.lua"""
custom_install = "local AUTOJUMP_BIN_DIR = \"%s\"\n" % bin_dir.replace( custom_install = "local AUTOJUMP_BIN_DIR = \"%s\"\n" % bin_dir.replace(
"\\", '\\',
"\\\\") '\\\\')
clink_file = os.path.join(clink_dir, 'autojump.lua') clink_file = os.path.join(clink_dir, 'autojump.lua')
with open(clink_file, 'r') as f: with open(clink_file, 'r') as f:
original = f.read() original = f.read()
@ -60,7 +60,7 @@ def parse_arguments(): # noqa
'autojump') 'autojump')
else: else:
default_user_destdir = os.path.join( default_user_destdir = os.path.join(
os.path.expanduser("~"), os.path.expanduser('~'),
'.autojump') '.autojump')
default_user_prefix = '' default_user_prefix = ''
default_user_zshshare = 'functions' default_user_zshshare = 'functions'
@ -73,10 +73,10 @@ def parse_arguments(): # noqa
description='Installs autojump globally for root users, otherwise \ description='Installs autojump globally for root users, otherwise \
installs in current user\'s home directory.') installs in current user\'s home directory.')
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(
'-f', '--force', action="store_true", default=False, '-f', '--force', action='store_true', default=False,
help='skip root user, shell type, Python version checks') help='skip root user, shell type, Python version checks')
parser.add_argument( parser.add_argument(
'-d', '--destdir', metavar='DIR', default=default_user_destdir, '-d', '--destdir', metavar='DIR', default=default_user_destdir,
@ -91,28 +91,28 @@ def parse_arguments(): # noqa
'-c', '--clinkdir', metavar='DIR', default=default_clink_dir, '-c', '--clinkdir', metavar='DIR', default=default_clink_dir,
help='set clink directory location to DIR (Windows only)') help='set clink directory location to DIR (Windows only)')
parser.add_argument( parser.add_argument(
'-s', '--system', action="store_true", default=False, '-s', '--system', action='store_true', default=False,
help='install system wide for all users') help='install system wide for all users')
args = parser.parse_args() args = parser.parse_args()
if not args.force: if not args.force:
if sys.version_info[0] == 2 and sys.version_info[1] < 6: if sys.version_info[0] == 2 and sys.version_info[1] < 6:
print("Python v2.6+ or v3.0+ required.", file=sys.stderr) print('Python v2.6+ or v3.0+ required.', file=sys.stderr)
sys.exit(1) sys.exit(1)
if args.system: if args.system:
if platform.system() == 'Windows': if platform.system() == 'Windows':
print("System-wide installation is not supported on Windows.", print('System-wide installation is not supported on Windows.',
file=sys.stderr) file=sys.stderr)
sys.exit(1) sys.exit(1)
elif os.geteuid() != 0: elif os.geteuid() != 0:
print("Please rerun as root for system-wide installation.", print('Please rerun as root for system-wide installation.',
file=sys.stderr) file=sys.stderr)
sys.exit(1) sys.exit(1)
if platform.system() != 'Windows' \ if platform.system() != 'Windows' \
and get_shell() not in SUPPORTED_SHELLS: and get_shell() not in SUPPORTED_SHELLS:
print("Unsupported shell: %s" % os.getenv('SHELL'), print('Unsupported shell: %s' % os.getenv('SHELL'),
file=sys.stderr) file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -125,7 +125,7 @@ def parse_arguments(): # noqa
if args.system: if args.system:
if args.custom_install: if args.custom_install:
print("Custom paths incompatible with --system option.", print('Custom paths incompatible with --system option.',
file=sys.stderr) file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -138,34 +138,34 @@ def parse_arguments(): # noqa
def show_post_installation_message(etc_dir, share_dir, bin_dir): def show_post_installation_message(etc_dir, share_dir, bin_dir):
if platform.system() == 'Windows': if platform.system() == 'Windows':
print("\nPlease manually add %s to your user path" % bin_dir) print('\nPlease manually add %s to your user path' % bin_dir)
else: else:
if get_shell() == 'fish': if get_shell() == 'fish':
aj_shell = '%s/autojump.fish' % share_dir aj_shell = '%s/autojump.fish' % share_dir
source_msg = "if test -f %s; . %s; end" % (aj_shell, aj_shell) source_msg = 'if test -f %s; . %s; end' % (aj_shell, aj_shell)
rcfile = '~/.config/fish/config.fish' rcfile = '~/.config/fish/config.fish'
else: else:
aj_shell = '%s/autojump.sh' % etc_dir aj_shell = '%s/autojump.sh' % etc_dir
source_msg = "[[ -s %s ]] && source %s" % (aj_shell, aj_shell) source_msg = '[[ -s %s ]] && source %s' % (aj_shell, aj_shell)
if platform.system() == 'Darwin' and get_shell() == 'bash': if platform.system() == 'Darwin' and get_shell() == 'bash':
rcfile = '~/.profile' rcfile = '~/.profile'
else: else:
rcfile = '~/.%src' % get_shell() rcfile = '~/.%src' % get_shell()
print("\nPlease manually add the following line(s) to %s:" % rcfile) print('\nPlease manually add the following line(s) to %s:' % rcfile)
print('\n\t' + source_msg) print('\n\t' + source_msg)
if get_shell() == 'zsh': if get_shell() == 'zsh':
print("\n\tautoload -U compinit && compinit -u") print('\n\tautoload -U compinit && compinit -u')
print("\nPlease restart terminal(s) before running autojump.\n") print('\nPlease restart terminal(s) before running autojump.\n')
def main(args): def main(args):
if args.dryrun: if args.dryrun:
print("Installing autojump to %s (DRYRUN)..." % args.destdir) print('Installing autojump to %s (DRYRUN)...' % args.destdir)
else: else:
print("Installing autojump to %s ..." % args.destdir) print('Installing autojump to %s ...' % args.destdir)
bin_dir = os.path.join(args.destdir, args.prefix, 'bin') bin_dir = os.path.join(args.destdir, args.prefix, 'bin')
etc_dir = os.path.join(args.destdir, 'etc', 'profile.d') etc_dir = os.path.join(args.destdir, 'etc', 'profile.d')
@ -212,5 +212,5 @@ def main(args):
show_post_installation_message(etc_dir, share_dir, bin_dir) show_post_installation_message(etc_dir, share_dir, bin_dir)
if __name__ == "__main__": if __name__ == '__main__':
sys.exit(main(parse_arguments())) sys.exit(main(parse_arguments()))

View File

@ -7,19 +7,19 @@ import mock
import pytest import pytest
sys.path.append(os.path.join(os.getcwd(), 'bin')) sys.path.append(os.path.join(os.getcwd(), 'bin'))
import autojump_utils import autojump_utils # noqa
from autojump_utils import encode_local from autojump_utils import encode_local # noqa
from autojump_utils import first from autojump_utils import first # noqa
from autojump_utils import get_tab_entry_info from autojump_utils import get_tab_entry_info # noqa
from autojump_utils import has_uppercase from autojump_utils import has_uppercase # noqa
from autojump_utils import in_bash from autojump_utils import in_bash # noqa
from autojump_utils import is_python3 from autojump_utils import is_python3 # noqa
from autojump_utils import last from autojump_utils import last # noqa
from autojump_utils import sanitize from autojump_utils import sanitize # noqa
from autojump_utils import second from autojump_utils import second # noqa
from autojump_utils import surround_quotes from autojump_utils import surround_quotes # noqa
from autojump_utils import take from autojump_utils import take # noqa
from autojump_utils import unico from autojump_utils import unico # noqa
if is_python3(): if is_python3():
@ -37,27 +37,27 @@ def u(string):
# strings # strings
@pytest.mark.skipif(is_python3(), reason="Unicode sucks.") @pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii') @mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')
def test_encode_local_ascii(_): def test_encode_local_ascii(_):
assert encode_local(u('foo')) == b'foo' assert encode_local(u('foo')) == b'foo'
@pytest.mark.skipif(is_python3(), reason="Unicode sucks.") @pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@pytest.mark.xfail(reason="disabled due to pytest bug: https://bitbucket.org/hpk42/pytest/issue/534/pytest-fails-to-catch-unicodedecodeerrors") # noqa @pytest.mark.xfail(reason='disabled due to pytest bug: https://bitbucket.org/hpk42/pytest/issue/534/pytest-fails-to-catch-unicodedecodeerrors') # noqa
@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii') @mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')
def test_encode_local_ascii_fails(_): def test_encode_local_ascii_fails(_):
with pytest.raises(UnicodeDecodeError): with pytest.raises(UnicodeDecodeError):
encode_local(u('日本語')) encode_local(u('日本語'))
@pytest.mark.skipif(is_python3(), reason="Unicode sucks.") @pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value=None) @mock.patch.object(sys, 'getfilesystemencoding', return_value=None)
def test_encode_local_empty(_): def test_encode_local_empty(_):
assert encode_local(b'foo') == u('foo') assert encode_local(b'foo') == u('foo')
@pytest.mark.skipif(is_python3(), reason="Unicode sucks.") @pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value='utf-8') @mock.patch.object(sys, 'getfilesystemencoding', return_value='utf-8')
def test_encode_local_unicode(_): def test_encode_local_unicode(_):
assert encode_local(b'foo') == u('foo') assert encode_local(b'foo') == u('foo')
@ -86,7 +86,7 @@ def test_sanitize():
assert sanitize([r'/foo/bar/', r'/']) == [u('/foo/bar'), u('/')] assert sanitize([r'/foo/bar/', r'/']) == [u('/foo/bar'), u('/')]
@pytest.mark.skipif(is_python3(), reason="Unicode sucks.") @pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
def test_unico(): def test_unico():
assert unico(str('blah')) == u('blah') assert unico(str('blah')) == u('blah')
assert unico(str('日本語')) == u('日本語') assert unico(str('日本語')) == u('日本語')

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
""" """
IPython autojump magic IPython autojump magic
@ -13,8 +14,8 @@ And copy this file into the "startup" folder of your new profile (e.g.
@TODO: extend %cd to call "autojump -a" @TODO: extend %cd to call "autojump -a"
""" """
from subprocess import Popen
from subprocess import PIPE from subprocess import PIPE
from subprocess import Popen
from IPython.core.magic import register_line_magic from IPython.core.magic import register_line_magic
@ -25,9 +26,9 @@ ip = get_ipython() # noqa
def j(path): def j(path):
cmd = ['autojump'] + path.split() cmd = ['autojump'] + path.split()
newpath = Popen( newpath = Popen(
cmd, cmd,
stdout=PIPE, stdout=PIPE,
shell=False).communicate()[0].strip() shell=False).communicate()[0].strip()
if newpath: if newpath:
ip.magic('cd %s' % newpath.decode('utf-8')) ip.magic('cd %s' % newpath.decode('utf-8'))

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
import os import os
@ -9,7 +8,7 @@ import shutil
import sys import sys
sys.path.append('bin') sys.path.append('bin')
from autojump_argparse import ArgumentParser from autojump_argparse import ArgumentParser # noqa
def is_empty_dir(path): def is_empty_dir(path):
@ -28,10 +27,10 @@ def parse_arguments():
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',
@ -61,7 +60,7 @@ def remove_custom_installation(args, dryrun=False):
if not os.path.exists(share_dir): if not os.path.exists(share_dir):
return return
print("\nFound custom installation...") print('\nFound custom installation...')
rm(os.path.join(bin_dir, 'autojump'), dryrun) rm(os.path.join(bin_dir, 'autojump'), dryrun)
rm(os.path.join(bin_dir, 'autojump_data.py'), dryrun) rm(os.path.join(bin_dir, 'autojump_data.py'), dryrun)
rm(os.path.join(bin_dir, 'autojump_utils.py'), dryrun) rm(os.path.join(bin_dir, 'autojump_utils.py'), dryrun)
@ -94,18 +93,27 @@ def remove_system_installation(dryrun=False):
default_zshshare = '/usr/share/zsh/site-functions' default_zshshare = '/usr/share/zsh/site-functions'
bin_dir = os.path.join(default_destdir, default_prefix, 'bin') bin_dir = os.path.join(default_destdir, default_prefix, 'bin')
doc_dir = os.path.join(default_destdir, default_prefix, 'share', 'man', 'man1') doc_dir = os.path.join(
default_destdir,
default_prefix,
'share',
'man',
'man1')
etc_dir = os.path.join(default_destdir, 'etc', 'profile.d') etc_dir = os.path.join(default_destdir, 'etc', 'profile.d')
share_dir = os.path.join(default_destdir, default_prefix, 'share', 'autojump') share_dir = os.path.join(
default_destdir,
default_prefix,
'share',
'autojump')
zshshare_dir = os.path.join(default_destdir, default_zshshare) zshshare_dir = os.path.join(default_destdir, default_zshshare)
if not os.path.exists(share_dir): if not os.path.exists(share_dir):
return return
print("\nFound system installation...") print('\nFound system installation...')
if os.geteuid() != 0: if os.geteuid() != 0:
print("Please rerun as root for system-wide uninstall, skipping...", print('Please rerun as root for system-wide uninstall, skipping...',
file=sys.stderr) file=sys.stderr)
return return
@ -142,7 +150,7 @@ def remove_user_data(dryrun=False):
'autojump')) 'autojump'))
if os.path.exists(data_home): if os.path.exists(data_home):
print("\nFound user data...") print('\nFound user data...')
rmdir(data_home, dryrun) rmdir(data_home, dryrun)
@ -152,10 +160,10 @@ def remove_user_installation(dryrun=False):
'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')
if os.path.exists(default_destdir): if os.path.exists(default_destdir):
print("\nFound user installation...") print('\nFound user installation...')
rmdir(default_destdir, dryrun) rmdir(default_destdir, dryrun)
if platform.system() == 'Windows' and os.path.exists(clink_dir): if platform.system() == 'Windows' and os.path.exists(clink_dir):
rm(os.path.join(clink_dir, 'autojump.lua'), dryrun) rm(os.path.join(clink_dir, 'autojump.lua'), dryrun)
@ -163,23 +171,23 @@ def remove_user_installation(dryrun=False):
def rm(path, dryrun): def rm(path, dryrun):
if os.path.exists(path): if os.path.exists(path):
print("deleting file:", path) print('deleting file:', path)
if not dryrun: if not dryrun:
os.remove(path) os.remove(path)
def rmdir(path, dryrun): def rmdir(path, dryrun):
if os.path.exists(path): if os.path.exists(path):
print("deleting directory:", path) print('deleting directory:', path)
if not dryrun: if not dryrun:
shutil.rmtree(path) shutil.rmtree(path)
def main(args): def main(args):
if args.dryrun: if args.dryrun:
print("Uninstalling autojump (DRYRUN)...") print('Uninstalling autojump (DRYRUN)...')
else: else:
print("Uninstalling autojump...") print('Uninstalling autojump...')
remove_user_installation(args.dryrun) remove_user_installation(args.dryrun)
remove_system_installation(args.dryrun) remove_system_installation(args.dryrun)
@ -188,5 +196,5 @@ def main(args):
remove_user_data(args.dryrun) remove_user_data(args.dryrun)
if __name__ == "__main__": if __name__ == '__main__':
sys.exit(main(parse_arguments())) sys.exit(main(parse_arguments()))