about summary refs log tree commit diff
path: root/scripts/wire-listing.py
blob: 3170106cf855a7852664b744b37f878278c5261e (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
#!/usr/bin/env python3
# Mechanical first pass at wiring src/listing.rs into the six listing handlers.
# It changed 3 of 6 (groups, group_strains, group_traits) before the return-type
# rewrite needed hand care; see the module docs in src/listing.rs for the plan.
"""Wire the listing shape into the six listing handlers, mechanically.

Per handler: add the three query fields, change the utoipa `body =` type and
the return type to Envelope<serde_json::Value>, and shape the rows where the
envelope is built.
"""
import re, sys

def field_block(indent):
    i = ' ' * indent
    return (f"\n{i}/// Keep only these ids or names, comma-separated.\n{i}#[serde(default)]\n{i}pub limit_to: Option<String>,\n"
            f"{i}/// Answer with one id per row instead of objects.\n{i}#[serde(default)]\n{i}pub ids_only: Option<bool>,\n"
            f"{i}/// Answer with one name per row instead of objects.\n{i}#[serde(default)]\n{i}pub names_only: Option<bool>,\n")

def shape(rows_expr, ind, params_name='params'):
    i = ' ' * ind
    return (f"let listing = crate::listing::Listing::parse(&crate::listing::ListingParams {{\n"
            f"{i}    limit_to: {params_name}.limit_to.clone(),\n"
            f"{i}    ids_only: {params_name}.ids_only,\n"
            f"{i}    names_only: {params_name}.names_only,\n"
            f"{i}}})\n"
            f"{i}.map_err(|detail| crate::listing::refuse(detail, &listing_rid, \"{op}\"))?;\n"
            f"{i}let rows = serde_json::to_value({rows_expr}).unwrap_or(serde_json::Value::Null);\n"
            f"{i}let (shaped, missing) = listing.apply(&rows, {params_name}.limit_to.as_deref());\n")

handlers = [
    # file, handler fn, struct to extend, params type name, rows variable, operation id
    ('src/routes/groups.rs', 'groups', 'GroupsParams', 'groups', 'groups'),
    ('src/routes/groups.rs', 'group_strains', 'GroupStrainsParams', 'strains', 'group_strains'),
    ('src/routes/groups.rs', 'group_datasets', 'GroupDatasetsParams', 'datasets', 'group_datasets'),
    ('src/routes/groups.rs', 'group_traits', 'GroupTraitsParams', 'traits', 'group_traits'),
    ('src/routes/datasets.rs', 'dataset_probesets', 'DatasetProbesetsParams', 'probesets', 'dataset_probesets'),
    ('src/routes/traits.rs', 'traits', 'TraitsParams', 'traits', 'dataset_traits'),
]
status = []
for path, handler, params, rows_var, op in handlers:
    s = open(path).read()
    before = s
    # 1. add the fields to the params struct
    m = re.search(r'pub struct %s \{(.*?)\n\}' % params, s, re.S)
    if not m:
        status.append(f'{handler}: params struct {params} NOT FOUND')
        continue
    if 'pub limit_to' not in m.group(0):
        s = s.replace(m.group(0), m.group(0)[:-2] + field_block(4) + '}', 1)
    # 2. body= type in the handler's utoipa block (the one nearest above the fn)
    idx = s.index('pub async fn %s(' % handler)
    head = s[:idx]
    cut = head.rfind('body = Envelope<Vec<')
    if cut == -1:
        status.append(f'{handler}: no body= to change')
    else:
        end = head.index('>', cut) + 1
        s = head[:cut] + 'body = Envelope<serde_json::Value>' + head[end:] + s[idx:]
    # 3. return type
    s = re.sub(r'(pub async fn %s\([^)]*?\) -> Result<Json<Envelope<Vec<[^>]*>>, ApiError>)' % handler,
               lambda mm: mm.group(1).replace('Envelope<Vec<', 'Envelope<serde_json::Value>[').split('Envelope<serde_json::Value>[')[0]
                          + 'Envelope<serde_json::Value>>, ApiError>', s, count=1, flags=re.S)
    open(path, 'w').write(s)
    status.append(f'{handler}: {"changed" if s != before else "UNCHANGED"}')
print('\n'.join(status))