aboutsummaryrefslogtreecommitdiff
path: root/tabify-nix.py
blob: 0220ab90b9d43c50441ef31976fbd82602a8bd7a (plain) (blame)
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
#!/usr/bin/env python3
"""Convert nixfmt's 2-space indentation to tabs.

Usage: ./tabify-nix.py [FILE...]   (default: every git-tracked .nix file)

Only lines that start in code are touched. Lines that start inside a string
('' or ") are left exactly as they are, because Nix only strips leading
*spaces* from '' strings, so tabs there would change the string's value.
"""
import subprocess
import sys

INDENT = 2


def lex_line(line, stack):
    """Advance the lexer state `stack` over one line (mutates it in place).

    Stack entries: ["code", brace_depth], ["ind"] (''), ["dq"] ("), ["block"].
    A "code" entry above a string entry is a ${ } interpolation.
    """
    i, n = 0, len(line)
    while i < n:
        mode = stack[-1][0]
        rest = line[i:]
        if mode == "code":
            c = line[i]
            if c == "#":
                return
            if rest.startswith("/*"):
                stack.append(["block"])
                i += 2
            elif c == '"':
                stack.append(["dq"])
                i += 1
            elif rest.startswith("''"):
                stack.append(["ind"])
                i += 2
            elif c == "{":
                stack[-1][1] += 1
                i += 1
            elif c == "}":
                if stack[-1][1] == 0 and len(stack) > 1:
                    stack.pop()  # end of ${ } interpolation
                else:
                    stack[-1][1] -= 1
                i += 1
            else:
                i += 1
        elif mode == "block":
            if rest.startswith("*/"):
                stack.pop()
                i += 2
            else:
                i += 1
        elif mode == "dq":
            if rest.startswith("\\"):
                i += 2
            elif rest.startswith("$${"):
                i += 3
            elif rest.startswith("${"):
                stack.append(["code", 0])
                i += 2
            elif rest.startswith('"'):
                stack.pop()
                i += 1
            else:
                i += 1
        elif mode == "ind":
            if rest.startswith("'''") or rest.startswith("''$"):
                i += 3
            elif rest.startswith("''\\"):
                i += 4
            elif rest.startswith("''"):
                stack.pop()
                i += 2
            elif rest.startswith("$${"):
                i += 3
            elif rest.startswith("${"):
                stack.append(["code", 0])
                i += 2
            else:
                i += 1


def tabify(text):
    stack = [["code", 0]]
    out = []
    for line in text.split("\n"):
        if stack[-1][0] in ("code", "block"):
            stripped = line.lstrip(" \t")
            ws = line[: len(line) - len(stripped)]
            if stripped:
                tabs = ws.count("\t")
                spaces = ws.count(" ")
                line = "\t" * (tabs + spaces // INDENT) + " " * (spaces % INDENT) + stripped
            else:
                line = ""
        out.append(line)
        lex_line(line, stack)
    if stack != [["code", 0]]:
        raise ValueError(f"unbalanced lexer state at EOF: {stack}")
    return "\n".join(out)


def main():
    files = sys.argv[1:] or subprocess.run(
        ["git", "ls-files", "*.nix"], capture_output=True, text=True, check=True
    ).stdout.split()
    failed = False
    for path in files:
        with open(path) as f:
            src = f.read()
        try:
            new = tabify(src)
        except ValueError as e:
            print(f"{path}: {e}, skipped", file=sys.stderr)
            failed = True
            continue
        if new != src:
            with open(path, "w") as f:
                f.write(new)
            print(f"tabified {path}")
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()