OpenCores
URL https://opencores.org/ocsvn/radiohdl/radiohdl/trunk

Subversion Repositories radiohdl

[/] [radiohdl/] [trunk/] [base/] [modify_configfiles] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 danv
#!/usr/bin/env python
2
###############################################################################
3
#
4
# Copyright (C) 2014-2018
5
# ASTRON (Netherlands Institute for Radio Astronomy) 
6
# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
7
#
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
12
#
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
# GNU General Public License for more details.
17
#
18
# You should have received a copy of the GNU General Public License
19
# along with this program.  If not, see .
20
#
21
# $Id: configfile_modifier.py 18609 2018-07-18 08:06:30Z overeem $
22
#
23
###############################################################################
24
 
25
"""
26
Interactive program to modify all configfiles found in the hierarchical directory
27
structure under the given top directory.
28
"""
29
 
30
from argparse import ArgumentParser
31
from hdl_raw_access import RawConfigTree
32
 
33
# Define a simple menu system that is based on a dict that contains the menu actions:
34
#   the keys are the valid strings the user may enter
35
#   the values are lists: the first element is the menu tekst, the second the function to call and
36
#                         the remaining elememts (if any) are the arguments to ask the user
37
#   All arguments are stored in a kwargs structure and passed to the functions that is called.
38
 
39
def get_menu_choice(menu, title):
40
    """
41
    Iterate over the menu dict, show the menu choices and ask for input till valid input is received.
42
    """
43
    print "\n", title
44
    print "-" * len(title)
45
    input_ok = False
46
    while not input_ok:
47
        for key in sorted(menu.iterkeys()):
48
            print "{}  {}".format(key, menu[key][0])
49
        choice = raw_input("\n >>: ")
50
        if choice not in menu.keys():
51
            print "ERROR: This input is not a valid menu choice. Try again."
52
        else:
53
            input_ok = True
54
    return menu[choice]
55
 
56
def execute_menu_line(line_spec, verbose):
57
    """
58
    Given a menu line specification it asks the user for the specified arguments, stores the values in a
59
    kwargs structure and finally call the specified function with this kwargs.
60
    """
61
    print "\n--- {} ---".format(line_spec[0])
62
    nr_args = len(line_spec) - 2
63
    if nr_args < 0:
64
        raise SyntaxError("Invalid formatted menuline definition: {}.\nNeed at least two items in the list".format(line_spec))
65
    if nr_args == 0:
66
        return line_spec[1]()
67
    # Iterate over the remaining items and get values for them
68
    kwargs = { "verbose": verbose }
69
    for spec_idx in xrange(2, len(line_spec)):
70
        answer = raw_input(line_spec[spec_idx].capitalize().replace("_", " ") + ": ")
71
        kwargs[line_spec[spec_idx]] = answer
72
    line_spec[1](**kwargs)
73
 
74
 
75
### Implementation of the menu commands
76
# Note: cleaner would to implement this with the Strategy pattern but we want to keep the code
77
#       to be readable for everyone. ;-)
78
def change_value_of_key(**kwargs):
79
    key       = kwargs.pop("key")
80
    new_value = kwargs.pop("new_value")
81
    verbose   = kwargs.pop("verbose")
82
    global tree
83
    for filename in sorted(tree.configfiles.keys()):
84
        tree.configfiles[filename].change_value(key, new_value, verbose)
85
 
86
def append_key_value(**kwargs):
87
    key       = kwargs.pop("new_key")
88
    new_value = kwargs.pop("new_value")
89
    verbose   = kwargs.pop("verbose")
90
    global tree
91
    for filename in sorted(tree.configfiles.keys()):
92
        tree.configfiles[filename].append_key_value(key, new_value, verbose)
93
 
94
def insert_key_at_linenr(**kwargs):
95
    new_key    = kwargs.pop("new_key")
96
    new_value  = kwargs.pop("new_value")
97
    linenumber = int(kwargs.pop("linenumber"))
98
    verbose    = kwargs.pop("verbose")
99
    global tree
100
    for filename in sorted(tree.configfiles.keys()):
101
        tree.configfiles[filename].insert_key_at_linenr(new_key, new_value, linenumber, verbose)
102
 
103
def insert_key_value_before_key(**kwargs):
104
    new_key    = kwargs.pop("new_key")
105
    new_value  = kwargs.pop("new_value")
106
    before_key = kwargs.pop("before_key")
107
    verbose    = kwargs.pop("verbose")
108
    global tree
109
    for filename in sorted(tree.configfiles.keys()):
110
        tree.configfiles[filename].insert_key_value_before_key(new_key, new_value, before_key, verbose)
111
 
112
def rename_key(**kwargs):
113
    old_key = kwargs.pop("old_key")
114
    new_key = kwargs.pop("new_key")
115
    verbose = kwargs.pop("verbose")
116
    global tree
117
    for filename in sorted(tree.configfiles.keys()):
118
        tree.configfiles[filename].rename_key(old_key, new_key, verbose)
119
 
120
def remove_key(**kwargs):
121
    key     = kwargs.pop("key")
122
    verbose = kwargs.pop("verbose")
123
    global tree
124
    for filename in sorted(tree.configfiles.keys()):
125
        tree.configfiles[filename].remove_key(key, verbose)
126
 
127
def end_menu():
128
    global running
129
    running = False
130
 
131
 
132
if __name__ == '__main__':
133
    # setup parser and parse the arguments.
134
    argparser = ArgumentParser(description='Options and arguments for modifying collections of configfiles.')
135
    argparser.add_argument('filename', help="Filename like 'hdl_buildset_.cfg'")
136
    argparser.add_argument('rootdir',  help="Top directory to start the search for configfiles.")
137
    argparser.add_argument('-v', '--verbose', help="Show more information on what happens.", action="store_true")
138
    args = argparser.parse_args()
139
 
140
    tree = RawConfigTree(args.rootdir, args.filename)
141
    print "Found {} configfiles in {}".format(len(tree.configfiles), args.rootdir)
142
    if args.verbose:
143
        for filename in sorted(tree.configfiles.keys()):
144
            print filename
145
 
146
    # define the menu including actions
147
    #     choice    choice description            function to call             arguments to ask for
148
    menu = {'1': [ "Change value",                change_value_of_key,         "key",     "new_value"],
149
            '2': [ "Append key",                  append_key_value,            "new_key", "new_value"],
150
            '3': [ "Insert key at linenr",        insert_key_at_linenr,        "new_key", "new_value", "linenumber"],
151
            '4': [ "Insert key before other key", insert_key_value_before_key, "new_key", "new_value", "before_key"],
152
            '5': [ "Rename key",                  rename_key,                  "old_key", "new_key"],
153
            '6': [ "Remove key",                  remove_key,                  "key"],
154
            'q': [ "Exit",                        end_menu ]
155
    }
156
 
157
    running = True
158
    while running:
159
        execute_menu_line(get_menu_choice(menu, "Menu for changing multiple configfiles"), args.verbose)
160
 

powered by: WebSVN 2.1.0

© copyright 1999-2019 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.