go_code.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. #!./kitty/launcher/kitty +launch
  2. # License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
  3. import argparse
  4. import bz2
  5. import io
  6. import json
  7. import os
  8. import re
  9. import shlex
  10. import struct
  11. import subprocess
  12. import sys
  13. import tarfile
  14. from collections.abc import Iterator, Sequence
  15. from contextlib import contextmanager, suppress
  16. from functools import lru_cache
  17. from itertools import chain
  18. from typing import (
  19. Any,
  20. BinaryIO,
  21. Optional,
  22. TextIO,
  23. Union,
  24. )
  25. import kitty.constants as kc
  26. from kittens.tui.operations import Mode
  27. from kittens.tui.spinners import spinners
  28. from kitty.actions import get_all_actions
  29. from kitty.cli import (
  30. CompletionSpec,
  31. GoOption,
  32. go_options_for_seq,
  33. parse_option_spec,
  34. serialize_as_go_string,
  35. )
  36. from kitty.conf.generate import gen_go_code
  37. from kitty.conf.types import Definition
  38. from kitty.config import commented_out_default_config
  39. from kitty.guess_mime_type import known_extensions, text_mimes
  40. from kitty.key_encoding import config_mod_map
  41. from kitty.key_names import character_key_name_aliases, functional_key_name_aliases
  42. from kitty.options.types import Options
  43. from kitty.rc.base import RemoteCommand, all_command_names, command_for_name
  44. from kitty.remote_control import global_options_spec
  45. from kitty.rgb import color_names
  46. if __name__ == '__main__' and not __package__:
  47. import __main__
  48. __main__.__package__ = 'gen'
  49. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  50. changed: list[str] = []
  51. def newer(dest: str, *sources: str) -> bool:
  52. try:
  53. dtime = os.path.getmtime(dest)
  54. except OSError:
  55. return True
  56. for s in chain(sources, (__file__,)):
  57. with suppress(FileNotFoundError):
  58. if os.path.getmtime(s) >= dtime:
  59. return True
  60. return False
  61. # Utils {{{
  62. def serialize_go_dict(x: Union[dict[str, int], dict[int, str], dict[int, int], dict[str, str]]) -> str:
  63. ans = []
  64. def s(x: Union[int, str]) -> str:
  65. if isinstance(x, int):
  66. return str(x)
  67. return f'"{serialize_as_go_string(x)}"'
  68. for k, v in x.items():
  69. ans.append(f'{s(k)}: {s(v)}')
  70. return '{' + ', '.join(ans) + '}'
  71. def replace(template: str, **kw: str) -> str:
  72. for k, v in kw.items():
  73. template = template.replace(k, v)
  74. return template
  75. # }}}
  76. # {{{ Stringer
  77. @lru_cache(maxsize=1)
  78. def enum_parser() -> argparse.ArgumentParser:
  79. p = argparse.ArgumentParser()
  80. p.add_argument('--from-string-func-name')
  81. return p
  82. def stringify_file(path: str) -> None:
  83. with open(path) as f:
  84. src = f.read()
  85. types = {}
  86. constant_name_maps = {}
  87. for m in re.finditer(r'^type +(\S+) +\S+ +// *enum *(.*?)$', src, re.MULTILINE):
  88. args = m.group(2)
  89. types[m.group(1)] = enum_parser().parse_args(args=shlex.split(args) if args else [])
  90. def get_enum_def(src: str) -> None:
  91. type_name = q = ''
  92. constants = {}
  93. for line in src.splitlines():
  94. line = line.strip()
  95. if not line:
  96. continue
  97. parts = line.split()
  98. if not type_name:
  99. if len(parts) < 2 or parts[1] not in types:
  100. return
  101. type_name = parts[1]
  102. q = type_name + '_'
  103. constant_name = parts[0]
  104. a, sep, b = line.partition('//')
  105. if sep:
  106. string_val = b.strip()
  107. else:
  108. string_val = constant_name
  109. if constant_name.startswith(q):
  110. string_val = constant_name[len(q):]
  111. constants[constant_name] = serialize_as_go_string(string_val)
  112. if constants and type_name:
  113. constant_name_maps[type_name] = constants
  114. for m in re.finditer(r'^const +\((.+?)^\)', src, re.MULTILINE|re.DOTALL):
  115. get_enum_def(m.group(1))
  116. with replace_if_needed(path.replace('.go', '_stringer_generated.go')):
  117. print('package', os.path.basename(os.path.dirname(path)))
  118. print ('import "fmt"')
  119. print ('import "encoding/json"')
  120. print()
  121. for type_name, constant_map in constant_name_maps.items():
  122. print(f'func (self {type_name}) String() string ''{')
  123. print('switch self {')
  124. is_first = True
  125. for constant_name, string_val in constant_map.items():
  126. if is_first:
  127. print(f'default: return "{string_val}"')
  128. is_first = False
  129. else:
  130. print(f'case {constant_name}: return "{string_val}"')
  131. print('}}')
  132. print(f'func (self {type_name}) MarshalJSON() ([]byte, error) {{ return json.Marshal(self.String()) }}')
  133. fsname = types[type_name].from_string_func_name or (type_name + '_from_string')
  134. print(f'func {fsname}(x string) (ans {type_name}, err error) ''{')
  135. print('switch x {')
  136. for constant_name, string_val in constant_map.items():
  137. print(f'case "{string_val}": return {constant_name}, nil')
  138. print('}')
  139. print(f'err = fmt.Errorf("unknown value for enum {type_name}: %#v", x)')
  140. print('return')
  141. print('}')
  142. print(f'func (self *{type_name}) SetString(x string) error ''{')
  143. print(f's, err := {fsname}(x); if err == nil {{ *self = s }}; return err''}')
  144. print(f'func (self *{type_name}) UnmarshalJSON(data []byte) (err error)''{')
  145. print('var x string')
  146. print('if err = json.Unmarshal(data, &x); err != nil {return err}')
  147. print('return self.SetString(x)}')
  148. def stringify() -> None:
  149. for path in (
  150. 'tools/tui/graphics/command.go',
  151. 'tools/rsync/algorithm.go',
  152. 'kittens/transfer/ftc.go',
  153. ):
  154. stringify_file(path)
  155. # }}}
  156. # Completions {{{
  157. @lru_cache
  158. def kitten_cli_docs(kitten: str) -> Any:
  159. from kittens.runner import get_kitten_cli_docs
  160. return get_kitten_cli_docs(kitten)
  161. @lru_cache
  162. def go_options_for_kitten(kitten: str) -> tuple[Sequence[GoOption], Optional[CompletionSpec]]:
  163. kcd = kitten_cli_docs(kitten)
  164. if kcd:
  165. ospec = kcd['options']
  166. return (tuple(go_options_for_seq(parse_option_spec(ospec())[0])), kcd.get('args_completion'))
  167. return (), None
  168. def generate_kittens_completion() -> None:
  169. from kittens.runner import all_kitten_names, get_kitten_wrapper_of
  170. for kitten in sorted(all_kitten_names()):
  171. kn = 'kitten_' + kitten
  172. print(f'{kn} := plus_kitten.AddSubCommand(&cli.Command{{Name:"{kitten}", Group: "Kittens"}})')
  173. wof = get_kitten_wrapper_of(kitten)
  174. if wof:
  175. print(f'{kn}.ArgCompleter = cli.CompletionForWrapper("{serialize_as_go_string(wof)}")')
  176. print(f'{kn}.OnlyArgsAllowed = true')
  177. continue
  178. gopts, ac = go_options_for_kitten(kitten)
  179. if gopts or ac:
  180. for opt in gopts:
  181. print(opt.as_option(kn))
  182. if ac is not None:
  183. print(''.join(ac.as_go_code(kn + '.ArgCompleter', ' = ')))
  184. else:
  185. print(f'{kn}.HelpText = ""')
  186. @lru_cache
  187. def clone_safe_launch_opts() -> Sequence[GoOption]:
  188. from kitty.launch import clone_safe_opts, options_spec
  189. ans = []
  190. allowed = clone_safe_opts()
  191. for o in go_options_for_seq(parse_option_spec(options_spec())[0]):
  192. if o.obj_dict['name'] in allowed:
  193. ans.append(o)
  194. return tuple(ans)
  195. def completion_for_launch_wrappers(*names: str) -> None:
  196. for o in clone_safe_launch_opts():
  197. for name in names:
  198. print(o.as_option(name))
  199. def generate_completions_for_kitty() -> None:
  200. print('package completion\n')
  201. print('import "kitty/tools/cli"')
  202. print('import "kitty/tools/cmd/tool"')
  203. print('import "kitty/tools/cmd/at"')
  204. print('func kitty(root *cli.Command) {')
  205. # The kitty exe
  206. print('k := root.AddSubCommand(&cli.Command{'
  207. 'Name:"kitty", SubCommandIsOptional: true, ArgCompleter: cli.CompleteExecutableFirstArg, SubCommandMustBeFirst: true })')
  208. print('kt := root.AddSubCommand(&cli.Command{Name:"kitten", SubCommandMustBeFirst: true })')
  209. print('tool.KittyToolEntryPoints(kt)')
  210. for opt in go_options_for_seq(parse_option_spec()[0]):
  211. print(opt.as_option('k'))
  212. # kitty +
  213. print('plus := k.AddSubCommand(&cli.Command{Name:"+", Group:"Entry points", ShortDescription: "Various special purpose tools and kittens"})')
  214. # kitty +launch
  215. print('plus_launch := plus.AddSubCommand(&cli.Command{'
  216. 'Name:"launch", Group:"Entry points", ShortDescription: "Launch Python scripts", ArgCompleter: complete_plus_launch})')
  217. print('k.AddClone("", plus_launch).Name = "+launch"')
  218. # kitty +list-fonts
  219. print('plus_list_fonts := plus.AddSubCommand(&cli.Command{'
  220. 'Name:"list-fonts", Group:"Entry points", ShortDescription: "List all available monospaced fonts"})')
  221. print('k.AddClone("", plus_list_fonts).Name = "+list-fonts"')
  222. # kitty +runpy
  223. print('plus_runpy := plus.AddSubCommand(&cli.Command{'
  224. 'Name: "runpy", Group:"Entry points", ArgCompleter: complete_plus_runpy, ShortDescription: "Run Python code"})')
  225. print('k.AddClone("", plus_runpy).Name = "+runpy"')
  226. # kitty +open
  227. print('plus_open := plus.AddSubCommand(&cli.Command{'
  228. 'Name:"open", Group:"Entry points", ArgCompleter: complete_plus_open, ShortDescription: "Open files and URLs"})')
  229. print('for _, og := range k.OptionGroups { plus_open.OptionGroups = append(plus_open.OptionGroups, og.Clone(plus_open)) }')
  230. print('k.AddClone("", plus_open).Name = "+open"')
  231. # kitty +kitten
  232. print('plus_kitten := plus.AddSubCommand(&cli.Command{Name:"kitten", Group:"Kittens", SubCommandMustBeFirst: true})')
  233. generate_kittens_completion()
  234. print('k.AddClone("", plus_kitten).Name = "+kitten"')
  235. # @
  236. print('at.EntryPoint(k)')
  237. # clone-in-kitty, edit-in-kitty
  238. print('cik := root.AddSubCommand(&cli.Command{Name:"clone-in-kitty"})')
  239. completion_for_launch_wrappers('cik')
  240. print('}')
  241. print('func init() {')
  242. print('cli.RegisterExeForCompletion(kitty)')
  243. print('}')
  244. # }}}
  245. # rc command wrappers {{{
  246. json_field_types: dict[str, str] = {
  247. 'bool': 'bool', 'str': 'escaped_string', 'list.str': '[]escaped_string', 'dict.str': 'map[escaped_string]escaped_string', 'float': 'float64', 'int': 'int',
  248. 'scroll_amount': 'any', 'spacing': 'any', 'colors': 'any',
  249. }
  250. def go_field_type(json_field_type: str) -> str:
  251. json_field_type = json_field_type.partition('=')[0]
  252. q = json_field_types.get(json_field_type)
  253. if q:
  254. return q
  255. if json_field_type.startswith('choices.'):
  256. return 'string'
  257. if '.' in json_field_type:
  258. p, r = json_field_type.split('.', 1)
  259. p = {'list': '[]', 'dict': 'map[string]'}[p]
  260. return p + go_field_type(r)
  261. raise TypeError(f'Unknown JSON field type: {json_field_type}')
  262. class JSONField:
  263. def __init__(self, line: str, field_to_option_map: dict[str, str], option_map: dict[str, GoOption]) -> None:
  264. field_def = line.split(':', 1)[0]
  265. self.required = False
  266. self.field, self.field_type = field_def.split('/', 1)
  267. self.go_option_name = field_to_option_map.get(self.field, self.field)
  268. self.go_option_name = ''.join(x.capitalize() for x in self.go_option_name.split('_'))
  269. self.omitempty = True
  270. if fo := option_map.get(self.go_option_name):
  271. if fo.type in ('int', 'float') and float(fo.default or 0) != 0:
  272. self.omitempty = False
  273. self.field_type, self.special_parser = self.field_type.partition('=')[::2]
  274. if self.field.endswith('+'):
  275. self.required = True
  276. self.field = self.field[:-1]
  277. self.struct_field_name = self.field[0].upper() + self.field[1:]
  278. def go_declaration(self) -> str:
  279. omitempty = ',omitempty' if self.omitempty else ''
  280. return self.struct_field_name + ' ' + go_field_type(self.field_type) + f'`json:"{self.field}{omitempty}"`'
  281. def go_code_for_remote_command(name: str, cmd: RemoteCommand, template: str) -> str:
  282. template = '\n' + template[len('//go:build exclude'):]
  283. af: list[str] = []
  284. a = af.append
  285. af.extend(cmd.args.as_go_completion_code('ans'))
  286. od: list[str] = []
  287. option_map: dict[str, GoOption] = {}
  288. for o in rc_command_options(name):
  289. option_map[o.go_var_name] = o
  290. a(o.as_option('ans'))
  291. if o.go_var_name in ('NoResponse', 'ResponseTimeout'):
  292. continue
  293. od.append(o.struct_declaration())
  294. jd: list[str] = []
  295. json_fields = []
  296. field_types: dict[str, str] = {}
  297. for line in cmd.protocol_spec.splitlines():
  298. line = line.strip()
  299. if ':' not in line:
  300. continue
  301. f = JSONField(line, cmd.field_to_option_map or {}, option_map)
  302. json_fields.append(f)
  303. field_types[f.field] = f.field_type
  304. jd.append(f.go_declaration())
  305. jc: list[str] = []
  306. handled_fields: set[str] = set()
  307. jc.extend(cmd.args.as_go_code(name, field_types, handled_fields))
  308. unhandled = {}
  309. used_options = set()
  310. for field in json_fields:
  311. if field.go_option_name in option_map:
  312. o = option_map[field.go_option_name]
  313. used_options.add(field.go_option_name)
  314. optstring = f'options_{name}.{o.go_var_name}'
  315. if field.special_parser:
  316. optstring = f'{field.special_parser}({optstring})'
  317. if field.field_type == 'str':
  318. jc.append(f'payload.{field.struct_field_name} = escaped_string({optstring})')
  319. elif field.field_type == 'list.str':
  320. jc.append(f'payload.{field.struct_field_name} = escape_list_of_strings({optstring})')
  321. elif field.field_type == 'dict.str':
  322. jc.append(f'payload.{field.struct_field_name} = escape_dict_of_strings({optstring})')
  323. else:
  324. jc.append(f'payload.{field.struct_field_name} = {optstring}')
  325. elif field.field in handled_fields:
  326. pass
  327. else:
  328. unhandled[field.field] = field
  329. for x in tuple(unhandled):
  330. if x == 'match_window' and 'Match' in option_map and 'Match' not in used_options:
  331. used_options.add('Match')
  332. o = option_map['Match']
  333. field = unhandled[x]
  334. if field.field_type == 'str':
  335. jc.append(f'payload.{field.struct_field_name} = escaped_string(options_{name}.{o.go_var_name})')
  336. else:
  337. jc.append(f'payload.{field.struct_field_name} = options_{name}.{o.go_var_name}')
  338. del unhandled[x]
  339. if unhandled:
  340. raise SystemExit(f'Cant map fields: {", ".join(unhandled)} for cmd: {name}')
  341. if name != 'send_text':
  342. unused_options = set(option_map) - used_options - {'NoResponse', 'ResponseTimeout'}
  343. if unused_options:
  344. raise SystemExit(f'Unused options: {", ".join(unused_options)} for command: {name}')
  345. argspec = cmd.args.spec
  346. if argspec:
  347. argspec = ' ' + argspec
  348. NO_RESPONSE = 'true' if cmd.disallow_responses else 'false'
  349. ans = replace(
  350. template,
  351. CMD_NAME=name, __FILE__=__file__, CLI_NAME=name.replace('_', '-'),
  352. SHORT_DESC=serialize_as_go_string(cmd.short_desc),
  353. LONG_DESC=serialize_as_go_string(cmd.desc.strip()),
  354. IS_ASYNC='true' if cmd.is_asynchronous else 'false',
  355. NO_RESPONSE_BASE=NO_RESPONSE, ADD_FLAGS_CODE='\n'.join(af),
  356. WAIT_TIMEOUT=str(cmd.response_timeout),
  357. OPTIONS_DECLARATION_CODE='\n'.join(od),
  358. JSON_DECLARATION_CODE='\n'.join(jd),
  359. JSON_INIT_CODE='\n'.join(jc), ARGSPEC=argspec,
  360. STRING_RESPONSE_IS_ERROR='true' if cmd.string_return_is_error else 'false',
  361. STREAM_WANTED='true' if cmd.reads_streaming_data else 'false',
  362. )
  363. return ans
  364. # }}}
  365. # kittens {{{
  366. @lru_cache
  367. def wrapped_kittens() -> tuple[str, ...]:
  368. with open('shell-integration/ssh/kitty') as f:
  369. for line in f:
  370. if line.startswith(' wrapped_kittens="'):
  371. val = line.strip().partition('"')[2][:-1]
  372. return tuple(sorted(filter(None, val.split())))
  373. raise Exception('Failed to read wrapped kittens from kitty wrapper script')
  374. def generate_conf_parser(kitten: str, defn: Definition) -> None:
  375. with replace_if_needed(f'kittens/{kitten}/conf_generated.go'):
  376. print(f'package {kitten}')
  377. print(gen_go_code(defn))
  378. def generate_extra_cli_parser(name: str, spec: str) -> None:
  379. print('import "kitty/tools/cli"')
  380. go_opts = tuple(go_options_for_seq(parse_option_spec(spec)[0]))
  381. print(f'type {name}_options struct ''{')
  382. for opt in go_opts:
  383. print(opt.struct_declaration())
  384. print('}')
  385. print(f'func parse_{name}_args(args []string) (*{name}_options, []string, error) ''{')
  386. print(f'root := cli.Command{{Name: `{name}` }}')
  387. for opt in go_opts:
  388. print(opt.as_option('root'))
  389. print('cmd, err := root.ParseArgs(args)')
  390. print('if err != nil { return nil, nil, err }')
  391. print(f'var opts {name}_options')
  392. print('err = cmd.GetOptionValues(&opts)')
  393. print('if err != nil { return nil, nil, err }')
  394. print('return &opts, cmd.Args, nil')
  395. print('}')
  396. def kittens_needing_cli_parsers() -> Iterator[str]:
  397. for d in os.scandir('kittens'):
  398. if not d.is_dir(follow_symlinks=False):
  399. continue
  400. if os.path.exists(os.path.join(d.path, 'main.py')) and os.path.exists(os.path.join(d.path, 'main.go')):
  401. with open(os.path.join(d.path, 'main.py')) as f:
  402. raw = f.read()
  403. if 'options' in raw:
  404. yield d.name
  405. def kitten_clis() -> None:
  406. from kittens.runner import get_kitten_conf_docs, get_kitten_extra_cli_parsers
  407. for kitten in kittens_needing_cli_parsers():
  408. defn = get_kitten_conf_docs(kitten)
  409. if defn is not None:
  410. generate_conf_parser(kitten, defn)
  411. ecp = get_kitten_extra_cli_parsers(kitten)
  412. if ecp:
  413. for name, spec in ecp.items():
  414. with replace_if_needed(f'kittens/{kitten}/{name}_cli_generated.go'):
  415. print(f'package {kitten}')
  416. generate_extra_cli_parser(name, spec)
  417. with replace_if_needed(f'kittens/{kitten}/cli_generated.go'):
  418. od = []
  419. kcd = kitten_cli_docs(kitten)
  420. has_underscore = '_' in kitten
  421. print(f'package {kitten}')
  422. print('import "kitty/tools/cli"')
  423. print('func create_cmd(root *cli.Command, run_func func(*cli.Command, *Options, []string)(int, error)) {')
  424. print('ans := root.AddSubCommand(&cli.Command{')
  425. print(f'Name: "{kitten}",')
  426. if kcd:
  427. print(f'ShortDescription: "{serialize_as_go_string(kcd["short_desc"])}",')
  428. if kcd['usage']:
  429. print(f'Usage: "[options] {serialize_as_go_string(kcd["usage"])}",')
  430. print(f'HelpText: "{serialize_as_go_string(kcd["help_text"])}",')
  431. print('Run: func(cmd *cli.Command, args []string) (int, error) {')
  432. print('opts := Options{}')
  433. print('err := cmd.GetOptionValues(&opts)')
  434. print('if err != nil { return 1, err }')
  435. print('return run_func(cmd, &opts, args)},')
  436. if has_underscore:
  437. print('Hidden: true,')
  438. print('})')
  439. gopts, ac = go_options_for_kitten(kitten)
  440. for opt in gopts:
  441. print(opt.as_option('ans'))
  442. od.append(opt.struct_declaration())
  443. if ac is not None:
  444. print(''.join(ac.as_go_code('ans.ArgCompleter', ' = ')))
  445. if not kcd:
  446. print('specialize_command(ans)')
  447. if has_underscore:
  448. print("clone := root.AddClone(ans.Group, ans)")
  449. print('clone.Hidden = false')
  450. print(f'clone.Name = "{serialize_as_go_string(kitten.replace("_", "-"))}"')
  451. print('}')
  452. print('type Options struct {')
  453. print('\n'.join(od))
  454. print('}')
  455. # }}}
  456. # Constants {{{
  457. def generate_spinners() -> str:
  458. ans = ['package tui', 'import "time"', 'func NewSpinner(name string) *Spinner {', 'var ans *Spinner', 'switch name {']
  459. a = ans.append
  460. for name, spinner in spinners.items():
  461. a(f'case "{serialize_as_go_string(name)}":')
  462. a('ans = &Spinner{')
  463. a(f'Name: "{serialize_as_go_string(name)}",')
  464. a(f'interval: {spinner["interval"]},')
  465. frames = ', '.join(f'"{serialize_as_go_string(x)}"' for x in spinner['frames'])
  466. a(f'frames: []string{{{frames}}},')
  467. a('}')
  468. a('}')
  469. a('if ans != nil {')
  470. a('ans.interval *= time.Millisecond')
  471. a('ans.current_frame = -1')
  472. a('ans.last_change_at = time.Now().Add(-ans.interval)')
  473. a('}')
  474. a('return ans}')
  475. return '\n'.join(ans)
  476. def generate_color_names() -> str:
  477. selfg = "" if Options.selection_foreground is None else Options.selection_foreground.as_sharp
  478. selbg = "" if Options.selection_background is None else Options.selection_background.as_sharp
  479. cursor = "" if Options.cursor is None else Options.cursor.as_sharp
  480. return 'package style\n\nvar ColorNames = map[string]RGBA{' + '\n'.join(
  481. f'\t"{name}": RGBA{{ Red:{val.red}, Green:{val.green}, Blue:{val.blue} }},'
  482. for name, val in color_names.items()
  483. ) + '\n}' + '\n\nvar ColorTable = [256]uint32{' + ', '.join(
  484. f'{x}' for x in Options.color_table) + '}\n' + f'''
  485. var DefaultColors = struct {{
  486. Foreground, Background, Cursor, SelectionFg, SelectionBg string
  487. }}{{
  488. Foreground: "{Options.foreground.as_sharp}",
  489. Background: "{Options.background.as_sharp}",
  490. Cursor: "{cursor}",
  491. SelectionFg: "{selfg}",
  492. SelectionBg: "{selbg}",
  493. }}
  494. '''
  495. def load_ref_map() -> dict[str, dict[str, str]]:
  496. with open('kitty/docs_ref_map_generated.h') as f:
  497. raw = f.read()
  498. raw = raw.split('{', 1)[1].split('}', 1)[0]
  499. data = json.loads(bytes(bytearray(json.loads(f'[{raw}]'))))
  500. return data # type: ignore
  501. def generate_constants() -> str:
  502. from kittens.hints.main import DEFAULT_REGEX
  503. from kittens.query_terminal.main import all_queries
  504. from kitty.colors import ThemeFile
  505. from kitty.config import option_names_for_completion
  506. from kitty.fast_data_types import FILE_TRANSFER_CODE
  507. from kitty.options.utils import allowed_shell_integration_values, url_style_map
  508. del sys.modules['kittens.hints.main']
  509. del sys.modules['kittens.query_terminal.main']
  510. ref_map = load_ref_map()
  511. with open('kitty/data-types.h') as dt:
  512. m = re.search(r'^#define IMAGE_PLACEHOLDER_CHAR (\S+)', dt.read(), flags=re.M)
  513. assert m is not None
  514. placeholder_char = int(m.group(1), 16)
  515. dp = ", ".join(map(lambda x: f'"{serialize_as_go_string(x)}"', kc.default_pager_for_help))
  516. url_prefixes = ','.join(f'"{x}"' for x in Options.url_prefixes)
  517. option_names = '`' + '\n'.join(option_names_for_completion()) + '`'
  518. url_style = {v:k for k, v in url_style_map.items()}[Options.url_style]
  519. query_names = ', '.join(f'"{name}"' for name in all_queries)
  520. return f'''\
  521. package kitty
  522. type VersionType struct {{
  523. Major, Minor, Patch int
  524. }}
  525. const VersionString string = "{kc.str_version}"
  526. const WebsiteBaseURL string = "{kc.website_base_url}"
  527. const FileTransferCode int = {FILE_TRANSFER_CODE}
  528. const ImagePlaceholderChar rune = {placeholder_char}
  529. const SSHControlMasterTemplate = "{kc.ssh_control_master_template}"
  530. const RC_ENCRYPTION_PROTOCOL_VERSION string = "{kc.RC_ENCRYPTION_PROTOCOL_VERSION}"
  531. var VCSRevision string = ""
  532. var IsFrozenBuild string = ""
  533. var IsStandaloneBuild string = ""
  534. const HandleTermiosSignals = {Mode.HANDLE_TERMIOS_SIGNALS.value[0]}
  535. const HintsDefaultRegex = `{DEFAULT_REGEX}`
  536. const DefaultTermName = `{Options.term}`
  537. const DefaultUrlStyle = `{url_style}`
  538. const DefaultUrlColor = `{Options.url_color.as_sharp}`
  539. var Version VersionType = VersionType{{Major: {kc.version.major}, Minor: {kc.version.minor}, Patch: {kc.version.patch},}}
  540. var DefaultPager []string = []string{{ {dp} }}
  541. var FunctionalKeyNameAliases = map[string]string{serialize_go_dict(functional_key_name_aliases)}
  542. var CharacterKeyNameAliases = map[string]string{serialize_go_dict(character_key_name_aliases)}
  543. var ConfigModMap = map[string]uint16{serialize_go_dict(config_mod_map)}
  544. var RefMap = map[string]string{serialize_go_dict(ref_map['ref'])}
  545. var DocTitleMap = map[string]string{serialize_go_dict(ref_map['doc'])}
  546. var AllowedShellIntegrationValues = []string{{ {str(sorted(allowed_shell_integration_values))[1:-1].replace("'", '"')} }}
  547. var QueryNames = []string{{ {query_names} }}
  548. var CommentedOutDefaultConfig = "{serialize_as_go_string(commented_out_default_config())}"
  549. var KittyConfigDefaults = struct {{
  550. Term, Shell_integration, Select_by_word_characters, Url_excluded_characters, Shell string
  551. Wheel_scroll_multiplier int
  552. Url_prefixes []string
  553. }}{{
  554. Term: "{Options.term}", Shell_integration: "{' '.join(Options.shell_integration)}", Url_prefixes: []string{{ {url_prefixes} }},
  555. Select_by_word_characters: `{Options.select_by_word_characters}`, Wheel_scroll_multiplier: {Options.wheel_scroll_multiplier},
  556. Shell: "{Options.shell}", Url_excluded_characters: "{Options.url_excluded_characters}",
  557. }}
  558. const OptionNames = {option_names}
  559. const DarkThemeFileName = "{ThemeFile.dark.value}"
  560. const LightThemeFileName = "{ThemeFile.light.value}"
  561. const NoPreferenceThemeFileName = "{ThemeFile.no_preference.value}"
  562. ''' # }}}
  563. # Boilerplate {{{
  564. @contextmanager
  565. def replace_if_needed(path: str, show_diff: bool = False) -> Iterator[io.StringIO]:
  566. buf = io.StringIO()
  567. origb = sys.stdout
  568. sys.stdout = buf
  569. try:
  570. yield buf
  571. finally:
  572. sys.stdout = origb
  573. orig = ''
  574. with suppress(FileNotFoundError), open(path) as f:
  575. orig = f.read()
  576. new = buf.getvalue()
  577. new = f'// Code generated by {os.path.basename(__file__)}; DO NOT EDIT.\n\n' + new
  578. if orig != new:
  579. changed.append(path)
  580. if show_diff:
  581. with open(path + '.new', 'w') as f:
  582. f.write(new)
  583. subprocess.run(['diff', '-Naurp', path, f.name], stdout=open('/dev/tty', 'w'))
  584. os.remove(f.name)
  585. with open(path, 'w') as f:
  586. f.write(new)
  587. @lru_cache(maxsize=256)
  588. def rc_command_options(name: str) -> tuple[GoOption, ...]:
  589. cmd = command_for_name(name)
  590. return tuple(go_options_for_seq(parse_option_spec(cmd.options_spec or '\n\n')[0]))
  591. def update_at_commands() -> None:
  592. with open('tools/cmd/at/template.go') as f:
  593. template = f.read()
  594. for name in all_command_names():
  595. cmd = command_for_name(name)
  596. code = go_code_for_remote_command(name, cmd, template)
  597. dest = f'tools/cmd/at/cmd_{name}_generated.go'
  598. with replace_if_needed(dest) as f:
  599. f.write(code)
  600. struct_def = []
  601. opt_def = []
  602. for o in go_options_for_seq(parse_option_spec(global_options_spec())[0]):
  603. struct_def.append(o.struct_declaration())
  604. opt_def.append(o.as_option(depth=1, group="Global options"))
  605. sdef = '\n'.join(struct_def)
  606. odef = '\n'.join(opt_def)
  607. code = f'''
  608. package at
  609. import "kitty/tools/cli"
  610. type rc_global_options struct {{
  611. {sdef}
  612. }}
  613. var rc_global_opts rc_global_options
  614. func add_rc_global_opts(cmd *cli.Command) {{
  615. {odef}
  616. }}
  617. '''
  618. with replace_if_needed('tools/cmd/at/global_opts_generated.go') as f:
  619. f.write(code)
  620. def update_completion() -> None:
  621. with replace_if_needed('tools/cmd/completion/kitty_generated.go'):
  622. generate_completions_for_kitty()
  623. with replace_if_needed('tools/cmd/at/kitty_actions_generated.go'):
  624. print("package at")
  625. print("const KittyActionNames = `", end='')
  626. for grp, actions in get_all_actions().items():
  627. for ac in actions:
  628. print(ac.name)
  629. print('`')
  630. with replace_if_needed('tools/cmd/edit_in_kitty/launch_generated.go'):
  631. print('package edit_in_kitty')
  632. print('import "kitty/tools/cli"')
  633. print('func AddCloneSafeOpts(cmd *cli.Command) {')
  634. completion_for_launch_wrappers('cmd')
  635. print(''.join(CompletionSpec.from_string('type:file mime:text/* group:"Text files"').as_go_code('cmd.ArgCompleter', ' = ')))
  636. print('}')
  637. def define_enum(package_name: str, type_name: str, items: str, underlying_type: str = 'uint') -> str:
  638. actions = []
  639. for x in items.splitlines():
  640. x = x.strip()
  641. if x:
  642. actions.append(x)
  643. ans = [f'package {package_name}', 'import "strconv"', f'type {type_name} {underlying_type}', 'const (']
  644. stringer = [f'func (ac {type_name}) String() string ''{', 'switch(ac) {']
  645. for i, ac in enumerate(actions):
  646. stringer.append(f'case {ac}: return "{ac}"')
  647. if i == 0:
  648. ac = ac + f' {type_name} = iota'
  649. ans.append(ac)
  650. ans.append(')')
  651. stringer.append('}\nreturn strconv.Itoa(int(ac)) }')
  652. return '\n'.join(ans + stringer)
  653. def generate_readline_actions() -> str:
  654. return define_enum('readline', 'Action', '''\
  655. ActionNil
  656. ActionBackspace
  657. ActionDelete
  658. ActionMoveToStartOfLine
  659. ActionMoveToEndOfLine
  660. ActionMoveToStartOfDocument
  661. ActionMoveToEndOfDocument
  662. ActionMoveToEndOfWord
  663. ActionMoveToStartOfWord
  664. ActionCursorLeft
  665. ActionCursorRight
  666. ActionEndInput
  667. ActionAcceptInput
  668. ActionCursorUp
  669. ActionHistoryPreviousOrCursorUp
  670. ActionCursorDown
  671. ActionHistoryNextOrCursorDown
  672. ActionHistoryNext
  673. ActionHistoryPrevious
  674. ActionHistoryFirst
  675. ActionHistoryLast
  676. ActionHistoryIncrementalSearchBackwards
  677. ActionHistoryIncrementalSearchForwards
  678. ActionTerminateHistorySearchAndApply
  679. ActionTerminateHistorySearchAndRestore
  680. ActionClearScreen
  681. ActionAddText
  682. ActionAbortCurrentLine
  683. ActionStartKillActions
  684. ActionKillToEndOfLine
  685. ActionKillToStartOfLine
  686. ActionKillNextWord
  687. ActionKillPreviousWord
  688. ActionKillPreviousSpaceDelimitedWord
  689. ActionEndKillActions
  690. ActionYank
  691. ActionPopYank
  692. ActionNumericArgumentDigit0
  693. ActionNumericArgumentDigit1
  694. ActionNumericArgumentDigit2
  695. ActionNumericArgumentDigit3
  696. ActionNumericArgumentDigit4
  697. ActionNumericArgumentDigit5
  698. ActionNumericArgumentDigit6
  699. ActionNumericArgumentDigit7
  700. ActionNumericArgumentDigit8
  701. ActionNumericArgumentDigit9
  702. ActionNumericArgumentDigitMinus
  703. ActionCompleteForward
  704. ActionCompleteBackward
  705. ''')
  706. def generate_mimetypes() -> str:
  707. import mimetypes
  708. if not mimetypes.inited:
  709. mimetypes.init()
  710. ans = ['package utils', 'import "sync"', 'var only_once sync.Once', 'var builtin_types_map map[string]string',
  711. 'func set_builtins() {', 'builtin_types_map = map[string]string{',]
  712. for k, v in mimetypes.types_map.items():
  713. ans.append(f' "{serialize_as_go_string(k)}": "{serialize_as_go_string(v)}",')
  714. ans.append('}}')
  715. return '\n'.join(ans)
  716. def generate_textual_mimetypes() -> str:
  717. ans = ['package utils', 'var KnownTextualMimes = map[string]bool{',]
  718. for k in text_mimes:
  719. ans.append(f' "{serialize_as_go_string(k)}": true,')
  720. ans.append('}')
  721. ans.append('var KnownExtensions = map[string]string{')
  722. for k, v in known_extensions.items():
  723. ans.append(f' ".{serialize_as_go_string(k)}": "{serialize_as_go_string(v)}",')
  724. ans.append('}')
  725. return '\n'.join(ans)
  726. def write_compressed_data(data: bytes, d: BinaryIO) -> None:
  727. d.write(struct.pack('<I', len(data)))
  728. d.write(bz2.compress(data))
  729. def generate_unicode_names(src: TextIO, dest: BinaryIO) -> None:
  730. num_names, num_of_words = map(int, next(src).split())
  731. gob = io.BytesIO()
  732. gob.write(struct.pack('<II', num_names, num_of_words))
  733. for line in src:
  734. line = line.strip()
  735. if line:
  736. a, aliases = line.partition('\t')[::2]
  737. cp, name = a.partition(' ')[::2]
  738. ename = name.encode()
  739. record = struct.pack('<IH', int(cp), len(ename)) + ename
  740. if aliases:
  741. record += aliases.encode()
  742. gob.write(struct.pack('<H', len(record)) + record)
  743. write_compressed_data(gob.getvalue(), dest)
  744. def generate_ssh_kitten_data() -> None:
  745. files = {
  746. 'terminfo/kitty.terminfo', 'terminfo/x/' + Options.term,
  747. }
  748. for dirpath, dirnames, filenames in os.walk('shell-integration'):
  749. for f in filenames:
  750. path = os.path.join(dirpath, f)
  751. files.add(path.replace(os.sep, '/'))
  752. dest = 'tools/tui/shell_integration/data_generated.bin'
  753. def normalize(t: tarfile.TarInfo) -> tarfile.TarInfo:
  754. t.uid = t.gid = 0
  755. t.uname = t.gname = ''
  756. t.mtime = 0
  757. return t
  758. if newer(dest, *files):
  759. buf = io.BytesIO()
  760. with tarfile.open(fileobj=buf, mode='w') as tf:
  761. for f in sorted(files):
  762. tf.add(f, filter=normalize)
  763. with open(dest, 'wb') as d:
  764. write_compressed_data(buf.getvalue(), d)
  765. def start_simdgen() -> 'subprocess.Popen[bytes]':
  766. return subprocess.Popen(['go', 'run', 'generate.go'], cwd='tools/simdstring', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  767. def main(args: list[str]=sys.argv) -> None:
  768. simdgen_process = start_simdgen()
  769. with replace_if_needed('constants_generated.go') as f:
  770. f.write(generate_constants())
  771. with replace_if_needed('tools/utils/style/color-names_generated.go') as f:
  772. f.write(generate_color_names())
  773. with replace_if_needed('tools/tui/readline/actions_generated.go') as f:
  774. f.write(generate_readline_actions())
  775. with replace_if_needed('tools/tui/spinners_generated.go') as f:
  776. f.write(generate_spinners())
  777. with replace_if_needed('tools/utils/mimetypes_generated.go') as f:
  778. f.write(generate_mimetypes())
  779. with replace_if_needed('tools/utils/mimetypes_textual_generated.go') as f:
  780. f.write(generate_textual_mimetypes())
  781. if newer('tools/unicode_names/data_generated.bin', 'tools/unicode_names/names.txt'):
  782. with open('tools/unicode_names/data_generated.bin', 'wb') as dest, open('tools/unicode_names/names.txt') as src:
  783. generate_unicode_names(src, dest)
  784. generate_ssh_kitten_data()
  785. update_completion()
  786. update_at_commands()
  787. kitten_clis()
  788. stringify()
  789. print(json.dumps(changed, indent=2))
  790. stdout, stderr = simdgen_process.communicate()
  791. if simdgen_process.wait() != 0:
  792. print('Failed to generate SIMD ASM', file=sys.stderr)
  793. sys.stdout.buffer.write(stdout)
  794. sys.stderr.buffer.write(stderr)
  795. raise SystemExit(simdgen_process.returncode)
  796. if __name__ == '__main__':
  797. import runpy
  798. m = runpy.run_path(os.path.dirname(os.path.abspath(__file__)))
  799. m['main']([sys.executable, 'go-code'])
  800. # }}}