File size: 12,862 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""Build the seed project: an existing-looking Python project the mission maintains.

The project is composed from the same catalog shapes so that every request in
tools/run_maintenance.py has a real target. It is checked in, and this tool reproduces it
byte for byte (--check verifies).
"""

import argparse
import json
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)

SEED = os.path.join(ROOT, "fixtures", "seed_project")

MODULES = {
    "inventory": ("def stock(items=[]):\n"
                  "    cleaned = []\n"
                  "    for item in items:\n"
                  "        cleaned.append(item.strip())\n"
                  "    return cleaned\n\n"
                  "def badge(qty: int):\n"
                  "    total = qty + 255\n"
                  "    return 'x' + str(total)\n\n"
                  "def reserve(order):\n"
                  "    if isinstance(order, dict):\n"
                  "        return order.get('id')\n"
                  "    return None\n\n"
                  "def load_rows(text):\n"
                  "    rows = []\n"
                  "    for line in text.splitlines():\n"
                  "        rows.append(line.split(','))\n"
                  "    return rows\n"),
    "billing": ("import json\n"
                "import os\n\n"
                "def price(lines=[]):\n"
                "    total = 0\n"
                "    for line in lines:\n"
                "        total = total + line['qty']\n"
                "    return total\n\n"
                "def invoice(customer, amount):\n"
                "    return customer + ' owes ' + str(amount)\n\n"
                "def refund(payment):\n"
                "    if payment.get('paid'):\n"
                "        return payment.get('amount')\n"
                "    return 0\n"),
    "routing": ("def pick(candidates=[]):\n"
                "    best = []\n"
                "    for c in candidates:\n"
                "        best.append(c[0])\n"
                "    return best\n\n"
                "def latency(ms: int):\n"
                "    return ms * 1000\n\n"
                "def choose(route):\n"
                "    if route.get('open'):\n"
                "        return route['name']\n"
                "    return ''\n\n"
                "def label(node):\n"
                "    return 'node ' + node['id']\n"),
    "reporting": ("import re\n"
                  "import time\n\n"
                  "def rows(data=[]):\n"
                  "    out = []\n"
                  "    for d in data:\n"
                  "        out.append(d['k'])\n"
                  "    return out\n\n"
                  "def stamp(sec: int):\n"
                  "    return sec + 3600\n\n"
                  "def title(row):\n"
                  "    return 'row ' + str(row['n'])\n\n"
                  "def keep(doc):\n"
                  "    if doc.get('live'):\n"
                  "        return True\n"
                  "    return False\n"),
    "session": ("import base64\n"
                "import uuid\n\n"
                "def tokens(parts=[]):\n"
                "    joined = []\n"
                "    for p in parts:\n"
                "        joined.append(p.lower())\n"
                "    return joined\n\n"
                "def ttl(minutes: int):\n"
                "    return minutes * 60\n\n"
                "def bind(user):\n"
                "    if user.get('verified'):\n"
                "        return user.get('id')\n"
                "    return None\n\n"
                "def tag(user):\n"
                "    return 'user ' + user['id']\n"),
    "search": ("def ranks(scores=[]):\n"
               "    top = []\n"
               "    for s in scores:\n"
               "        top.append(s['id'])\n"
               "    return top\n\n"
               "def weight(pos: int):\n"
               "    return pos + 50\n\n"
               "def scope(index):\n"
               "    if index.get('ready'):\n"
               "        return index['name']\n"
               "    return ''\n\n"
               "def caption(hit):\n"
               "    return hit['title'] + ' (' + hit['kind'] + ')'\n"),
    "cache": ("import hashlib\n"
              "import time\n\n"
              "def memo(items=[]):\n"
              "    keys = []\n"
              "    for item in items:\n"
              "        keys.append(item[0])\n"
              "    return keys\n\n"
              "def expiry(hours: int):\n"
              "    return hours * 86400\n\n"
              "def touch(entry):\n"
              "    if entry.get('warm'):\n"
              "        return entry['key']\n"
              "    return ''\n\n"
              "def mark(entry):\n"
              "    return 'key ' + entry['key']\n"),
    "auth": ("def scopes(roles=[]):\n"
             "    names = []\n"
             "    for role in roles:\n"
             "        names.append(role.lower())\n"
             "    return names\n\n"
             "def window(days: int):\n"
             "    return days * 24\n\n"
             "def permit(ticket):\n"
             "    if ticket.get('valid'):\n"
             "        return ticket.get('who')\n"
             "    return None\n\n"
             "def whois(ticket):\n"
             "    return 'who ' + ticket['who']\n"),
    "jobqueue": ("import heapq\n"
              "import os\n\n"
              "def drain(jobs=[]):\n"
              "    names = []\n"
              "    for job in jobs:\n"
              "        names.append(job['id'])\n"
              "    return names\n\n"
              "def retry(seconds: int):\n"
              "    return seconds + 30\n\n"
              "def head(task):\n"
              "    if task.get('queued'):\n"
              "        return task['id']\n"
              "    return None\n\n"
              "def line(task):\n"
              "    return task['id'] + ' @ ' + task['at']\n"),
    "export": ("def columns(rows_=[]):\n"
               "    names = []\n"
               "    for row in rows_:\n"
               "        names.append(row[0])\n"
               "    return names\n\n"
               "def limit(rows_n: int):\n"
               "    return rows_n * 500\n\n"
               "def ready(sheet):\n"
               "    if sheet.get('built'):\n"
               "        return sheet['name']\n"
               "    return ''\n\n"
               "def name(sheet):\n"
               "    return 'sheet ' + sheet['name']\n"),
}

TESTS = {
    "inventory": ("from inventory import badge, load_rows, reserve, stock\n\n"
                  "def test_stock_strips():\n"
                  "    assert stock([' a ', 'b']) == ['a', 'b']\n\n"
                  "def test_badge():\n"
                  "    assert badge(1) == 'x256'\n\n"
                  "def test_reserve():\n"
                  "    assert reserve({'id': 3}) == 3\n\n"
                  "def test_load_rows():\n"
                  "    assert load_rows('a,b\\nc') == [['a', 'b'], ['c']]\n"),
    "billing": ("from billing import invoice, price, refund\n\n"
                "def test_price():\n"
                "    assert price([{'qty': 2}, {'qty': 1}]) == 3\n\n"
                "def test_invoice():\n"
                "    assert invoice('acme', 4) == 'acme owes 4'\n\n"
                "def test_refund():\n"
                "    assert refund({'paid': True, 'amount': 9}) == 9\n"),
    "routing": ("from routing import choose, label, latency, pick\n\n"
                "def test_pick():\n"
                "    assert pick([('a', 1), ('b', 2)]) == ['a', 'b']\n\n"
                "def test_latency():\n"
                "    assert latency(2) == 2000\n\n"
                "def test_choose():\n"
                "    assert choose({'open': True, 'name': 'n1'}) == 'n1'\n\n"
                "def test_label():\n"
                "    assert label({'id': 'z'}) == 'node z'\n"),
    "reporting": ("from reporting import keep, rows, stamp, title\n\n"
                  "def test_rows():\n"
                  "    assert rows([{'k': 'a'}]) == ['a']\n\n"
                  "def test_stamp():\n"
                  "    assert stamp(10) == 3610\n\n"
                  "def test_title():\n"
                  "    assert title({'n': 2}) == 'row 2'\n\n"
                  "def test_keep():\n"
                  "    assert keep({'live': True}) is True\n"),
    "session": ("from session import bind, tag, tokens, ttl\n\n"
                "def test_tokens():\n"
                "    assert tokens(['A', 'B']) == ['a', 'b']\n\n"
                "def test_ttl():\n"
                "    assert ttl(2) == 120\n\n"
                "def test_bind():\n"
                "    assert bind({'verified': True, 'id': 7}) == 7\n\n"
                "def test_tag():\n"
                "    assert tag({'id': 'q'}) == 'user q'\n"),
    "search": ("from search import caption, ranks, scope, weight\n\n"
               "def test_ranks():\n"
               "    assert ranks([{'id': 'a'}]) == ['a']\n\n"
               "def test_weight():\n"
               "    assert weight(3) == 53\n\n"
               "def test_scope():\n"
               "    assert scope({'ready': True, 'name': 'i'}) == 'i'\n\n"
               "def test_caption():\n"
               "    assert caption({'title': 't', 'kind': 'k'}) == 't (k)'\n"),
    "cache": ("from cache import expiry, mark, memo, touch\n\n"
              "def test_memo():\n"
              "    assert memo([('a',), ('b',)]) == ['a', 'b']\n\n"
              "def test_expiry():\n"
              "    assert expiry(2) == 172800\n\n"
              "def test_touch():\n"
              "    assert touch({'warm': True, 'key': 'k'}) == 'k'\n\n"
              "def test_mark():\n"
              "    assert mark({'key': 'z'}) == 'key z'\n"),
    "auth": ("from auth import permit, scopes, whois, window\n\n"
             "def test_scopes():\n"
             "    assert scopes(['A']) == ['a']\n\n"
             "def test_window():\n"
             "    assert window(3) == 72\n\n"
             "def test_permit():\n"
             "    assert permit({'valid': True, 'who': 'u'}) == 'u'\n\n"
             "def test_whois():\n"
             "    assert whois({'who': 'u'}) == 'who u'\n"),
    "jobqueue": ("from jobqueue import drain, head, line, retry\n\n"
              "def test_drain():\n"
              "    assert drain([{'id': 'j'}]) == ['j']\n\n"
              "def test_retry():\n"
              "    assert retry(5) == 35\n\n"
              "def test_head():\n"
              "    assert head({'queued': True, 'id': 'j'}) == 'j'\n\n"
              "def test_line():\n"
              "    assert line({'id': 'j', 'at': '9'}) == 'j @ 9'\n"),
    "export": ("from export import columns, limit, name, ready\n\n"
               "def test_columns():\n"
               "    assert columns([('a',), ('b',)]) == ['a', 'b']\n\n"
               "def test_limit():\n"
               "    assert limit(2) == 1000\n\n"
               "def test_ready():\n"
               "    assert ready({'built': True, 'name': 's'}) == 's'\n\n"
               "def test_name():\n"
               "    assert name({'name': 's'}) == 'sheet s'\n"),
}

CONFTEST = ("import os\nimport sys\n\n"
            "sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n")


def files() -> dict:
    out = {"conftest.py": CONFTEST, "README.md":
           "Seed project for the maintenance mission. Every module carries at least one\n"
           "shape listed in the catalog; the tests are the safety net the executor runs.\n"}
    for name, body in MODULES.items():
        out[name + ".py"] = body
    for name, body in TESTS.items():
        out[os.path.join("tests", "test_%s.py" % name)] = body
    return out


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="Build the seed project.")
    parser.add_argument("--check", action="store_true")
    args = parser.parse_args(argv)

    wanted = files()
    if args.check:
        missing = []
        for rel, text in wanted.items():
            path = os.path.join(SEED, rel)
            if not os.path.isfile(path):
                missing.append(rel + " missing")
            elif open(path, "r", encoding="utf-8").read() != text:
                missing.append(rel + " differs")
        print("seed=%s files=%d issues=%d %s"
              % ("PASS" if not missing else "FAIL", len(wanted), len(missing),
                 "; ".join(missing[:5])))
        return 0 if not missing else 1

    for rel, text in wanted.items():
        path = os.path.join(SEED, rel)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(text)
    print(json.dumps({"wrote": len(wanted)}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())