Skip to content

Instantly share code, notes, and snippets.

@andrewytliu
Last active August 29, 2015 14:04
Show Gist options
  • Save andrewytliu/5dddfa1ffa62ec502a47 to your computer and use it in GitHub Desktop.
Save andrewytliu/5dddfa1ffa62ec502a47 to your computer and use it in GitHub Desktop.
dx - easy tool for changing long directory path

dx - easy tool for changing long directory path

Install

Put dx to $PATH, and add d function to your shell configuration (bash or fish).

Usage

~/some/long/path $ dx add sc
~/some/long/path $ dx ls
sc     ~/some/long/path
~/some/long/path $ cd ~
~ $ pwd
~
~ $ d sc
~/some/long/path $
function d {
dir=$("dx" $*) && cd $dir;
}
function _dcomp () {
local cur dlist
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
dlist=$(dx tab)
if [[ ${prev} == d ]] ; then
COMPREPLY=( $(compgen -W "${dlist}" -- $cur) )
return 0
fi
}
complete -F _dcomp d
function d
cd (dx $argv)
end
#!/usr/bin/env ruby
require 'fileutils'
def load_path file
lines = IO.readlines file
mapping = {}
for line in lines
name, dir = line.chomp.split ' = '
mapping[name] = dir
end
mapping
end
def save_path file, mapping
File.open(file, 'w') do |f|
for name, dir in mapping
f.puts "#{name} = #{dir}"
end
end
end
SINGLE = %w[ls help tab]
if __FILE__ == $0
rc = File.expand_path(ENV['DXRC'] || '~/.dxrc')
FileUtils.touch rc unless File.exists? rc
mapping = load_path rc
ARGV << 'ls' if ARGV.empty?
if ARGV.size == 1 and !SINGLE.include?(ARGV[0])
dir = mapping[ARGV[0]]
if dir
puts dir
else
$stderr.puts "Mapping #{ARGV[0]} is not found!"
end
else
case ARGV[0]
when 'add'
if ARGV[1] == 'ls' or ARGV[1] == 'help'
puts "Name cannot be 'ls' or 'help'!"
exit 1
end
dir = if ARGV.size < 3
`pwd`
else
ARGV[2]
end
mapping[ARGV[1]] = dir
save_path rc, mapping
when 'rm'
mapping.delete! ARGV[1]
save_path rc, mapping
when 'ls'
for name, dir in mapping
puts "#{name}\t#{dir}"
end
when 'tab'
puts mapping.keys.join ' '
when 'help'
puts "Usage: dx [ls]"
puts " dx add [name] [path (default = pwd)]"
puts " dx rm [name]"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment