Committer:
borlanic
Date:
Fri Mar 30 14:07:05 2018 +0000
Revision:
4:75df35ef4fb6
Parent:
0:380207fcb5c1
commentar

Who changed what in which revision?

UserRevisionLine numberNew contents of line
borlanic 0:380207fcb5c1 1 import json
borlanic 0:380207fcb5c1 2 import os
borlanic 0:380207fcb5c1 3 import stat
borlanic 0:380207fcb5c1 4 import re
borlanic 0:380207fcb5c1 5 from collections import OrderedDict
borlanic 0:380207fcb5c1 6 from subprocess import Popen
borlanic 0:380207fcb5c1 7
borlanic 0:380207fcb5c1 8 git_processes = []
borlanic 0:380207fcb5c1 9
borlanic 0:380207fcb5c1 10 class MyJSONEncoder(json.JSONEncoder):
borlanic 0:380207fcb5c1 11 def __init__(self, *args, **kwargs):
borlanic 0:380207fcb5c1 12 super(MyJSONEncoder, self).__init__(*args, **kwargs)
borlanic 0:380207fcb5c1 13 self.current_indent = 0
borlanic 0:380207fcb5c1 14 self.current_indent_str = ""
borlanic 0:380207fcb5c1 15
borlanic 0:380207fcb5c1 16
borlanic 0:380207fcb5c1 17 def encode(self, o):
borlanic 0:380207fcb5c1 18 #Special Processing for lists
borlanic 0:380207fcb5c1 19 if isinstance(o, (list, tuple)):
borlanic 0:380207fcb5c1 20 primitives_only = True
borlanic 0:380207fcb5c1 21 for item in o:
borlanic 0:380207fcb5c1 22 if isinstance(item, (list, tuple, dict)):
borlanic 0:380207fcb5c1 23 primitives_only = False
borlanic 0:380207fcb5c1 24 break
borlanic 0:380207fcb5c1 25 output = []
borlanic 0:380207fcb5c1 26 if primitives_only:
borlanic 0:380207fcb5c1 27 for item in o:
borlanic 0:380207fcb5c1 28 output.append(json.dumps(item))
borlanic 0:380207fcb5c1 29 return "[" + ", ".join(output) + "]"
borlanic 0:380207fcb5c1 30 else:
borlanic 0:380207fcb5c1 31 self.current_indent += self.indent
borlanic 0:380207fcb5c1 32 self.current_indent_str = " " * self.current_indent
borlanic 0:380207fcb5c1 33 for item in o:
borlanic 0:380207fcb5c1 34 output.append(self.current_indent_str + self.encode(item))
borlanic 0:380207fcb5c1 35 self.current_indent -= self.indent
borlanic 0:380207fcb5c1 36 self.current_indent_str = " " * self.current_indent
borlanic 0:380207fcb5c1 37 return "[\n" + ",\n".join(output) + "\n" + self.current_indent_str + "]"
borlanic 0:380207fcb5c1 38 elif isinstance(o, dict):
borlanic 0:380207fcb5c1 39 primitives_only = True
borlanic 0:380207fcb5c1 40 for item in o.values():
borlanic 0:380207fcb5c1 41 if isinstance(item, (list, tuple, dict)):
borlanic 0:380207fcb5c1 42 primitives_only = False
borlanic 0:380207fcb5c1 43 break
borlanic 0:380207fcb5c1 44 output = []
borlanic 0:380207fcb5c1 45 if primitives_only and len(o) < 3:
borlanic 0:380207fcb5c1 46 for key, value in o.items():
borlanic 0:380207fcb5c1 47 output.append(json.dumps(key) + ": " + self.encode(value))
borlanic 0:380207fcb5c1 48 return "{" + ", ".join(output) + "}"
borlanic 0:380207fcb5c1 49 else:
borlanic 0:380207fcb5c1 50 self.current_indent += self.indent
borlanic 0:380207fcb5c1 51 self.current_indent_str = " " * self.current_indent
borlanic 0:380207fcb5c1 52 for key, value in o.items():
borlanic 0:380207fcb5c1 53 output.append(self.current_indent_str + json.dumps(key) + ": " + self.encode(value))
borlanic 0:380207fcb5c1 54 self.current_indent -= self.indent
borlanic 0:380207fcb5c1 55 self.current_indent_str = " " * self.current_indent
borlanic 0:380207fcb5c1 56 return "{\n" + ",\n".join(output) + "\n" + self.current_indent_str + "}"
borlanic 0:380207fcb5c1 57 else:
borlanic 0:380207fcb5c1 58 return json.dumps(o)
borlanic 0:380207fcb5c1 59
borlanic 0:380207fcb5c1 60 def load(path):
borlanic 0:380207fcb5c1 61 with open(path, 'r') as f :
borlanic 0:380207fcb5c1 62 return json.load(f, object_pairs_hook=OrderedDict)
borlanic 0:380207fcb5c1 63
borlanic 0:380207fcb5c1 64 def dump(path, obj):
borlanic 0:380207fcb5c1 65 with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f :
borlanic 0:380207fcb5c1 66 os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
borlanic 0:380207fcb5c1 67 f.write(MyJSONEncoder(indent=4).encode(obj))
borlanic 0:380207fcb5c1 68 f.write(u'\n')
borlanic 0:380207fcb5c1 69 f.truncate()
borlanic 0:380207fcb5c1 70
borlanic 0:380207fcb5c1 71 def find(stem, path) :
borlanic 0:380207fcb5c1 72 for root, directories, files in os.walk(path, followlinks=True) :
borlanic 0:380207fcb5c1 73 [dir for dir in directories if dir[0] != '.']
borlanic 0:380207fcb5c1 74 if (stem_match(stem,os.path.basename(os.path.normpath(root))) and
borlanic 0:380207fcb5c1 75 "device.h" in files) :
borlanic 0:380207fcb5c1 76 return os.path.join(root, "device.h")
borlanic 0:380207fcb5c1 77
borlanic 0:380207fcb5c1 78 def find_all_devices(path, verbose=False) :
borlanic 0:380207fcb5c1 79 for root, directories, files in os.walk(path, followlinks=True) :
borlanic 0:380207fcb5c1 80 [dir for dir in directories if dir[0] != '.']
borlanic 0:380207fcb5c1 81 if "device.h" in files :
borlanic 0:380207fcb5c1 82 if verbose : print("[VERBOSE] found a device.h file in {}".format(root))
borlanic 0:380207fcb5c1 83 yield os.path.join(root, "device.h")
borlanic 0:380207fcb5c1 84
borlanic 0:380207fcb5c1 85 mbed_matcher = re.compile('mbed', re.IGNORECASE)
borlanic 0:380207fcb5c1 86 def stem_match(stem, thing) :
borlanic 0:380207fcb5c1 87 return (stem in thing or
borlanic 0:380207fcb5c1 88 re.sub(mbed_matcher, '', stem) in thing)
borlanic 0:380207fcb5c1 89
borlanic 0:380207fcb5c1 90 attr_matcher = re.compile('^#define\W+DEVICE_(\w+)\W+1.*$')
borlanic 0:380207fcb5c1 91 def parse_attributes(path) :
borlanic 0:380207fcb5c1 92 with open(path) as input :
borlanic 0:380207fcb5c1 93 for line in input :
borlanic 0:380207fcb5c1 94 m = re.match(attr_matcher, line)
borlanic 0:380207fcb5c1 95 if m: yield m.group(1)
borlanic 0:380207fcb5c1 96
borlanic 0:380207fcb5c1 97 remove_matcher = re.compile('^#define\W+DEVICE_(\w+)\W+[10].*$')
borlanic 0:380207fcb5c1 98 def remove_attributes(path) :
borlanic 0:380207fcb5c1 99 with open(path) as input :
borlanic 0:380207fcb5c1 100 remainder = filter(lambda l: not re.match(remove_matcher, l), input)
borlanic 0:380207fcb5c1 101 with open(path,"wb") as output :
borlanic 0:380207fcb5c1 102 output.truncate(0)
borlanic 0:380207fcb5c1 103 output.write("// The 'provides' section in 'target.json' is now used"+
borlanic 0:380207fcb5c1 104 " to create the device's hardware preprocessor switches.\n")
borlanic 0:380207fcb5c1 105 output.write("// Check the 'provides' section of the target description"+
borlanic 0:380207fcb5c1 106 " in 'targets.json' for more details.\n")
borlanic 0:380207fcb5c1 107 output.writelines(remainder)
borlanic 0:380207fcb5c1 108
borlanic 0:380207fcb5c1 109 def user_select(things, message) :
borlanic 0:380207fcb5c1 110 print(message)
borlanic 0:380207fcb5c1 111 for thing, number in zip(things, range(len(things))):
borlanic 0:380207fcb5c1 112 print("{} : {}".format(number, thing))
borlanic 0:380207fcb5c1 113 selection = None
borlanic 0:380207fcb5c1 114 while selection is None :
borlanic 0:380207fcb5c1 115 print("please select an integer [0..{}] or specify all".format(len(things) - 1))
borlanic 0:380207fcb5c1 116 try :
borlanic 0:380207fcb5c1 117 i = raw_input()
borlanic 0:380207fcb5c1 118 if i == "all" :
borlanic 0:380207fcb5c1 119 selection = "all"
borlanic 0:380207fcb5c1 120 else :
borlanic 0:380207fcb5c1 121 selection = int(i)
borlanic 0:380207fcb5c1 122 if (selection > len(things) or
borlanic 0:380207fcb5c1 123 selection < 0) :
borlanic 0:380207fcb5c1 124 print("selection {} out of range".format(selection))
borlanic 0:380207fcb5c1 125 selection = None
borlanic 0:380207fcb5c1 126 except (ValueError, SyntaxError) :
borlanic 0:380207fcb5c1 127 print("selection not understood")
borlanic 0:380207fcb5c1 128 if selection == "all" :
borlanic 0:380207fcb5c1 129 return things
borlanic 0:380207fcb5c1 130 else :
borlanic 0:380207fcb5c1 131 return [things[selection]]
borlanic 0:380207fcb5c1 132
borlanic 0:380207fcb5c1 133 target_matcher = re.compile("TARGET_")
borlanic 0:380207fcb5c1 134 def strip_target(str) :
borlanic 0:380207fcb5c1 135 return re.sub(target_matcher, "", str)
borlanic 0:380207fcb5c1 136
borlanic 0:380207fcb5c1 137 def add_to_targets(targets, device_file, verbose=False, remove=False) :
borlanic 0:380207fcb5c1 138 if verbose : print("[VERBOSE] trying target {}".format(device_file))
borlanic 0:380207fcb5c1 139 device = strip_target(os.path.basename(os.path.normpath(os.path.dirname(device_file))))
borlanic 0:380207fcb5c1 140 if not device :
borlanic 0:380207fcb5c1 141 print("[WARNING] device {} did not have an associated device.h".format(device))
borlanic 0:380207fcb5c1 142 else :
borlanic 0:380207fcb5c1 143 possible_matches = set([key for key in targets.keys() if stem_match(device, key)])
borlanic 0:380207fcb5c1 144 for key, value in targets.items() :
borlanic 0:380207fcb5c1 145 for alt in value['extra_labels'] if 'extra_labels' in value else [] :
borlanic 0:380207fcb5c1 146 if stem_match(device, alt) : possible_matches.add(key)
borlanic 0:380207fcb5c1 147 for alt in value['extra_labels_add'] if 'extra_labels_add' in value else [] :
borlanic 0:380207fcb5c1 148 if stem_match(device, alt) : possible_matches.add(key)
borlanic 0:380207fcb5c1 149 possible_matches = list(possible_matches)
borlanic 0:380207fcb5c1 150 for match in possible_matches :
borlanic 0:380207fcb5c1 151 if device == match : possible_matches = [match]
borlanic 0:380207fcb5c1 152 if not possible_matches :
borlanic 0:380207fcb5c1 153 print("[WARNING] device {} did not have an associated entry in targets.json".format(device))
borlanic 0:380207fcb5c1 154 return None
borlanic 0:380207fcb5c1 155 elif len(possible_matches) > 1 :
borlanic 0:380207fcb5c1 156 message = ("possible matches for file {}".format(device_file))
borlanic 0:380207fcb5c1 157 target = user_select(possible_matches, message)
borlanic 0:380207fcb5c1 158 else :
borlanic 0:380207fcb5c1 159 target = possible_matches
borlanic 0:380207fcb5c1 160 attrs = list(parse_attributes(device_file))
borlanic 0:380207fcb5c1 161 if attrs :
borlanic 0:380207fcb5c1 162 for t in target :
borlanic 0:380207fcb5c1 163 targets[t]["device_has"] = sorted(list(set(targets[t].setdefault("device_has",[]) + attrs)))
borlanic 0:380207fcb5c1 164 if verbose : print("[VERBOSE] target {} now device_has {}".format(t, attrs))
borlanic 0:380207fcb5c1 165 if remove is True:
borlanic 0:380207fcb5c1 166 remove_attributes(device_file)
borlanic 0:380207fcb5c1 167
borlanic 0:380207fcb5c1 168 if __name__ == '__main__' :
borlanic 0:380207fcb5c1 169 import argparse
borlanic 0:380207fcb5c1 170 parser = argparse.ArgumentParser(description='A helpful little script for converting' +
borlanic 0:380207fcb5c1 171 ' device.h files to parts of the targets.json file')
borlanic 0:380207fcb5c1 172 parser.add_argument('-a', '--all', action='store_true',
borlanic 0:380207fcb5c1 173 help='find and convert all available device.h files in the'+
borlanic 0:380207fcb5c1 174 ' directory tree starting at the current directory')
borlanic 0:380207fcb5c1 175 parser.add_argument('-f', '--file', nargs='+', help='specify an individual file to '+
borlanic 0:380207fcb5c1 176 'convert from device.h format to a piece of targets.json')
borlanic 0:380207fcb5c1 177 parser.add_argument('-t', '--target', nargs='+', help='specify an individual target'+
borlanic 0:380207fcb5c1 178 ' to convert from device.h format to a piece of targets.json')
borlanic 0:380207fcb5c1 179 parser.add_argument('-v', '--verbose', action='store_true',
borlanic 0:380207fcb5c1 180 help="print out every target that is updated in the targets.json")
borlanic 0:380207fcb5c1 181 parser.add_argument('-r', '--rm', action='store_true',
borlanic 0:380207fcb5c1 182 help="remove the used attributes from a device.h file")
borlanic 0:380207fcb5c1 183 args = parser.parse_args()
borlanic 0:380207fcb5c1 184 if not args.target and not args.file and not args.all :
borlanic 0:380207fcb5c1 185 print("[WARNING] no action specified; auto-formatting targets.json")
borlanic 0:380207fcb5c1 186
borlanic 0:380207fcb5c1 187 targets_file_name = os.path.join(os.curdir, "hal", "targets.json")
borlanic 0:380207fcb5c1 188 try :
borlanic 0:380207fcb5c1 189 targets = load(targets_file_name)
borlanic 0:380207fcb5c1 190 except OSError :
borlanic 0:380207fcb5c1 191 print("[ERROR] did not find targets.json where I expected it {}".format(targets_file_name))
borlanic 0:380207fcb5c1 192 exit(1)
borlanic 0:380207fcb5c1 193 except ValueError :
borlanic 0:380207fcb5c1 194 print("[ERROR] invalid json found in {}".format(targets_file_name))
borlanic 0:380207fcb5c1 195 exit(2)
borlanic 0:380207fcb5c1 196
borlanic 0:380207fcb5c1 197 if args.target :
borlanic 0:380207fcb5c1 198 for target in args.target :
borlanic 0:380207fcb5c1 199 device_file = find(target, os.curdir)
borlanic 0:380207fcb5c1 200 if device_file :
borlanic 0:380207fcb5c1 201 add_to_targets(targets, device_file, verbose=args.verbose, remove=args.rm)
borlanic 0:380207fcb5c1 202 else :
borlanic 0:380207fcb5c1 203 print("[WARNING] could not locate a device file for target {}".format(target))
borlanic 0:380207fcb5c1 204
borlanic 0:380207fcb5c1 205 if args.file :
borlanic 0:380207fcb5c1 206 for file in args.file :
borlanic 0:380207fcb5c1 207 add_to_targets(targets, file, verbose=args.verbose, remove=args.rm)
borlanic 0:380207fcb5c1 208
borlanic 0:380207fcb5c1 209 if args.all :
borlanic 0:380207fcb5c1 210 for file in find_all_devices(os.curdir, verbose=args.verbose) :
borlanic 0:380207fcb5c1 211 add_to_targets(targets, file, verbose=args.verbose, remove=args.rm)
borlanic 0:380207fcb5c1 212
borlanic 0:380207fcb5c1 213 dump(targets_file_name, targets)
borlanic 0:380207fcb5c1 214
borlanic 0:380207fcb5c1 215 for process in git_processes :
borlanic 0:380207fcb5c1 216 process.wait()