def parseDoc(doc: list, lookup: dict = None, meta: dict = None) -> list: line_edits = [ ] #list of tuples, where element 0 is the index of the line and element 1 is the new text i = 0 for i, line in enumerate(doc, i): results = parseLine( line ) #a list of Edit dicts, with keys for command, argument, and the index of the closing paren if len(results) > 0: new_line = carryOut( results, line, lookup ) #every command function should return a single string, the text to overwrite the line where the command was written if new_line == "bad command": raise CommandError("Invalid command at line " + str(i + 1) + " in the " + meta["template"] + " template while building " + meta["path"] + ".") if new_line == "bad key": raise CommandError("Key does not exist at line " + str(i + 1) + " in the " + meta["template"] + " template while building " + meta["path"] + ".") else: line_edits.append((i, new_line)) return line_edits
def record(self, patch_source, all=False, patch_name=None, no_color=False, keep_in_tree=False): if no_color is False: color = None else: color = False patches = patch_source.readpatches() if all: to_shelve = patches else: to_shelve = RecordPatchHunkSelector(patches, color).select()[0] if len(to_shelve) == 0: raise CommandError('Nothing to record') if patch_name is None: patch_name = raw_input('Patch name: ') assert '\n' not in patch_name patch_path = os.path.join(self.dir, patch_name + ".diff") self.log('Saving patch to: "%s"\n' % patch_path) f = open(patch_path, 'w') f.write("%s%s\n" % (self.MESSAGE_PREFIX, patch_name)) for patch in to_shelve: f.write(str(patch)) f.flush() os.fsync(f.fileno()) f.close() if keep_in_tree: return try: self._run_patch(to_shelve, reverse=True, dry_run=True) self._run_patch(to_shelve, reverse=True) except PatchFailed: try: self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True) self._run_patch(to_shelve, reverse=True, strip=1) except PatchFailed: raise CommandError("Failed removing recorded changes from the" "working tree!")
def __init__(self, video_source, ffmpeg_bin="ffmpeg"): if not os.path.exists(video_source): raise InputFileDoesNotExist() self.filename = os.path.basename(video_source) self.path = os.path.dirname(video_source) self.full_filename = video_source self._exec_response = commands.getoutput( "%s -i %s" % (ffmpeg_bin, self.full_filename)) if re.search(".*command\snot\sfound", self._exec_response, flags=re.IGNORECASE): raise CommandError() self._metadata = re.search("(Input \#.*)\n(Must|At\sleast)", self._exec_response, flags=re.MULTILINE | re.DOTALL) if re.search("Unknown format", self._exec_response, flags=re.IGNORECASE) or not self._metadata: raise UnknownFormat() if re.search("Duration: N\/A", self._exec_response, flags=re.IGNORECASE | re.MULTILINE): raise UnreadableFile() self._metadata = self._metadata.group(1) self._valid = True
def setUp(self, video_source, ffmpeg_bin="ffmpeg"): self.filename = os.path.basename(video_source) self.path = os.path.dirname(video_source) self.full_filename = video_source if not os.path.exists(self.full_filename): raise InputFileDoesNotExist() self._cmd = "%s -i %s" % (ffmpeg_bin, self.full_filename) proc = subprocess.Popen(self._cmd, stderr=subprocess.PIPE, shell=True) self._exec_stdout, self._exec_response = proc.communicate() if re.search(".*command\snot\sfound", self._exec_response, flags=re.IGNORECASE): raise CommandError() self._metadata = re.search("(Input \#.*)\n(Must|At\sleast)", self._exec_response, flags=re.MULTILINE | re.DOTALL) if re.search("Unknown format", self._exec_response, flags=re.IGNORECASE) or not self._metadata: raise UnknownFormat() if re.search("Duration: N\/A", self._exec_response, flags=re.IGNORECASE | re.MULTILINE): raise UnreadableFile() self._metadata = self._metadata.group(1) self._valid = True
def execute(self, _name, *args, **options): error = None try: if _name not in self.Command: raise CommandError(name=_name) result = self.Command[_name](*args, **options) except PublicError, e: error = e
def _run_patch_retry(self, patches, base_dir, reverse=False, *args, **kwargs): if len(patches) > 0: try: self._run_patch(patches, base_dir, reverse=reverse, *args, **kwargs) except PatchFailed: try: self._run_patch(patches, base_dir, reverse=reverse, strip=1, *args, **kwargs) except PatchFailed: raise CommandError("Failed removing changes not to be " "committed from the working tree!")
def run(self, all=False, file_list=None, message=None, revision=None, no_color=False, keep=False): if revision is not None and revision: if len(revision) == 1: revision = revision[0] else: raise CommandError("record only accepts a single revision " "parameter.") source = BzrPatchSource(revision, file_list) s = record.Record(source.base) s.record(source, all, message, no_color, keep) return 0
def exec_command(command, command_stdin=None): if command_stdin: child = subprocess.Popen(command, stdin=subprocess.PIPE) child.communicate(input=command_stdin.encode()) else: child = subprocess.Popen(command) child.communicate() rc = child.returncode if rc != 0: raise CommandError( f"Command \"{' '.join(child.args)}\" returned exit code {rc}") return rc
def run(self, command_name, **options): command_name = from_cli(command_name) if command_name not in self.Command: raise CommandError(name=command_name) params = self.Command[command_name].options out = [('Parameter', 'LDAP attribute'), ('=========', '==============')] mcl = len(out[0][0]) for param in params(): if param.exclude and 'webui' in param.exclude: continue out.append((param.cli_name, param.param_spec)) mcl = max(mcl, len(param.cli_name)) for item in out: print to_cli(item[0]).ljust(mcl) + ' : ' + item[1]
def get_command(self, argv): """Given CLI arguments, return the Command to use On incorrect invocation, prints out a help message and returns None """ if len(argv) == 0: self.Command.help() return (key, argv) = (argv[0], argv[1:]) name = from_cli(key) if name not in self.Command and len(argv) == 0: try: self.Command.help(unicode(key)) return except HelpError: pass if name not in self.Command or self.Command[name].NO_CLI: raise CommandError(name=key) cmd = self.Command[name] return cmd
def run(self, selected_list=None, interactive=False, message=None, file=None, **kw): if interactive: source = BzrPatchSource(None, selected_list) self.base = source.base patches = source.readpatches() to_commit, to_keep = RecordPatchHunkSelector(patches).select() if len(to_commit) == 0: raise CommandError('Nothing to commit') # Remove the changes not be committed from the tree self._run_patch_retry(to_keep, source.base, reverse=True) try: old_commit.run(self, selected_list=selected_list, message=message, file=file, **kw) finally: # Readd the changes not be committed from the tree self._run_patch_retry(to_keep, source.base) else: old_commit.run(self, selected_list=selected_list, message=message, file=file, **kw)
def analyze(self, response): try: if response is None or len(response) == 0: return False self._exec_response = response if re.search(".*command\snot\sfound", self._exec_response, flags=re.IGNORECASE): raise CommandError() self._metadata = re.search("(Input \#.*)\n", self._exec_response, flags=re.MULTILINE | re.DOTALL) self._metadata = self._metadata.group(1) self.setValid(True) return True except Exception as err: print("Source:{}, Error:{}".format(self.m_source, err)) return False
def get_command(self, argv): """Given CLI arguments, return the Command to use On incorrect invocation, prints out a help message and returns None """ if len(argv) == 0: self.Command.help(outfile=sys.stderr) print >> sys.stderr print >> sys.stderr, 'Error: Command not specified' exit(2) (key, argv) = (argv[0], argv[1:]) name = from_cli(key) if name not in self.Command and len(argv) == 0: try: self.Command.help(unicode(key), outfile=sys.stderr) except HelpError: pass if name not in self.Command or self.Command[name].NO_CLI: raise CommandError(name=key) cmd = self.Command[name] return cmd
def execute(self, cmd, video_output, progress_callback=None, complete_callback=None): if os.path.exists(video_output) and " -y " not in cmd: raise CantOverwrite() cmd = cmd % { "ffmpeg_bin": self._ffmpeg_bin, "input_file": self.original_file.full_filename, "output_file": video_output } if progress_callback: cmd = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE) duration = None header = "" progress_regex = re.compile("frame=.*time=([0-9\:\.]+)", flags=re.IGNORECASE) header_received = False while True: progressline = select.select([cmd.stderr.fileno()], [], [])[0] if progressline: line = cmd.stderr.read() if line == "": if complete_callback: complete_callback() break progress_match = progress_regex.match(line) if progress_match: if not header_received: header_received = True if re.search(".*command\snot\sfound", header, flags=re.IGNORECASE): raise CommandError() if re.search("Unknown format", header, flags=re.IGNORECASE): raise UnknownFormat() if re.search("Duration: N\/A", header, flags=re.IGNORECASE | re.MULTILINE): raise UnreadableFile() raw_duration = re.search( "Duration:\s*([0-9\:\.]+),", header) if raw_duration: units = raw_duration.group(1).split(":") duration = (int(units[0]) * 60 * 60) + \ (int(units[1]) * 60) + \ int(float(units[2])) if duration and progress_callback: progress_callback( float(progress_match.group(1)) * 1000, duration) else: header += line else: cmd = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
def _ifconfig_(cmd): try: return __IFCONFIG__(cmd) except Exception, e: raise CommandError('command "ifconfig %s" gets: %s' % (cmd, str(e)))