1
0
mirror of https://github.com/wting/autojump synced 2025-06-13 12:54:07 +00:00

Compare commits

..

1 Commits

Author SHA1 Message Date
William Ting
c5a018df16 switch to semantic versioning 2012-06-16 13:45:55 -10:00
43 changed files with 1574 additions and 5125 deletions

2
.gitattributes vendored
View File

@ -1,2 +0,0 @@
# Ensure batch files are crlf
*.bat text eol=crlf

7
.gitignore vendored
View File

@ -1,10 +1,5 @@
.cache
.coverage
tags
*.pyc
__pycache__
*~
*.tar.gz
*.patch
.pytest_cache
.tox
tags

View File

@ -1,51 +0,0 @@
repos:
- repo: git@github.com:pre-commit/pre-commit-hooks.git
rev: v1.4.0
hooks:
- id: autopep8-wrapper
language_version: python2
args:
- --in-place
- --aggressive
- --aggressive
- --ignore=E731
- --max-line-length=131
- id: check-added-large-files
language_version: python2
- id: check-ast
language_version: python2
- id: check-case-conflict
language_version: python2
- id: check-docstring-first
language_version: python2
- id: debug-statements
language_version: python2
- id: double-quote-string-fixer
language_version: python2
- id: end-of-file-fixer
language_version: python2
exclude_types: [batch, lua]
- id: fix-encoding-pragma
language_version: python2
- id: flake8
language_version: python2
args:
- --max-complexity=10
- --max-line-length=131
- --ignore=E402,E731
- --exclude=bin/autojump_argparse.py
- id: name-tests-test
language_version: python2
- id: requirements-txt-fixer
language_version: python2
- id: trailing-whitespace
language_version: python2
- repo: git@github.com:asottile/reorder_python_imports.git
rev: v1.1.1
hooks:
- id: reorder-python-imports
language_version: python2
- repo: git@github.com:asottile/add-trailing-comma
rev: v0.7.0
hooks:
- id: add-trailing-comma

View File

@ -1,17 +0,0 @@
language: python
python: 2.7
env:
- TOX_ENV=py26
- TOX_ENV=py27
- TOX_ENV=py32
- TOX_ENV=py33
- TOX_ENV=py34
- TOX_ENV=flake8
install:
- pip install tox
script:
- tox -e $TOX_ENV

View File

@ -15,13 +15,7 @@ made autojump that much better (in no particular order):
Neeraj Verma
Evan Shelhamer
xiannaitong
Simon Marache-Francisco
Pierre Gueth
Tom Parker
Liyang Chang
Jez Ng
jjk-jacky
Daniel Hahler
Jui-Shan Liang
Pierre Gueth
Alexander Bolodurin

View File

