summaryrefslogtreecommitdiff
path: root/util/.marauder/marauder/install.py
blob: 3c7b20405eed4c89ba2f455ca959b4b32fe4fdd6 (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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env python3
import re
import csv
import sys


# FIXME 18 Errors - 18/02

def _variable(word):

    def ENV():
        # Easier to parse & handle this way.
        ENV.cc  = '${PKG_TARG}-clang'
        ENV.ld  = '${PKG_TARG}-ld'
        ENV.cxx = '${PKG_TARG}-clang++'
        ENV.cflags  = '${CFLAGS}'
        ENV.ldflags = '${LDFLAGS}'
        ENV.cxxflags = '${CXXFLAGS}'
        ENV.cppflags = '${CPPFLAGS}'
    ENV()

    prefix  = '${PKG_TAPF}'
    man     = '${PKG_TAPF}'  + '/share/man'
    pkgshare = '${PKG_TAPF}' + '/share'
    lib     = '${PKG_TAPF}'  + '/lib'
    share   = '${PKG_TAPF}'   + '/share'

    sysconfig = '/etc'
    bin       = '${PKG_TAPF}' + 'bin'

    # include = '$SDK' + '/usr/include'

    b = ['ENV', 'prefix', 'man', 'pkgshare', 'lib', 'include']

    w = ''.join(word)
    try:
        if not any([x for x in b if w.startswith(x)]):
            return False  # Prevent code execution
        word = eval(w)
    except NameError:
        return False
    except AttributeError:
#        print(f'WARNING: {w} needs to be defined.', file=sys.stderr)
        # raise
        return False

    return word



def _system():
    """ Handles strings like: system "make", "install """

    def _configure():
        nonlocal l
        banned = [#'--disable-debug',
                    '--prefix=',
                    '--man=',
                    '--mandir=',
                    '--localstatedir=',
                    '--sysconfdir=',
                    '--infodir=',
                    '--datadir'
                    '--disable-dependency-tracking',
                    '--disable-debug']
        regex = re.compile(f"{'|'.join(banned)}*")
        track = ''
        for x in l:
            if not any([a for a in x.split() if regex.search(a)]):
                track += f' {x}'

        l = track.strip()
        try:
            conf = re.search('(^.+/configure)', l).group(1)
        except AttributeError:
            # print("ERROR: configure - AttributeError - NoneType has no attribute 'group'", file=sys.stderr)
            conf = l[0]
        if conf == './configure':
            l = l.replace(conf, f"pkg:configure")
        else:
            l = l.replace(conf, f"PKG_CONF={conf} pkg:configure")

    def _make():
        nonlocal l
        l = ' '.join(l)
        l = l.replace('install', 'DESTDIR=${PKG_DEST} install', 1)
#        if  == 'make':  # if the line is just `make`
#            l = l.replace('make', 'pkg:make')  # Hand it to pkg:make for the args

    def _cmake():
        nonlocal l
        l = ' '.join(l)
        l = l.replace(r'*std_cmake_args', r'-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}')


    l = re.sub(r'^system', '', g_line).strip()
    l = list(csv.reader([l], quotechar='"', skipinitialspace=True))[0]

    # Convert #{variable} to a bash variable.
    variable = [k for k, p in enumerate(l) if re.findall(r'#{(?:[A-Za-z0-9.]+)}', p)]
    if variable:
        for p in variable:
            n = re.findall(r'#{([A-Za-z0-9.]+)}', l[p])
            k = _variable(n)
            if not k:
                continue  # _variable() returned False for some reason.
            l[p] = l[p].replace(f"#{{{''.join(n)}}}", f'{k}')

    if 'configure' in l[0]:
        _configure()
    elif 'cmake' in l[0]:
        _cmake()
    elif 'make' in l[0]:
        _make()
    else:
        l = ' '.join(l)

    return l


def _inreplace():
    # TODO: inreplace |s|, let replace be a bash function, so remove any shell characters.
    return -1

def _clean(file):
    """ Cleans up input for parsing """
    file = iter(file)

    def list():
        # FIXME: 2 Formulas will error out here - ['inreplace %w[configure Makefile], for example.
        nonlocal x
        if re.search(r'%[A-Za-z]\[', x):
            track = x
            if x.endswith("]") or '].each' in x:
                return track
            else:
                while True:
                    l = next(file)
                    track += f'{l}'
                    if re.search(r'^\]\.?', l):
                        break
                    track += ' '
            return track
        return False

    def newlines():
        nonlocal x
        if not x.endswith(','):
            return False
        line = x
        l = x
        while True:
            if not line.endswith(','):
                break
            line = next(file)
            l += f' {line}'
        return l

    out = []
    for x in file:
        _list = list()
        if _list:
            out += [_list]
        else:
            _newline = newlines()
            if _newline:
                out += [_newline]
            else:
                out += [x]
    return out


def makesh(file=None):
    try:
        data = _clean(file)
    except StopIteration:
        # print(f'ERROR: parse - StopIteration - {file}', file=sys.stderr)
        return None  # Error
    global g_line  # Global line
    n = []
    for g_line in data:
        if g_line.endswith('if build.head?'):
            continue  # Doesn't support head.
        elif g_line.startswith("system"):
            n += [_system()]
        elif g_line.startswith("mkdir"):
            try:
                cd = re.findall(r'\"(.+?)\"', g_line)[0]
            except IndexError:
                # TODO - Fix index error
                # print("ERROR: parse - IndexError - cd regex failed", file=sys.stderr)
                n += [g_line]
                continue
            n += [re.sub('do$', f'&& cd {cd}', g_line)]
        elif g_line.startswith("cd"):
            n += [re.sub('do$', '', g_line)]
        else:
            n += [g_line]

    return n