summaryrefslogtreecommitdiff
path: root/vish.py
blob: 8d8f6e14630f77e2170d41d25109bc18531b7644 (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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3

import os
import re
import argparse
import sys

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=[], stdout=None, stderr=None):
        self.prog = tokens[0]
        self.args = tokens[1:]
        self.stdout = stdout
        self.stderr = stderr


    def execute(self):
        cpid = os.fork()
        if cpid == 0:
            if self.stdout is not None:
                fd = os.open(self.stdout, os.O_WRONLY)
                os.dup2(sys.stdout.fileno(), fd)
            if self.stderr is not None:
                fd = os.open(self.stderr, os.O_WRONLY)
                os.dup2(sys.stderr.fileno(), fd)

            os.execvp(self.prog, [self.prog] + self.args)
        else:
            _, status = os.waitpid(cpid, 0)
            return status


class AndInstruction(Instruction):
    def __init__(self, instruction1: Instruction, instruction2: Instruction):
        self.instruction1 = instruction1
        self.instruction2 = instruction2

    def execute(self):
        status = self.instruction1.execute()
        if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0:
            return self.instruction2.execute()


class OrInstruction(Instruction):
    def __init__(self, instruction1: Instruction, instruction2: Instruction):
        self.instruction1 = instruction1
        self.instruction2 = instruction2

    def execute(self):
        status = self.instruction1.execute()
        if not os.WIFEXITED(status) or not os.WEXITSTATUS(status) == 0:
            return self.instruction2.execute()


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))