1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | # findlinksto |
---|
4 | n/a | # |
---|
5 | n/a | # find symbolic links to a path matching a regular expression |
---|
6 | n/a | |
---|
7 | n/a | import os |
---|
8 | n/a | import sys |
---|
9 | n/a | import re |
---|
10 | n/a | import getopt |
---|
11 | n/a | |
---|
12 | n/a | def main(): |
---|
13 | n/a | try: |
---|
14 | n/a | opts, args = getopt.getopt(sys.argv[1:], '') |
---|
15 | n/a | if len(args) < 2: |
---|
16 | n/a | raise getopt.GetoptError('not enough arguments', None) |
---|
17 | n/a | except getopt.GetoptError as msg: |
---|
18 | n/a | sys.stdout = sys.stderr |
---|
19 | n/a | print(msg) |
---|
20 | n/a | print('usage: findlinksto pattern directory ...') |
---|
21 | n/a | sys.exit(2) |
---|
22 | n/a | pat, dirs = args[0], args[1:] |
---|
23 | n/a | prog = re.compile(pat) |
---|
24 | n/a | for dirname in dirs: |
---|
25 | n/a | os.walk(dirname, visit, prog) |
---|
26 | n/a | |
---|
27 | n/a | def visit(prog, dirname, names): |
---|
28 | n/a | if os.path.islink(dirname): |
---|
29 | n/a | names[:] = [] |
---|
30 | n/a | return |
---|
31 | n/a | if os.path.ismount(dirname): |
---|
32 | n/a | print('descend into', dirname) |
---|
33 | n/a | for name in names: |
---|
34 | n/a | name = os.path.join(dirname, name) |
---|
35 | n/a | try: |
---|
36 | n/a | linkto = os.readlink(name) |
---|
37 | n/a | if prog.search(linkto) is not None: |
---|
38 | n/a | print(name, '->', linkto) |
---|
39 | n/a | except OSError: |
---|
40 | n/a | pass |
---|
41 | n/a | |
---|
42 | n/a | if __name__ == '__main__': |
---|
43 | n/a | main() |
---|