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 |
| 9 | import regex |
| 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(): |
| 13 | try: |
| 14 | opts, args = getopt.getopt(sys.argv[1:], '') |
| 15 | if len(args) < 2: |
| 16 | raise getopt.error, 'not enough arguments' |
| 17 | except getopt.error, msg: |
| 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:] |
| 23 | prog = regex.compile(pat) |
| 24 | for dirname in dirs: |
| 25 | os.path.walk(dirname, visit, prog) |
| 26 | |
| 27 | def visit(prog, dirname, names): |
Guido van Rossum | 391b8b7 | 1992-03-30 11:14:36 +0000 | [diff] [blame] | 28 | if os.path.islink(dirname): |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 29 | names[:] = [] |
| 30 | return |
Guido van Rossum | 391b8b7 | 1992-03-30 11:14:36 +0000 | [diff] [blame] | 31 | if os.path.ismount(dirname): |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 32 | print 'descend into', dirname |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 33 | for name in names: |
Guido van Rossum | 391b8b7 | 1992-03-30 11:14:36 +0000 | [diff] [blame] | 34 | name = os.path.join(dirname, name) |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 35 | try: |
Guido van Rossum | 391b8b7 | 1992-03-30 11:14:36 +0000 | [diff] [blame] | 36 | linkto = os.readlink(name) |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 37 | if prog.search(linkto) >= 0: |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 38 | print name, '->', linkto |
Guido van Rossum | 391b8b7 | 1992-03-30 11:14:36 +0000 | [diff] [blame] | 39 | except os.error: |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 40 | pass |
| 41 | |
Guido van Rossum | 5ec8b52 | 1994-01-21 15:47:00 +0000 | [diff] [blame] | 42 | main() |