Skip to content

Instantly share code, notes, and snippets.

@thejmazz
Last active August 29, 2015 14:19
Show Gist options
  • Save thejmazz/8995921d65f2be20d7a7 to your computer and use it in GitHub Desktop.
Save thejmazz/8995921d65f2be20d7a7 to your computer and use it in GitHub Desktop.
Small python script to replace full path in prompt with symlinks where appropriate.
# Small python script to replace full path in prompt with symlinks where
# appropiate. Set your shell prompt to this script's output with
######################################################################
# export PROMPT_COMMAND='PS1="$(python /path-to/symlinkifypath.py)"' #
######################################################################
# in your .bashrc.
# Set 'symLinksDir' and 'tilde' as per your needs below.
# Please make sure all your symlinks are the complete path - no symlinks
# inside another.. This script works for symlinks that start from the root
# directory, it replaces the set of characters starting from the beginning of
# the complete path with your symlink name.
import os
from os.path import isfile,islink,join
from commands import getoutput
from socket import gethostname
import operator
# Set this to where you store symbolic links
symLinksDir = '/home/jmazz'
# May not wish to use '~' if your symLinksDir is not your home directory
tilde = '~'
# Get hostname, username, cwd, homedir
hostname = gethostname()
username = os.environ['USER']
pwd = os.getcwd()
homedir = os.path.expanduser('~')
# Build list of directories in symLinksDir
dirs = []
for (dirpath, dirnames, filenames) in os.walk(symLinksDir):
dirs.extend(dirnames)
break
# Build dict of symlinks. {key,value} pair as
# {linkName, linkPath}
symLinks = {}
for potentialLink in dirs:
if islink(join(symLinksDir,potentialLink)):
symLink = potentialLink
path = join(symLinksDir,potentialLink)
symLinks.update({symLink:os.readlink(path)})
# Build dict storing lengths of linkPath for each linkName
# {linkName, len(linkPath)}
symLinksLens = {}
for key in symLinks.keys():
symLinksLens.update({key:len(symLinks[key])})
# Sort symLinksLens by values; gives list of tuples of the form
# (linkName, len(linkPath))
sorted_symLinksLens = sorted(symLinksLens.items(), key=operator.itemgetter(1))
# Highest to lowest
sorted_symLinksLens.reverse()
# List of linkNames, in order from highest to lowest string length of linkPath
linkNames = []
for link in sorted_symLinksLens:
linkNames.append(link[0])
# Check if full path contains any of the symLinks, and alter pwd accordingly
for linkName in linkNames:
sL = symLinks[linkName]
if sL == pwd[:len(sL)]:
pwd = '%s/%s%s' % (tilde,linkName,pwd[len(sL):])
break
# Replace /home/<user> with `tilde`
pwd = pwd.replace(homedir, tilde, 1)
# Print string for the shell prompt
print '%s@%s:%s$ ' % (username, hostname, pwd)
#print '%s ' % (pwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment