def action(self, args): """Perform the action associated with this command. :type args: list of titus.inspector.parser.Ast :param args: arguments passed to the command :rtype: ``None`` :return: nothing; results must be printed to the screen """ if len(args) == 1 and args[0] == parser.Word("help"): print self.help else: if len(args) == 4 and isinstance(args[0], parser.Word): if args[0].text not in self.mode.pfaFiles: raise InspectorError("no PFA document named \"{0}\" in memory (try 'load <file> as {1}')".format(args[0].text, args[0].text)) model = self.mode.pfaFiles[args[0].text] node = model.obj safecopy = copy.deepcopy(node) def rollback(): self.mode.pfaFiles[args[0].text].obj = safecopy regex = args[1].regex() replacement = args[3].replacement() elif len(args) == 4 and isinstance(args[0], parser.Extract): if args[0].text not in self.mode.pfaFiles: raise InspectorError("no PFA document named \"{0}\" in memory (try 'load <file> as {1}')".format(args[0].text, args[0].text)) model = self.mode.pfaFiles[args[0].text] node = model.obj safecopy = copy.deepcopy(node) def rollback(): self.mode.pfaFiles[args[0].text].obj = safecopy items = args[0].items node = extaction(args[0], node, items) regex = args[1].regex() replacement = args[3].replacement() else: self.syntaxError() def display(i): if isinstance(i, basestring): if " " in i: return json.dumps(i) else: return i else: return str(i) def replace(value, groups): if isinstance(value, parser.Replacement): try: return groups[value.name] except KeyError: raise InspectorError("group ({0}) not found in regular expression".format(value.name)) elif isinstance(value, dict): return dict((k, replace(v, groups)) for k, v in value.items()) elif isinstance(value, (list, tuple)): return [replace(x, groups) for x in value] else: return value def removeAts(obj): if isinstance(obj, dict): return dict((k, removeAts(v)) for k, v in obj.items() if k != "@") elif isinstance(obj, (list, tuple)): return [removeAts(x) for x in obj] else: return obj ask = True self.mode.pause() try: for index, match in t.search(regex, node): replacedReplacement = replace(replacement, match.groups) if ask: print "At index [" + ", ".join(display(i) for i in index) + "]:" print "Original: " + json.dumps(removeAts(t.get(node, index))) print "Change to: " + json.dumps(replacedReplacement) action = None while action is None: response = raw_input("(Y/n/all/stop/revert): ") normalized = response.strip().lower() if normalized in ("", "y", "yes"): action = "yes" elif normalized in ("n", "no"): action = "no" elif normalized == "all": action = "all" elif normalized == "stop": action = "stop" elif normalized == "revert": action = "revert" print else: action = "yes" if action == "yes": t.assign(node, index, replacedReplacement) elif action == "all": t.assign(node, index, replacedReplacement) ask = False elif action == "stop": break elif action == "revert": rollback() break except: rollback() self.mode.resume() raise else: model.reset() self.mode.resume()
def action(self, args): """Perform the action associated with this command. :type args: list of titus.inspector.parser.Ast :param args: arguments passed to the command :rtype: ``None`` :return: nothing; results must be printed to the screen """ if len(args) == 1 and args[0] == parser.Word("help"): print self.help else: if len(args) == 4 and isinstance(args[0], parser.Word): if args[0].text not in self.mode.pfaFiles: raise InspectorError( "no PFA document named \"{0}\" in memory (try 'load <file> as {1}')" .format(args[0].text, args[0].text)) model = self.mode.pfaFiles[args[0].text] node = model.obj safecopy = copy.deepcopy(node) def rollback(): self.mode.pfaFiles[args[0].text].obj = safecopy regex = args[1].regex() replacement = args[3].replacement() elif len(args) == 4 and isinstance(args[0], parser.Extract): if args[0].text not in self.mode.pfaFiles: raise InspectorError( "no PFA document named \"{0}\" in memory (try 'load <file> as {1}')" .format(args[0].text, args[0].text)) model = self.mode.pfaFiles[args[0].text] node = model.obj safecopy = copy.deepcopy(node) def rollback(): self.mode.pfaFiles[args[0].text].obj = safecopy items = args[0].items node = extaction(args[0], node, items) regex = args[1].regex() replacement = args[3].replacement() else: self.syntaxError() def display(i): if isinstance(i, basestring): if " " in i: return json.dumps(i) else: return i else: return str(i) def replace(value, groups): if isinstance(value, parser.Replacement): try: return groups[value.name] except KeyError: raise InspectorError( "group ({0}) not found in regular expression". format(value.name)) elif isinstance(value, dict): return dict( (k, replace(v, groups)) for k, v in value.items()) elif isinstance(value, (list, tuple)): return [replace(x, groups) for x in value] else: return value def removeAts(obj): if isinstance(obj, dict): return dict( (k, removeAts(v)) for k, v in obj.items() if k != "@") elif isinstance(obj, (list, tuple)): return [removeAts(x) for x in obj] else: return obj ask = True self.mode.pause() try: for index, match in t.search(regex, node): replacedReplacement = replace(replacement, match.groups) if ask: print "At index [" + ", ".join( display(i) for i in index) + "]:" print "Original: " + json.dumps( removeAts(t.get(node, index))) print "Change to: " + json.dumps(replacedReplacement) action = None while action is None: response = raw_input("(Y/n/all/stop/revert): ") normalized = response.strip().lower() if normalized in ("", "y", "yes"): action = "yes" elif normalized in ("n", "no"): action = "no" elif normalized == "all": action = "all" elif normalized == "stop": action = "stop" elif normalized == "revert": action = "revert" print else: action = "yes" if action == "yes": t.assign(node, index, replacedReplacement) elif action == "all": t.assign(node, index, replacedReplacement) ask = False elif action == "stop": break elif action == "revert": rollback() break except: rollback() self.mode.resume() raise else: model.reset() self.mode.resume()
def action(self, args): """Perform the action associated with this command. :type args: list of titus.inspector.parser.Ast :param args: arguments passed to the command :rtype: ``None`` :return: nothing; results must be printed to the screen """ if len(args) == 1 and args[0] == parser.Word("help"): print self.help else: options = {"maxDepth": 3, "indexWidth": 30} while len(args) > 0 and isinstance(args[-1], parser.Option): opt = args.pop() if opt.word.text in ["maxDepth", "indexWidth"]: try: options[opt.word.text] = opt.value.value() except TypeError: raise InspectorError("illegal value for {0}".format(opt.word.text)) else: raise InspectorError("option {1} unrecognized".format(opt.word.text)) if not isinstance(options["maxDepth"], (int, long)) or options["maxDepth"] <= 0: raise InspectorError("maxDepth must be a positive integer") if not isinstance(options["indexWidth"], (int, long)) or options["indexWidth"] <= 0: raise InspectorError("indexWidth must be a positive integer") if len(args) == 2 and isinstance(args[0], parser.Word): if args[0].text not in self.mode.pfaFiles: raise InspectorError("no PFA document named \"{0}\" in memory (try 'load <file> as {1}')".format(args[0].text, args[0].text)) node = self.mode.pfaFiles[args[0].text].obj elif len(args) == 2 and isinstance(args[0], parser.Extract): if args[0].text not in self.mode.pfaFiles: raise InspectorError("no PFA document named \"{0}\" in memory (try 'load <file> as {1}')".format(args[0].text, args[0].text)) node = self.mode.pfaFiles[args[0].text].obj items = args[0].items node = extaction(args[0], node, items) else: self.syntaxError() regex = args[-1].regex() def display(i): if isinstance(i, basestring): if " " in i: return json.dumps(i) else: return i else: return str(i) content = StringIO.StringIO() count = 0 for index in t.indexes(regex, node): content.write("At index [" + ", ".join(display(i) for i in index) + "]:\n") matched = t.get(node, index) if not depthGreaterThan(matched, 0): content.write(json.dumps(matched) + "\n") elif not depthGreaterThan(matched, 1): t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=0, stream=content) elif not depthGreaterThan(matched, 2): t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=1, stream=content) else: t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=2, stream=content) content.write("\n") count += 1 if count == 0: print " (none)" content = content.getvalue() if content.count("\n") <= 100: print content else: proc = pipe("less") try: proc.stdin.write(content) except IOError as err: if str(err) != "[Errno 32] Broken pipe": raise pipewait(proc)
def action(self, args): """Perform the action associated with this command. :type args: list of titus.inspector.parser.Ast :param args: arguments passed to the command :rtype: ``None`` :return: nothing; results must be printed to the screen """ if len(args) == 1 and args[0] == parser.Word("help"): print self.help else: options = {"maxDepth": 3, "indexWidth": 30} while len(args) > 0 and isinstance(args[-1], parser.Option): opt = args.pop() if opt.word.text in ["maxDepth", "indexWidth"]: try: options[opt.word.text] = opt.value.value() except TypeError: raise InspectorError("illegal value for {0}".format( opt.word.text)) else: raise InspectorError("option {1} unrecognized".format( opt.word.text)) if not isinstance(options["maxDepth"], (int, long)) or options["maxDepth"] <= 0: raise InspectorError("maxDepth must be a positive integer") if not isinstance(options["indexWidth"], (int, long)) or options["indexWidth"] <= 0: raise InspectorError("indexWidth must be a positive integer") if len(args) == 2 and isinstance(args[0], parser.Word): if args[0].text not in self.mode.pfaFiles: raise InspectorError( "no PFA document named \"{0}\" in memory (try 'load <file> as {1}')" .format(args[0].text, args[0].text)) node = self.mode.pfaFiles[args[0].text].obj elif len(args) == 2 and isinstance(args[0], parser.Extract): if args[0].text not in self.mode.pfaFiles: raise InspectorError( "no PFA document named \"{0}\" in memory (try 'load <file> as {1}')" .format(args[0].text, args[0].text)) node = self.mode.pfaFiles[args[0].text].obj items = args[0].items node = extaction(args[0], node, items) else: self.syntaxError() regex = args[-1].regex() def display(i): if isinstance(i, basestring): if " " in i: return json.dumps(i) else: return i else: return str(i) content = StringIO.StringIO() count = 0 for index in t.indexes(regex, node): content.write("At index [" + ", ".join(display(i) for i in index) + "]:\n") matched = t.get(node, index) if not depthGreaterThan(matched, 0): content.write(json.dumps(matched) + "\n") elif not depthGreaterThan(matched, 1): t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=0, stream=content) elif not depthGreaterThan(matched, 2): t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=1, stream=content) else: t.look(matched, maxDepth=options["maxDepth"], indexWidth=options["indexWidth"], inlineDepth=2, stream=content) content.write("\n") count += 1 if count == 0: print " (none)" content = content.getvalue() if content.count("\n") <= 100: print content else: proc = pipe("less") try: proc.stdin.write(content) except IOError as err: if str(err) != "[Errno 32] Broken pipe": raise pipewait(proc)