/Tools/scripts/linktree.py

http://unladen-swallow.googlecode.com/ · Python · 80 lines · 63 code · 7 blank · 10 comment · 22 complexity · dd50106f4b5b9df1e71d0ef9723e4bb3 MD5 · raw file

  1. #! /usr/bin/env python
  2. # linktree
  3. #
  4. # Make a copy of a directory tree with symbolic links to all files in the
  5. # original tree.
  6. # All symbolic links go to a special symbolic link at the top, so you
  7. # can easily fix things if the original source tree moves.
  8. # See also "mkreal".
  9. #
  10. # usage: mklinks oldtree newtree
  11. import sys, os
  12. LINK = '.LINK' # Name of special symlink at the top.
  13. debug = 0
  14. def main():
  15. if not 3 <= len(sys.argv) <= 4:
  16. print 'usage:', sys.argv[0], 'oldtree newtree [linkto]'
  17. return 2
  18. oldtree, newtree = sys.argv[1], sys.argv[2]
  19. if len(sys.argv) > 3:
  20. link = sys.argv[3]
  21. link_may_fail = 1
  22. else:
  23. link = LINK
  24. link_may_fail = 0
  25. if not os.path.isdir(oldtree):
  26. print oldtree + ': not a directory'
  27. return 1
  28. try:
  29. os.mkdir(newtree, 0777)
  30. except os.error, msg:
  31. print newtree + ': cannot mkdir:', msg
  32. return 1
  33. linkname = os.path.join(newtree, link)
  34. try:
  35. os.symlink(os.path.join(os.pardir, oldtree), linkname)
  36. except os.error, msg:
  37. if not link_may_fail:
  38. print linkname + ': cannot symlink:', msg
  39. return 1
  40. else:
  41. print linkname + ': warning: cannot symlink:', msg
  42. linknames(oldtree, newtree, link)
  43. return 0
  44. def linknames(old, new, link):
  45. if debug: print 'linknames', (old, new, link)
  46. try:
  47. names = os.listdir(old)
  48. except os.error, msg:
  49. print old + ': warning: cannot listdir:', msg
  50. return
  51. for name in names:
  52. if name not in (os.curdir, os.pardir):
  53. oldname = os.path.join(old, name)
  54. linkname = os.path.join(link, name)
  55. newname = os.path.join(new, name)
  56. if debug > 1: print oldname, newname, linkname
  57. if os.path.isdir(oldname) and \
  58. not os.path.islink(oldname):
  59. try:
  60. os.mkdir(newname, 0777)
  61. ok = 1
  62. except:
  63. print newname + \
  64. ': warning: cannot mkdir:', msg
  65. ok = 0
  66. if ok:
  67. linkname = os.path.join(os.pardir,
  68. linkname)
  69. linknames(oldname, newname, linkname)
  70. else:
  71. os.symlink(linkname, newname)
  72. if __name__ == '__main__':
  73. sys.exit(main())