summaryrefslogtreecommitdiff
path: root/vish.py
blob: ec601a0b4fe79dfe954400fb43479f48abf9d5ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3

import os
import re
import argparse

IFS = (" ", "\t", "\n")


class EOFException(Exception):
    pass


class Argument():
    def __init__(self, value: str, allow_expansion=True):
        pass

    def expand():
        pass


class Pipeline():
    def __init__(self, instructions: list=[]):
        self.instructions = instructions

    def execute(self):
        for instruction in self.instructions:
            instruction.execute()


class Instruction():
    def __init__(self, tokens: list=[]):
        self.prog = tokens[0]
        self.args = tokens[1:]


    def execute(self):
        cpid = os.fork()
        if cpid == 0:
            os.execvp(self.prog, [self.prog] + self.args)
        else:
            os.waitpid(cpid, 0)


class PipelineParser():
    def read_escaped(self, string_iterator):
        return next(string_iterator)

    def read_literal(self, string_iterator):
        literal = ""
        while True:
            c = next(string_iterator)
            if c != "'":
                literal += c
            else:
                return literal

    def read_quoted(self, string_iterator):
        # TODO handle substitutions
        quoted = ""
        while True:
            c = next(string_iterator)
            if c == "\\":
                quoted += self.read_escaped(string_iterator)
            elif c != '"':
                quoted += c
            else:
                return quoted


    def get_next_token(self, string_iterator):
        token = None
        while True:
            try:
                c = next(string_iterator)
            except StopIteration:
                break

            # Skip leading whitespaces
            if token is None and c in IFS:
                continue
            elif token is None:
                token = ""

            if c == "'":
                token += self.read_literal(string_iterator)
            elif c == "\\":
                token += self.read_escaped(string_iterator)
            elif c == "\"":
                token += self.read_quoted(string_iterator)
            elif c in IFS:
                return token
            else:
                token += c

        return token

    def tokenize(self, string_iterator):
        while True:
            token = self.get_next_token(string_iterator)
            if token is None:
                break
            yield token

    def parse(self, line):
        tokens = list(self.tokenize(iter(line)))
        return Pipeline([Instruction(tokens)])


def read_next_pipeline(fh):
    # TODO Support multiple pipelines per line
    # TODO Support instructions spawning multiple lines

    parser = PipelineParser()

    while True:
        line = fh.readline()
        if line == "":
            raise EOFException()

        line = line.strip()
        # We ignore empty lines and lines which start with #
        if not line.startswith("#") and not line == "":
            break

    return parser.parse(line)


def main(arguments):
    for script in arguments["<script>"]:
        with open(script, mode="r", encoding="utf-8") as fh:
            while True:
                try:
                    pipeline = read_next_pipeline(fh)
                    pipeline.execute()

                except EOFException:
                    break

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Command interpreter written in Python.")
    parser.add_argument("<script>", action="store", nargs="+", help="Script to run")
    args = parser.parse_args()
    main(vars(args))