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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import subprocess
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Mapping
from typing import TypeAlias
Version: TypeAlias = tuple[int, ...]
OPTIONS: Mapping[str, tuple[str, Version, Version | None]] = {
"afterends": ("nextword function (Ctrl+Right) stops at word ends", (4, 0), None),
"atblanks": ("Soft wrapping breaks on spaces", (4, 0), None),
"nonewlines": ("Do not ensure final newline", (4, 1), None),
"historylog": ("Remember search history", (4, 0), None),
"linenumbers": ("Show line numbers", (4, 0), None),
"locking": ("Vim-style soft lock files", (4, 0), None),
"mouse": ("Enable mouse", (4, 0), None),
"multibuffer": ("Allow multiple buffers", (4, 0), None),
"positionlog": ("Remember place in file", (4, 0), None),
"quickblank": ("Clear status bar after one keystroke", (4, 0), None),
"regexp": ("Regex search by default", (4, 0), None),
"smarthome": ("Home toggles start of line and start of text", (4, 0), None),
"speller": ("Spelling checker", (4, 0), None),
"suspend": ("Allow suspending", (4, 0), (4, 9)),
"suspendable": ("Allow suspending", (4, 9), (6, 0)),
"tabsize 4": ("Sane tab size", (4, 0), None),
"tabstospaces": ("Convert tabs to spaces", (4, 0), None),
"whitespace": ("Whitespace characters", (4, 0), None),
"zap": ("Let delete/backspace delete selection", (4, 0), None),
"indicator": ("Scrollbar on the right", (5, 0), None),
"minibar": ("Supress title bar and show state at the bottom", (5, 5), None),
"guidestripe 80": ("Show guide stripe", (6, 1), None),
"stateflags": ("Show state in title bar", (5, 3), None),
"magic": ("Fall back to libmagic for syntax choosing", (4, 0), (5, 3)),
}
BINDS: Mapping[str, tuple[str, Version, Version | None]] = {
"suspend main": ("Allow suspending", (6, 0), None),
}
DEFAULT_BINDS: Mapping[str, tuple[str, Version, Version | None]] = {}
def _named_colour(
version: Version,
colour: str,
base16: bool,
) -> str:
"""Based on src/rcfile.c"""
_ansi_8 = [
"red",
"green",
"blue",
"magenta",
"yellow",
"cyan",
"white",
"black",
]
_ansi_16 = [
*_ansi_8,
*(f"light{colour}" for colour in _ansi_8),
*(f"bright{colour}" for colour in _ansi_8),
"grey",
"gray",
]
_named_256 = [
"pink",
"purple",
"mauve",
"lagoon",
"mint",
"lime",
"peach",
"orange",
"latte",
"rosy",
"beet",
"plum",
"sea",
"sky",
"slate",
"teal",
"sage",
"brown",
"ocher",
"sand",
"tawny",
"brick",
"crimson",
"normal",
]
if colour in _named_256:
if base16:
raise ValueError("Fuck off, use base 16 colours")
elif colour not in _ansi_16:
raise ValueError(f"Unknown colour {colour}")
if colour.startswith("light") and version < (5, 0):
colour = f"bright{colour[5:]}"
if colour.startswith("bright") and version >= (5, 0):
colour = f"light{colour[5:]}"
return colour
def _segment(
version: Version,
name: str,
value: str,
base16: bool,
) -> str | None:
# Segment name part
valid = {
"titlecolor": (4, 0),
"statuscolor": (4, 0),
"errorcolor": (4, 0),
"selectedcolor": (4, 0),
"stripecolor": (4, 0),
"numbercolor": (4, 0),
"keycolor": (4, 0),
"functioncolor": (4, 0),
"scrollercolor": (5, 3),
"promptcolor": (5, 5),
"spotlightcolor": (5, 6),
}
if name not in valid:
raise ValueError(f"Unknown segment: {name}")
if version < valid[name]:
return None
if name == "spotlightcolor" and version < (5, 6, 1):
name = "highlightcolor"
# Colour value part
raw_parts = value.split(",")
bold = "bold" in raw_parts
italic = "italic" in raw_parts
fg_bg = [part for part in raw_parts if part != "bold" if part != "italic"]
if len(fg_bg) == 1:
(fg,) = fg_bg
bg = None
else:
fg, bg = fg_bg
parts = []
if version >= (5, 0):
if bold:
parts.append("bold")
if italic:
parts.append("italic")
elif bold:
try:
fg = _named_colour(version, f"bright{fg}", base16)
except ValueError:
pass
parts.append(_named_colour(version, fg, base16) if fg else "")
if bg:
parts.append(_named_colour(version, bg, base16))
value = ",".join(parts)
return f"set {name} {value}"
def _version(string: str) -> Version:
if string.startswith("v"):
string = string[1:]
return tuple(map(int, string.split(".")))
def generate_changes(start_version: Version):
with tempfile.TemporaryDirectory() as temp_dir:
nano_git = Path(temp_dir) / "nano.git"
# Clone repo
subprocess.check_call(
[
"git",
"clone",
"--bare",
"https://git.savannah.gnu.org/git/nano.git",
nano_git,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# Find relevant tags
tags = [
tag
for tag in subprocess.check_output(
[
"git",
"--git-dir",
nano_git,
"tag",
"--list",
],
stderr=subprocess.PIPE,
)
.decode()
.splitlines()
if tag.startswith("v")
if all(map(str.isnumeric, tag[1:].split(".")))
]
# Built a history of changes to the sample configuration
_configs_per_version = []
_versions = []
tracked_config = set()
for tag in sorted(tags, key=_version):
version = _version(tag)
if version < start_version:
continue
nanorc = subprocess.check_output(
["git", "--git-dir", nano_git, "show", f"{tag}:doc/sample.nanorc.in"],
stderr=subprocess.PIPE,
).decode()
config_lines = {
line
for line in nanorc.splitlines()
if line.strip()
if not line.startswith("##")
if line != '" main'
if line != '\x1bu" main'
}
assert all(line.startswith("#") for line in config_lines)
added = config_lines - tracked_config
removed = tracked_config - config_lines
tracked_config = config_lines
if added or removed:
_configs_per_version.append((version, removed, added))
_versions.append(version)
return _versions, _configs_per_version
def generate_config(
version: Version,
config_path: Path,
out_path: Path | None,
base16: bool,
) -> None:
config = json.loads(config_path.read_text())
output = []
# Non-theme options
for option, value in config["set"].items():
if option not in OPTIONS:
raise ValueError(f"Untracked option {option}")
doc, start, stop = OPTIONS[option]
if version >= start and (stop is None or version < stop):
if value is True:
output.extend((f"# {doc}", f"set {option}", ""))
else:
output.extend((f"# {doc}", f'set {option} "{value}"', ""))
# Binds
for key, bind in config["bind"].items():
if bind not in BINDS:
raise ValueError(f"Untracked binding {bind}")
doc, start, stop = BINDS[bind]
if version >= start and (stop is None or version < stop):
output.extend((f"# {doc}", f"bind {key} {bind}", ""))
# Unbinds
for key, _ in config["unbind"].items():
if key not in DEFAULT_BINDS:
raise ValueError(f"Untracked unbinding {key}")
doc, start, stop = DEFAULT_BINDS
if version >= start and (stop is None or version < stop):
output.extend((f"# {doc}", f"unbind {key}", ""))
# Theme
output.append("# Theme")
for name, value in config["theme"].items():
segment = _segment(version, name, value, base16)
if segment:
output.append(segment)
output.append("")
if out_path:
out_path.write_text("\n".join(output))
else:
print("\n".join(output))
def check_updates(
start_version: Version,
last_checked_version: Version,
) -> None:
versions, configs_per_version = generate_changes(start_version)
last_changed_version, _, _ = configs_per_version[-1]
if last_changed_version > last_checked_version:
version_str = ".".join(map(str, last_changed_version))
raise RuntimeError(f"Update for newest version: {version_str}")
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="action")
check_parser = subparsers.add_parser("check")
check_parser.add_argument(
"--start",
type=_version,
default=(4, 0),
)
check_parser.add_argument(
"--last-checked",
type=_version,
default=(7, 2),
)
generate_parser = subparsers.add_parser("generate")
generate_parser.add_argument(
"--version",
type=_version,
default=(7, 2),
)
generate_parser.add_argument(
"--config",
type=Path,
required=True,
)
generate_parser.add_argument(
"--out",
type=Path,
)
generate_parser.add_argument(
"--256-colours",
action="store_false",
default=True,
dest="base16",
)
args = parser.parse_args()
if args.action == "check":
check_updates(args.start, args.last_checked)
elif args.action == "generate":
generate_config(args.version, args.config, args.out, args.base16)
if __name__ == "__main__":
main()
|