more work on porting command parsing to Go

This commit is contained in:
Kovid Goyal 2022-08-30 20:30:25 +05:30
parent 6f4968305a
commit a4b2e2a196
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
7 changed files with 29 additions and 12 deletions

View File

@ -49,7 +49,7 @@ def replace(template: str, **kw: str) -> str:
json_field_types: Dict[str, str] = { json_field_types: Dict[str, str] = {
'bool': 'bool', 'str': 'string', 'list.str': '[]string', 'dict.str': 'map[string]string', 'float': 'float64', 'int': 'int', 'bool': 'bool', 'str': 'string', 'list.str': '[]string', 'dict.str': 'map[string]string', 'float': 'float64', 'int': 'int',
'scroll_amount': '[2]interface{}', 'spacing': 'interface{}', 'colors': 'interface{}', 'scroll_amount': 'interface{}', 'spacing': 'interface{}', 'colors': 'interface{}',
} }
@ -124,10 +124,7 @@ def build_go_code(name: str, cmd: RemoteCommand, seq: OptionSpecSeq, template: s
jd.append(f.go_declaration()) jd.append(f.go_declaration())
jc: List[str] = [] jc: List[str] = []
handled_fields: Set[str] = set() handled_fields: Set[str] = set()
try: jc.extend(cmd.args.as_go_code(name, field_types, handled_fields))
jc.extend(cmd.args.as_go_code(name, field_types, handled_fields))
except TypeError:
print(f'Cant parse args for cmd: {name}', file=sys.stderr)
for field in json_fields: for field in json_fields:
if field.field in option_map: if field.field in option_map:
@ -137,7 +134,6 @@ def build_go_code(name: str, cmd: RemoteCommand, seq: OptionSpecSeq, template: s
pass pass
else: else:
print(f'Cant map field: {field.field} for cmd: {name}', file=sys.stderr) print(f'Cant map field: {field.field} for cmd: {name}', file=sys.stderr)
print('TODO: test set_window_logo, set_window_background, set_font_size, send_text, env, scroll_window', file=sys.stderr)
argspec = cmd.args.spec argspec = cmd.args.spec
if argspec: if argspec:
@ -232,6 +228,7 @@ def update_at_commands() -> None:
os.remove(dest) os.remove(dest)
with open(dest, 'w') as f: with open(dest, 'w') as f:
f.write(code) f.write(code)
print('TODO: test set_window_logo, set_window_background, set_font_size, send_text, env, scroll_window', file=sys.stderr)
def main() -> None: def main() -> None:

View File

@ -193,12 +193,13 @@ class ArgsHandling:
yield f'args = append(args, "{x}")' yield f'args = append(args, "{x}")'
yield '}' yield '}'
if self.minimum_count > -1: if self.minimum_count > -1:
yield f'if len(args) < {self.minimum_count} {{ return fmt.Errorf("%s", Must specify at least {self.minimum_count} arguments to {cmd_name}) }}' yield f'if len(args) < {self.minimum_count} {{ return fmt.Errorf("%s", "Must specify at least {self.minimum_count} arguments to {cmd_name}") }}'
if self.args_choices: if self.args_choices:
achoices = tuple(self.args_choices()) achoices = tuple(self.args_choices())
yield 'achoices := map[string]bool{' + ' '.join(f'"{x}":true,' for x in achoices) + '}' yield 'achoices := map[string]bool{' + ' '.join(f'"{x}":true,' for x in achoices) + '}'
yield 'for _, a := range args {' yield 'for _, a := range args {'
yield 'if !achoices[a] { return fmt.Errorf("Not a valid choice: %s. Allowed values are: %s", a, "' + ', '.join(achoices) + '") }' yield 'if !achoices[a] { return fmt.Errorf("Not a valid choice: %s. Allowed values are: %s", a, "' + ', '.join(achoices) + '") }'
yield '}'
if self.json_field: if self.json_field:
jf = self.json_field jf = self.json_field
dest = f'payload.{jf.capitalize()}' dest = f'payload.{jf.capitalize()}'
@ -240,6 +241,7 @@ class ArgsHandling:
return return
if jt == 'dict.str': if jt == 'dict.str':
yield f'{dest} = parse_key_val_args(args)' yield f'{dest} = parse_key_val_args(args)'
return
raise TypeError(f'Unknown args handling for cmd: {cmd_name}') raise TypeError(f'Unknown args handling for cmd: {cmd_name}')

View File

@ -63,7 +63,7 @@ default=false
Don't wait for a response from kitty. This means that even if setting the background image Don't wait for a response from kitty. This means that even if setting the background image
failed, the command will exit with a success code. failed, the command will exit with a success code.
''' + '\n\n' + MATCH_WINDOW_OPTION ''' + '\n\n' + MATCH_WINDOW_OPTION
args = RemoteCommand.Args(spec='PATH_TO_PNG_IMAGE', count=1, special_parse='!read_window_logo(args[0])', completion={ args = RemoteCommand.Args(spec='PATH_TO_PNG_IMAGE', count=1, json_field='data', special_parse='!read_window_logo(args[0])', completion={
'files': ('PNG Images', ('*.png',))}) 'files': ('PNG Images', ('*.png',))})
images_in_flight: Dict[str, IO[bytes]] = {} images_in_flight: Dict[str, IO[bytes]] = {}
is_asynchronous = True is_asynchronous = True

View File

@ -37,7 +37,7 @@ By default, background opacity are only changed for the currently active window.
cause background opacity to be changed in all windows. cause background opacity to be changed in all windows.
''' + '\n\n' + MATCH_WINDOW_OPTION + '\n\n' + MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t') ''' + '\n\n' + MATCH_WINDOW_OPTION + '\n\n' + MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
args = RemoteCommand.Args(spec='OPACITY', count=1, json_field='opacity') args = RemoteCommand.Args(spec='OPACITY', count=1, json_field='opacity', special_parse='parse_opacity(args[0])')
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType: def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
opacity = max(0.1, min(float(args[0]), 1.0)) opacity = max(0.1, min(float(args[0]), 1.0))

View File

@ -9,7 +9,6 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"strconv"
"strings" "strings"
"time" "time"

View File

@ -8,8 +8,8 @@ import (
"strings" "strings"
) )
func parse_scroll_amount(amt string) ([2]interface{}, error) { func parse_scroll_amount(amt string) ([]interface{}, error) {
var ans [2]interface{} var ans = make([]interface{}, 2)
if amt == "start" || amt == "end" { if amt == "start" || amt == "end" {
ans[0] = amt ans[0] = amt
ans[1] = nil ans[1] = nil

View File

@ -0,0 +1,19 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import "strconv"
func parse_opacity(arg string) (float64, error) {
ans, err := strconv.ParseFloat(arg, 64)
if err != nil {
return 0, nil
}
if ans < 0.1 {
ans = 0.1
}
if ans > 1 {
ans = 1
}
return ans, nil
}