A Python script to update links under a path to use new prefix.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, getopt;
options = {'start': None, 'oprefix': None, 'nprefix': None, 'simulate': True};

class PathError (Exception):

def ShowUsage():
  progname = os.path.split(sys.argv[0])[1];
  print progname;
  print '-'*len(progname)
  print " Usage: %s [-w] [-s startpath] -o oldprefix -n newprefix\n" % progname;
  print " Parameters: "
  print " -w, --write       Dont run the program run in simulation mode.\n";
  print " -s, --start-path  Use custom starting directory.\n";
  print " -o, --old-prefix  Find link(s) with prefix as specified by this parameter.\n";
  print " -n, --new-prefix  New prefix for the offending link(s) to use.\n";
def GetOptions():
  global options;
  ret = 0;
  arguments = sys.argv[1:];
    wnt, dummy = getopt.getopt(arguments, "o:n:s:w", ["old-prefix=",
                    "new-prefix=", "start-path=", "write"]);
    for name, val in wnt:
      if name in ('-o', '--old-prefix'):
        options['oprefix'] = val;
      elif name in ('-n', '--new-prefix'):
        options['nprefix'] = val;
      elif name in ('-s', '--start-path'):
        options['start'] = val;
      elif name in ('-w', '--write'):
        options['simulate'] = False;
    if options['start'] == None:
      options['start'] = os.getcwd();
  except getopt.GetoptError:
    ret = -1;
  if (options['oprefix'] == None) or (options['nprefix'] == None): ret = -1;  
  if ret != -1:
    print "Start      : %s" % options['start'];
    print "Old prefix : %s" % options['oprefix'];
    print "New prefix : %s" % options['nprefix'];
    if options['simulate'] == False:  print "WARNING    : This program may change links.";
  return ret;

def ProcessPath(curPath, recursive):
  proccount = 0;
  files = os.listdir(curPath);
  if len(files) > 0:
    print "Examining %s" % curPath;

  for entry in files:
    curFile = os.path.join(curPath, entry);
    if os.path.islink(curFile):
      linkPath = os.readlink(curFile);
      if linkPath.find(options['oprefix']) == 0:
        # we need to update this one
        newLinkPath = linkPath.replace(options['oprefix'], options['nprefix'], 
        print "Fixing %s\n   Old path: %s\n   New path: %s" % (curFile, 
          linkPath, newLinkPath);
        if options['simulate'] == False:         
          # these two lines will modify/regenerate the symbolic link        
          os.symlink(newLinkPath, curFile);
          proccount += 1;
        # good link, skip it
    elif os.path.isdir( curFile ) and recursive:
      proccount += ProcessPath(curFile, recursive);
  return proccount;

def main():   
    if GetOptions() == 0:
      i = ProcessPath(options['start'], True);
      print ["Nothing processed by this program", \
             "There are %s link(s) processed" % i][i > 0] + '.';

if __name__ == '__main__':

Leave a comment

Filed under Ilmu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s