Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 2 | |
| 3 | # findlinksto |
| 4 | # |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 5 | # find symbolic links to a path matching a regular expression |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 7 | import os |
| 8 | import sys |
Andrew M. Kuchling | d683504 | 2003-02-06 19:55:35 +0000 | [diff] [blame] | 9 | import re |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 10 | import getopt |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 11 | |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 12 | def main(): |
Tim Peters | 70c4378 | 2001-01-17 08:48:39 +0000 | [diff] [blame] | 13 | try: |
| 14 | opts, args = getopt.getopt(sys.argv[1:], '') |
| 15 | if len(args) < 2: |
Andrew M. Kuchling | d683504 | 2003-02-06 19:55:35 +0000 | [diff] [blame] | 16 | raise getopt.GetoptError('not enough arguments', None) |
| 17 | except getopt.GetoptError, msg: |
Tim Peters | 70c4378 | 2001-01-17 08:48:39 +0000 | [diff] [blame] | 18 | sys.stdout = sys.stderr |
| 19 | print msg |
| 20 | print 'usage: findlinksto pattern directory ...' |
| 21 | sys.exit(2) |
| 22 | pat, dirs = args[0], args[1:] |
Andrew M. Kuchling | d683504 | 2003-02-06 19:55:35 +0000 | [diff] [blame] | 23 | prog = re.compile(pat) |
Tim Peters | 70c4378 | 2001-01-17 08:48:39 +0000 | [diff] [blame] | 24 | for dirname in dirs: |
| 25 | os.path.walk(dirname, visit, prog) |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 26 | |
| 27 | def visit(prog, dirname, names): |
Tim Peters | 70c4378 | 2001-01-17 08:48:39 +0000 | [diff] [blame] | 28 | if os.path.islink(dirname): |
| 29 | names[:] = [] |
| 30 | return |
| 31 | if os.path.ismount(dirname): |
| 32 | print 'descend into', dirname |
| 33 | for name in names: |
| 34 | name = os.path.join(dirname, name) |
| 35 | try: |
| 36 | linkto = os.readlink(name) |
Andrew M. Kuchling | d683504 | 2003-02-06 19:55:35 +0000 | [diff] [blame] | 37 | if prog.search(linkto) is not None: |
Tim Peters | 70c4378 | 2001-01-17 08:48:39 +0000 | [diff] [blame] | 38 | print name, '->', linkto |
| 39 | except os.error: |
| 40 | pass |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 41 | |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 42 | main() |