1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this,
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5import re
6from compare_locales import mozpath
7
8
9# The local path where we write the config files to
10TARGET_PATH = b"_configs"
11
12
13def process_config(toml_content):
14    """Process TOML configuration content to match the l10n setup for
15    the reference localization, return target_path and content.
16
17    The code adjusts basepath, [[paths]], and [[includes]]
18    """
19    # adjust basepath in content. '.' works in practice, also in theory?
20    new_base = mozpath.relpath(b".", TARGET_PATH)
21    if not new_base:
22        new_base = b"."  # relpath to '.' is '', sadly
23    base_line = b'\nbasepath = "%s"' % new_base
24    content1 = re.sub(br"^\s*basepath\s*=\s*.+", base_line, toml_content, flags=re.M)
25
26    # process [[paths]]
27    start = 0
28    content2 = b""
29    for m in re.finditer(
30        br"\[\[\s*paths\s*\]\].+?(?=\[|\Z)", content1, re.M | re.DOTALL
31    ):
32        content2 += content1[start : m.start()]
33        path_content = m.group()
34        l10n_line = re.search(br"^\s*l10n\s*=.*$", path_content, flags=re.M).group()
35        # remove variable expansions
36        new_reference = re.sub(br"{\s*\S+\s*}", b"", l10n_line)
37        # make the l10n a reference line
38        new_reference = re.sub(br"^(\s*)l10n(\s*=)", br"\1reference\2", new_reference)
39        content2 += re.sub(
40            br"^\s*reference\s*=.*$", new_reference, path_content, flags=re.M
41        )
42        start = m.end()
43    content2 += content1[start:]
44
45    start = 0
46    content3 = b""
47    for m in re.finditer(
48        br"\[\[\s*includes\s*\]\].+?(?=\[|\Z)", content2, re.M | re.DOTALL
49    ):
50        content3 += content2[start : m.start()]
51        include_content = m.group()
52        m_ = re.search(br'^\s*path = "(.+?)"', include_content, flags=re.M)
53        content3 += (
54            include_content[: m_.start(1)]
55            + generate_filename(m_.group(1))
56            + include_content[m_.end(1) :]
57        )
58        start = m.end()
59    content3 += content2[start:]
60
61    return content3
62
63
64def generate_filename(path):
65    segs = path.split(b"/")
66    # strip /locales/ from filename
67    segs = [seg for seg in segs if seg != b"locales"]
68    # strip variables from filename
69    segs = [seg for seg in segs if not seg.startswith(b"{") and not seg.endswith(b"}")]
70    if segs[-1] == b"l10n.toml":
71        segs.pop()
72        segs[-1] += b".toml"
73    outpath = b"-".join(segs)
74    if TARGET_PATH != b".":
75        # prepend the target path, if it's not '.'
76        outpath = mozpath.join(TARGET_PATH, outpath)
77    return outpath
78