@ -1,194 +0,0 @@
## Summary of release changes, see commit history for more details:
## https://github.com/wting/autojump/commits/master/
### Release v22.4.0:
- minor zsh performance improvement
### Release v22.3.0:
- use colors only if stdout is a terminal
- updated RedHat docs
- misc bug fixes for fish and Clink versions
### Release v22.2.2:
#### Backwards Incompatible
- install.sh -> install.py
- `--auto` option removed
- `--local` option removed, defaults to local user install
- `--global` option renamed to `--system`
- install.py modifies autojump.sh accordingly for custom installations
- it is recommended that maintainers use install.py with `--destdir` and
`--prefix` accordingly. Two stage installations requires manually updating
autojump.sh.
- uninstall.sh -> uninstall.py
- automatically removes user and system installations
- now removes custom installations cleanly when passed appropriate
`--destdir` and/or `--prefix` options.
- new `--userdata` option to remove autojump database
- all user environmental options removed:
- AUTOJUMP_DATA_DIR
- AUTOJUMP_IGNORE_CASE
- AUTOJUMP_KEEP_SYMLINKS
- misc bug fixes
#### Features and Bug Fixes
- fish shell support added
- defaults to smartcasing
- If any uppercase characters are detected, then search is case sensitive.
Otherwise searches default to case insensitive.
- defaults to symlinks
- symlinks are not resolved to real path and thus results in duplicate
database entries but ensuring that short paths will be used
- autojump now uses ~/Library/autojump for storing data on OS X instead of
incorrectly using Linux's $XDG_DATA_HOME. Existing data should automatically
be migrated to the new location.
- Past behavior jumped to the highest weight database entry when not passed any
arguments. The new behavior is to stay in the current directory.
### Release v21.6.8:
- fix --increase and --decrease options
- heavy refactoring
- remove unused unit tests
### Release v21.5.8:
- fix security bug: http://www.openwall.com/lists/oss-security/2013/04/25/14
- minor documentation updates, optimization performances, bug fixes
### Release v21.5.1:
- add options to manually increase or decrease weight of the current directory
with --increase or --decrease
- add `_j` back, necessary for zsh tab completion
### Release v21.4.2:
- add options to open file explorer windows with `jo`, `jco` which maps to jump
open, jump child open.
- remove `_j`
### Release v21.3.0:
- `jumpapplet` removed.
- performance improvements when using network mounts (e.g. sshfs)
### Release v21.2.0:
- Add `jc` command (jump child). Jumps to a subdirectory of the current working
directory.
### Release v21.1.0:
- install.sh is rewritten to add support for --path and --destdir options,
making it easier for package maintainers to install autojump specifically into
certain locations. Thanks to jjk-jacky for his contributions.
### Release v21.0.0:
- Switch to semantic versioning (http://semver.org/): major.minor.micro
- Migration code for v17 or older users has been removed.
During testing, it was apparent that the migration code wasn't working to
begin with. The major distros (Debian, RedHat) have already moved to v18+
for LTS. Rolling release distros and Homebrew / Macports are regularly kept
up to date.
Users upgrading from v17 or older will start with a new database.
- Approximate matching introduced. Matching priority is now:
1. exact match
2. case insensitive match
3. approximate match
- The `j` function now accepts autojump arguments (e.g. --help, --stat).
As a result, the `jumpstat` alias is now removed. The preferred method is `j
--stat` or `j -s`. Consequently, autojump cannot jump to directories
beginning with a hyphen '-'.
- Always use case insensitive search with AUTOJUMP_IGNORE_CASE=1
As mentioned earlier, normal priority is to prefer exact match and then
check for case insensitive match. For users who prefer case insensitivity
can now modify the program behavior.
- Prevent database decay with AUTOJUMP_KEEP_ALL_ENTRIES=1
The database is regularly trimmed for performance reasons. However users can
prevent database maintenance with the above environmental variable.
- ZSH tab completion fixed.
ZSH behavior now matches Bash behavior. However it requires the `compinit`
module to be loaded. Add the following line to ~/.zshrc:
autoload -U compinit; compinit
To use type:
j<space><tab><tab>
A menu showing the top database entries will be displayed. Type in any
number followed by <tab> to complete the entry.
- Database entry weight growth changed form linear to logarithmic scale.
A combination of low total weight ceiling and linear growth resulted in a
few, commonly used directories to be responsible for 50%+ of the total
database weight. This caused unnecessary trimming of long tail entries.
Switching to logarithmic growth combined with regular decay meant that
commonly used directories still climbed database ranking appropriately with
a more even weight distribution.
- Vendorize argparse so now Python v2.6+ is supported (from v2.7).
- Unit testing suite added.
- Miscellaneous refactoring, bug fixes, documentation updates.
### Release v20.0.0:
- Python versions supported is now v2.7+ and v3.2+ due to rewrite using
argparse.
- Man page and --help has been overhauled to provide better documentation and
usage scenarios.
- Installation scripts now act dependent on current environmental settings.
If run as root, will do a global install. Installation script also detects
which version to install (bash or zsh) dependent on $SHELL. Both of these
behaviors can be overrode using --local/--global or --bash/--zsh arguments.
- Uninstallation script added, will remove both global and local installations
but ignores database.
- Allow symlink database entries with AUTOJUMP_KEEP_SYMLINKS=1
Normally symlinks are resolved to full path to prevent duplicate database
entries. However users who prefer symlink paths can modify behavior with the
above environmental variable.
- This ChangeLog added to better help package maintainers keep track of changes
between releases.
- Miscellaneous bug fixes.
### Release v19.0.0:
- prototype `cp` and `mv` directory tab completion
- Debian post-installation instructions
- minor Mac OS X fixes
### Release v18.0.0:
- add automated version numbering
- performance tweaks to reduce filesystem checks
- add local installation option
- unicode fixes
- ugly fixes for Python 3
- migrate to new database format

29
ChangeLog Normal file
View File

@ -0,0 +1,29 @@
# Summary of release changes, see commit history for more details:
# https://github.com/joelthelion/autojump/commits/master/
* Release v20:
- Python versions supported is now v2.7+ and v3.2+ due to rewrite using argparse.
- Man page and --help has been overhauled to provide better documentation and usage scenarios.
- Installation scripts now act dependent on current environmental settings.
If run as root, will do a global install. Installation script also detects which version to install (bash or zsh) dependent on $SHELL. Both of these behaviors can be overrode using --local/--global or --bash/--zsh arguments.
- Uninstallation script added, will remove both global and local installations but ignores database.
- Symlinks can be preserved as database entries, refer to man page for more details.
- This change log added to better help package maintainers keep track of changes between releases.
- Miscellaneous bug fixes.
* Release v19:
- prototype `cp` and `mv` directory tab completion
- Debian post-installation instructions
- minor Mac OS X fixes
* Release v18:
- add automated version numbering
- performance tweaks to reduce filesystem checks
- add local installation option
- unicode fixes
- ugly fixes for Python 3
- migrate to new database format

View File

@ -1,32 +1,19 @@
VERSION = $(shell grep -oE "[0-9]+\.[0-9]+\.[0-9]+" bin/autojump)
TAGNAME = release-v$(VERSION)
VERSION = v20
TAGNAME = release-$(VERSION)
.PHONY: docs install uninstall
.PHONY: install
install:
./install.py
install.sh
.PHONY: uninstall
uninstall:
./uninstall.py
uninstall.sh
.PHONY: docs
docs:
@echo "% autojump(1) ${TAGNAME}" >docs/manpage_header.md
@echo "%" >>docs/manpage_header.md
@echo "% $(shell \date +%Y-%m-%d)" >>docs/manpage_header.md
pandoc -s -w man docs/manpage_header.md docs/header.md docs/body.md -o docs/autojump.1
pandoc -s -w markdown docs/header.md docs/install.md docs/body.md -o README.md
.PHONY: lint
lint: pre-commit
@tox -e pre-commit -- run --all-files
.PHONY: pre-commit
pre-commit:
@tox -e pre-commit -- install -f --install-hooks
.PHONY: release
release: docs
release:
# Check for tag existence
# git describe release-$(VERSION) 2>&1 >/dev/null || exit 1
@ -40,29 +27,4 @@ release: docs
git tag -a $(TAGNAME)
# Create tagged archive
git archive --format=tar --prefix autojump_v$(VERSION)/ $(TAGNAME) | gzip > autojump_v$(VERSION).tar.gz
sha1sum autojump_v$(VERSION).tar.gz
.PHONY: tar
tar:
# Create tagged archive
git archive --format=tar --prefix autojump_v$(VERSION)/ $(TAGNAME) | gzip > autojump_v$(VERSION).tar.gz
sha1sum autojump_v$(VERSION).tar.gz
.PHONY: test
test: pre-commit
@tox
.PHONY: test-xfail
test-xfail: pre-commit
@tox -- --runxfail
.PHONY: test-fast
test-fast: pre-commit
@tox -e py27
.PHONY: clean
clean:
@find . -type f -iname '*.py[co]' -delete
@find . -type d -iname '__pycache__' -delete
@rm -fr .tox
git archive --format=tar --prefix autojump_$(VERSION)/ $(TAGNAME) | gzip > autojump_$(VERSION).tar.gz

270
README.md
View File

@ -3,171 +3,223 @@ NAME
autojump - a faster way to navigate your filesystem
SYNOPSIS
--------
Jump to a previously visited directory 'foobar':
j foo
Show all database entries and their respective key weights:
jumpstat
DESCRIPTION
-----------
autojump is a faster way to navigate your filesystem. It works by
maintaining a database of the directories you use the most from the
command line.
*Directories must be visited first before they can be jumped to.*
USAGE
-----
`j` is a convenience wrapper function around `autojump`. Any option that
can be used with `autojump` can be used with `j` and vice versa.
- Jump To A Directory That Contains `foo`:
j foo
- Jump To A Directory That Contains `foo`, Preferring Child Directories:
You can prioritize child directories over matches in the databases via
jc foo
- Open File Manager To Directories (instead of jumping):
Instead of jumping to a directory, you can open a file explorer
window (Mac Finder, Windows Explorer, GNOME Nautilus, etc.) to the
directory instead.
jo music
Opening a file manager to a child directory is also supported:
jco images
- Using Multiple Arguments:
Let's assume the following database:
30 /home/user/mail/inbox
10 /home/user/work/inbox
`j in` would jump into /home/user/mail/inbox as the higher
weighted entry. However you can pass multiple arguments to autojump
to prefer a different entry. In the above example, `j w in` would
then change directory to /home/user/work/inbox.
For more options refer to help:
autojump --help
command line. The jumpstat command shows you the current contents of the
database. Directories must be visited first before they can be jumped
to.
INSTALLATION
------------
### REQUIREMENTS
- Python v2.6+ or Python v3.3+
- Supported shells
- bash - first class support
- zsh - first class support
- fish - community supported
- tcsh - community supported
- clink - community supported
- Supported platforms
- Linux - first class support
- OS X - first class support
- Windows - community supported
- BSD - community supported
- Supported installation methods
- source code - first class support
- Debian and derivatives - first class support
- ArchLinux / Gentoo / openSUSE / RedHat and derivatives -
community supported
- Homebrew / MacPorts - community supported
- Python v2.7+ or 3.2+
- Bash v4.0+ for tab completion
Due to limited time and resources, only "first class support" items will
be maintained by the primary committers. All "community supported" items
will be updated based on pull requests submitted by the general public.
If you are unable to update Python to a supported version, older
versions of autojump can be
[downloaded](https://github.com/joelthelion/autojump/downloads) and
installed manually.
Please continue opening issues and providing feedback for community
supported items since consolidating information helps other users
troubleshoot and submit enhancements and fixes.
- Python v2.6+ is supported by [release
v19](https://github.com/downloads/joelthelion/autojump/autojump_v19.tar.gz).
- Python v2.4+ is supported by [release
v12](https://github.com/downloads/joelthelion/autojump/autojump_v12.tar.gz).
### MANUAL
### AUTOMATIC INSTALLATION
Grab a copy of autojump:
git clone https://github.com/wting/autojump.git
Run the installation script and follow on screen instructions.
cd autojump
./install.py or ./uninstall.py
### AUTOMATIC
#### Linux
**Linux**
autojump is included in the following distro repositories, please use
relevant package management utilities to install (e.g. apt-get, yum,
pacman, etc):
- Debian, Ubuntu, Linux Mint
All Debian-derived distros require manual activation for policy
reasons, please see `/usr/share/doc/autojump/README.Debian`.
relevant package management utilities to install (e.g. yum, apt-get,
etc):
- Debian\* testing/unstable, Ubuntu, Linux Mint
- RedHat, Fedora, CentOS
Install `autojump-zsh` for zsh, `autojump-fish` for fish, etc.
- ArchLinux
- Gentoo
- Frugalware
- Slackware
#### OS X
\* Requires manual activation for policy reasons, please see
`/usr/share/doc/autojump/README.Debian`.
**Mac**
Homebrew is the recommended installation method for Mac OS X:
brew install autojump
MacPorts is also available:
MacPorts also available:
port install autojump
Windows
**Other**
Please check the [Wiki](https://github.com/joelthelion/autojump/wiki)
for an up to date listing of installation methods.
### MANUAL INSTALLATION
Grab a copy of autojump:
git clone git://github.com/joelthelion/autojump.git
Run the installation script:
cd autojump
./install.sh [ --local ] [ --zsh ]
and follow on screen instructions.
### MANUAL UNINSTALLATION
It is recommended to use your distribution's relevant package management
utilities, unless you installed manually or ran into uninstallation
issues.
Grab a copy of autojump:
git clone git://github.com/joelthelion/autojump.git
Run the uninstallation script:
cd autojump
./uninstall.sh
and follow on screen instructions.
If you keep getting `autojump: command not found` at the prompt,
do:`unset PROMPT_COMMAND`. You can also restart your shell.
OPTIONS
-------
Windows support is enabled by [clink](https://mridgers.github.io/clink/)
which should be installed prior to installing autojump.
Options must be passed to 'autojump' and not the 'j' wrapper function.
-a, --add DIR manually add path to database
--purge deletes all database entries that no longer exist on system
--stat show database entries and their key weights
--version show version information and exit
INTERNAL OPTIONS
----------------
-b, --bash enclose directory with quotes to prevent errors
--complete used for tab completion
ADDITIONAL CONFIGURATION
------------------------
- Always Ignore Case
Default behavior is to prioritize exact matches over all else. For
example, `j foo` will prefer /foobar over /FooBar even if the latter
has a higher weight. To change this behavior and ignore case, add
the following environmental variable in your \~/.bashrc:
export AUTOJUMP_IGNORE_CASE=1
- Prevent Database Entries' Decay
Default behavior is to decay unused database entries slowly over
time. Eventually when database limits are hit and maintenance is
run, autojump will purge older less used entries. To prevent decay,
add the following variable in your \~/.bashrc:
export AUTOJUMP_KEEP_ALL_ENTRIES=1
- Prefer Symbolic Links
Default behavior is to evaluate symbolic links into full paths as to
reduce duplicate entries in the database. However, some users prefer
a shorter working directory path in their shell prompt. To switch
behavior to prefer symbolic links, add the following environmental
variable in your \~/.bashrc:
export AUTOJUMP_KEEP_SYMLINKS=1
ADVANCED USAGE
--------------
- Change Directory Weight
To manually change a directory's key weight, you can edit the file
*$XDG\_DATA\_HOME/autojump/autojump.txt*. Each entry has two
columns. The first is the key weight and the second is the path:
29.3383211216 /home/user/downloads
All negative key weights are purged automatically.
KNOWN ISSUES
------------
- autojump does not support directories that begin with `-`.
- zsh (bug \#86)
- For bash users, autojump keeps track of directories by modifying
`$PROMPT_COMMAND`. Do not overwrite `$PROMPT_COMMAND`:
Tab completion does not work.
export PROMPT_COMMAND="history -a"
- jumpapplet (bug \#59)
Instead append to the end of the existing \$PROMPT\_COMMAND:
Does not work in Gnome 3 shell or LDXE.
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ;} history -a"
FILES
-----
If installed locally, autojump is self-contained in *\~/.autojump/*.
The database is stored in *$XDG\_DATA\_HOME/autojump/autojump.txt*.
REPORTING BUGS
--------------
For any questions or issues please visit:
For any usage related issues or feature requests please visit:
https://github.com/wting/autojump/issues
*https://github.com/joelthelion/autojump/issues*
MAILING LIST
------------
For release announcements and development related discussion please
visit:
*https://groups.google.com/forum/?fromgroups\#!forum/autojump*
THANKS
------
Special thanks goes out to: Pierre Gueth, Simon Marache-Francisco,
Daniel Jackoway, and many others.
AUTHORS
-------
autojump was originally written by Joël Schaerer, and currently
maintained by William Ting. More contributors can be found in `AUTHORS`.
maintained by William Ting.
COPYRIGHT
---------
Copyright © 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL
Copyright © 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <http://gnu.org/licenses/gpl.html>. This is free
software: you are free to change and redistribute it. There is NO
WARRANTY, to the extent permitted by law.

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright © 2008-2012 Joel Schaerer
Copyright © 2012-2016 William Ting
Copyright © 2012 William Ting
* This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -15,328 +15,401 @@
GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from __future__ import print_function
import os
import sys
from itertools import chain
from math import sqrt
from operator import attrgetter
from __future__ import division, print_function
import argparse
from operator import itemgetter
import os
import re
import shutil
import sys
from tempfile import NamedTemporaryFile
if sys.version_info[0] == 3:
ifilter = filter
imap = map
os.getcwdu = os.getcwd
VERSION = 'release-v20.5'
MAX_KEYWEIGHT = 1000
MAX_STORED_PATHS = 1000
COMPLETION_SEPARATOR = '__'
ARGS = None
# load config from environmental variables
if 'AUTOJUMP_DATA_DIR' in os.environ:
CONFIG_DIR = os.environ.get('AUTOJUMP_DATA_DIR')
else:
from itertools import ifilter
from itertools import imap
xdg_data_dir = os.environ.get('XDG_DATA_HOME') or os.path.join(os.environ['HOME'], '.local', 'share')
CONFIG_DIR = os.path.join(xdg_data_dir, 'autojump')
# Vendorized argparse for Python 2.6 support
from autojump_argparse import ArgumentParser
KEEP_ALL_ENTRIES = False
if 'AUTOJUMP_KEEP_ALL_ENTRIES' in os.environ and os.environ.get('AUTOJUMP_KEEP_ALL_ENTRIES') == '1':
KEEP_ALL_ENTRIES = True
# autojump is not a standard python package but rather installed as a mixed
# shell + Python app with no outside dependencies (except Python). As a
# consequence we use relative imports and depend on file prefixes to prevent
# module conflicts.
from autojump_data import dictify
from autojump_data import entriefy
from autojump_data import Entry
from autojump_data import load
from autojump_data import save
from autojump_match import match_anywhere
from autojump_match import match_consecutive
from autojump_match import match_fuzzy
from autojump_utils import first
from autojump_utils import get_pwd
from autojump_utils import get_tab_entry_info
from autojump_utils import has_uppercase
from autojump_utils import is_autojump_sourced
from autojump_utils import is_osx
from autojump_utils import is_windows
from autojump_utils import last
from autojump_utils import print_entry
from autojump_utils import print_local
from autojump_utils import print_tab_menu
from autojump_utils import sanitize
from autojump_utils import take
from autojump_utils import unico
ALWAYS_IGNORE_CASE = False
if 'AUTOJUMP_IGNORE_CASE' in os.environ and os.environ.get('AUTOJUMP_IGNORE_CASE') == '1':
ALWAYS_IGNORE_CASE = True
VERSION = '22.5.3'
FUZZY_MATCH_THRESHOLD = 0.6
TAB_ENTRIES_COUNT = 9
TAB_SEPARATOR = '__'
def set_defaults():
config = {}
if is_osx():
data_home = os.path.join(os.path.expanduser('~'), 'Library')
elif is_windows():
data_home = os.getenv('APPDATA')
if CONFIG_DIR == os.path.expanduser('~'):
DB_FILE = CONFIG_DIR + '/.autojump.txt'
else:
data_home = os.getenv(
'XDG_DATA_HOME',
os.path.join(
os.path.expanduser('~'),
'.local',
'share',
),
)
config['data_path'] = os.path.join(data_home, 'autojump', 'autojump.txt')
config['backup_path'] = os.path.join(data_home, 'autojump', 'autojump.txt.bak')
DB_FILE = CONFIG_DIR + '/autojump.txt'
return config
class Database:
""" Object for interfacing with autojump database. """
def __init__(self, filename):
self.filename = filename
self.data = {}
self.load()
def parse_arguments():
parser = ArgumentParser(
description='Automatically jump to directory passed as an argument.',
epilog='Please see autojump(1) man pages for full documentation.',
)
parser.add_argument(
'directory', metavar='DIRECTORY', nargs='*', default='',
help='directory to jump to',
)
parser.add_argument(
'-a', '--add', metavar='DIRECTORY',
help='add path',
)
parser.add_argument(
'-i', '--increase', metavar='WEIGHT', nargs='?', type=int,
const=10, default=False,
help='increase current directory weight',
)
parser.add_argument(
'-d', '--decrease', metavar='WEIGHT', nargs='?', type=int,
const=15, default=False,
help='decrease current directory weight',
)
parser.add_argument(
'--complete', action='store_true', default=False,
help='used for tab completion',
)
parser.add_argument(
'--purge', action='store_true', default=False,
help='remove non-existent paths from database',
)
parser.add_argument(
'-s', '--stat', action='store_true', default=False,
help='show database entries and their key weights',
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s v' +
VERSION, help='show version information',
)
def add(self, path, increment=1):
""" Increment existing paths or initialize new ones to 0. """
if path not in self.data:
self.data[path] = 10
else:
import math
self.data[path] = math.sqrt((self.data[path]**2)+100)
return parser.parse_args()
def add_path(data, path, weight=10):
"""
Add a new path or increment an existing one.
os.path.realpath() is not used because it's preferable to use symlinks
with resulting duplicate entries in the database than a single canonical
path.
"""
path = unico(path).rstrip(os.sep)
if path == os.path.expanduser('~'):
return data, Entry(path, 0)
data[path] = sqrt((data.get(path, 0) ** 2) + (weight ** 2))
return data, Entry(path, data[path])
def decrease_path(data, path, weight=15):
"""Decrease or zero out a path."""
path = unico(path).rstrip(os.sep)
data[path] = max(0, data.get(path, 0) - weight)
return data, Entry(path, data[path])
def detect_smartcase(needles):
"""
If any needles contain an uppercase letter then use case sensitive
searching. Otherwise use case insensitive searching.
"""
return not any(imap(has_uppercase, needles))
def find_matches(entries, needles, check_entries=True):
"""Return an iterator to matching entries."""
# TODO(wting|2014-02-24): replace assertion with unit test
assert isinstance(needles, list), 'Needles must be a list.'
ignore_case = detect_smartcase(needles)
def decay(self):
""" Decay database entries. """
for k in self.data.keys():
self.data[k] *= 0.9
def load(self, error_recovery = False):
""" Try to open the database file, recovering from backup if needed. """
try:
pwd = os.getcwdu()
except OSError:
pwd = None
# using closure to prevent constantly hitting hdd
def is_cwd(entry):
return os.path.realpath(entry.path) == pwd
if check_entries:
path_exists = lambda entry: os.path.exists(entry.path)
with open(self.filename, 'r') as aj_file:
for line in aj_file.readlines():
weight, path = line[:-1].split("\t", 1)
path = decode(path, 'utf-8')
self.data[path] = float(weight)
except (IOError, EOFError):
if not error_recovery and os.path.exists(self.filename + ".bak"):
print('Problem with autojump database,\
trying to recover from backup...', file=sys.stderr)
shutil.copy(self.filename + '.bak', self.filename)
return self.load(True)
else:
path_exists = lambda _: True
data = sorted(
entries,
key=attrgetter('weight', 'path'),
reverse=True,
)
return ifilter(
lambda entry: not is_cwd(entry) and path_exists(entry),
chain(
match_consecutive(needles, data, ignore_case),
match_fuzzy(needles, data, ignore_case),
match_anywhere(needles, data, ignore_case),
),
)
def handle_tab_completion(needle, entries):
tab_needle, tab_index, tab_path = get_tab_entry_info(needle, TAB_SEPARATOR)
if tab_path:
print_local(tab_path)
elif tab_index:
get_ith_path = lambda i, iterable: last(take(i, iterable)).path
print_local(get_ith_path(
tab_index,
find_matches(entries, [tab_needle], check_entries=False),
))
elif tab_needle:
# found partial tab completion entry
print_tab_menu(
tab_needle,
take(
TAB_ENTRIES_COUNT, find_matches(
entries,
[tab_needle],
check_entries=False,
),
),
TAB_SEPARATOR,
)
else:
print_tab_menu(
needle,
take(
TAB_ENTRIES_COUNT, find_matches(
entries,
[needle],
check_entries=False,
),
),
TAB_SEPARATOR,
)
def purge_missing_paths(entries):
"""Remove non-existent paths from a list of entries."""
exists = lambda entry: os.path.exists(entry.path)
return ifilter(exists, entries)
def print_stats(data, data_path):
for path, weight in sorted(data.items(), key=itemgetter(1)):
print_entry(Entry(path, weight))
print('________________________________________\n')
print('%d:\t total weight' % sum(data.values()))
print('%d:\t number of entries' % len(data))
# TODO: migration code, will be removed in v22+
# autojump_py last used in v17
self.filename = get_db_file('autojump_py')
if os.path.exists(self.filename):
try: # fix to get optimised pickle in python < 3
import cPickle as pickle
except ImportError:
import pickle
try:
print_local(
'%.2f:\t current directory weight' % data.get(os.getcwdu(), 0),
)
except OSError:
# current directory no longer exists
with open(self.filename, 'rb') as aj_file:
# encoding is only specified for Python 2 compatibility
if sys.version_info[0] > 2:
self.data = pickle.load(aj_file, encoding="utf-8")
else:
self.data = pickle.load(aj_file)
unicode_dict = {}
for k, v in self.data.items():
print(k)
unicode_dict[decode(k, errors="replace")] = v
return unicode_dict
except (IOError, EOFError, pickle.UnpicklingError):
pass
return {} # if everything fails, return an empty dictionary
print('\ndata:\t %s' % data_path)
def maintenance(self):
""" Trims and decays database entries when exceeding settings. """
if sum(self.data.values()) > MAX_KEYWEIGHT:
self.decay()
if len(self.data) > MAX_STORED_PATHS:
self.trim()
self.save()
def purge(self):
""" Deletes all entries that no longer exist on system. """
removed = []
for path in self.data.keys():
if not os.path.exists(path):
removed.append(path)
del self.data[path]
self.save()
return removed
def save(self):
""" Save database atomically and preserve backup. """
# check file existence and permissions
if ((not os.path.exists(self.filename)) or
os.name == 'nt' or
os.getuid() == os.stat(self.filename)[4]):
temp = NamedTemporaryFile(dir = CONFIG_DIR, delete = False)
for path, weight in sorted(self.data.items(),
key=itemgetter(1),
reverse=True):
temp.write((unico("%s\t%s\n")%(weight, path)).encode("utf-8"))
# catching disk errors and skipping save when file handle can't be closed.
try:
# http://thunk.org/tytso/blog/2009/03/15/dont-fear-the-fsync/
temp.flush()
os.fsync(temp)
temp.close()
except IOError as ex:
print("Error saving autojump database (disk full?)" %
ex, file=sys.stderr)
return
shutil.move(temp.name, self.filename)
try: # backup file
import time
if (not os.path.exists(self.filename+".bak") or
time.time()-os.path.getmtime(self.filename+".bak") > 86400):
shutil.copy(self.filename, self.filename+".bak")
except OSError as ex:
print("Error while creating backup autojump file. (%s)" %
ex, file=sys.stderr)
def trim(self):
""" If database has exceeded MAX_STORED_PATHS, removes bottom 10%. """
dirs = list(self.data.items())
dirs.sort(key=itemgetter(1))
remove_cnt = .1 * MAX_STORED_PATHS
for path, _ in dirs[:remove_cnt]:
del self.data[path]
def main(args): # noqa
if not is_autojump_sourced() and not is_windows():
print("Please source the correct autojump file in your shell's")
print('startup file. For more information, please reinstall autojump')
print('and read the post installation instructions.')
return 1
config = set_defaults()
# all arguments are mutually exclusive
if args.add:
save(config, first(add_path(load(config), args.add)))
elif args.complete:
handle_tab_completion(
needle=first(chain(sanitize(args.directory), [''])),
entries=entriefy(load(config)),
)
elif args.decrease:
data, entry = decrease_path(load(config), get_pwd(), args.decrease)
save(config, data)
print_entry(entry)
elif args.increase:
data, entry = add_path(load(config), get_pwd(), args.increase)
save(config, data)
print_entry(entry)
elif args.purge:
old_data = load(config)
new_data = dictify(purge_missing_paths(entriefy(old_data)))
save(config, new_data)
print('Purged %d entries.' % (len(old_data) - len(new_data)))
elif args.stat:
print_stats(load(config), config['data_path'])
elif not args.directory:
# Return best match.
entries = entriefy(load(config))
print_local(first(chain(
imap(attrgetter('path'), find_matches(entries, [''])),
# always return a path to calling shell functions
['.'],
)))
def get_db_file(filename = "autojump.txt"):
""" Retrieve full database path. """
# TODO: Remove when migration code is removed.
if CONFIG_DIR == os.path.expanduser("~"):
return CONFIG_DIR + "/." + filename
else:
entries = entriefy(load(config))
needles = sanitize(args.directory)
tab_needle, tab_index, tab_path = \
get_tab_entry_info(first(needles), TAB_SEPARATOR)
return CONFIG_DIR + "/" + filename
# Handle `j foo__`, assuming first index.
if not tab_path and not tab_index \
and tab_needle and needles[0] == tab_needle + TAB_SEPARATOR:
tab_index = 1
def options():
""" Parse command line options. """
global ARGS
if tab_path:
print_local(tab_path)
elif tab_index:
get_ith_path = lambda i, iterable: last(take(i, iterable)).path
print_local(
get_ith_path(
tab_index,
find_matches(entries, [tab_needle]),
),
)
parser = argparse.ArgumentParser(description='Automatically jump to directory passed as an argument.',
epilog="Please see autojump(1) man pages for full documentation.")
parser.add_argument('directory', metavar='DIR', nargs='*', default='',
help='directory to jump to')
parser.add_argument('-a', '--add', metavar='DIR',
help='manually add path to database')
parser.add_argument('-b', '--bash', action="store_true", default=False,
help='enclose directory quotes to prevent errors')
parser.add_argument('--complete', action="store_true", default=False,
help='used for bash tab completion')
parser.add_argument('--purge', action="store_true", default=False,
help='delete all database entries that no longer exist on system')
parser.add_argument('--stat', action="store_true", default=False,
help='show database entries and their key weights')
parser.add_argument('--version', action="version", version="%(prog)s " + VERSION,
help='show version information and exit')
ARGS = parser.parse_args()
# The home dir can be reached quickly by "cd" and may interfere with other directories
if (ARGS.add):
if(ARGS.add != os.path.expanduser("~")):
db = Database(DB_FILE)
db.add(decode(ARGS.add))
db.save()
return True
if (ARGS.purge):
db = Database(DB_FILE)
removed = db.purge()
if len(removed) > 0:
for dir in removed:
output(unico(dir))
print("Number of database entries removed: %d" % len(removed))
return True
if (ARGS.stat):
db = Database(DB_FILE)
dirs = list(db.data.items())
dirs.sort(key=itemgetter(1))
for path, count in dirs[-100:]:
output(unico("%.1f:\t%s") % (count, path))
print("Total key weight: %d. Number of stored dirs: %d" %
(sum(db.data.values()), len(dirs)))
return True
return False
def decode(text, encoding=None, errors="strict"):
""" Decoding step for Python 2 which does not default to unicode. """
if sys.version_info[0] > 2:
return text
else:
print_local(first(chain(
imap(attrgetter('path'), find_matches(entries, needles)),
# always return a path to calling shell functions
['.'],
)))
if encoding is None:
encoding = sys.getfilesystemencoding()
return text.decode(encoding, errors)
return 0
def output(unicode_text, encoding=None):
""" Wrapper for the print function, using the filesystem encoding by default
to minimize encoding mismatch problems in directory names. """
if sys.version_info[0] > 2:
print(unicode_text)
else:
if encoding is None:
encoding = sys.getfilesystemencoding()
print(unicode_text.encode(encoding))
def unico(text):
""" If Python 2, convert to a unicode object. """
if sys.version_info[0] > 2:
return text
else:
return unicode(text)
if __name__ == '__main__':
sys.exit(main(parse_arguments()))
def match_last(pattern):
""" If the last pattern contains a full path, jump there.
The regexp is because we need to support stuff like
"j wo jo__3__/home/joel/workspace/joel" for zsh. """
last_pattern_path = re.sub("(.*)"+COMPLETION_SEPARATOR, "", pattern[-1])
if (len(last_pattern_path) > 0 and
last_pattern_path[0] == "/" and
os.path.exists(last_pattern_path)):
if not ARGS.complete:
output(last_pattern_path)
return True
return False
def match(path, pattern, only_end=False, ignore_case=False):
""" Check whether a path matches a particular pattern, and return
the remaining part of the string. """
if only_end:
match_path = "/".join(path.split('/')[-1-pattern.count('/'):])
else:
match_path = path
if ignore_case:
match_path = match_path.lower()
pattern = pattern.lower()
find_idx = match_path.find(pattern)
# truncate path to avoid matching a pattern multiple times
if find_idx != -1:
return (True, path)
else:
return (False, path[find_idx+len(pattern):])
def find_matches(db, patterns, max_matches=1, ignore_case=False, fuzzy=False):
""" Find max_matches paths that match the pattern, and add them to the result_list. """
try:
current_dir = decode(os.path.realpath(os.curdir))
except OSError:
current_dir = None
dirs = list(db.data.items())
dirs.sort(key=itemgetter(1), reverse=True)
results = []
if fuzzy:
from difflib import get_close_matches
# create dictionary of end paths to compare against
end_dirs = {}
for d in dirs:
if ignore_case:
end = d[0].split('/')[-1].lower()
else:
end = d[0].split('/')[-1]
# collisions: ignore lower weight paths
if end not in end_dirs and os.path.exists(d[0]):
end_dirs[end] = d[0]
# find the first match (heighest weight)
found = get_close_matches(patterns[-1], end_dirs, 1, .6)
if found:
found = found[0]
results.append(end_dirs[found])
return results
else:
return []
for path, _ in dirs:
# avoid jumping to current directory
if current_dir == path :
continue
found, tmp = True, path
for n, p in enumerate(patterns):
# for single/last pattern, only check end of path
if n == len(patterns)-1:
found, tmp = match(tmp, p, True, ignore_case)
else:
found, tmp = match(tmp, p, False, ignore_case)
if not found: break
if found and os.path.exists(path):
if path not in results:
results.append(path)
if len(results) >= max_matches:
break
return results
def shell_utility():
""" Run this when autojump is called as a shell utility. """
if options(): return True
db = Database(DB_FILE)
# if no directories, add empty string
if (ARGS.directory == ''):
patterns = [unico('')]
else:
patterns = [decode(a) for a in ARGS.directory]
# check last pattern for full path
# FIXME: disabled until zsh tab completion is fixed on the shell side
# if match_last(patterns): return True
# check for tab completion
tab_choice = -1
tab_match = re.search(COMPLETION_SEPARATOR+"([0-9]+)", patterns[-1])
if tab_match: # user has selected a tab completion entry
tab_choice = int(tab_match.group(1))
patterns[-1] = re.sub(COMPLETION_SEPARATOR+"[0-9]+.*", "", patterns[-1])
else: # user hasn't selected a tab completion, display choices again
tab_match = re.match("(.*)"+COMPLETION_SEPARATOR, patterns[-1])
if tab_match:
patterns[-1] = tab_match.group(1)
# on tab completion always show all results
if ARGS.complete or tab_choice != -1:
max_matches = 9
else:
max_matches = 1
results = []
if not ALWAYS_IGNORE_CASE:
results = find_matches(db, patterns, max_matches, False)
# if no results, try ignoring case
if ARGS.complete or not results:
results = find_matches(db, patterns, max_matches, True)
# if no results, try approximate matching
if not results:
results = find_matches(db, patterns, max_matches, True, True)
quotes = ""
if ARGS.complete and ARGS.bash: quotes = "'"
if tab_choice != -1:
if len(results) > tab_choice-1:
output(unico("%s%s%s") % (quotes,results[tab_choice-1],quotes))
elif len(results) > 1 and ARGS.complete:
output("\n".join(("%s%s%d%s%s" % (patterns[-1],
COMPLETION_SEPARATOR, n+1, COMPLETION_SEPARATOR, r)
for n, r in enumerate(results[:8]))))
elif results:
output(unico("%s%s%s")%(quotes,results[0],quotes))
else:
return False
if not KEEP_ALL_ENTRIES:
db.maintenance()
return True
if __name__ == "__main__":
if not shell_utility(): sys.exit(1)

View File

@ -1,31 +1,10 @@
export AUTOJUMP_SOURCED=1
# set user installation paths
if [[ -d ~/.autojump/ ]]; then
export PATH=~/.autojump/bin:"${PATH}"
fi
# set error file location
if [[ "$(uname)" == "Darwin" ]]; then
export AUTOJUMP_ERROR_PATH=~/Library/autojump/errors.log
elif [[ -n "${XDG_DATA_HOME}" ]]; then
export AUTOJUMP_ERROR_PATH="${XDG_DATA_HOME}/autojump/errors.log"
else
export AUTOJUMP_ERROR_PATH=~/.local/share/autojump/errors.log
fi
if [[ ! -d "$(dirname ${AUTOJUMP_ERROR_PATH})" ]]; then
mkdir -p "$(dirname ${AUTOJUMP_ERROR_PATH})"
fi
# enable tab completion
_autojump() {
_autojump()
{
local cur
cur=${COMP_WORDS[*]:1}
comps=$(autojump --complete $cur)
while read i; do
comps=$(autojump --bash --complete $cur)
while read i
do
COMPREPLY=("${COMPREPLY[@]}" "${i}")
done <<EOF
$comps
@ -33,98 +12,67 @@ EOF
}
complete -F _autojump j
# change pwd hook
autojump_add_to_database() {
if [[ -f "${AUTOJUMP_ERROR_PATH}" ]]; then
(autojump --add "$(pwd)" >/dev/null 2>>${AUTOJUMP_ERROR_PATH} &) &>/dev/null
else
(autojump --add "$(pwd)" >/dev/null &) &>/dev/null
_autojump_files()
{
if [[ ${COMP_WORDS[COMP_CWORD]} == *__* ]]; then
local cur
#cur=${COMP_WORDS[*]:1}
cur=${COMP_WORDS[COMP_CWORD]}
comps=$(autojump --bash --complete $cur)
while read i
do
COMPREPLY=("${COMPREPLY[@]}" "${i}")
done <<EOF
$comps
EOF
fi
}
complete -o default -o bashdefault -F _autojump_files cp mv meld diff kdiff3 vim emacs
#determine the data directory according to the XDG Base Directory Specification
if [[ -n ${XDG_DATA_HOME} ]] && [[ ${XDG_DATA_HOME} =~ ${USER} ]]; then
export AUTOJUMP_DATA_DIR="${XDG_DATA_HOME}/autojump"
else
export AUTOJUMP_DATA_DIR=~/.local/share/autojump
fi
if [ ! -e "${AUTOJUMP_DATA_DIR}" ]; then
mkdir -p "${AUTOJUMP_DATA_DIR}"
mv ~/.autojump_py "${AUTOJUMP_DATA_DIR}/autojump_py" 2>>/dev/null #migration
mv ~/.autojump_py.bak "${AUTOJUMP_DATA_DIR}/autojump_py.bak" 2>>/dev/null
mv ~/.autojump_errors "${AUTOJUMP_DATA_DIR}/autojump_errors" 2>>/dev/null
fi
# set paths if necessary for local installations
if [ -d ~/.autojump/ ]; then
export PATH=~/.autojump/bin:"${PATH}"
fi
export AUTOJUMP_HOME=${HOME}
if [ "${AUTOJUMP_KEEP_SYMLINKS}" == "1" ]
then
_PWD_ARGS=""
else
_PWD_ARGS="-P"
fi
AUTOJUMP='{ [[ "$AUTOJUMP_HOME" == "$HOME" ]] && (autojump -a "$(pwd ${_PWD_ARGS})"&)>/dev/null 2>>"${AUTOJUMP_DATA_DIR}/.autojump_errors";} 2>/dev/null'
case $PROMPT_COMMAND in
*autojump*)
;;
*)
PROMPT_COMMAND="${PROMPT_COMMAND:+$(echo "${PROMPT_COMMAND}" | awk '{gsub(/; *$/,"")}1') ; }autojump_add_to_database"
;;
*autojump*) ;;
*) export PROMPT_COMMAND="$AUTOJUMP ; ${PROMPT_COMMAND:-:}";;
esac
alias jumpstat="autojump --stat"
# default autojump command
j() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
fi
function j {
new_path="$(autojump $@)"
output="$(autojump ${@})"
if [[ -d "${output}" ]]; then
if [ -t 1 ]; then # if stdout is a terminal, use colors
echo -e "\\033[31m${output}\\033[0m"
else
echo -e "${output}"
fi
cd "${output}"
if [ -d "${new_path}" ]; then
echo -e "\\033[31m${new_path}\\033[0m"
cd "${new_path}"
else
echo "autojump: directory '${@}' not found"
echo "\n${output}\n"
echo "Try \`autojump --help\` for more information."
false
fi
}
# jump to child directory (subdirectory of current path)
jc() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
else
j $(pwd) ${@}
fi
}
# open autojump results in file browser
jo() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
fi
output="$(autojump ${@})"
if [[ -d "${output}" ]]; then
case ${OSTYPE} in
linux*)
xdg-open "${output}"
;;
darwin*)
open "${output}"
;;
cygwin)
cygstart "" $(cygpath -w -a ${output})
;;
*)
echo "Unknown operating system: ${OSTYPE}." 1>&2
;;
esac
else
echo "autojump: directory '${@}' not found"
echo "\n${output}\n"
echo "Try \`autojump --help\` for more information."
false
fi
}
# open autojump results (child directory) in file browser
jco() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
else
jo $(pwd) ${@}
fi
}

View File

@ -1,2 +0,0 @@
@echo off
python "%~dp0\autojump" %*

View File

@ -1,112 +0,0 @@
set -gx AUTOJUMP_SOURCED 1
# set user installation path
if test -d ~/.autojump
set -x PATH ~/.autojump/bin $PATH
end
# Set ostype, if not set
if not set -q OSTYPE
set -gx OSTYPE (bash -c 'echo ${OSTYPE}')
end
# enable tab completion
complete -x -c j -a '(autojump --complete (commandline -t))'
# set error file location
if test (uname) = "Darwin"
set -gx AUTOJUMP_ERROR_PATH ~/Library/autojump/errors.log
else if test -d "$XDG_DATA_HOME"
set -gx AUTOJUMP_ERROR_PATH $XDG_DATA_HOME/autojump/errors.log
else
set -gx AUTOJUMP_ERROR_PATH ~/.local/share/autojump/errors.log
end
if test ! -d (dirname $AUTOJUMP_ERROR_PATH)
mkdir -p (dirname $AUTOJUMP_ERROR_PATH)
end
# change pwd hook
function __aj_add --on-variable PWD
status --is-command-substitution; and return
autojump --add (pwd) >/dev/null 2>>$AUTOJUMP_ERROR_PATH &
end
# misc helper functions
function __aj_err
# TODO(ting|#247): set error file location
echo -e $argv 1>&2; false
end
# default autojump command
function j
switch "$argv"
case '-*' '--*'
autojump $argv
case '*'
set -l output (autojump $argv)
# Check for . and attempt a regular cd
if [ $output = "." ]
cd $argv
else
if test -d "$output"
set_color red
echo $output
set_color normal
cd $output
else
__aj_err "autojump: directory '"$argv"' not found"
__aj_err "\n$output\n"
__aj_err "Try `autojump --help` for more information."
end
end
end
end
# jump to child directory (subdirectory of current path)
function jc
switch "$argv"
case '-*'
j $argv
case '*'
j (pwd) $argv
end
end
# open autojump results in file browser
function jo
set -l output (autojump $argv)
if test -d "$output"
switch $OSTYPE
case 'linux*'
xdg-open (autojump $argv)
case 'darwin*'
open (autojump $argv)
case cygwin
cygstart "" (cygpath -w -a (pwd))
case '*'
__aj_err "Unknown operating system: \"$OSTYPE\""
end
else
__aj_err "autojump: directory '"$argv"' not found"
__aj_err "\n$output\n"
__aj_err "Try `autojump --help` for more information."
end
end
# open autojump results (child directory) in file browser
function jco
switch "$argv"
case '-*'
j $argv
case '*'
jo (pwd) $argv
end
end

View File

@ -1,21 +0,0 @@
local AUTOJUMP_DIR = debug.getinfo(1, "S").source:match[[^@?(.*[\/])[^\/]-$]] .. "..\\AutoJump"
local AUTOJUMP_BIN_DIR = AUTOJUMP_DIR .. "\\bin"
local AUTOJUMP_BIN = (AUTOJUMP_BIN_DIR or clink.get_env("LOCALAPPDATA") .. "\\autojump\\bin") .. "\\autojump"
function autojump_add_to_database()
os.execute("python " .. "\"" .. AUTOJUMP_BIN .. "\"" .. " --add " .. "\"" .. clink.get_cwd() .. "\"" .. " 2> " .. clink.get_env("TEMP") .. "\\autojump_error.txt")
end
clink.prompt.register_filter(autojump_add_to_database, 99)
function autojump_completion(word)
for line in io.popen("python " .. "\"" .. AUTOJUMP_BIN .. "\"" .. " --complete " .. word):lines() do
clink.add_match(line)
end
return {}
end
local autojump_parser = clink.arg.new_parser()
autojump_parser:set_arguments({ autojump_completion })
clink.arg.register_parser("j", autojump_parser)

View File

@ -1,26 +1,14 @@
# the login $SHELL isn't always the one used
# NOTE: problems might occur if /bin/sh is symlinked to /bin/bash
if [ -n "${BASH}" ]; then
shell="bash"
elif [ -n "${ZSH_NAME}" ]; then
shell="zsh"
elif [ -n "${__fish_datadir}" ]; then
shell="fish"
elif [ -n "${version}" ]; then
shell="tcsh"
else
shell=$(echo ${SHELL} | awk -F/ '{ print $NF }')
# Source autojump on BASH or ZSH depending on the shell
if [ "$BASH_VERSION" ] && [ -n "$PS1" ] && echo $SHELLOPTS | grep -v posix >>/dev/null; then
if [ -f ~/.autojump/etc/profile.d/autojump.bash ]; then
source ~/.autojump/etc/profile.d/autojump.bash
elif [ -f /etc/profile.d/autojump.bash ]; then
source /etc/profile.d/autojump.bash
fi
elif [ "$ZSH_VERSION" ] && [ -n "$PS1" ]; then
if [ -f ~/.autojump/etc/profile.d/autojump.zsh ]; then
source ~/.autojump/etc/profile.d/autojump.zsh
elif [ -f /etc/profile.d/autojump.zsh ]; then
source /etc/profile.d/autojump.zsh
fi
# prevent circular loop for sh shells
if [ "${shell}" = "sh" ]; then
return 0
# check local install
elif [ -s ~/.autojump/share/autojump/autojump.${shell} ]; then
source ~/.autojump/share/autojump/autojump.${shell}
# check global install
elif [ -s /usr/local/share/autojump/autojump.${shell} ]; then
source /usr/local/share/autojump/autojump.${shell}
fi

View File

@ -1,12 +0,0 @@
# set user installation paths
if (-d ~/.autojump/bin) then
set path = (~/.autojump/bin path)
endif
# prepend autojump to cwdcmd (run after every change of working directory)
if (`alias cwdcmd` !~ *autojump*) then
alias cwdcmd 'autojump --add $cwd >/dev/null;' `alias cwdcmd`
endif
#default autojump command
alias j 'cd `autojump -- \!:1`'

View File

@ -1,125 +1,50 @@
export AUTOJUMP_SOURCED=1
# set user installation paths
if [[ -d ~/.autojump/bin ]]; then
path=(~/.autojump/bin ${path})
fi
if [[ -d ~/.autojump/functions ]]; then
fpath=(~/.autojump/functions ${fpath})
fi
# set homebrew installation paths
if command -v brew &>/dev/null; then
local brew_prefix=${BREW_PREFIX:-$(brew --prefix)}
if [[ -d "${brew_prefix}/share/zsh/site-functions" ]]; then
fpath=("${brew_prefix}/share/zsh/site-functions" ${fpath})
fi
fi
# set error file location
if [[ "$(uname)" == "Darwin" ]]; then
export AUTOJUMP_ERROR_PATH=~/Library/autojump/errors.log
elif [[ -n "${XDG_DATA_HOME}" ]]; then
export AUTOJUMP_ERROR_PATH="${XDG_DATA_HOME}/autojump/errors.log"
# determine the data directory according to the XDG Base Directory Specification
if [[ -n ${XDG_DATA_HOME} ]] && [[ ${XDG_DATA_HOME} =~ ${USER} ]]; then
export AUTOJUMP_DATA_DIR="${XDG_DATA_HOME}/autojump"
else
export AUTOJUMP_ERROR_PATH=~/.local/share/autojump/errors.log
export AUTOJUMP_DATA_DIR=${HOME}/.local/share/autojump
fi
if [[ ! -d ${AUTOJUMP_ERROR_PATH:h} ]]; then
mkdir -p ${AUTOJUMP_ERROR_PATH:h}
if [[ ! -e ${AUTOJUMP_DATA_DIR} ]]; then
mkdir -p "${AUTOJUMP_DATA_DIR}"
mv ${HOME}/.autojump_py "${AUTOJUMP_DATA_DIR}/autojump_py" 2>>/dev/null #migration
mv ${HOME}/.autojump_py.bak "${AUTOJUMP_DATA_DIR}/autojump_py.bak" 2>>/dev/null
mv ${HOME}/.autojump_errors "${AUTOJUMP_DATA_DIR}/autojump_errors" 2>>/dev/null
fi
# set paths if necessary for local installations
if [[ -d ${HOME}/.autojump ]]; then
path=(${HOME}/.autojump/bin ${path})
fpath=(${HOME}/.autojump/functions/ ${fpath})
fi
# set fpath if necessary for homebrew installation
if [[ -d "`brew --prefix 2>/dev/null`/share/zsh/functions" ]]; then
fpath=(`brew --prefix`/share/zsh/functions ${fpath})
fi
# change pwd hook
autojump_chpwd() {
if [[ -f "${AUTOJUMP_ERROR_PATH}" ]]; then
autojump --add "$(pwd)" >/dev/null 2>>${AUTOJUMP_ERROR_PATH} &!
function autojump_preexec() {
if [[ "${AUTOJUMP_KEEP_SYMLINKS}" == "1" ]]; then
_PWD_ARGS=""
else
autojump --add "$(pwd)" >/dev/null &!
_PWD_ARGS="-P"
fi
{ (autojump -a "$(pwd ${_PWD_ARGS})"&)>/dev/null 2>>|${AUTOJUMP_DATA_DIR}/.autojump_errors ; } 2>/dev/null
}
typeset -gaU chpwd_functions
chpwd_functions+=autojump_chpwd
typeset -ga preexec_functions
preexec_functions+=autojump_preexec
alias jumpstat="autojump --stat"
# default autojump command
j() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
fi
function j {
local new_path="$(autojump $@)"
setopt localoptions noautonamedirs
local output="$(autojump ${@})"
if [[ -d "${output}" ]]; then
if [ -t 1 ]; then # if stdout is a terminal, use colors
echo -e "\\033[31m${output}\\033[0m"
else
echo -e "${output}"
fi
cd "${output}"
if [ -d "${new_path}" ]; then
echo -e "\\033[31m${new_path}\\033[0m"
cd "${new_path}"
else
echo "autojump: directory '${@}' not found"
echo "\n${output}\n"
echo "Try \`autojump --help\` for more information."
false
fi
}
# jump to child directory (subdirectory of current path)
jc() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
else
j $(pwd) ${@}
fi
}
# open autojump results in file browser
jo() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
fi
setopt localoptions noautonamedirs
local output="$(autojump ${@})"
if [[ -d "${output}" ]]; then
case ${OSTYPE} in
linux*)
xdg-open "${output}"
;;
darwin*)
open "${output}"
;;
cygwin)
cygstart "" $(cygpath -w -a ${output})
;;
*)
echo "Unknown operating system: ${OSTYPE}" 1>&2
;;
esac
else
echo "autojump: directory '${@}' not found"
echo "\n${output}\n"
echo "Try \`autojump --help\` for more information."
false
fi
}
# open autojump results (child directory) in file browser
jco() {
if [[ ${1} == -* ]] && [[ ${1} != "--" ]]; then
autojump ${@}
return
else
jo $(pwd) ${@}
fi
}

File diff suppressed because it is too large Load Diff

View File

@ -1,148 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import shutil
import sys
from codecs import open
from collections import namedtuple
from tempfile import NamedTemporaryFile
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:
ifilter = filter
imap = map
else:
from itertools import ifilter # noqa
from itertools import imap # noqa
BACKUP_THRESHOLD = 24 * 60 * 60
Entry = namedtuple('Entry', ['path', 'weight'])
def dictify(entries):
"""
Converts a list of entries into a dictionary where
key = path
value = weight
"""
result = {}
for entry in entries:
result[entry.path] = entry.weight
return result
def entriefy(data):
"""Converts a dictionary into an iterator of entries."""
convert = lambda tup: Entry(*tup)
if is_python3():
return map(convert, data.items())
return imap(convert, data.iteritems())
def load(config):
"""Returns a dictonary (key=path, value=weight) loaded from data file."""
xdg_aj_home = os.path.join(
os.path.expanduser('~'),
'.local',
'share',
'autojump',
)
if is_osx() and os.path.exists(xdg_aj_home):
migrate_osx_xdg_data(config)
if not os.path.exists(config['data_path']):
return {}
# example: u'10.0\t/home/user\n' -> ['10.0', u'/home/user']
parse = lambda line: line.strip().split('\t')
correct_length = lambda x: len(x) == 2
# example: ['10.0', u'/home/user'] -> (u'/home/user', 10.0)
tupleize = lambda x: (x[1], float(x[0]))
try:
with open(
config['data_path'],
'r', encoding='utf-8',
errors='replace',
) as f:
return dict(
imap(
tupleize,
ifilter(correct_length, imap(parse, f)),
),
)
except (IOError, EOFError):
return load_backup(config)
def load_backup(config):
if os.path.exists(config['backup_path']):
move_file(config['backup_path'], config['data_path'])
return load(config)
return {}
def migrate_osx_xdg_data(config):
"""
Older versions incorrectly used Linux XDG_DATA_HOME paths on OS X. This
migrates autojump files from ~/.local/share/autojump to ~/Library/autojump
"""
assert is_osx(), 'This function should only be run on OS X.'
xdg_data_home = os.path.join(os.path.expanduser('~'), '.local', 'share')
xdg_aj_home = os.path.join(xdg_data_home, 'autojump')
data_path = os.path.join(xdg_aj_home, 'autojump.txt')
backup_path = os.path.join(xdg_aj_home, 'autojump.txt.bak')
if os.path.exists(data_path):
move_file(data_path, config['data_path'])
if os.path.exists(backup_path):
move_file(backup_path, config['backup_path'])
# cleanup
shutil.rmtree(xdg_aj_home)
if len(os.listdir(xdg_data_home)) == 0:
shutil.rmtree(xdg_data_home)
def save(config, data):
"""Save data and create backup, creating a new data file if necessary."""
data_dir = os.path.dirname(config['data_path'])
create_dir(data_dir)
# atomically save by writing to temporary file and moving to destination
try:
temp = NamedTemporaryFile(delete=False, dir=data_dir)
# Windows cannot reuse the same open file name
temp.close()
with open(temp.name, 'w', encoding='utf-8', errors='replace') as f:
for path, weight in data.items():
f.write(unico('%s\t%s\n' % (weight, path)))
f.flush()
os.fsync(f)
except IOError as ex:
print('Error saving autojump data (disk full?)' % ex, file=sys.stderr)
sys.exit(1)
# move temp_file -> autojump.txt
move_file(temp.name, config['data_path'])
# create backup file if it doesn't exist or is older than BACKUP_THRESHOLD
if not os.path.exists(config['backup_path']) or \
(time() - os.path.getmtime(config['backup_path']) > BACKUP_THRESHOLD): # noqa
shutil.copy(config['data_path'], config['backup_path'])

View File

@ -1,129 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
from difflib import SequenceMatcher
from autojump_utils import is_python3
from autojump_utils import last
if is_python3(): # pragma: no cover
ifilter = filter
imap = map
os.getcwdu = os.getcwd
else:
from itertools import ifilter
from itertools import imap
def match_anywhere(needles, haystack, ignore_case=False):
"""
Matches needles anywhere in the path as long as they're in the same (but
not necessary consecutive) order.
For example:
needles = ['foo', 'baz']
regex needle = r'.*foo.*baz.*'
haystack = [
(path='/foo/bar/baz', weight=10),
(path='/baz/foo/bar', weight=10),
(path='/foo/baz', weight=10),
]
result = [
(path='/moo/foo/baz', weight=10),
(path='/foo/baz', weight=10),
]
"""
regex_needle = '.*' + '.*'.join(imap(re.escape, needles)) + '.*'
regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE
found = lambda haystack: re.search(
regex_needle,
haystack.path,
flags=regex_flags,
)
return ifilter(found, haystack)
def match_consecutive(needles, haystack, ignore_case=False):
"""
Matches consecutive needles at the end of a path.
For example:
needles = ['foo', 'baz']
haystack = [
(path='/foo/bar/baz', weight=10),
(path='/foo/baz/moo', weight=10),
(path='/moo/foo/baz', weight=10),
(path='/foo/baz', weight=10),
]
# We can't actually use re.compile because of re.UNICODE
regex_needle = re.compile(r'''
foo # needle #1
[^/]* # all characters except os.sep zero or more times
/ # os.sep
[^/]* # all characters except os.sep zero or more times
baz # needle #2
[^/]* # all characters except os.sep zero or more times
$ # end of string
''')
result = [
(path='/moo/foo/baz', weight=10),
(path='/foo/baz', weight=10),
]
"""
regex_no_sep = '[^' + os.sep + ']*'
regex_no_sep_end = regex_no_sep + '$'
regex_one_sep = regex_no_sep + os.sep + regex_no_sep
regex_needle = regex_one_sep.join(imap(re.escape, needles)) + regex_no_sep_end
regex_flags = re.IGNORECASE | re.UNICODE if ignore_case else re.UNICODE
found = lambda entry: re.search(
regex_needle,
entry.path,
flags=regex_flags,
)
return ifilter(found, haystack)
def match_fuzzy(needles, haystack, ignore_case=False, threshold=0.6):
"""
Performs an approximate match with the last needle against the end of
every path past an acceptable threshold.
For example:
needles = ['foo', 'bar']
haystack = [
(path='/foo/bar/baz', weight=11),
(path='/foo/baz/moo', weight=10),
(path='/moo/foo/baz', weight=10),
(path='/foo/baz', weight=10),
(path='/foo/bar', weight=10),
]
result = [
(path='/foo/bar/baz', weight=11),
(path='/moo/foo/baz', weight=10),
(path='/foo/baz', weight=10),
(path='/foo/bar', weight=10),
]
This is a weak heuristic and used as a last resort to find matches.
"""
end_dir = lambda path: last(os.path.split(path))
if ignore_case:
needle = last(needles).lower()
match_percent = lambda entry: SequenceMatcher(
a=needle,
b=end_dir(entry.path.lower()),
).ratio()
else:
needle = last(needles)
match_percent = lambda entry: SequenceMatcher(
a=needle,
b=end_dir(entry.path),
).ratio()
meets_threshold = lambda entry: match_percent(entry) >= threshold
return ifilter(meets_threshold, haystack)

View File

@ -1,211 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import errno
import os
import platform
import re
import shutil
import sys
import unicodedata
from itertools import islice
if sys.version_info[0] == 3:
imap = map
os.getcwdu = os.getcwd
else:
from itertools import imap
def create_dir(path):
"""Creates a directory atomically."""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def encode_local(string):
"""Converts string into user's preferred encoding."""
if is_python3():
return string
return string.encode(sys.getfilesystemencoding() or 'utf-8')
def first(xs):
it = iter(xs)
try:
if is_python3():
return it.__next__()
return it.next()
except StopIteration:
return None
def get_tab_entry_info(entry, separator):
"""
Given a tab entry in the following format return needle, index, and path:
[needle]__[index]__[path]
"""
needle, index, path = None, None, None
match_needle = re.search(r'(.*?)' + separator, entry)
match_index = re.search(separator + r'([0-9]{1})', entry)
match_path = re.search(
separator + r'[0-9]{1}' + separator + r'(.*)',
entry,
)
if match_needle:
needle = match_needle.group(1)
if match_index:
index = int(match_index.group(1))
if match_path:
path = match_path.group(1)
return needle, index, path
def get_pwd():
try:
return os.getcwdu()
except OSError:
print('Current directory no longer exists.', file=sys.stderr)
raise
def has_uppercase(string):
if is_python3():
return any(ch.isupper() for ch in string)
return any(unicodedata.category(c) == 'Lu' for c in unicode(string))
def in_bash():
return 'bash' in os.getenv('SHELL')
def is_autojump_sourced():
return '1' == os.getenv('AUTOJUMP_SOURCED')
def is_python2():
return sys.version_info[0] == 2
def is_python3():
return sys.version_info[0] == 3
def is_linux():
return platform.system() == 'Linux'
def is_osx():
return platform.system() == 'Darwin'
def is_windows():
return platform.system() == 'Windows'
def last(xs):
it = iter(xs)
tmp = None
try:
if is_python3():
while True:
tmp = it.__next__()
else:
while True:
tmp = it.next()
except StopIteration:
return tmp
def move_file(src, dst):
"""
Atomically move file.
Windows does not allow for atomic file renaming (which is used by
os.rename / shutil.move) so destination paths must first be deleted.
"""
if is_windows() and os.path.exists(dst):
# raises exception if file is in use on Windows
os.remove(dst)
shutil.move(src, dst)
def print_entry(entry):
print_local('%.1f:\t%s' % (entry.weight, entry.path))
def print_local(string):
print(encode_local(string))
def print_tab_menu(needle, tab_entries, separator):
"""
Prints the tab completion menu according to the following format:
[needle]__[index]__[possible_match]
The needle (search pattern) and index are necessary to recreate the results
on subsequent calls.
"""
for i, entry in enumerate(tab_entries):
print_local(
'%s%s%d%s%s' % (
needle,
separator,
i + 1,
separator,
entry.path,
),
)
def sanitize(directories):
# edge case to allow '/' as a valid path
clean = lambda x: unico(x) if x == os.sep else unico(x).rstrip(os.sep)
return list(imap(clean, directories))
def second(xs):
it = iter(xs)
try:
if is_python2():
it.next()
return it.next()
elif is_python3():
next(it)
return next(it)
except StopIteration:
return None
def surround_quotes(string):
"""
Bash has problems dealing with certain paths so we're surrounding all
path outputs with quotes.
"""
if in_bash() and string:
# Python 2.6 requres field numbers
return '"{0}"'.format(string)
return string
def take(n, iterable):
"""Return first n items of an iterable."""
return islice(iterable, n)
def unico(string):
"""Converts into Unicode string."""
if is_python2() and not isinstance(string, unicode):
return unicode(string, encoding='utf-8', errors='replace')
return string

View File

@ -1,21 +0,0 @@
@echo off
setlocal EnableDelayedExpansion
echo %*|>nul findstr /rx \-.*
if ERRORLEVEL 1 (
for /f "delims=" %%i in ('python "%~dp0\autojump" %*') do set new_path=%%i
if exist !new_path!\nul (
echo !new_path!
pushd !new_path!
REM endlocal is necessary so that we can change directory for outside of this script
REM but will automatically popd. We mush pushd twice to work around this.
pushd !new_path!
endlocal
popd
) else (
echo autojump: directory %* not found
echo try `autojump --help` for more information
)
) else (
python "%~dp0\autojump" %*
)

View File

@ -1,8 +0,0 @@
@echo off
echo %*|>nul findstr /rx \-.*
if ERRORLEVEL 1 (
"%~dp0\j.bat" "%cd%" %*
) else (
python "%~dp0\autojump" %*
)

View File

@ -1,8 +0,0 @@
@echo off
echo %*|>nul findstr /rx \-.*
if ERRORLEVEL 1 (
"%~dp0\jc.bat" "%cd%" %*
) else (
python "%~dp0\autojump" %*
)

View File

@ -1,15 +0,0 @@
@echo off
setlocal EnableDelayedExpansion
echo %*|>nul findstr /rx \-.*
if ERRORLEVEL 1 (
for /f "delims=" %%i in ('python "%~dp0\autojump" %*') do set new_path=%%i
if exist !new_path!\nul (
start "" "explorer" !new_path!
) else (
echo autojump: directory %* not found
echo try `autojump --help` for more information
)
) else (
python "%~dp0\autojump" %*
)

289
bin/jumpapplet Executable file
View File

@ -0,0 +1,289 @@
#!/usr/bin/env python2
import subprocess
import cPickle
import os.path
import os
import sys
import pygtk
pygtk.require('2.0')
import gtk
from autojump import open_dic,get_dic_file
defaults={}
actions={}
#directory finding helpers, conforming to the XDG Base Directory Specification
def data_dir():
xdg_data_dir = os.environ.get('XDG_DATA_HOME') or os.path.join(os.environ['HOME'], '.local', 'share')
return os.path.join(xdg_data_dir, 'autojump')
def config_dir():
xdg_config_dir = os.environ.get('XDG_CONFIG_HOME') or os.path.join(os.environ['HOME'], '.config')
return os.path.join(xdg_config_dir, 'autojump')
#decorator truff
def action(validator,name=None):
if name is None:
def wrapper(action):
actions[action.__name__]=(action,validator)
else:
def wrapper(action):
actions[name]=(action,validator)
return wrapper
#validator helper
def has_child_dir(dirname,recursion=0):
def wrapper(path):
k=recursion
ii=""
while k>=0:
if os.path.isdir(os.path.join(path,ii,dirname)): return True
k-=1
ii=os.path.join("..",ii)
return False
return wrapper
def has_child_file(filename):
def wrapper(path):
return os.path.isfile(os.path.join(path,filename))
return wrapper
def load_paths(maxpath=10):
path_dict=open_dic(get_dic_file())
path_dict=path_dict.items()
path_dict.sort(key=lambda x: x[1],reverse=True)
return [path for path,score in path_dict[:maxpath]]
def load_settings_file():
filename = os.path.join(config_dir(), 'jumpapplet_py')
#migration from old location
old_filename = os.path.join(os.environ['HOME'], '.jumpapplet_py')
if not os.path.exists(filename) and os.path.exists(old_filename):
os.rename(old_filename, filename)
print "loading settings"
global defaults
dic_file = filename
try:
aj_file=open(dic_file,'r')
defaults=cPickle.load(aj_file)
aj_file.close()
except IOError:
print "no config file"
pass
if not "terminal" in defaults: defaults["terminal"]="gnome-terminal"
if not "navigator" in defaults: defaults["navigator"]="nautilus"
if not "maxpath" in defaults: defaults["maxpath"]=15
if not "invert" in defaults: defaults["invert"]=False
if not "collapse" in defaults: defaults["collapse"]=True
create_actions()
def save_settings_file(filename=None):
directory = config_dir()
if not filename:
filename = os.path.join(directory, 'jumpapplet_py')
if not os.path.exists(directory):
os.makedirs(directory)
print "saving settings"
dic_file= filename
aj_file=open(dic_file,'w')
cPickle.dump(defaults,aj_file)
aj_file.close()
def get_actions(path):
return [(name,action) for name,(action,validator) in actions.items() if validator(path)]
def popup(sender,button,activation):
paths=load_paths(maxpath=defaults["maxpath"])
if defaults["collapse"]:
def collapse_home(path):
return path.replace(os.path.expanduser('~'),"~")
else:
def collapse_home(path):
return path
menu=gtk.Menu()
if defaults["invert"]:
item=gtk.ImageMenuItem(stock_id=gtk.STOCK_QUIT)
item.connect("activate",quit)
menu.append(item)
item=gtk.ImageMenuItem(stock_id=gtk.STOCK_PREFERENCES)
item.connect("activate",settings)
menu.append(item)
menu.append(gtk.SeparatorMenuItem())
for path in reversed(paths):
actions=get_actions(path)
if not actions: continue
item=gtk.MenuItem(collapse_home(path),use_underline=False)
submenu=gtk.Menu()
item.set_submenu(submenu)
for name,action in actions:
subitem=gtk.MenuItem(name)
subitem.connect("activate",action,path)
submenu.append(subitem)
menu.append(item)
else:
for path in paths:
actions=get_actions(path)
if not actions: continue
item=gtk.MenuItem(collapse_home(path),use_underline=False)
submenu=gtk.Menu()
item.set_submenu(submenu)
for name,action in actions:
subitem=gtk.MenuItem(name)
subitem.connect("activate",action,path)
submenu.append(subitem)
menu.append(item)
menu.append(gtk.SeparatorMenuItem())
item=gtk.ImageMenuItem(stock_id=gtk.STOCK_PREFERENCES)
item.connect("activate",settings)
menu.append(item)
item=gtk.ImageMenuItem(stock_id=gtk.STOCK_QUIT)
item.connect("activate",quit)
menu.append(item)
menu.show_all()
menu.popup(None,None,gtk.status_icon_position_menu,button,activation,sender)
def settings(sender):
window=gtk.Dialog("jump applet preferences",None,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_SAVE,gtk.RESPONSE_OK,gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL))
window.set_border_width(3)
window.set_resizable(False)
if os.path.isfile("icon.png"): window.set_icon_from_file("icon.png")
elif os.path.isfile("/usr/share/autojump/icon.png"): window.set_icon_from_file("/usr/share/autojump/icon.png")
vbox=gtk.Table(5,2)
vbox.set_row_spacings(3)
window.get_child().add(vbox)
def add_string_setting(name,label,nsettings):
label=gtk.Label(label+' ')
label.set_alignment(1.,.5)
entry=gtk.Entry()
if name in defaults: entry.set_text(defaults[name])
vbox.attach(label,0,1,nsettings,nsettings+1)
vbox.attach(entry,1,2,nsettings,nsettings+1)
return (name,entry)
def add_integer_setting(name,label,nsettings):
label=gtk.Label(label+' ')
label.set_alignment(1.,.5)
entry=gtk.SpinButton()
entry.set_range(5,35)
entry.set_numeric(True)
entry.set_increments(1,5)
entry.set_snap_to_ticks(True)
if name in defaults: entry.set_value(defaults[name])
vbox.attach(label,0,1,nsettings,nsettings+1)
vbox.attach(entry,1,2,nsettings,nsettings+1)
return (name,entry)
def add_bool_setting(name,label,nsettings):
entry=gtk.CheckButton(label=label,use_underline=False)
if name in defaults: entry.set_active(defaults[name])
vbox.attach(entry,0,2,nsettings,nsettings+1)
return (name,entry)
entries=[]
entries.append(add_string_setting("terminal","Terminal program",0))
entries.append(add_string_setting("navigator","Navigator program",1))
entries.append(add_integer_setting("maxpath","Number of directories",2))
entries.append(add_bool_setting("invert","List directories in reverse order",3))
entries.append(add_bool_setting("collapse","Collapse home directory to ~",4))
window.connect("response",save_settings,entries,window)
window.show_all();
def save_settings(sender,response,entries,window):
window.hide_all()
if response!=gtk.RESPONSE_OK: return
global defaults
for name,entry in entries:
try:
defaults[name]=int(entry.get_text())
except (ValueError,AttributeError):
try:
defaults[name]=entry.get_active()
except AttributeError:
defaults[name]=entry.get_text()
save_settings_file()
create_actions()
def init():
load_settings_file()
if os.path.isfile("icon.png"): icon=gtk.status_icon_new_from_file("icon.png")
elif os.path.isfile("/usr/share/autojump/icon.png"): icon=gtk.status_icon_new_from_file("/usr/share/autojump/icon.png")
else: icon=gtk.status_icon_new_from_icon_name("help")
icon.set_visible(True)
icon.connect("popup-menu",popup)
def quit(sender):
gtk.main_quit()
######################################################
#insert other actions here using the action decorator#
######################################################
def create_actions():
global actions
actions={}
@action(has_child_dir(".git",recursion=3))
def gitk(sender,path):
if not os.fork():
os.chdir(path)
subprocess.Popen(['gitk']).wait()
sys.exit()
@action(has_child_file("CMakeCache.txt"),"configure")
def cmake(sender,path):
if not os.fork():
os.chdir(path)
subprocess.Popen(['cmake-gui','.']).wait()
sys.exit()
@action(os.path.isdir)
def terminal(sender,path):
print "launch terminal '%s'" % defaults["terminal"]
if not os.fork():
try:
if defaults["terminal"]=="konsole":
subprocess.Popen([defaults["terminal"],"--workdir=%s"%path]).wait()
else:
os.chdir(path)
subprocess.Popen([defaults["terminal"]]).wait()
except OSError:
pass
sys.exit()
@action(os.path.isdir)
def navigator(sender,path):
print "launch navigator '%s'" % defaults["navigator"]
if not os.fork():
try:
subprocess.Popen([defaults["navigator"],path]).wait()
except OSError:
pass
sys.exit()
if __name__=='__main__':
init()
gtk.main()

View File

@ -1,136 +1,164 @@
.\" Automatically generated by Pandoc 1.16.0.2
.\"
.TH "autojump" "1" "2018\-09\-09" "release\-v22.5.3" ""
.hy
.TH autojump 1 "10 April 2012" "release-v20"
.SS NAME
.PP
autojump \- a faster way to navigate your filesystem
.SS DESCRIPTION
autojump - a faster way to navigate your filesystem
.SS SYNOPSIS
.PP
autojump is a faster way to navigate your filesystem.
It works by maintaining a database of the directories you use the most
from the command line.
.PP
\f[I]Directories must be visited first before they can be jumped to.\f[]
.SS USAGE
.PP
\f[C]j\f[] is a convenience wrapper function around \f[C]autojump\f[].
Any option that can be used with \f[C]autojump\f[] can be used with
\f[C]j\f[] and vice versa.
.IP \[bu] 2
Jump To A Directory That Contains \f[C]foo\f[]:
.RS 2
Jump to a previously visited directory \[aq]foobar\[aq]:
.IP
.nf
\f[C]
j\ foo
\f[]
.fi
.RE
.IP \[bu] 2
Jump To A Child Directory:
.RS 2
.PP
Sometimes it\[aq]s convenient to jump to a child directory
(sub\-directory of current directory) rather than typing out the full
name.
Show all database entries and their respective key weights:
.IP
.nf
\f[C]
jc\ bar
jumpstat
\f[]
.fi
.SS DESCRIPTION
.PP
autojump is a faster way to navigate your filesystem.
It works by maintaining a database of the directories you use the most
from the command line.
The jumpstat command shows you the current contents of the database.
Directories must be visited first before they can be jumped to.
.SS OPTIONS
.PP
Options must be passed to \[aq]autojump\[aq] and not the \[aq]j\[aq]
wrapper function.
.IP
.nf
\f[C]
-a,\ --add\ DIR\ \ \ \ \ \ \ manually\ add\ path\ to\ database
--purge\ \ \ \ \ \ \ \ \ \ \ \ \ deletes\ all\ database\ entries\ that\ no\ longer\ exist\ on\ system
--stat\ \ \ \ \ \ \ \ \ \ \ \ \ \ show\ database\ entries\ and\ their\ key\ weights
--version\ \ \ \ \ \ \ \ \ \ \ show\ version\ information\ and\ exit
\f[]
.fi
.SS INTERNAL OPTIONS
.IP
.nf
\f[C]
-b,\ --bash\ \ \ \ \ \ \ \ \ \ enclose\ directory\ with\ quotes\ to\ prevent\ errors
--complete\ \ \ \ \ \ \ \ \ \ used\ for\ tab\ completion
\f[]
.fi
.SS ADDITIONAL CONFIGURATION
.IP \[bu] 2
Always Ignore Case
.RS 2
.PP
Default behavior is to prioritize exact matches over all else.
For example, \f[C]j\ foo\f[] will prefer /foobar over /FooBar even if
the latter has a higher weight.
To change this behavior and ignore case, add the following environmental
variable in your ~/.bashrc:
.IP
.nf
\f[C]
export\ AUTOJUMP_IGNORE_CASE=1
\f[]
.fi
.RE
.IP \[bu] 2
Open File Manager To Directories (instead of jumping):
Prevent Database Entries\[aq] Decay
.RS 2
.PP
Instead of jumping to a directory, you can open a file explorer window
(Mac Finder, Windows Explorer, GNOME Nautilus, etc.) to the directory
instead.
Default behavior is to decay unused database entries slowly over time.
Eventually when database limits are hit and maintenance is run, autojump
will purge older less used entries.
To prevent decay, add the following variable in your ~/.bashrc:
.IP
.nf
\f[C]
jo\ music
\f[]
.fi
.PP
Opening a file manager to a child directory is also supported:
.IP
.nf
\f[C]
jco\ images
export\ AUTOJUMP_KEEP_ALL_ENTRIES=1
\f[]
.fi
.RE
.IP \[bu] 2
Using Multiple Arguments:
Prefer Symbolic Links
.RS 2
.PP
Let\[aq]s assume the following database:
Default behavior is to evaluate symbolic links into full paths as to
reduce duplicate entries in the database.
However, some users prefer a shorter working directory path in their
shell prompt.
To switch behavior to prefer symbolic links, add the following
environmental variable in your ~/.bashrc:
.IP
.nf
\f[C]
30\ \ \ /home/user/mail/inbox
10\ \ \ /home/user/work/inbox
export\ AUTOJUMP_KEEP_SYMLINKS=1
\f[]
.fi
.PP
\f[C]j\ in\f[] would jump into /home/user/mail/inbox as the higher
weighted entry.
However you can pass multiple arguments to autojump to prefer a
different entry.
In the above example, \f[C]j\ w\ in\f[] would then change directory to
/home/user/work/inbox.
.RE
.SS ADVANCED USAGE
.IP \[bu] 2
Change Directory Weight
.RS 2
.PP
For more options refer to help:
To manually change a directory\[aq]s key weight, you can edit the file
\f[I]$XDG_DATA_HOME/autojump/autojump.txt\f[].
Each entry has two columns.
The first is the key weight and the second is the path:
.IP
.nf
\f[C]
autojump\ \-\-help
29.3383211216\ \ \ /home/user/downloads
\f[]
.fi
.PP
All negative key weights are purged automatically.
.RE
.SS KNOWN ISSUES
.IP \[bu] 2
autojump does not support directories that begin with \f[C]\-\f[].
.IP \[bu] 2
For bash users, autojump keeps track of directories by modifying
\f[C]$PROMPT_COMMAND\f[].
Do not overwrite \f[C]$PROMPT_COMMAND\f[]:
zsh (bug #86)
.RS 2
.IP
.nf
\f[C]
export\ PROMPT_COMMAND="history\ \-a"
\f[]
.fi
.PP
Instead append to the end of the existing $PROMPT_COMMAND:
.IP
.nf
\f[C]
export\ PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND\ ;}\ history\ \-a"
\f[]
.fi
Tab completion does not work.
.RE
.IP \[bu] 2
jumpapplet (bug #59)
.RS 2
.PP
Does not work in Gnome 3 shell or LDXE.
.RE
.SS FILES
.PP
If installed locally, autojump is self-contained in
\f[I]~/.autojump/\f[].
.PP
The database is stored in \f[I]$XDG_DATA_HOME/autojump/autojump.txt\f[].
.SS REPORTING BUGS
.PP
For any questions or issues please visit:
.IP
.nf
\f[C]
https://github.com/wting/autojump/issues
\f[]
.fi
For any usage related issues or feature requests please visit:
.PP
\f[I]https://github.com/joelthelion/autojump/issues\f[]
.SS MAILING LIST
.PP
For release announcements and development related discussion please
visit:
.PP
\f[I]https://groups.google.com/forum/?fromgroups#!forum/autojump\f[]
.SS THANKS
.PP
Special thanks goes out to: Pierre Gueth, Simon Marache-Francisco,
Daniel Jackoway, and many others.
.SS AUTHORS
.PP
autojump was originally written by Joël Schaerer, and currently
maintained by William Ting.
More contributors can be found in \f[C]AUTHORS\f[].
.SS COPYRIGHT
.PP
Copyright © 2016 Free Software Foundation, Inc.
Copyright © 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.

View File

@ -1,34 +1,87 @@
KNOWN ISSUES
------------
## OPTIONS
- autojump does not support directories that begin with `-`.
Options must be passed to 'autojump' and not the 'j' wrapper function.
- For bash users, autojump keeps track of directories by modifying
`$PROMPT_COMMAND`. Do not overwrite `$PROMPT_COMMAND`:
-a, --add DIR manually add path to database
export PROMPT_COMMAND="history -a"
--purge deletes database entries that no longer exist on system
Instead append to the end of the existing \$PROMPT\_COMMAND:
--stat show database entries and their key weights
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ;} history -a"
--version show version information and exit
REPORTING BUGS
--------------
## INTERNAL OPTIONS
For any questions or issues please visit:
-b, --bash enclose directory with quotes to prevent errors
https://github.com/wting/autojump/issues
--complete used for tab completion
AUTHORS
-------
## ADDITIONAL CONFIGURATION
autojump was originally written by Joël Schaerer, and currently maintained by
William Ting. More contributors can be found in `AUTHORS`.
- Always Ignore Case
COPYRIGHT
---------
Default behavior is to prioritize exact matches over all else. For example, `j foo` will prefer /foobar over /FooBar even if the latter has a higher weight. To change this behavior and ignore case, add the following environmental variable in your ~/.bashrc:
Copyright © 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version
3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are
free to change and redistribute it. There is NO WARRANTY, to the extent
permitted by law.
export AUTOJUMP_IGNORE_CASE=1
- Prevent Database Entries' Decay
Default behavior is to decay unused database entries slowly over time. Eventually when database limits are hit and maintenance is run, autojump will purge older less used entries. To prevent decay, add the following variable in your ~/.bashrc:
export AUTOJUMP_KEEP_ALL_ENTRIES=1
- Prefer Symbolic Links
Default behavior is to evaluate symbolic links into full paths as to reduce duplicate entries in the database. However, some users prefer a shorter working directory path in their shell prompt. To switch behavior to prefer symbolic links, add the following environmental variable in your ~/.bashrc:
export AUTOJUMP_KEEP_SYMLINKS=1
## ADVANCED USAGE
- Change Directory Weight
To manually change a directory's key weight, you can edit the file _$XDG_DATA_HOME/autojump/autojump.txt_. Each entry has two columns. The first is the key weight and the second is the path:
29.3383211216 /home/user/downloads
All negative key weights are purged automatically.
## KNOWN ISSUES
- zsh (bug #86)
Tab completion does not work.
- jumpapplet (bug #59)
Does not work in Gnome 3 shell or LDXE.
## FILES
If installed locally, autojump is self-contained in _~/.autojump/_.
The database is stored in _$XDG_DATA_HOME/autojump/autojump.txt_.
## REPORTING BUGS
For any usage related issues or feature requests please visit:
_https://github.com/joelthelion/autojump/issues_
## MAILING LIST
For release announcements and development related discussion please visit:
_https://groups.google.com/forum/?fromgroups#!forum/autojump_
## THANKS
Special thanks goes out to: Pierre Gueth, Simon Marache-Francisco, Daniel Jackoway, and many others.
## AUTHORS
autojump was originally written by Joël Schaerer, and currently maintained by William Ting.
## COPYRIGHT
Copyright © 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

View File

@ -1,56 +1,16 @@
NAME
----
## NAME
autojump - a faster way to navigate your filesystem
DESCRIPTION
-----------
autojump is a faster way to navigate your filesystem. It works by maintaining a
database of the directories you use the most from the command line.
*Directories must be visited first before they can be jumped to.*
USAGE
-----
`j` is a convenience wrapper function around `autojump`. Any option that can
be used with `autojump` can be used with `j` and vice versa.
- Jump To A Directory That Contains `foo`:
## SYNOPSIS
Jump to a previously visited directory 'foobar':
j foo
- Jump To A Child Directory:
Show all database entries and their respective key weights:
Sometimes it's convenient to jump to a child directory (sub-directory of
current directory) rather than typing out the full name.
jumpstat
jc bar
## DESCRIPTION
- Open File Manager To Directories (instead of jumping):
Instead of jumping to a directory, you can open a file explorer window (Mac
Finder, Windows Explorer, GNOME Nautilus, etc.) to the directory instead.
jo music
Opening a file manager to a child directory is also supported:
jco images
- Using Multiple Arguments:
Let's assume the following database:
30 /home/user/mail/inbox
10 /home/user/work/inbox
`j in` would jump into /home/user/mail/inbox as the higher weighted
entry. However you can pass multiple arguments to autojump to prefer
a different entry. In the above example, `j w in` would then change
directory to /home/user/work/inbox.
For more options refer to help:
autojump --help
autojump is a faster way to navigate your filesystem. It works by maintaining a database of the directories you use the most from the command line. The jumpstat command shows you the current contents of the database. Directories must be visited first before they can be jumped to.

View File

@ -2,75 +2,74 @@
### REQUIREMENTS
- Python v2.6+ or Python v3.3+
- Supported shells
- bash - first class support
- zsh - first class support
- fish - community supported
- tcsh - community supported
- clink - community supported
- Supported platforms
- Linux - first class support
- OS X - first class support
- Windows - community supported
- BSD - community supported
- Supported installation methods
- source code - first class support
- Debian and derivatives - first class support
- ArchLinux / Gentoo / openSUSE / RedHat and derivatives - community supported
- Homebrew / MacPorts - community supported
- Python v2.7+ or 3.2+
- Bash v4.0+ for tab completion
Due to limited time and resources, only "first class support" items will be
maintained by the primary committers. All "community supported" items will be
updated based on pull requests submitted by the general public.
If you are unable to update Python to a supported version, older versions of autojump can be [downloaded][dl] and installed manually.
Please continue opening issues and providing feedback for community supported
items since consolidating information helps other users troubleshoot and submit
enhancements and fixes.
- Python v2.6+ is supported by [release v19][v19].
- Python v2.4+ is supported by [release v12][v12].
### MANUAL
### AUTOMATIC INSTALLATION
Grab a copy of autojump:
**Linux**
git clone git://github.com/wting/autojump.git
Run the installation script and follow on screen instructions.
cd autojump
./install.py or ./uninstall.py
### AUTOMATIC
#### Linux
autojump is included in the following distro repositories, please use relevant
package management utilities to install (e.g. apt-get, yum, pacman, etc):
- Debian, Ubuntu, Linux Mint
All Debian-derived distros require manual activation for policy reasons,
please see `/usr/share/doc/autojump/README.Debian`.
autojump is included in the following distro repositories, please use relevant package management utilities to install (e.g. yum, apt-get, etc):
- Debian\* testing/unstable, Ubuntu, Linux Mint
- RedHat, Fedora, CentOS
Install `autojump-zsh` for zsh, `autojump-fish` for fish, etc.
- ArchLinux
- Gentoo
- Frugalware
- Slackware
#### OS X
\* Requires manual activation for policy reasons, please see ``/usr/share/doc/autojump/README.Debian``.
**Mac**
Homebrew is the recommended installation method for Mac OS X:
brew install autojump
MacPorts is also available:
MacPorts also available:
port install autojump
## Windows
**Other**
Windows support is enabled by [clink](https://mridgers.github.io/clink/) which
should be installed prior to installing autojump.
Please check the [Wiki][wiki] for an up to date listing of installation methods.
### MANUAL INSTALLATION
Grab a copy of autojump:
git clone git://github.com/joelthelion/autojump.git
Run the installation script:
cd autojump
./install.sh [ --local ] [ --zsh ]
and follow on screen instructions.
### MANUAL UNINSTALLATION
It is recommended to use your distribution's relevant package management utilities, unless you installed manually or ran into uninstallation issues.
Grab a copy of autojump:
git clone git://github.com/joelthelion/autojump.git
Run the uninstallation script:
cd autojump
./uninstall.sh
and follow on screen instructions.
If you keep getting `autojump: command not found` at the prompt, do:`unset PROMPT_COMMAND`. You can also restart your shell.
[dl]: https://github.com/joelthelion/autojump/downloads
[v12]: https://github.com/downloads/joelthelion/autojump/autojump_v12.tar.gz
[v19]: https://github.com/downloads/joelthelion/autojump/autojump_v19.tar.gz
[wiki]: https://github.com/joelthelion/autojump/wiki

View File

@ -1,3 +1,3 @@
% autojump(1) release-v22.5.3
% autojump(1) release-v20
%
% 2018-09-09
% 10 April 2012

View File

@ -1,236 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import platform
import shutil
import sys
sys.path.append('bin')
from autojump_argparse import ArgumentParser # noqa
SUPPORTED_SHELLS = ('bash', 'zsh', 'fish', 'tcsh')
def cp(src, dest, dryrun=False):
print('copying file: %s -> %s' % (src, dest))
if not dryrun:
shutil.copy(src, dest)
def get_shell():
return os.path.basename(os.getenv('SHELL', ''))
def mkdir(path, dryrun=False):
print('creating directory:', path)
if not dryrun and not os.path.exists(path):
os.makedirs(path)
def modify_autojump_sh(etc_dir, share_dir, dryrun=False):
"""Append custom installation path to autojump.sh"""
custom_install = '\
\n# check custom install \
\nif [ -s %s/autojump.${shell} ]; then \
\n source %s/autojump.${shell} \
\nfi\n' % (share_dir, share_dir)
with open(os.path.join(etc_dir, 'autojump.sh'), 'a') as f:
f.write(custom_install)
def modify_autojump_lua(clink_dir, bin_dir, dryrun=False):
"""Prepend custom AUTOJUMP_BIN_DIR definition to autojump.lua"""
custom_install = "local AUTOJUMP_BIN_DIR = \"%s\"\n" % bin_dir.replace(
'\\',
'\\\\',
)
clink_file = os.path.join(clink_dir, 'autojump.lua')
with open(clink_file, 'r') as f:
original = f.read()
with open(clink_file, 'w') as f:
f.write(custom_install + original)
def parse_arguments(): # noqa
if platform.system() == 'Windows':
default_user_destdir = os.path.join(
os.getenv('LOCALAPPDATA', ''),
'autojump',
)
else:
default_user_destdir = os.path.join(
os.path.expanduser('~'),
'.autojump',
)
default_user_prefix = ''
default_user_zshshare = 'functions'
default_system_destdir = '/'
default_system_prefix = '/usr/local'
default_system_zshshare = '/usr/share/zsh/site-functions'
default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')
parser = ArgumentParser(
description='Installs autojump globally for root users, otherwise \
installs in current user\'s home directory.'
)
parser.add_argument(
'-n', '--dryrun', action='store_true', default=False,
help='simulate installation',
)
parser.add_argument(
'-f', '--force', action='store_true', default=False,
help='skip root user, shell type, Python version checks',
)
parser.add_argument(
'-d', '--destdir', metavar='DIR', default=default_user_destdir,
help='set destination to DIR',
)
parser.add_argument(
'-p', '--prefix', metavar='DIR', default=default_user_prefix,
help='set prefix to DIR',
)
parser.add_argument(
'-z', '--zshshare', metavar='DIR', default=default_user_zshshare,
help='set zsh share destination to DIR',
)
parser.add_argument(
'-c', '--clinkdir', metavar='DIR', default=default_clink_dir,
help='set clink directory location to DIR (Windows only)',
)
parser.add_argument(
'-s', '--system', action='store_true', default=False,
help='install system wide for all users',
)
args = parser.parse_args()
if not args.force:
if sys.version_info[0] == 2 and sys.version_info[1] < 6:
print('Python v2.6+ or v3.0+ required.', file=sys.stderr)
sys.exit(1)
if args.system:
if platform.system() == 'Windows':
print(
'System-wide installation is not supported on Windows.',
file=sys.stderr,
)
sys.exit(1)
elif os.geteuid() != 0:
print(
'Please rerun as root for system-wide installation.',
file=sys.stderr,
)
sys.exit(1)
if platform.system() != 'Windows' \
and get_shell() not in SUPPORTED_SHELLS:
print(
'Unsupported shell: %s' % os.getenv('SHELL'),
file=sys.stderr,
)
sys.exit(1)
if args.destdir != default_user_destdir \
or args.prefix != default_user_prefix \
or args.zshshare != default_user_zshshare:
args.custom_install = True
else:
args.custom_install = False
if args.system:
if args.custom_install:
print(
'Custom paths incompatible with --system option.',
file=sys.stderr,
)
sys.exit(1)
args.destdir = default_system_destdir
args.prefix = default_system_prefix
args.zshshare = default_system_zshshare
return args
def show_post_installation_message(etc_dir, share_dir, bin_dir):
if platform.system() == 'Windows':
print('\nPlease manually add %s to your user path' % bin_dir)
else:
if get_shell() == 'fish':
aj_shell = '%s/autojump.fish' % share_dir
source_msg = 'if test -f %s; . %s; end' % (aj_shell, aj_shell)
rcfile = '~/.config/fish/config.fish'
else:
aj_shell = '%s/autojump.sh' % etc_dir
source_msg = '[[ -s %s ]] && source %s' % (aj_shell, aj_shell)
if platform.system() == 'Darwin' and get_shell() == 'bash':
rcfile = '~/.profile'
else:
rcfile = '~/.%src' % get_shell()
print('\nPlease manually add the following line(s) to %s:' % rcfile)
print('\n\t' + source_msg)
if get_shell() == 'zsh':
print('\n\tautoload -U compinit && compinit -u')
print('\nPlease restart terminal(s) before running autojump.\n')
def main(args):
if args.dryrun:
print('Installing autojump to %s (DRYRUN)...' % args.destdir)
else:
print('Installing autojump to %s ...' % args.destdir)
bin_dir = os.path.join(args.destdir, args.prefix, 'bin')
etc_dir = os.path.join(args.destdir, 'etc', 'profile.d')
doc_dir = os.path.join(args.destdir, args.prefix, 'share', 'man', 'man1')
share_dir = os.path.join(args.destdir, args.prefix, 'share', 'autojump')
zshshare_dir = os.path.join(args.destdir, args.zshshare)
mkdir(bin_dir, args.dryrun)
mkdir(doc_dir, args.dryrun)
mkdir(etc_dir, args.dryrun)
mkdir(share_dir, args.dryrun)
cp('./bin/autojump', bin_dir, args.dryrun)
cp('./bin/autojump_argparse.py', bin_dir, args.dryrun)
cp('./bin/autojump_data.py', bin_dir, args.dryrun)
cp('./bin/autojump_match.py', bin_dir, args.dryrun)
cp('./bin/autojump_utils.py', bin_dir, args.dryrun)
cp('./bin/icon.png', share_dir, args.dryrun)
cp('./docs/autojump.1', doc_dir, args.dryrun)
if platform.system() == 'Windows':
cp('./bin/autojump.lua', args.clinkdir, args.dryrun)
cp('./bin/autojump.bat', bin_dir, args.dryrun)
cp('./bin/j.bat', bin_dir, args.dryrun)
cp('./bin/jc.bat', bin_dir, args.dryrun)
cp('./bin/jo.bat', bin_dir, args.dryrun)
cp('./bin/jco.bat', bin_dir, args.dryrun)
if args.custom_install:
modify_autojump_lua(args.clinkdir, bin_dir, args.dryrun)
else:
mkdir(etc_dir, args.dryrun)
mkdir(share_dir, args.dryrun)
mkdir(zshshare_dir, args.dryrun)
cp('./bin/autojump.sh', etc_dir, args.dryrun)
cp('./bin/autojump.bash', share_dir, args.dryrun)
cp('./bin/autojump.fish', share_dir, args.dryrun)
cp('./bin/autojump.zsh', share_dir, args.dryrun)
cp('./bin/_j', zshshare_dir, args.dryrun)
if args.custom_install:
modify_autojump_sh(etc_dir, share_dir, args.dryrun)
show_post_installation_message(etc_dir, share_dir, bin_dir)
if __name__ == '__main__':
sys.exit(main(parse_arguments()))

214
install.sh Executable file
View File

@ -0,0 +1,214 @@
#!/usr/bin/env bash
function add_msg {
echo
echo "Please add the line to ~/.${2}rc :"
echo
if [ "${1}" == "global" ]; then
echo -e "\t[[ -s /etc/profile.d/autojump.${2} ]] && source /etc/profile.d/autojump.${2}"
elif [ "${1}" == "local" ]; then
echo -e "\t[[ -s ~/.autojump/etc/profile.d/autojump.${2} ]] && source ~/.autojump/etc/profile.d/autojump.${2}"
fi
echo
echo "You need to run 'source ~/.${2}rc' before you can start using autojump."
echo
echo "To remove autojump, run './uninstall.sh'"
echo
}
function help_msg {
echo
echo "./install.sh [--global or --local] [--bash or --zsh] [--prefix /usr/] "
echo
echo "If run without any arguments, the installer will:"
echo
echo -e "\t- as root install globally into /usr/"
echo -e "\t- as non-root install locally to ~/.autojump/"
echo -e "\t- version will be based on \$SHELL environmental variable"
echo
}
# Default install directory.
shell=`echo ${SHELL} | awk -F/ '{ print $NF }'`
force=
if [[ ${UID} -eq 0 ]]; then
local=
prefix=/usr
else
local=true
prefix=~/.autojump
fi
user=${SUDO_USER:-${USER}}
OS=`uname`
if [ $OS == 'Darwin' ]; then
user_home=$(dscl . -search /Users UniqueID ${user} | cut -d: -f6)
else
user_home=$(getent passwd ${user} | cut -d: -f6)
fi
bashrc_file=${user_home}/.bashrc
# Command line parsing
while true; do
case "$1" in
-b|--bash)
shell="bash"
shift
;;
-f|--force)
force=true
shift
;;
-g|--global)
local=
shift
;;
-h|--help|-\?)
help_msg;
exit 0
;;
-l|--local)
local=true
prefix=~/.autojump
shift
;;
-p|--prefix)
if [ $# -gt 1 ]; then
prefix=$2; shift 2
else
echo "--prefix or -p requires an argument" 1>&2
exit 1
fi
;;
-z|--zsh)
shell="zsh"
shift
;;
--)
shift
break
;;
-*)
echo "invalid option: $1" 1>&2;
help_msg;
exit 1
;;
*)
break
;;
esac
done
# check for valid local install options
if [[ ${UID} != 0 ]] && [ ! ${local} ]; then
echo
echo "Please rerun as root or use the --local option."
echo
exit 1
fi
# check shell if supported
if [[ ${shell} != "bash" ]] && [[ ${shell} != "zsh" ]]; then
echo "Unsupported shell (${shell}). Use --bash or --zsh to explicitly define shell."
exit 1
fi
# check Python version
if [ ! ${force} ]; then
python_version=`python -c 'import sys; print(sys.version_info[:])'`
if [[ ${python_version:1:1} -eq 3 && ${python_version:4:1} -lt 2 ]]; then
echo
echo "Incompatible Python version, please upgrade to v2.7+ or v3.2+."
echo
echo "Alternatively, you can download v19 that supports Python v3.0+ from:"
echo
echo -e "\thttps://github.com/joelthelion/autojump/downloads"
echo
echo "OR"
echo
echo "Install argparse manually using 'pip install argparse' and then reattempt the installation using the --force option."
echo
exit 1
fi
if [[ ${python_version:1:1} -eq 2 && ${python_version:4:1} -lt 7 ]]; then
echo
echo "Incompatible Python version, please upgrade to v2.7+ or v3.2+."
if [[ ${python_version:4:1} -ge 6 ]]; then
echo
echo "Alternatively, you can download v19 that supports Python v2.6+ from:"
echo
echo -e "\thttps://github.com/joelthelion/autojump/downloads"
echo
echo "OR"
echo
echo "Install argparse manually using 'pip install argparse' and then reattempt the installation using the --force option."
echo
elif [[ ${python_version:4:1} -ge 4 ]]; then
echo
echo "Alternatively, you can download v12 that supports Python v2.4+ from:"
echo
echo -e "\thttps://github.com/joelthelion/autojump/downloads"
echo
fi
exit 1
fi
fi
echo
echo "Installing ${shell} version of autojump to ${prefix} ..."
echo
# add git revision to autojump
./tools/git-version.sh
# INSTALL AUTOJUMP
mkdir -p ${prefix}/share/autojump/
mkdir -p ${prefix}/bin/
mkdir -p ${prefix}/share/man/man1/
cp -v ./bin/icon.png ${prefix}/share/autojump/
cp -v ./bin/jumpapplet ${prefix}/bin/
cp -v ./bin/autojump ${prefix}/bin/
cp -v ./docs/autojump.1 ${prefix}/share/man/man1/
# global installation
if [ ! ${local} ]; then
# install _j to the first accessible directory
if [ ${shell} == "zsh" ]; then
success=
fpath=`/usr/bin/env zsh -c 'echo $fpath'`
for f in ${fpath}; do
cp -v ./bin/_j ${f} && success=true && break
done
if [ ! ${success} ]; then
echo
echo "Couldn't find a place to put the autocompletion file, please copy _j into your \$fpath"
echo "Installing the rest of autojump ..."
echo
fi
fi
if [ -d "/etc/profile.d" ]; then
cp -v ./bin/autojump.sh /etc/profile.d/
cp -v ./bin/autojump.${shell} /etc/profile.d/
add_msg "global" ${shell}
else
echo "Your distribution does not have a '/etc/profile.d/' directory, please create it manually or use the local install option."
fi
else # local installation
mkdir -p ${prefix}/etc/profile.d/
cp -v ./bin/autojump.sh ${prefix}/etc/profile.d/
cp -v ./bin/autojump.${shell} ${prefix}/etc/profile.d/
if [ ${shell} == "zsh" ]; then
mkdir -p ${prefix}/functions/
cp ./bin/_j ${prefix}/functions/
fi
add_msg "local" ${shell}
fi

View File

View File

View File

@ -1,131 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import pytest
sys.path.append(os.path.join(os.getcwd(), 'bin')) # noqa
from autojump_data import Entry
from autojump_match import match_anywhere
from autojump_match import match_consecutive
class TestMatchAnywhere(object):
entry1 = Entry('/foo/bar/baz', 10)
entry2 = Entry('/baz/foo/bar', 10)
entry3 = Entry('/foo/baz', 10)
entry4 = Entry('/中/zhong/国/guo', 10)
entry5 = Entry('/is\'t/this/a/b*tchin/edge/case?', 10)
win_entry1 = Entry('C:\\foo\\bar\\baz', 10)
win_entry2 = Entry('D:\Program Files (x86)\GIMP', 10)
win_entry3 = Entry('C:\Windows\System32', 10)
@pytest.fixture
def haystack(self):
return [
self.entry1,
self.entry2,
self.entry3,
self.entry4,
self.entry5,
]
@pytest.fixture
def windows_haystack(self):
return [self.win_entry1, self.win_entry2, self.win_entry3]
def test_single_needle(self, haystack):
assert list(match_anywhere(['bar'], haystack)) == [self.entry1, self.entry2]
def test_consecutive(self, haystack):
assert list(match_anywhere(['foo', 'bar'], haystack)) \
== [self.entry1, self.entry2]
assert list(match_anywhere(['bar', 'foo'], haystack)) == []
def test_skip(self, haystack):
assert list(match_anywhere(['baz', 'bar'], haystack)) == [self.entry2]
assert list(match_anywhere(['', ''], haystack)) == [self.entry4]
def test_ignore_case(self, haystack):
assert list(match_anywhere(['bAz', 'bAR'], haystack, ignore_case=True)) \
== [self.entry2]
def test_backslashes_for_windows_paths(self, windows_haystack):
# https://github.com/wting/autojump/issues/281
assert list(match_anywhere(['foo', 'baz'], windows_haystack)) \
== [self.win_entry1]
assert list(match_anywhere(['program', 'gimp'], windows_haystack, True)) \
== [self.win_entry2]
assert list(match_anywhere(['win', '32'], windows_haystack, True)) \
== [self.win_entry3]
def test_wildcard_in_needle(self, haystack):
# https://github.com/wting/autojump/issues/402
assert list(match_anywhere(['*', 'this'], haystack)) == []
assert list(match_anywhere(['this', '*'], haystack)) == [self.entry5]
class TestMatchConsecutive(object):
entry1 = Entry('/foo/bar/baz', 10)
entry2 = Entry('/baz/foo/bar', 10)
entry3 = Entry('/foo/baz', 10)
entry4 = Entry('/中/zhong/国/guo', 10)
entry5 = Entry('/日/本', 10)
entry6 = Entry('/is\'t/this/a/b*tchin/edge/case?', 10)
win_entry1 = Entry('C:\Foo\Bar\Baz', 10)
win_entry2 = Entry('D:\Program Files (x86)\GIMP', 10)
win_entry3 = Entry('C:\Windows\System32', 10)
@pytest.fixture
def haystack(self):
return [
self.entry1,
self.entry2,
self.entry3,
self.entry4,
self.entry5,
]
@pytest.fixture
def windows_haystack(self):
return [self.win_entry1, self.win_entry2, self.win_entry3]
def test_single_needle(self, haystack):
assert list(match_consecutive(['baz'], haystack)) == [self.entry1, self.entry3]
assert list(match_consecutive([''], haystack)) == [self.entry5]
def test_consecutive(self, haystack):
assert list(match_consecutive(['bar', 'baz'], haystack)) == [self.entry1]
assert list(match_consecutive(['foo', 'bar'], haystack)) == [self.entry2]
assert list(match_consecutive(['', 'guo'], haystack)) == [self.entry4]
assert list(match_consecutive(['bar', 'foo'], haystack)) == []
def test_ignore_case(self, haystack):
assert list(match_consecutive(['FoO', 'bAR'], haystack, ignore_case=True)) \
== [self.entry2]
def test_windows_ignore_case(self, windows_haystack):
assert list(match_consecutive(['gimp'], windows_haystack, True)) == [self.win_entry2]
@pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/418')
def test_backslashes_for_windows_paths(self, windows_haystack):
assert list(match_consecutive(['program', 'gimp'], windows_haystack, True)) \
== [self.win_entry2]
@pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/418')
def test_foo_bar_baz(self, windows_haystack):
assert list(match_consecutive(['bar', 'baz'], windows_haystack, ignore_case=True)) \
== [self.win_entry1]
@pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/402')
def test_thing(self, windows_haystack):
assert list(match_consecutive(['win', '32'], windows_haystack, True)) \
== [self.win_entry3]
@pytest.mark.xfail(reason='https://github.com/wting/autojump/issues/402')
def test_wildcard_in_needle(self, haystack):
assert list(match_consecutive(['*', 'this'], haystack)) == []
assert list(match_consecutive(['*', 'edge', 'case'], haystack)) == [self.entry6]

View File

@ -1,145 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import mock
import pytest
sys.path.append(os.path.join(os.getcwd(), 'bin')) # noqa
import autojump_utils
from autojump_utils import encode_local
from autojump_utils import first
from autojump_utils import get_tab_entry_info
from autojump_utils import has_uppercase
from autojump_utils import in_bash
from autojump_utils import is_python3
from autojump_utils import last
from autojump_utils import sanitize
from autojump_utils import second
from autojump_utils import surround_quotes
from autojump_utils import take
from autojump_utils import unico
if is_python3():
os.getcwdu = os.getcwd
xrange = range
def u(string):
"""
This is a unicode() wrapper since u'string' is a Python3 compiler error.
"""
if is_python3():
return string
return unicode(string, encoding='utf-8', errors='strict')
# strings
@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')
def test_encode_local_ascii(_):
assert encode_local(u('foo')) == b'foo'
@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
@mock.patch.object(sys, 'getfilesystemencoding', return_value='ascii')
def test_encode_local_ascii_fails(_):
with pytest.raises(UnicodeDecodeError):
encode_local(u('日本語'))
@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value=None)
def test_encode_local_empty(_):
assert encode_local(b'foo') == u('foo')
@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
@mock.patch.object(sys, 'getfilesystemencoding', return_value='utf-8')
def test_encode_local_unicode(_):
assert encode_local(b'foo') == u('foo')
assert encode_local(u('foo')) == u('foo')
def test_has_uppercase():
assert has_uppercase('Foo')
assert has_uppercase('foO')
assert not has_uppercase('foo')
assert not has_uppercase('')
@mock.patch.object(autojump_utils, 'in_bash', return_value=True)
def test_surround_quotes_in_bash(_):
assert surround_quotes('foo') == '"foo"'
@mock.patch.object(autojump_utils, 'in_bash', return_value=False)
def test_dont_surround_quotes_not_in_bash(_):
assert surround_quotes('foo') == 'foo'
def test_sanitize():
assert sanitize([]) == []
assert sanitize([r'/foo/bar/', r'/']) == [u('/foo/bar'), u('/')]
@pytest.mark.skipif(is_python3(), reason='Unicode sucks.')
def test_unico():
assert unico(str('blah')) == u('blah')
assert unico(str('日本語')) == u('日本語')
assert unico(u('でもおれは中国人だ。')) == u('でもおれは中国人だ。')
# iteration
def test_first():
assert first(xrange(5)) == 0
assert first([]) is None
def test_second():
assert second(xrange(5)) == 1
assert second([]) is None
def test_last():
assert last(xrange(4)) == 3
assert last([]) is None
def test_take():
assert list(take(1, xrange(3))) == [0]
assert list(take(2, xrange(3))) == [0, 1]
assert list(take(4, xrange(3))) == [0, 1, 2]
assert list(take(10, [])) == []
# environment variables
def test_in_bash():
for path in ['/bin/bash', '/usr/bin/bash']:
os.environ['SHELL'] = path
assert in_bash()
for path in ['/bin/zsh', '/usr/bin/zsh']:
os.environ['SHELL'] = '/usr/bin/zsh'
assert not in_bash()
# helper functions
def test_get_needle():
assert get_tab_entry_info('foo__', '__') == ('foo', None, None)
def test_get_index():
assert get_tab_entry_info('foo__2', '__') == ('foo', 2, None)
def test_get_path():
assert get_tab_entry_info('foo__3__/foo/bar', '__') \
== ('foo', 3, '/foo/bar')
def test_get_none():
assert get_tab_entry_info('gibberish content', '__') == (None, None, None)

View File

@ -1,39 +1,36 @@
# -*- coding: utf-8 -*-
"""
IPython autojump magic
# This module was contributed by Mario Pastorelli <pastorelli.mario@gmail.com>
# It is released in the public domain
Written by keith hughitt <keith.hughitt@gmail.com>, based on an earlier
version by Mario Pastorelli <pastorelli.mario@gmail.com>.
# This tool provides "j" for ipython
# To use it, copy it in your ~/.ipython directory
# and add the following line to ipy_user_conf.py:
# import autojump_ipython
To install, create a new IPython user profile by running:
import os
import subprocess as sub
from IPython.ipapi import get
from IPython.iplib import InteractiveShell
ipython profile create
And copy this file into the "startup" folder of your new profile (e.g.
"$HOME/.config/ipython/profile_default/startup/").
@TODO: extend %cd to call "autojump -a"
"""
from subprocess import PIPE
from subprocess import Popen
from IPython.core.magic import register_line_magic
ip = get_ipython() # noqa
@register_line_magic
def j(path):
cmd = ['autojump'] + path.split()
newpath = Popen(
cmd,
stdout=PIPE,
shell=False,
).communicate()[0].strip()
ip = get()
def magic_j(self,parameter_s=''):
cmd = ['autojump']+parameter_s.split()
# print 'executing autojump with args %s' % str(cmd)
newpath=sub.Popen(cmd,stdout=sub.PIPE,shell=False).communicate()[0][:-1] # delete last '\n'
# print 'Autojump answer: \'%s\'' % newpath
if newpath:
ip.magic('cd %s' % newpath.decode('utf-8'))
ip.magic('cd \'%s\'' % newpath)
def cd_decorator(f):
def autojump_cd_monitor(self,parameter_s=''):
f(self,parameter_s)
sub.call(['autojump','-a',os.getcwd()])
return autojump_cd_monitor
# remove from namespace
del j
# Add the new magic function to the class dict and decorate magic_cd:
InteractiveShell.magic_j = magic_j
InteractiveShell.magic_cd = cd_decorator(InteractiveShell.magic_cd)
# And remove the global name to keep global namespace clean.
del magic_j
del cd_decorator

18
tools/git-version.sh Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# add git revision to autojump
# Fail silently if there is no git directory, ie. if the user installed from a regular download
if [[ ! -d .git ]]; then
exit
fi
if [ -z "$1" ]; then
gitrevision=`git describe`
if [[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]]; then
gitrevision=$gitrevision"-dirty"
fi
else
gitrevision="$1"
fi
sed -i "s/^VERSION = \".*\"$/VERSION = \"$gitrevision\"/" ./bin/autojump

33
tox.ini
View File

@ -1,33 +0,0 @@
[tox]
envlist =
py26,
py27,
py33,
py34,
py35
# ignore missing setup.py
skipsdist = True
[testenv]
setenv =
PYTHONDONTWRITEBYTECODE = 1
deps =
mock
coverage
ipdb
ipython
pytest >= 2.9
commands =
coverage run --source=bin/ --omit=bin/autojump_argparse.py -m \
py.test -vv -rxs --tb native -s --strict {posargs:tests}
coverage report -m
[testenv:pre-commit]
deps =
pre-commit>=0.7.0
commands =
pre-commit {posargs}
[pytest]
norecursedirs = .git .tox docs

View File

@ -1,217 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import platform
import shutil
import sys
sys.path.append('bin')
from autojump_argparse import ArgumentParser # noqa
def is_empty_dir(path):
"""
Checks if any files are present within a directory and all sub-directories.
"""
for _, _, files in os.walk(path):
if files:
return False
return True
def parse_arguments():
default_clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')
parser = ArgumentParser(
description='Uninstalls autojump.',
)
parser.add_argument(
'-n', '--dryrun', action='store_true', default=False,
help='simulate installation',
)
parser.add_argument(
'-u', '--userdata', action='store_true', default=False,
help='delete user data',
)
parser.add_argument(
'-d', '--destdir', metavar='DIR',
help='custom destdir',
)
parser.add_argument(
'-p', '--prefix', metavar='DIR', default='',
help='custom prefix',
)
parser.add_argument(
'-z', '--zshshare', metavar='DIR', default='functions',
help='custom zshshare',
)
parser.add_argument(
'-c', '--clinkdir', metavar='DIR', default=default_clink_dir,
)
return parser.parse_args()
def remove_custom_installation(args, dryrun=False):
if not args.destdir:
return
bin_dir = os.path.join(args.destdir, args.prefix, 'bin')
doc_dir = os.path.join(args.destdir, args.prefix, 'share', 'man', 'man1')
etc_dir = os.path.join(args.destdir, 'etc', 'profile.d')
share_dir = os.path.join(args.destdir, args.prefix, 'share', 'autojump')
zshshare_dir = os.path.join(args.destdir, args.zshshare)
if not os.path.exists(share_dir):
return
print('\nFound custom installation...')
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_utils.py'), dryrun)
rm(os.path.join(bin_dir, 'autojump_argparse.py'), dryrun)
if platform.system() == 'Windows':
if os.path.exists(args.clinkdir):
rm(os.path.join(args.clinkdir, 'autojump.lua'), dryrun)
rm(os.path.join(bin_dir, 'autojump.bat'), dryrun)
rm(os.path.join(bin_dir, 'j.bat'), dryrun)
rm(os.path.join(bin_dir, 'jc.bat'), dryrun)
rm(os.path.join(bin_dir, 'jco.bat'), dryrun)
rm(os.path.join(bin_dir, 'jo.bat'), dryrun)
else:
rm(os.path.join(etc_dir, 'autojump.sh'), dryrun)
rm(os.path.join(share_dir, 'autojump.bash'), dryrun)
rm(os.path.join(share_dir, 'autojump.fish'), dryrun)
rm(os.path.join(share_dir, 'autojump.tcsh'), dryrun)
rm(os.path.join(share_dir, 'autojump.zsh'), dryrun)
rm(os.path.join(zshshare_dir, '_j'), dryrun)
rmdir(share_dir, dryrun)
rm(os.path.join(doc_dir, 'autojump.1'), dryrun)
if is_empty_dir(args.destdir):
rmdir(args.destdir, dryrun)
def remove_system_installation(dryrun=False):
default_destdir = '/'
default_prefix = '/usr/local'
default_zshshare = '/usr/share/zsh/site-functions'
bin_dir = os.path.join(default_destdir, default_prefix, 'bin')
doc_dir = os.path.join(
default_destdir,
default_prefix,
'share',
'man',
'man1',
)
etc_dir = os.path.join(default_destdir, 'etc', 'profile.d')
share_dir = os.path.join(
default_destdir,
default_prefix,
'share',
'autojump',
)
zshshare_dir = os.path.join(default_destdir, default_zshshare)
if not os.path.exists(share_dir):
return
print('\nFound system installation...')
if os.geteuid() != 0:
print(
'Please rerun as root for system-wide uninstall, skipping...',
file=sys.stderr,
)
return
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_utils.py'), dryrun)
rm(os.path.join(etc_dir, 'autojump.sh'), dryrun)
rm(os.path.join(share_dir, 'autojump.bash'), dryrun)
rm(os.path.join(share_dir, 'autojump.fish'), dryrun)
rm(os.path.join(share_dir, 'autojump.tcsh'), dryrun)
rm(os.path.join(share_dir, 'autojump.zsh'), dryrun)
rm(os.path.join(zshshare_dir, '_j'), dryrun)
rmdir(share_dir, dryrun)
rm(os.path.join(doc_dir, 'autojump.1'), dryrun)
def remove_user_data(dryrun=False):
if platform.system() == 'Darwin':
data_home = os.path.join(
os.path.expanduser('~'),
'Library',
'autojump',
)
elif platform.system() == 'Windows':
data_home = os.path.join(
os.getenv('APPDATA'),
'autojump',
)
else:
data_home = os.getenv(
'XDG_DATA_HOME',
os.path.join(
os.path.expanduser('~'),
'.local',
'share',
'autojump',
),
)
if os.path.exists(data_home):
print('\nFound user data...')
rmdir(data_home, dryrun)
def remove_user_installation(dryrun=False):
if platform.system() == 'Windows':
default_destdir = os.path.join(
os.getenv('LOCALAPPDATA', ''),
'autojump',
)
clink_dir = os.path.join(os.getenv('LOCALAPPDATA', ''), 'clink')
else:
default_destdir = os.path.join(os.path.expanduser('~'), '.autojump')
if os.path.exists(default_destdir):
print('\nFound user installation...')
rmdir(default_destdir, dryrun)
if platform.system() == 'Windows' and os.path.exists(clink_dir):
rm(os.path.join(clink_dir, 'autojump.lua'), dryrun)
def rm(path, dryrun):
if os.path.exists(path):
print('deleting file:', path)
if not dryrun:
os.remove(path)
def rmdir(path, dryrun):
if os.path.exists(path):
print('deleting directory:', path)
if not dryrun:
shutil.rmtree(path)
def main(args):
if args.dryrun:
print('Uninstalling autojump (DRYRUN)...')
else:
print('Uninstalling autojump...')
remove_user_installation(args.dryrun)
remove_system_installation(args.dryrun)
remove_custom_installation(args, args.dryrun)
if args.userdata:
remove_user_data(args.dryrun)
if __name__ == '__main__':
sys.exit(main(parse_arguments()))

95
uninstall.sh Executable file
View File

@ -0,0 +1,95 @@
#!/usr/bin/env bash
function help_msg {
echo "sudo ./uninstall.sh [--prefix /usr/local]"
}
function remove_msg {
echo
echo "Please remove the line from .${2}rc :"
echo
if [ "${1}" == "global" ]; then
echo -e "\t[[ -s /etc/profile.d/autojump.${2} ]] && source /etc/profile.d/autojump.${2}"
elif [ "${1}" == "local" ]; then
echo -e "\t[[ -s ~/.autojump/etc/profile.d/autojump.${2} ]] && source ~/.autojump/etc/profile.d/autojump.${2}"
fi
echo
}
# Default install directory.
prefix=/usr
user=${SUDO_USER:-${USER}}
OS=`uname`
if [ $OS == 'Darwin' ]; then
user_home=$(dscl . -search /Users UniqueID ${user} | cut -d: -f6)
else
user_home=$(getent passwd ${user} | cut -d: -f6)
fi
bashrc_file=${user_home}/.bashrc
# Command line parsing
while true; do
case "$1" in
-h|--help|-\?) help_msg; exit 0;;
-p|--prefix)
if [ $# -gt 1 ]; then
prefix=$2; shift 2
else
echo "--prefix or -p require an argument" 1>&2
exit 1
fi
;;
--) shift; break;;
-*) echo "invalid option: $1" 1>&2; help_msg; exit 1;;
*) break;;
esac
done
# UNINSTALL AUTOJUMP
# global / custom location installations
if [ -d "${prefix}/share/autojump/" ]; then
echo
echo "Uninstalling from ${prefix} ..."
echo
sudo rm -rv ${prefix}/share/autojump/
sudo rm -v ${prefix}/bin/jumpapplet
sudo rm -v ${prefix}/bin/autojump
sudo rm -v ${prefix}/share/man/man1/autojump.1
sudo rm -v /etc/profile.d/autojump.sh
if [ -f /etc/profile.d/autojump.bash ]; then
sudo rm -v /etc/profile.d/autojump.bash
remove_msg "global" "bash"
fi
if [ -f /etc/profile.d/autojump.zsh ]; then
sudo rm -v /etc/profile.d/autojump.zsh
fpath=`/usr/bin/env zsh -c 'echo $fpath'`
for f in ${fpath}; do
if [[ -f ${f}/_j ]]; then
sudo rm -v ${f}/_j
fi
done
remove_msg "global" "zsh"
fi
fi
# local installations
if [ -d ~/.autojump/ ]; then
echo
echo "Uninstalling from ~/.autojump/ ..."
echo
if [ -f ~/.autojump/etc/profile.d/autojump.bash ]; then
rm -rv ~/.autojump/
remove_msg "local" "bash"
fi
if [ -f ~/.autojump/etc/profile.d/autojump.zsh ]; then
rm -rv ~/.autojump/
remove_msg "local" "zsh"
fi
fi