OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python2 |
| 2 |
| 3 import argparse |
| 4 import os |
| 5 import sys |
| 6 |
| 7 from utils import shellcmd |
| 8 |
| 9 def GetFileAttributes(Filename): |
| 10 """Returns the set of names contained in file named Filename. |
| 11 """ |
| 12 if not os.path.isfile(Filename): |
| 13 raise RuntimeError("Can't open: %s" % Filename) |
| 14 with open(Filename, 'r') as f: |
| 15 return f.read().split() |
| 16 |
| 17 def HasFileAttributes(Filename, Attributes): |
| 18 """Returns true if the set of names in Attributes also appear |
| 19 in the set of names contained in file named Filename. |
| 20 """ |
| 21 return set(Attributes) <= set(GetFileAttributes(Filename)) |
| 22 |
| 23 def main(): |
| 24 """Check if the set attributes (i.e. names), contained in FILE, |
| 25 contains the attributes defined by --att=ATTRIBUTE arguments. If |
| 26 so, runs in a shell the command defined by the remaining |
| 27 arguments. Otherwise, quits (generating no output) and returns |
| 28 success. |
| 29 """ |
| 30 argparser = argparse.ArgumentParser( |
| 31 description=' ' + main.__doc__, |
| 32 formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 33 argparser.add_argument('file', metavar='FILE', |
| 34 help='File defining attributes to check against.') |
| 35 argparser.add_argument('--att', required=False, default=[], |
| 36 action='append', metavar='ATTRIBUTE', |
| 37 help='Attribute to check. May be repeated.') |
| 38 argparser.add_argument('--echo-cmd', required=False, |
| 39 action='store_true', |
| 40 help='Trace the command before running.') |
| 41 argparser.add_argument('--command', nargs=argparse.REMAINDER, |
| 42 help='Command to run if attributes found.') |
| 43 |
| 44 args = argparser.parse_args() |
| 45 |
| 46 # Quit early if no command to run. |
| 47 if not args.command: |
| 48 raise RuntimeError("No command argument(s) specified for ifatts") |
| 49 |
| 50 if HasFileAttributes(args.file, args.att): |
| 51 stdout_result = shellcmd(args.command, echo=args.echo_cmd) |
| 52 if not args.echo_cmd: |
| 53 sys.stdout.write(stdout_result) |
| 54 |
| 55 return 0 |
| 56 |
| 57 if __name__ == '__main__': |
| 58 main() |
OLD | NEW |