lmr | c6bd3a6 | 2009-06-10 19:38:06 +0000 | [diff] [blame^] | 1 | #!/usr/bin/python |
lmr | 6f669ce | 2009-05-31 19:02:42 +0000 | [diff] [blame] | 2 | import shutil, os, sys |
lmr | c6bd3a6 | 2009-06-10 19:38:06 +0000 | [diff] [blame^] | 3 | import common |
lmr | 6f669ce | 2009-05-31 19:02:42 +0000 | [diff] [blame] | 4 | |
| 5 | """ |
| 6 | Program that replaces the CD keys present on a KVM autotest configuration file. |
| 7 | |
| 8 | @copyright: Red Hat 2008-2009 |
| 9 | @author: uril@redhat.com (Uri Lublin) |
| 10 | """ |
| 11 | |
| 12 | |
| 13 | def file_to_lines(filename): |
| 14 | f = open(filename, 'r') |
| 15 | lines = f.readlines() |
| 16 | f.close |
| 17 | return lines |
| 18 | |
| 19 | def lines_to_file(filename, lines): |
| 20 | f = open(filename, 'w') |
| 21 | f.writelines(lines) |
| 22 | f.close() |
| 23 | |
| 24 | def replace_var_with_val(lines, variables): |
| 25 | new = [] |
| 26 | for line in lines: |
| 27 | for (var,val) in variables: |
| 28 | if var in line: |
| 29 | print 'replacing %s with %s in "%s"' % (var, val, line[:-1]) |
| 30 | line = line.replace(var, val) |
| 31 | print ' ... new line is "%s"' % (line[:-1]) |
| 32 | new.append(line) |
| 33 | return new |
| 34 | |
| 35 | def filter_comments(line): |
| 36 | return not line.strip().startswith('#') |
| 37 | |
| 38 | def filter_empty(line): |
| 39 | return len(line.strip()) != 0 |
| 40 | |
| 41 | def line_to_pair(line): |
| 42 | x,y = line.split('=', 1) |
| 43 | return (x.strip(), y.strip()) |
| 44 | |
| 45 | def read_vars(varfile): |
| 46 | varlines = file_to_lines(varfile) |
| 47 | varlines = filter(filter_comments, varlines) |
| 48 | varlines = filter(filter_empty, varlines) |
| 49 | vars = map(line_to_pair, varlines) |
| 50 | return vars |
| 51 | |
| 52 | def main(cfgfile, varfile): |
| 53 | # first save a copy of the original file (if does not exist) |
| 54 | backupfile = '%s.backup' % cfgfile |
| 55 | if not os.path.exists(backupfile): |
| 56 | shutil.copy(cfgfile, backupfile) |
| 57 | |
| 58 | vars = read_vars(varfile) |
| 59 | datalines = file_to_lines(cfgfile) |
| 60 | newlines = replace_var_with_val(datalines, vars) |
| 61 | lines_to_file(cfgfile, newlines) |
| 62 | |
| 63 | |
| 64 | if __name__ == '__main__': |
| 65 | def die(msg, val): |
| 66 | print msg |
| 67 | sys.exit(val) |
| 68 | if len(sys.argv) != 3: |
| 69 | die('usage: %s <kvm_tests-config-file> <varfile>', 1) |
| 70 | cfgfile = sys.argv[1] |
| 71 | varfile = sys.argv[2] |
| 72 | if not os.path.exists(cfgfile): |
| 73 | die('bad cfgfile "%s"' % cfgfile, 2) |
| 74 | if not os.path.exists(varfile): |
| 75 | die('bad varfile "%s"' % varfile, 2) |
| 76 | main(cfgfile, varfile) |