| 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 """Run the specified command only if attributes are defined. | |
| 25 | |
| 26 Check if the fset of attributes (i.e. names), contained in FILE, | |
| 27 contains the attributes defined by --att=ATTRIBUTE arguments. If | |
| 28 so, runs in a shell the command defined by the remaining | |
| 29 arguments. | |
| 30 """ | |
| 31 argparser = argparse.ArgumentParser( | |
| 32 description=' ' + main.__doc__, | |
| 33 formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
| 34 argparser.add_argument('file', metavar='FILE', | |
| 35 help='File defining attributes to check against.') | |
| 36 argparser.add_argument('--att', required=False, default=[], | |
| 37 action='append', metavar='ATTRIBUTE', | |
| 38 help='Attribute to check. May be repeated.') | |
| 39 argparser.add_argument('--echo-cmd', required=False, | |
| 40 action='store_true', | |
| 41 help='Trace the command before running.') | |
| 42 argparser.add_argument('--command', nargs=argparse.REMAINDER, | |
| 43 help='Command to run if attributes found.') | |
| 44 | |
| 45 args = argparser.parse_args() | |
| 46 | |
| 47 # Quit early if no command to run. | |
| 48 if not args.command: | |
| 49 raise RuntimeError("No command argument(s) specified for ifatts") | |
| 50 | |
| 51 if HasFileAttributes(args.file, args.att): | |
| 52 stdout_result = shellcmd(args.command, echo=args.echo_cmd) | |
| 53 if not args.echo_cmd: | |
| 54 sys.stdout.write(stdout_result) | |
| 55 | |
| 56 if __name__ == '__main__': | |
| 57 main() | |
| 58 sys.exit(0) | |
| OLD | NEW |