mbed-os

Dependents:   cobaLCDJoyMotor_Thread odometry_omni_3roda_v3 odometry_omni_3roda_v1 odometry_omni_3roda_v2 ... more

Committer:
be_bryan
Date:
Mon Dec 11 17:54:04 2017 +0000
Revision:
0:b74591d5ab33
motor ++

Who changed what in which revision?

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