go_code.py 34 KB

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