예제 #1
0
 def test_variables_assign(self):
     HEADING("assign key=value")
     v = Variables()
     n = len(v)
     v["gregor"] = "gregor"
     assert (len(v) == n + 1)
     assert "gregor" in v
     v.close()
예제 #2
0
    def test_test_variable_remove(self):
        HEADING("directory and key subtract ")
        d = {"a": "1", "b": "2"}
        v = Variables()
        v + d
        print(v)
        assert "a" in v and "b" in v
        v - d.keys()
        assert "a" not in v and "b" not in v

        print(v)
        v.close()
예제 #3
0
    def postcmd(self, stop, line):
        StopWatch.stop("command")

        try:
            variable = Variables()
            if "timer" not in variable:
                variable["timer"] = "False"
            if str(variable["timer"].lower()) in ['on', 'true']:
                print("Timer: {:.4f}s ({})".format(StopWatch.get("command"),
                                                   line.strip()))
            variable.close()
        except Exception as e:
            Error.traceback(error=e)

        return stop
예제 #4
0
    def test_variables_add(self):
        HEADING("directory add ")
        d = {"a": "1", "b": "2"}
        v = Variables()
        v + d
        print(v)
        assert "a" in v and "b" in v
        del v["a"]
        del v["b"]

        v + d
        assert "a" in v and "b" in v
        v - d
        assert "a" not in v and "b" not in v

        print(v)
        v.close()
예제 #5
0
    def postcmd(self, stop, line):
        StopWatch.stop("command")

        try:
            variable = Variables()
            if "timer" not in variable:
                variable["timer"] = "False"
            if str(variable["timer"].lower()) in ['on', 'true']:
                command_time = StopWatch.get("command")
                load_time = StopWatch.get("load")
                line_strip = line.strip()
                print(f"# Timer: {command_time:.4f}s "
                      f"Load: {load_time:.4f}s "
                      f"{line_strip}")
            variable.close()
        except Exception as e:
            Error.traceback(error=e)

        return stop
예제 #6
0
    def replace_vars(self, line):

        # self.update_time()

        variable = Variables()
        newline = line

        if len(variable) is not None:
            for name in variable.data:
                value = str(variable[name])
                newline = newline.replace("$" + name, value)
                newline = newline.replace("var." + name, value)
            for v in os.environ:
                name = v.replace('os.', '')
                if name in newline:
                    value = os.environ[name]
                    newline = newline.replace("os." + v, value)

            default = Default()
            if default is not None:
                for v in default.data:
                    name = "default." + v.replace(",", ".")
                    value = default.data[v]
                    if name in newline:
                        newline = newline.replace(name, value)

                # replace if global is missing

                global_default = default["global"]
                if global_default is not None:
                    for v in global_default:
                        name = "default." + v
                        value = global_default[v]
                        if name in newline:
                            newline = newline.replace(name, value)

            default.close()
            variable.close()

        newline = path_expand(newline)
        return line, newline
예제 #7
0
 def test_variables_delete(self):
     HEADING("delete")
     v = Variables()
     del v["gregor"]
     assert "gregor" not in v
     v.close()
예제 #8
0
    def onecmd(self, line):
        """Interpret the argument as though it had been typed in response
        to the prompt.

        This may be overridden, but should not normally need to be;
        see the precmd() and postcmd() methods for useful execution hooks.
        The return value is a flag indicating whether interpretation of
        commands by the interpreter should stop.

        """
        oldline, line = self.replace_vars(line)

        # -----------------------------
        # print comment lines, but do not execute them
        # -----------------------------
        if line.startswith('#') or line.startswith('//') or line.startswith(
                '/*'):
            print(line)
            return ""

        if line.startswith('!'):
            os.system(line[1:])

            return ""
        # if line is None:
        #    return ""

        # if line.startswith("!"):
        #    line.replace("!", "! ")
        # line = self.var_replacer(line)
        # if line != "hist" and line:
        #    self._hist += [line.strip()]
        # if line.startswith("!") or line.startswith("shell"):
        #    self.do_shell_exec(line[1:])
        #    return ""
        cmd, arg, line = self.parseline(line)

        if line.startswith("$") or line.startswith('var.'):
            line = line.replace("$", "", 1)
            line = line.replace("var.", "", 1)
            print("FIND>", line, "<", sep='')
            variable = Variables()
            print(variable[line])
            variable.close()
            return ""

        # -----------------------------
        # handle empty line
        # -----------------------------
        if not line:
            return self.emptyline()

        # -----------------------------
        # handle file execution
        # -----------------------------
        #
        # this does not yet work
        #
        # if os.path.isfile(line):
        #    print ("... execute", line)
        #    self.do_exec(line)
        #    return ""

        if cmd != '':

            if cmd in ['dryrun']:
                variables = Variables()
                if arg.startswith("="):
                    arg = arg[1:]
                try:
                    value = arg
                    if arg == "":
                        print("dryrun=", variables['dryrun'], sep="")
                    else:
                        variables.boolean("dryrun", value)
                except IndexError:
                    Console.error("value for dryrun is missing")
                except Exception as e:
                    print(e)

                return ""
            elif cmd in ['debug']:
                if arg.startswith("="):
                    arg = arg[1:]
                try:
                    value = arg
                    if arg == "":
                        variables = Variables()
                        print("debug=", variables['debug'], sep="")
                    else:
                        self.set_debug(value)
                except IndexError:
                    Console.error("value for dryrun is missing")
                except Exception as e:
                    print(e)

                return ""

            try:
                func = getattr(self, 'do_' + cmd)
                return func(arg)

            except AttributeError as e:

                variables = Variables()

                if variables['trace'] is None:
                    variables['trace'] = "False"
                    trace = False
                else:
                    trace = "T" in variables['trace']

                if variables['debug'] is None:
                    variables['debug'] = "False"
                    debug = False
                else:
                    debug = "T" in variables['debug']

                command_missing = "'CMShell' object has no attribute 'do_{cmd}'".format(
                    cmd=cmd)

                if e.args[0] == command_missing:
                    Console.error(
                        "this command does not exist: '{cmd}'".format(cmd=cmd),
                        traceflag=False)
                else:
                    Error.traceback(error=e, debug=debug, trace=trace)

                # noinspection PyUnusedLocal
                cmd = None
                line = oldline

        return ""