1#! /usr/bin/env python3
2
3# findlinksto
4#
5# find symbolic links to a path matching a regular expression
6
7import os
8import sys
9import re
10import getopt
11
12def main():
13    try:
14        opts, args = getopt.getopt(sys.argv[1:], '')
15        if len(args) < 2:
16            raise getopt.GetoptError('not enough arguments', None)
17    except getopt.GetoptError as 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 = re.compile(pat)
24    for dirname in dirs:
25        os.walk(dirname, visit, prog)
26
27def visit(prog, dirname, names):
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)
37            if prog.search(linkto) is not None:
38                print(name, '->', linkto)
39        except OSError:
40            pass
41
42if __name__ == '__main__':
43    main()
44