Have the rc command wrapper sauto-generated on build

This commit is contained in:
Kovid Goyal 2022-08-16 21:14:40 +05:30
parent 47f35a06e6
commit 4ac4ee643e
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
5 changed files with 44 additions and 71 deletions

1
.gitignore vendored
View File

@ -14,6 +14,7 @@
/glad/out/
/kitty/launcher/kitty*
/tools/cmd/at/*_generated.go
/constants.go
/*.dSYM/
__pycache__/
/glfw/wayland-*-client-protocol.[ch]

View File

@ -9,6 +9,7 @@ from typing import Any
from kitty.rc.base import (
RemoteCommand, all_command_names, command_for_name, parse_subcommand_cli
)
import kitty.constants as kc
def serialize_as_go_string(x: str) -> str:
@ -26,6 +27,22 @@ def main() -> None:
if 'prewarmed' in getattr(sys, 'kitty_run_data'):
os.environ.pop('KITTY_PREWARM_SOCKET')
os.execlp(sys.executable, sys.executable, '+launch', __file__, *sys.argv[1:])
with open('constants.go', 'w') as f:
dp = ", ".join(map(lambda x: f'"{serialize_as_go_string}"', kc.default_pager_for_help))
f.write(f'''\
// auto-generated by {__file__} do no edit
package kitty
type VersionType struct {{
Major, Minor, Patch int
}}
var VersionString string = "{kc.str_version}"
var WebsiteBaseURL string = "{kc.website_base_url}"
var Version VersionType = VersionType{{Major: {kc.version.major}, Minor: {kc.version.minor}, Patch: {kc.version.patch},}}
var DefaultPager []string = []string{{ {dp} }}
var VCSRevision string = ""
''')
with open('tools/cmd/at/template.go') as f:
template = f.read()
for name in all_command_names():

View File

@ -505,8 +505,9 @@ def run_tool(cmd: Union[str, List[str]], desc: Optional[str] = None) -> None:
raise SystemExit(ret)
def get_vcs_rev_defines(env: Env, src: str) -> List[str]:
ans = []
@lru_cache
def get_vcs_rev_define() -> str:
ans = ''
if os.path.exists('.git'):
try:
rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8')
@ -520,7 +521,7 @@ def get_vcs_rev_defines(env: Env, src: str) -> List[str]:
with open(os.path.join(gitloc, 'refs/heads/master')) as f:
rev = f.read()
ans.append(f'KITTY_VCS_REV="{rev.strip()}"')
ans = rev.strip()
return ans
@ -528,7 +529,7 @@ def get_source_specific_defines(env: Env, src: str) -> Tuple[str, Optional[List[
if src == 'kitty/parser_dump.c':
return 'kitty/parser.c', ['DUMP_COMMANDS']
if src == 'kitty/data-types.c':
return src, get_vcs_rev_defines(env, src)
return src, [f'KITTY_VCS_REV="{get_vcs_rev_define()}"']
with suppress(KeyError):
return src, env.library_paths[src]
return src, None
@ -875,15 +876,34 @@ def safe_makedirs(path: str) -> None:
os.makedirs(path, exist_ok=True)
def update_go_generated_files() -> None:
# update all the various auto-generated go files, if needed
rc_sources = [x for x in glob.glob('kitty/rc/*.py') if os.path.basename(x) not in ('base.py', '__init__.py')]
rc_objects = glob.glob('tools/cmd/at/*_generated.go')
generated = rc_objects + glob.glob('constants.go')
sources = ['gen-rc-go.py', 'kitty/constants.py', 'setup.py', 'tools/cmd/at/template.go'] + rc_sources
if generated:
oldest_generated = min(map(os.path.getmtime, generated))
newest_source = max(map(os.path.getmtime, sources))
if oldest_generated > newest_source and len(rc_sources) == len(rc_objects) and 'constants.go' in generated:
return
print('Updating Go generated files...')
subprocess.check_call(['./gen-rc-go.py'])
def build_kitty_tool(args: Options, launcher_dir: str = '.') -> None:
go = shutil.which('go')
if not go:
raise SystemExit('The go tool was not found on this system. Install Go')
update_go_generated_files()
cmd = [go, 'build']
if args.verbose:
cmd.append('-v')
ld_flags = [f"-X 'kitty.VCSRevision={get_vcs_rev_define()}'"]
if not args.debug:
cmd += ['-ldflags', '-s -w']
ld_flags.append('-s')
ld_flags.append('-w')
cmd += ['-ldflags', ' '.join(ld_flags)]
cmd += ['-o', os.path.join(launcher_dir, 'kitty-tool'), os.path.abspath('tools/cmd')]
print(shlex.join(cmd))
cp = subprocess.run(cmd)

View File

@ -173,7 +173,7 @@ func website_url(doc string) string {
doc += "/"
}
}
return kitty.WebsiteBaseUrl + doc
return kitty.WebsiteBaseURL + doc
}
var prettify_pat = regexp.MustCompile(":([a-z]+):`([^`]+)`")

View File

@ -1,65 +0,0 @@
package kitty
import (
_ "embed"
"encoding/json"
"fmt"
"os"
"regexp"
"runtime/debug"
"strconv"
"strings"
)
//go:embed kitty/constants.py
var raw string
type VersionType struct {
major, minor, patch int
}
var VersionString string
var Version VersionType
var VCSRevision string
var WebsiteBaseUrl string
var DefaultPager []string
func init() {
verpat := regexp.MustCompile(`Version\((\d+),\s*(\d+),\s*(\d+)\)`)
matches := verpat.FindStringSubmatch(raw)
major, err := strconv.Atoi(matches[1])
minor, err := strconv.Atoi(matches[2])
patch, err := strconv.Atoi(matches[3])
if err != nil {
panic(err)
}
Version.major = major
Version.minor = minor
Version.patch = patch
VersionString = fmt.Sprint(major, ".", minor, ".", patch)
bi, ok := debug.ReadBuildInfo()
if ok {
for _, bs := range bi.Settings {
if bs.Key == "vcs.revision" {
VCSRevision = bs.Value
}
}
}
website_pat := regexp.MustCompile(`website_base_url\s+=\s+['"](.+?)['"]`)
matches = website_pat.FindStringSubmatch(raw)
WebsiteBaseUrl = matches[1]
if matches[1] == "" {
panic(fmt.Errorf("Failed to find the website base url"))
}
pager_pat := regexp.MustCompile(`default_pager_for_help\s+=\s+\((.+?)\)`)
matches = pager_pat.FindStringSubmatch(raw)
if matches[1] == "" {
panic(fmt.Errorf("Failed to find the default_pager_for_help"))
}
text := strings.ReplaceAll("["+matches[1]+"]", "'", "\"")
err = json.Unmarshal([]byte(text), &DefaultPager)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to unmarshal default pager text:", text)
panic(err)
}
}