chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

+466
View File
@@ -0,0 +1,466 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
const (
folder = "dependencies"
fonts_folder = "fonts"
macos_prefix = "/Users/Shared/kitty-build/sw/sw"
macos_python = "python/Python.framework/Versions/Current/bin/python3"
macos_python_framework = "python/Python.framework/Versions/Current/Python"
macos_python_framework_exe = "python/Python.framework/Versions/Current/Resources/Python.app/Contents/MacOS/Python"
NERD_URL = "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/NerdFontsSymbolsOnly.tar.xz"
)
func root_dir() string {
f, e := filepath.Abs(filepath.Join(folder, runtime.GOOS+"-"+runtime.GOARCH))
if e != nil {
exit(e)
}
return f
}
func fonts_dir() string {
f, e := filepath.Abs(fonts_folder)
if e != nil {
exit(e)
}
return f
}
var _ = fmt.Print
func exit(x any) {
switch v := x.(type) {
case error:
if v == nil {
os.Exit(0)
}
var ee *exec.ExitError
if errors.As(v, &ee) {
os.Exit(ee.ExitCode())
}
case string:
if v == "" {
os.Exit(0)
}
case int:
os.Exit(v)
}
fmt.Fprintf(os.Stderr, "\x1b[31mError\x1b[m: %s\n", x)
os.Exit(1)
}
// download deps {{{
type dependency struct {
path string
basename string
is_id bool
}
func lines(exe string, cmd ...string) []string {
c := exec.Command(exe, cmd...)
c.Stderr = os.Stderr
out, err := c.Output()
if err != nil {
exit(fmt.Errorf("Failed to run '%s' with error: %w", strings.Join(append([]string{exe}, cmd...), " "), err))
}
ans := []string{}
for s := bufio.NewScanner(bytes.NewReader(out)); s.Scan(); {
ans = append(ans, s.Text())
}
return ans
}
func get_dependencies(path string) (ans []dependency) {
a := lines("otool", "-D", path)
install_name := strings.TrimSpace(a[len(a)-1])
for _, line := range lines("otool", "-L", path) {
line = strings.TrimSpace(line)
if strings.Contains(line, "compatibility") && !strings.HasSuffix(line, ":") {
before, _, _ := strings.Cut(line, "(")
dep := strings.TrimSpace(before)
ans = append(ans, dependency{path: dep, is_id: dep == install_name})
}
}
return
}
func get_local_dependencies(path string) (ans []dependency) {
for _, dep := range get_dependencies(path) {
for _, y := range []string{filepath.Join(macos_prefix, "lib") + "/", filepath.Join(macos_prefix, "python", "Python.framework") + "/", "@rpath/"} {
if strings.HasPrefix(dep.path, y) {
if y == "@rpath/" {
dep.basename = "lib/" + dep.path[len(y):]
} else {
y = macos_prefix + "/"
dep.basename = dep.path[len(y):]
}
ans = append(ans, dep)
break
}
}
}
return
}
func change_dep(path string, dep dependency) {
cmd := []string{}
fid := filepath.Join(root_dir(), dep.basename)
if dep.is_id {
cmd = append(cmd, "-id", fid)
} else {
cmd = append(cmd, "-change", dep.path, fid)
}
cmd = append(cmd, path)
c := exec.Command("install_name_tool", cmd...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err := c.Run(); err != nil {
exit(fmt.Errorf("Failed to run command '%s' with error: %w", strings.Join(c.Args, " "), err))
}
}
func fix_dependencies_in_lib(path string) {
path, err := filepath.EvalSymlinks(path)
if err != nil {
exit(err)
}
if s, err := os.Stat(path); err != nil {
exit(err)
} else if err := os.Chmod(path, s.Mode().Perm()|0o200); err != nil {
exit(err)
}
for _, dep := range get_local_dependencies(path) {
change_dep(path, dep)
}
if ldeps := get_local_dependencies(path); len(ldeps) > 0 {
exit(fmt.Errorf("Failed to fix local dependencies in: %s", path))
}
}
func cached_download(url string) string {
fname := filepath.Base(url)
fmt.Println("Downloading", fname)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
exit(err)
}
etag_file := filepath.Join(folder, fname+".etag")
if etag, err := os.ReadFile(etag_file); err == nil {
if _, err := os.Stat(filepath.Join(folder, fname)); err == nil {
req.Header.Add("If-None-Match", string(etag))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
exit(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotModified {
return filepath.Join(folder, fname)
}
exit(fmt.Errorf("The server responded with the HTTP error: %s", resp.Status))
}
f, err := os.Create(filepath.Join(folder, fname))
if err != nil {
exit(err)
}
defer f.Close()
if _, err := io.Copy(f, resp.Body); err != nil {
exit(fmt.Errorf("Failed to download file with error: %w", err))
}
if etag := resp.Header.Get("ETag"); etag != "" {
if err := os.WriteFile(etag_file, []byte(etag), 0o644); err != nil {
exit(err)
}
}
return f.Name()
}
func relocate_pkgconfig(path, old_prefix, new_prefix string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
replacement := new_prefix
if filepath.Ext(path) == ".pc" {
// pkg-config tokenizes Cflags/Libs on unescaped whitespace, so a
// prefix containing a space must have that space backslash-escaped,
// otherwise `pkg-config --cflags`/`--libs` silently truncates the
// path at the first space, breaking the build whenever the checkout
// lives under a directory with a space in its name.
replacement = strings.NewReplacer(`\`, `\\`, ` `, `\ `).Replace(new_prefix)
}
nraw := bytes.ReplaceAll(raw, []byte(old_prefix), []byte(replacement))
return os.WriteFile(path, nraw, 0o644)
}
func chdir_to_base() {
_, filename, _, _ := runtime.Caller(0)
base_dir := filepath.Dir(filepath.Dir(filename))
if err := os.Chdir(base_dir); err != nil {
exit(err)
}
}
func dependencies_for_docs() {
fmt.Println("Downloading get-pip.py")
rq, err := http.Get("https://bootstrap.pypa.io/get-pip.py")
if err != nil {
exit(err)
}
defer rq.Body.Close()
if rq.StatusCode != http.StatusOK {
exit(fmt.Errorf("Server responded with HTTP error: %s", rq.Status))
}
gp, err := os.Create(filepath.Join(folder, "get-pip.py"))
if err != nil {
exit(err)
}
defer gp.Close()
if _, err = io.Copy(gp, rq.Body); err != nil {
exit(err)
}
python := setup_to_run_python()
run := func(exe string, args ...string) {
c := exec.Command(exe, args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err := c.Run(); err != nil {
exit(err)
}
}
run(python, gp.Name())
run(python, "-m", "pip", "install", "-r", "docs/requirements.txt")
}
func dependencies(args []string) {
chdir_to_base()
nf := flag.NewFlagSet("deps", flag.ExitOnError)
docsptr := nf.Bool("for-docs", false, "download the dependencies needed to build the documentation")
if err := nf.Parse(args); err != nil {
exit(err)
}
if *docsptr {
dependencies_for_docs()
fmt.Println("Dependencies needed to generate documentation have been installed. Build docs with ./dev.sh docs")
exit(0)
}
data, err := os.ReadFile(".github/workflows/ci.py")
if err != nil {
exit(err)
}
pat := regexp.MustCompile("BUNDLE_URL = '(.+?)'")
prefix := "/sw/sw"
var url string
if m := pat.FindStringSubmatch(string(data)); len(m) < 2 {
exit("Failed to find BUNDLE_URL in ci.py")
} else {
url = m[1]
}
var which string
switch runtime.GOOS {
case "darwin":
prefix = macos_prefix
which = "macos"
case "linux":
which = "linux"
switch runtime.GOARCH {
case "amd64":
case "arm64", "arm64be":
url = strings.Replace(url, "-64.", "-arm64.", 1)
default:
exit(fmt.Sprintf("Pre-built binaries are not available for the %s architecture", runtime.GOARCH))
}
}
if which == "" {
exit("Prebuilt dependencies are only available for Linux and macOS")
}
url = strings.Replace(url, "{}", which, 1)
if err := os.RemoveAll(root_dir()); err != nil {
exit(err)
}
if err := os.MkdirAll(folder, 0o755); err != nil {
exit(err)
}
tarfile, _ := filepath.Abs(cached_download(url))
root := root_dir()
if err := os.MkdirAll(root, 0o755); err != nil {
exit(err)
}
cmd := exec.Command("tar", "xf", tarfile)
cmd.Dir = root
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
exit(err)
}
if runtime.GOOS == "darwin" {
fix_dependencies_in_lib(filepath.Join(root, macos_python))
fix_dependencies_in_lib(filepath.Join(root, macos_python_framework))
fix_dependencies_in_lib(filepath.Join(root, macos_python_framework_exe))
}
if err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.Type().IsRegular() {
name := d.Name()
ext := filepath.Ext(name)
if ext == ".pc" || (ext == ".py" && strings.HasPrefix(name, "_sysconfigdata_")) {
err = relocate_pkgconfig(path, prefix, root)
}
// remove libfontconfig so that we use the system one because
// different distros stupidly use different fontconfig configuration dirs
if strings.HasPrefix(name, "libfontconfig.so") {
os.Remove(path)
}
if runtime.GOOS == "darwin" {
if ext == ".so" || ext == ".dylib" {
fix_dependencies_in_lib(path)
}
}
}
return err
}); err != nil {
exit(err)
}
tarfile, _ = filepath.Abs(cached_download(NERD_URL))
root = fonts_dir()
if err := os.MkdirAll(root, 0o755); err != nil {
exit(err)
}
cmd = exec.Command("tar", "xf", tarfile, "SymbolsNerdFontMono-Regular.ttf")
cmd.Dir = root
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
exit(err)
}
fmt.Println(`Dependencies downloaded. Now build kitty with: ./dev.sh build`)
}
// }}}
func prepend(env_var, path string) {
val := os.Getenv(env_var)
if val != "" {
val = string(filepath.ListSeparator) + val
}
os.Setenv(env_var, path+val)
}
func setup_to_run_python() (python string) {
root := root_dir()
for _, x := range os.Environ() {
if strings.HasPrefix(x, "PYTHON") {
a, _, _ := strings.Cut(x, "=")
os.Unsetenv(a)
}
}
switch runtime.GOOS {
case "linux":
prepend("LD_LIBRARY_PATH", filepath.Join(root, "lib"))
os.Setenv("PYTHONHOME", root)
python = filepath.Join(root, "bin", "python")
case `darwin`:
python = filepath.Join(root, macos_python)
default:
exit("Building is only supported on Linux and macOS")
}
return
}
func build(args []string) {
chdir_to_base()
if _, err := os.Stat(folder); err != nil {
dependencies(nil)
}
root := root_dir()
os.Setenv("DEVELOP_ROOT", root)
os.Setenv("SLANGC", filepath.Join(root, "bin", "slangc"))
prepend("PKG_CONFIG_PATH", filepath.Join(root, "lib", "pkgconfig"))
if runtime.GOOS == "darwin" {
os.Setenv("PKGCONFIG_EXE", filepath.Join(root, "bin", "pkg-config"))
}
python := setup_to_run_python()
args = append([]string{"setup.py", "develop"}, args...)
cmd := exec.Command(python, args...)
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
if err := cmd.Run(); err != nil {
fmt.Fprintln(os.Stderr, "The following build command failed:", python, strings.Join(args, " "))
exit(err)
}
fmt.Println("Build successful. Run kitty as: kitty/launcher/kitty")
}
func docs(args []string) {
setup_to_run_python()
nf := flag.NewFlagSet("deps", flag.ExitOnError)
livereload := nf.Bool("live-reload", false, "build the docs and make them available via s local server with live reloading for ease of development")
failwarn := nf.Bool("fail-warn", false, "make warnings fatal when building the docs")
if err := nf.Parse(args); err != nil {
exit(err)
}
exe := filepath.Join(root_dir(), "bin", "sphinx-build")
aexe := filepath.Join(root_dir(), "bin", "sphinx-autobuild")
target := "docs"
if *livereload {
target = "develop-docs"
}
cmd := []string{target, "SPHINXBUILD=" + exe, "SPHINXAUTOBUILD=" + aexe}
if *failwarn {
cmd = append(cmd, "FAIL_WARN=1")
}
c := exec.Command("make", cmd...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
err := c.Run()
if err != nil {
exit(err)
}
fmt.Println("docs successfully built")
}
func main() {
if len(os.Args) < 2 {
exit(`Expected "deps" or "build" subcommands`)
}
switch os.Args[1] {
case "deps":
dependencies(os.Args[2:])
case "build":
build(os.Args[2:])
case "docs":
docs(os.Args[2:])
case "-h", "--help":
fmt.Fprintln(os.Stderr, "Usage: ./dev.sh [build|deps|docs] [options...]")
default:
exit(`Expected "deps" or "build" subcommands`)
}
}
+57
View File
@@ -0,0 +1,57 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// When the kitty checkout lives under a directory whose name contains a
// space (a common occurrence on macOS, e.g. "Desktop/My Projects/kitty"),
// pkg-config tokenizes the Cflags/Libs lines it emits on unescaped
// whitespace. If relocate_pkgconfig writes the new, real prefix into a .pc
// file without escaping spaces, pkg-config truncates the path at the first
// space and the build fails with errors such as "hb.h file not found".
func TestRelocatePkgconfigEscapesSpacesInPcFiles(t *testing.T) {
dir := t.TempDir()
pc_path := filepath.Join(dir, "harfbuzz.pc")
old_prefix := "/sw/sw"
new_prefix := "/Users/someone/has space/kitty/dependencies/darwin-amd64"
contents := "prefix=" + old_prefix + "\nincludedir=${prefix}/include\n\nName: harfbuzz\nCflags: -I${includedir}/harfbuzz\n"
if err := os.WriteFile(pc_path, []byte(contents), 0o644); err != nil {
t.Fatal(err)
}
if err := relocate_pkgconfig(pc_path, old_prefix, new_prefix); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(pc_path)
if err != nil {
t.Fatal(err)
}
expected_prefix_line := `prefix=/Users/someone/has\ space/kitty/dependencies/darwin-amd64`
if !strings.Contains(string(raw), expected_prefix_line) {
t.Fatalf("space in new prefix was not escaped in .pc file, got:\n%s", raw)
}
// The same function is also used to relocate paths embedded in
// Python's _sysconfigdata_*.py, which is a plain Python string literal,
// not something pkg-config tokenizes. Escaping the space there would
// corrupt the path, so it must be left untouched.
py_path := filepath.Join(dir, "_sysconfigdata_darwin.py")
if err := os.WriteFile(py_path, []byte("prefix = '"+old_prefix+"'\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := relocate_pkgconfig(py_path, old_prefix, new_prefix); err != nil {
t.Fatal(err)
}
raw, err = os.ReadFile(py_path)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), "prefix = '"+new_prefix+"'") {
t.Fatalf("plain (non pkg-config) relocation should not escape spaces, got:\n%s", raw)
}
}
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from contextlib import suppress
from bypy.constants import BIN, LIBDIR, PREFIX, PYTHON, ismacos, worker_env
from bypy.constants import SRC as KITTY_DIR
from bypy.utils import run_shell, walk
def read_src_file(name):
with open(os.path.join(KITTY_DIR, 'kitty', name), 'rb') as f:
return f.read().decode('utf-8')
def initialize_constants():
kitty_constants = {}
src = read_src_file('constants.py')
nv = re.search(r'Version\((\d+), (\d+), (\d+)\)', src)
kitty_constants['version'] = f'{nv.group(1)}.{nv.group(2)}.{nv.group(3)}'
kitty_constants['appname'] = re.search(r'appname: str\s+=\s+(u{0,1})[\'"]([^\'"]+)[\'"]', src).group(2)
kitty_constants['cacerts_url'] = 'https://curl.haxx.se/ca/cacert.pem'
return kitty_constants
def run(*args, **extra_env):
env = os.environ.copy()
env.update(worker_env)
env.update(extra_env)
env['SW'] = PREFIX
env['LD_LIBRARY_PATH'] = LIBDIR
env['SLANGC'] = os.path.join(BIN, 'slangc')
if ismacos:
env['PKGCONFIG_EXE'] = os.path.join(PREFIX, 'bin', 'pkg-config')
cwd = env.pop('cwd', KITTY_DIR)
print(' '.join(map(shlex.quote, args)), flush=True)
return subprocess.call(list(args), env=env, cwd=cwd)
SETUP_CMD = [PYTHON, 'setup.py']
def setup_py_options(extra_program_data: str) -> list[str]:
# extra_program_data is the VCS revision, followed by :nightly:<commit time> for nightly builds
if not extra_program_data:
return []
vcs_rev, _, commit_time = extra_program_data.partition(':nightly:')
ans = [f'--vcs-rev={vcs_rev}']
if commit_time:
ans += ['--nightly', f'--vcs-commit-time={commit_time}']
return ans
def build_frozen_launcher(extra_include_dirs):
inc_dirs = [f'--extra-include-dirs={x}' for x in extra_include_dirs]
cmd = SETUP_CMD + ['--prefix', build_frozen_launcher.prefix] + inc_dirs + build_frozen_launcher.setup_py_options + ['build-frozen-launcher']
if run(*cmd, cwd=build_frozen_launcher.writeable_src_dir) != 0:
print('Building of frozen kitty launcher failed', file=sys.stderr)
os.chdir(KITTY_DIR)
run_shell()
raise SystemExit('Building of kitty launcher failed')
return build_frozen_launcher.writeable_src_dir
def run_tests(kitty_exe) -> None:
with tempfile.TemporaryDirectory() as tdir:
uenv = {'KITTY_CONFIG_DIRECTORY': os.path.join(tdir, 'conf'), 'KITTY_CACHE_DIRECTORY': os.path.join(tdir, 'cache')}
[os.mkdir(x) for x in uenv.values()]
env = os.environ.copy()
env.update(uenv)
cmd = [kitty_exe, '+runpy', 'from kitty_tests.main import run_tests; run_tests(report_env=True)']
print(*map(shlex.quote, cmd), flush=True)
if subprocess.call(cmd, env=env, cwd=build_frozen_launcher.writeable_src_dir) != 0:
print('Checking of kitty build failed, in directory:', build_frozen_launcher.writeable_src_dir, file=sys.stderr)
os.chdir(os.path.dirname(kitty_exe))
run_shell()
raise SystemExit('Checking of kitty build failed')
def build_frozen_tools(kitty_exe) -> None:
cmd = SETUP_CMD + ['--prefix', os.path.dirname(kitty_exe)] + build_frozen_launcher.setup_py_options + ['build-frozen-tools']
if run(*cmd, cwd=build_frozen_launcher.writeable_src_dir) != 0:
print('Building of frozen kitten failed', file=sys.stderr)
os.chdir(KITTY_DIR)
run_shell()
raise SystemExit('Building of kitten launcher failed')
def sanitize_source_folder(path: str) -> None:
for q in walk(path):
if os.path.splitext(q)[1] not in ('.py', '.glsl', '.slang', '.pipeline', '.ttf', '.otf', '.json'):
os.unlink(q)
def build_c_extensions(ext_dir, args):
writeable_src_dir = os.path.join(ext_dir, 'src')
build_frozen_launcher.writeable_src_dir = writeable_src_dir
shutil.copytree(
KITTY_DIR, writeable_src_dir, symlinks=True, ignore=shutil.ignore_patterns('b', 'build', 'dist', '*_commands.json', '*.o', '*.so', '*.dylib', '*.pyd')
)
with suppress(FileNotFoundError):
shutil.rmtree(os.path.join(writeable_src_dir, 'shaders'))
with suppress(FileNotFoundError):
os.unlink(os.path.join(writeable_src_dir, 'kitty', 'launcher', 'kitty'))
cmd = SETUP_CMD + ['macos-freeze' if ismacos else 'linux-freeze']
if args.dont_strip:
cmd.append('--debug')
build_frozen_launcher.setup_py_options = setup_py_options(args.extra_program_data)
cmd += build_frozen_launcher.setup_py_options
dest = kitty_constants['appname'] + ('.app' if ismacos else '')
dest = build_frozen_launcher.prefix = os.path.join(ext_dir, dest)
cmd += ['--prefix', dest, '--full']
if run(*cmd, cwd=writeable_src_dir) != 0:
print('Building of kitty package failed', file=sys.stderr)
os.chdir(writeable_src_dir)
run_shell()
raise SystemExit('Building of kitty package failed')
return ext_dir
if __name__ == 'program':
kitty_constants = initialize_constants()
+3
View File
@@ -0,0 +1,3 @@
image 'https://cloud-images.ubuntu.com/releases/jammy/release/ubuntu-22.04-server-cloudimg-{}.img'
deps 'bison flex libxcursor-dev libxrandr-dev libxi-dev libxinerama-dev libgl1-mesa-dev libx11-xcb-dev libxcb-xkb-dev libfontconfig1-dev libdbus-1-dev libsystemd-dev'
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import errno
import os
import shutil
import stat
import subprocess
import tarfile
import time
from bypy.constants import BIN, LIBDIR, OUTPUT_DIR, PREFIX, python_major_minor_version
from bypy.freeze import extract_extension_modules, freeze_python, path_to_freeze_dir
from bypy.utils import get_dll_path, mkdtemp, py_compile, walk
j = os.path.join
machine = (os.uname()[4] or '').lower()
self_dir = os.path.dirname(os.path.abspath(__file__))
py_ver = '.'.join(map(str, python_major_minor_version()))
iv = globals()['init_env']
kitty_constants = iv['kitty_constants']
def binary_includes():
return tuple(
map(
get_dll_path,
(
'expat',
'sqlite3',
'ffi',
'z',
'lzma',
'png16',
'lcms2',
'ssl',
'crypto',
'crypt',
'iconv',
'pcre2-8',
'graphite2',
'glib-2.0',
'freetype',
'xxhash',
'pixman-1',
'cairo',
'harfbuzz',
'xkbcommon',
'xkbcommon-x11',
# fontconfig is not bundled because in typical brain dead Linux
# distro fashion, different distros use different default config
# paths for fontconfig.
'ncursesw',
'readline',
'brotlicommon',
'brotlienc',
'brotlidec',
'wayland-client',
'wayland-cursor',
),
)
) + (
get_dll_path('bz2', 2),
get_dll_path(f'python{py_ver}', 2),
)
class Env:
def __init__(self, package_dir) -> None:
self.base = package_dir
self.lib_dir = j(self.base, 'lib')
self.py_dir = j(self.lib_dir, f'python{py_ver}')
os.makedirs(self.py_dir)
self.bin_dir = j(self.base, 'bin')
self.obj_dir = mkdtemp('launchers-')
def ignore_in_lib(base, items, ignored_dirs=None):
ans = []
if ignored_dirs is None:
ignored_dirs = {'.svn', '.bzr', '.git', 'test', 'tests', 'testing'}
for name in items:
path = j(base, name)
if os.path.isdir(path):
if name in ignored_dirs or not os.path.exists(j(path, '__init__.py')):
if name != 'plugins':
ans.append(name)
else:
if name.rpartition('.')[-1] not in ('so', 'py'):
ans.append(name)
return ans
def import_site_packages(srcdir, dest) -> None:
if not os.path.exists(dest):
os.mkdir(dest)
for x in os.listdir(srcdir):
ext = x.rpartition('.')[-1]
f = j(srcdir, x)
if ext in ('py', 'so'):
shutil.copy2(f, dest)
elif ext == 'pth' and x != 'setuptools.pth':
for line in open(f):
src = os.path.abspath(j(srcdir, line))
if os.path.exists(src) and os.path.isdir(src):
import_site_packages(src, dest)
elif os.path.exists(j(f, '__init__.py')):
shutil.copytree(f, j(dest, x), ignore=ignore_in_lib)
def copy_libs(env) -> None:
print('Copying libs...')
for x in binary_includes():
dest = env.bin_dir if '/bin/' in x else env.lib_dir
shutil.copy2(x, dest)
dest = os.path.join(dest, os.path.basename(x))
subprocess.check_call(['chrpath', '-d', dest])
# Copy slang
x = 'libslang-compiler.so'
shutil.copy2(os.path.join(LIBDIR, f'{x}.0.0.0.0'), env.lib_dir)
os.symlink(f'{x}.0.0.0.0', os.path.join(env.lib_dir, x))
for x in ('glsl-module', 'glslang'):
x = f'libslang-{x}-0.0.0.so'
shutil.copy2(os.path.join(LIBDIR, x), env.lib_dir)
shutil.copy2(os.path.join(BIN, 'slangc'), env.bin_dir)
def add_ca_certs(env) -> None:
print('Downloading CA certs...')
from urllib.request import urlopen
cdata = urlopen(kitty_constants['cacerts_url']).read()
dest = os.path.join(env.lib_dir, 'cacert.pem')
with open(dest, 'wb') as f:
f.write(cdata)
def copy_python(env) -> None:
print('Copying python...')
srcdir = j(PREFIX, f'lib/python{py_ver}')
for x in os.listdir(srcdir):
y = j(srcdir, x)
ext = os.path.splitext(x)[1]
if os.path.isdir(y) and x not in ('test', 'hotshot', 'distutils', 'tkinter', 'turtledemo', 'site-packages', 'idlelib', 'lib2to3', 'dist-packages'):
shutil.copytree(y, j(env.py_dir, x), ignore=ignore_in_lib)
if os.path.isfile(y) and ext in ('.py', '.so'):
shutil.copy2(y, env.py_dir)
srcdir = j(srcdir, 'site-packages')
import_site_packages(srcdir, env.py_dir)
pdir = os.path.join(env.lib_dir, 'kitty-extensions')
os.makedirs(pdir, exist_ok=True)
kitty_dir = os.path.join(env.lib_dir, 'kitty')
bases = ('kitty', 'kittens', 'kitty_tests')
for x in bases:
dest = os.path.join(env.py_dir, x)
os.rename(os.path.join(kitty_dir, x), dest)
if x == 'kitty':
shutil.rmtree(os.path.join(dest, 'launcher'))
os.rename(os.path.join(kitty_dir, '__main__.py'), os.path.join(env.py_dir, 'kitty_main.py'))
shutil.rmtree(os.path.join(kitty_dir, '__pycache__'))
print('Extracting extension modules from', env.py_dir, 'to', pdir)
ext_map = extract_extension_modules(env.py_dir, pdir)
shutil.copy(os.path.join(os.path.dirname(self_dir), 'site.py'), os.path.join(env.py_dir, 'site.py'))
for x in bases:
iv['sanitize_source_folder'](os.path.join(env.py_dir, x))
py_compile(env.py_dir)
freeze_python(env.py_dir, pdir, env.obj_dir, ext_map, develop_mode_env_var='KITTY_DEVELOP_FROM', remove_pyc_files=True)
shutil.rmtree(env.py_dir)
def is_elf(path):
with open(path, 'rb') as f:
return f.read(4) == b'\x7fELF'
def fix_permissions(files) -> None:
for path in files:
os.chmod(path, 0o755)
STRIPCMD = ['strip']
def find_binaries(env):
files = {j(env.bin_dir, x) for x in os.listdir(env.bin_dir)} | {
x for x in {j(os.path.dirname(env.bin_dir), x) for x in os.listdir(env.bin_dir)} if os.path.exists(x)
}
for x in walk(env.lib_dir):
x = os.path.realpath(x)
if x not in files and is_elf(x):
files.add(x)
return files
def strip_files(files, argv_max=(256 * 1024)) -> None:
"""Strip a list of files"""
while files:
cmd = list(STRIPCMD)
pathlen = sum(len(s) + 1 for s in cmd)
while pathlen < argv_max and files:
f = files.pop()
cmd.append(f)
pathlen += len(f) + 1
if len(cmd) > len(STRIPCMD):
all_files = cmd[len(STRIPCMD) :]
unwritable_files = tuple(filter(None, (None if os.access(x, os.W_OK) else (x, os.stat(x).st_mode) for x in all_files)))
[os.chmod(x, stat.S_IWRITE | old_mode) for x, old_mode in unwritable_files]
subprocess.check_call(cmd)
[os.chmod(x, old_mode) for x, old_mode in unwritable_files]
def strip_binaries(files) -> None:
print(f'Stripping {len(files)} files...')
before = sum(os.path.getsize(x) for x in files)
strip_files(files)
after = sum(os.path.getsize(x) for x in files)
print('Stripped {:.1f} MB'.format((before - after) / (1024 * 1024.0)))
def create_tarfile(env, compression_level='9') -> None:
print('Creating archive...')
base = OUTPUT_DIR
arch = 'arm64' if 'arm64' in os.environ['BYPY_ARCH'] else ('i686' if 'i386' in os.environ['BYPY_ARCH'] else 'x86_64')
try:
shutil.rmtree(base)
except OSError as err:
if err.errno not in (errno.ENOENT, errno.EBUSY): # EBUSY when the directory is mountpoint
raise
os.makedirs(base, exist_ok=True)
dist = os.path.join(base, f'{kitty_constants["appname"]}-{kitty_constants["version"]}-{arch}.tar')
with tarfile.open(dist, mode='w', format=tarfile.PAX_FORMAT) as tf:
cwd = os.getcwd()
os.chdir(env.base)
try:
for x in os.listdir('.'):
tf.add(x)
finally:
os.chdir(cwd)
print('Compressing archive...')
ans = f'{dist.rpartition(".")[0]}.txz'
start_time = time.time()
threads = 4 if arch == 'i686' else 0
subprocess.check_call(['xz', '--verbose', f'--threads={threads}', '-f', f'-{compression_level}', dist])
secs = time.time() - start_time
print('Compressed in {} minutes {} seconds'.format(secs // 60, secs % 60))
os.rename(f'{dist}.xz', ans)
print('Archive {} created: {:.2f} MB'.format(os.path.basename(ans), os.stat(ans).st_size / (1024.0**2)))
def main() -> None:
args = globals()['args']
ext_dir = globals()['ext_dir']
env = Env(os.path.join(ext_dir, kitty_constants['appname']))
copy_libs(env)
copy_python(env)
iv['build_frozen_launcher']([path_to_freeze_dir(), env.obj_dir])
files = find_binaries(env)
fix_permissions(files)
add_ca_certs(env)
kitty_exe = os.path.join(env.base, 'bin', 'kitty')
iv['build_frozen_tools'](kitty_exe)
if not args.dont_strip:
strip_binaries(files)
if not args.skip_tests:
iv['run_tests'](kitty_exe)
create_tarfile(env, args.compression_level)
if __name__ == '__main__':
main()
+8
View File
@@ -0,0 +1,8 @@
# Requires installation of XCode >= 26.3 and go 1.26 and Python 3 and
# python3 -m pip install certifi meson ninja
vm_name 'macos-kitty'
root '/Users/Shared/kitty-build'
python '/Library/Frameworks/Python.framework/Versions/Current/bin/python3'
universal 'true'
deploy_target '12.0'
+547
View File
@@ -0,0 +1,547 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import glob
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import zipfile
from collections.abc import Iterable
from bypy.constants import BIN, LIBDIR, PREFIX, PYTHON, SW, python_major_minor_version
from bypy.freeze import extract_extension_modules, freeze_python, path_to_freeze_dir
from bypy.macos_sign import codesign, create_entitlements_file, make_certificate_useable, notarize_app, verify_signature
from bypy.utils import current_dir, mkdtemp, py_compile, run_shell, timeit, walk
iv = globals()['init_env']
kitty_constants = iv['kitty_constants']
self_dir = os.path.dirname(os.path.abspath(__file__))
join = os.path.join
basename = os.path.basename
dirname = os.path.dirname
abspath = os.path.abspath
APPNAME = kitty_constants['appname']
VERSION = kitty_constants['version']
py_ver = '.'.join(map(str, python_major_minor_version()))
def flush(func):
def ff(*args, **kwargs):
sys.stdout.flush()
sys.stderr.flush()
ret = func(*args, **kwargs)
sys.stdout.flush()
sys.stderr.flush()
return ret
return ff
def flipwritable(fn, mode=None):
"""
Flip the writability of a file and return the old mode. Returns None
if the file is already writable.
"""
if os.access(fn, os.W_OK):
return None
old_mode = os.stat(fn).st_mode
os.chmod(fn, stat.S_IWRITE | old_mode)
return old_mode
STRIPCMD = ('/usr/bin/strip', '-x', '-S', '-')
def strip_files(files, argv_max=(256 * 1024)) -> None:
"""
Strip a list of files
"""
tostrip = [(fn, flipwritable(fn)) for fn in files if os.path.exists(fn)]
while tostrip:
cmd = list(STRIPCMD)
flips = []
pathlen = sum(len(s) + 1 for s in cmd)
while pathlen < argv_max:
if not tostrip:
break
added, flip = tostrip.pop()
pathlen += len(added) + 1
cmd.append(added)
flips.append((added, flip))
else:
cmd.pop()
tostrip.append(flips.pop())
os.spawnv(os.P_WAIT, cmd[0], cmd)
for args in flips:
flipwritable(*args)
def files_in(folder):
for record in os.walk(folder):
for f in record[-1]:
yield join(record[0], f)
def expand_dirs(items, exclude=lambda x: x.endswith('.so')):
items = set(items)
dirs = set(x for x in items if os.path.isdir(x))
items.difference_update(dirs)
for x in dirs:
items.update({y for y in files_in(x) if not exclude(y)})
return items
def do_sign(app_dir: str) -> None:
seen = set()
def sign(files: Iterable[str] | str) -> None:
nonlocal seen
if isinstance(files, str):
files = (files,)
files = {os.path.abspath(os.path.realpath(x)) for x in files} - seen
seen |= files
codesign(files)
with current_dir(join(app_dir, 'Contents')):
# Sign all .so files
so_files = {x for x in files_in('.') if x.endswith('.so')}
sign(so_files)
# Sign everything else in Frameworks
with current_dir('Frameworks'):
fw = set(glob.glob('*.framework'))
sign(fw)
items = set(os.listdir('.')) - fw
sign(expand_dirs(items))
# Sign executables
with current_dir('MacOS'):
sign(('kitten', 'slangc'))
# Sign sub-apps
for x in os.listdir('.'):
if x.endswith('.app'):
sign(x)
# Now sign the main app
codesign(app_dir)
verify_signature(app_dir)
def sign_app(app_dir, notarize) -> None:
# Copied from iTerm2: https://github.com/gnachman/iTerm2/blob/master/iTerm2.entitlements
create_entitlements_file(
{
'com.apple.security.automation.apple-events': True,
'com.apple.security.cs.allow-jit': True,
'com.apple.security.device.audio-input': True,
'com.apple.security.device.camera': True,
'com.apple.security.personal-information.addressbook': True,
'com.apple.security.personal-information.calendars': True,
'com.apple.security.personal-information.location': True,
'com.apple.security.personal-information.photos-library': True,
}
)
with make_certificate_useable():
do_sign(app_dir)
if notarize:
notarize_app(app_dir, 'kitty')
class Freeze(object):
FID = '@executable_path/../Frameworks'
def __init__(self, build_dir, dont_strip=False, sign_installers=False, notarize=False, skip_tests=False) -> None:
self.build_dir = build_dir
self.skip_tests = skip_tests
self.sign_installers = sign_installers
self.notarize = notarize
self.dont_strip = dont_strip
self.contents_dir = join(self.build_dir, 'Contents')
self.resources_dir = join(self.contents_dir, 'Resources')
self.frameworks_dir = join(self.contents_dir, 'Frameworks')
self.to_strip = []
self.warnings = []
self.py_ver = py_ver
self.python_stdlib = join(self.resources_dir, 'Python', 'lib', f'python{self.py_ver}')
self.site_packages = self.python_stdlib # hack to avoid needing to add site-packages to path
self.obj_dir = mkdtemp('launchers-')
self.run()
def run_shell(self) -> None:
with current_dir(self.contents_dir):
run_shell()
def run(self):
ret = 0
self.add_python_framework()
self.add_site_packages()
self.add_stdlib()
self.add_misc_libraries()
self.freeze_python()
self.add_ca_certs()
self.build_frozen_tools()
self.complete_sub_bundles()
if not self.dont_strip:
self.strip_files()
if not self.skip_tests:
self.run_tests()
# self.run_shell()
ret = self.makedmg(self.build_dir, f'{APPNAME}-{VERSION}')
return ret
@flush
def complete_sub_bundles(self) -> None:
count = 0
for qapp in glob.glob(join(self.contents_dir, '*.app')):
for exe in glob.glob(join(self.contents_dir, 'MacOS', '*')):
os.symlink(f'../../../MacOS/{os.path.basename(exe)}', os.path.join(qapp, 'Contents', 'MacOS', os.path.basename(exe)))
count += 1
if count < 2:
raise SystemExit(f'Could not complete sub-bundles in {self.contents_dir}')
@flush
def add_ca_certs(self) -> None:
print('\nDownloading CA certs...')
from urllib.request import urlopen
cdata = None
for i in range(5):
try:
cdata = urlopen(kitty_constants['cacerts_url']).read()
break
except Exception as e:
print(f'Downloading CA certs failed with error: {e}, retrying...')
if cdata is None:
raise SystemExit('Downloading C certs failed, giving up')
dest = join(self.contents_dir, 'Resources', 'cacert.pem')
with open(dest, 'wb') as f:
f.write(cdata)
@flush
def strip_files(self) -> None:
print('\nStripping files...')
strip_files(self.to_strip)
@flush
def run_tests(self) -> None:
iv['run_tests'](join(self.contents_dir, 'MacOS', 'kitty'))
@flush
def set_id(self, path_to_lib, new_id) -> None:
old_mode = flipwritable(path_to_lib)
subprocess.check_call(['install_name_tool', '-id', new_id, path_to_lib])
if old_mode is not None:
flipwritable(path_to_lib, old_mode)
@flush
def get_dependencies(self, path_to_lib):
install_name = subprocess.check_output(['otool', '-D', path_to_lib]).decode('utf-8').splitlines()[-1].strip()
raw = subprocess.check_output(['otool', '-L', path_to_lib]).decode('utf-8')
for line in raw.splitlines():
if 'compatibility' not in line or line.strip().endswith(':'):
continue
idx = line.find('(')
path = line[:idx].strip()
yield path, path == install_name
@flush
def get_local_dependencies(self, path_to_lib):
for x, is_id in self.get_dependencies(path_to_lib):
for y in (f'{PREFIX}/lib/', f'{PREFIX}/python/Python.framework/', '@rpath/'):
if x.startswith(y):
if y == f'{PREFIX}/python/Python.framework/':
y = f'{PREFIX}/python/'
yield x, x[len(y) :], is_id
break
@flush
def change_dep(self, old_dep, new_dep, is_id, path_to_lib) -> None:
cmd = ['-id', new_dep] if is_id else ['-change', old_dep, new_dep]
subprocess.check_call(['install_name_tool'] + cmd + [path_to_lib])
@flush
def fix_dependencies_in_lib(self, path_to_lib) -> None:
self.to_strip.append(path_to_lib)
old_mode = flipwritable(path_to_lib)
for dep, bname, is_id in self.get_local_dependencies(path_to_lib):
ndep = f'{self.FID}/{bname}'
self.change_dep(dep, ndep, is_id, path_to_lib)
ldeps = list(self.get_local_dependencies(path_to_lib))
if ldeps:
print('\nFailed to fix dependencies in', path_to_lib)
print('Remaining local dependencies:', ldeps)
raise SystemExit(1)
if old_mode is not None:
flipwritable(path_to_lib, old_mode)
@flush
def add_python_framework(self) -> None:
print('\nAdding Python framework')
src = join(f'{PREFIX}/python', 'Python.framework')
x = join(self.frameworks_dir, 'Python.framework')
curr = os.path.realpath(join(src, 'Versions', 'Current'))
currd = join(x, 'Versions', basename(curr))
rd = join(currd, 'Resources')
os.makedirs(rd)
shutil.copy2(join(curr, 'Resources', 'Info.plist'), rd)
shutil.copy2(join(curr, 'Python'), currd)
self.set_id(join(currd, 'Python'), f'{self.FID}/Python.framework/Versions/{basename(curr)}/Python')
# The following is needed for codesign
with current_dir(x):
os.symlink(basename(curr), 'Versions/Current')
for y in ('Python', 'Resources'):
os.symlink(f'Versions/Current/{y}', y)
@flush
def install_dylib(self, path, set_id=True) -> None:
shutil.copy2(path, self.frameworks_dir)
if set_id:
self.set_id(join(self.frameworks_dir, basename(path)), f'{self.FID}/{basename(path)}')
self.fix_dependencies_in_lib(join(self.frameworks_dir, basename(path)))
@flush
def add_misc_libraries(self) -> None:
for x in (
'sqlite3.0',
'z.1',
'harfbuzz.0',
'png16.16',
'lcms2.2',
'crypto.3',
'ssl.3',
'xxhash.0',
):
print('\nAdding', x)
x = f'lib{x}.dylib'
src = join(PREFIX, 'lib', x)
shutil.copy2(src, self.frameworks_dir)
dest = join(self.frameworks_dir, x)
self.set_id(dest, f'{self.FID}/{x}')
self.fix_dependencies_in_lib(dest)
# Copy slang
x = 'libslang-compiler.0.0.0.0.dylib'
shutil.copy2(os.path.join(LIBDIR, x), self.frameworks_dir)
os.symlink(x, os.path.join(self.frameworks_dir, 'libslang-compiler.dylib'))
dest = join(self.frameworks_dir, x)
self.set_id(dest, f'{self.FID}/{x}')
self.fix_dependencies_in_lib(dest)
for x in ('glsl-module', 'glslang'):
x = f'libslang-{x}-0.0.0.dylib'
shutil.copy2(os.path.join(LIBDIR, x), self.frameworks_dir)
dest = join(self.frameworks_dir, x)
self.set_id(dest, f'{self.FID}/{x}')
dest = os.path.join(self.contents_dir, 'MacOS')
shutil.copy2(os.path.join(BIN, 'slangc'), dest)
dest = os.path.join(dest, 'slangc')
self.fix_dependencies_in_lib(dest)
@flush
def add_package_dir(self, x, dest=None) -> None:
def ignore(root, files):
ans = []
for y in files:
ext = os.path.splitext(y)[1]
if ext not in ('', '.py', '.so') or (not ext and not os.path.isdir(join(root, y))):
ans.append(y)
return ans
if dest is None:
dest = self.site_packages
dest = join(dest, basename(x))
shutil.copytree(x, dest, symlinks=True, ignore=ignore)
for f in walk(dest):
if f.endswith('.so'):
self.fix_dependencies_in_lib(f)
@flush
def add_stdlib(self) -> None:
print('\nAdding python stdlib')
src = f'{PREFIX}/python/Python.framework/Versions/Current/lib/python{self.py_ver}'
dest = self.python_stdlib
if not os.path.exists(dest):
os.makedirs(dest)
for x in os.listdir(src):
if x in (
'site-packages',
'config',
'test',
'lib2to3',
'lib-tk',
'lib-old',
'idlelib',
'plat-mac',
'plat-darwin',
'site.py',
'distutils',
'turtledemo',
'tkinter',
):
continue
x = join(src, x)
if os.path.isdir(x):
self.add_package_dir(x, dest)
elif os.path.splitext(x)[1] in ('.so', '.py'):
shutil.copy2(x, dest)
dest2 = join(dest, basename(x))
if dest2.endswith('.so'):
self.fix_dependencies_in_lib(dest2)
@flush
def freeze_python(self) -> None:
print('\nFreezing python')
kitty_dir = join(self.resources_dir, 'kitty')
bases = ('kitty', 'kittens', 'kitty_tests')
for x in bases:
dest = join(self.python_stdlib, x)
os.rename(join(kitty_dir, x), dest)
if x == 'kitty':
shutil.rmtree(join(dest, 'launcher'))
os.rename(join(kitty_dir, '__main__.py'), join(self.python_stdlib, 'kitty_main.py'))
shutil.rmtree(join(kitty_dir, '__pycache__'))
pdir = join(dirname(self.python_stdlib), 'kitty-extensions')
os.mkdir(pdir)
print('Extracting extension modules from', self.python_stdlib, 'to', pdir)
ext_map = extract_extension_modules(self.python_stdlib, pdir)
shutil.copy(join(os.path.dirname(self_dir), 'site.py'), join(self.python_stdlib, 'site.py'))
for x in bases:
iv['sanitize_source_folder'](join(self.python_stdlib, x))
self.compile_py_modules()
freeze_python(self.python_stdlib, pdir, self.obj_dir, ext_map, develop_mode_env_var='KITTY_DEVELOP_FROM', remove_pyc_files=True)
shutil.rmtree(self.python_stdlib)
iv['build_frozen_launcher']([path_to_freeze_dir(), self.obj_dir])
os.rename(join(dirname(self.contents_dir), 'bin', 'kitty'), join(self.contents_dir, 'MacOS', 'kitty'))
shutil.rmtree(join(dirname(self.contents_dir), 'bin'))
self.fix_dependencies_in_lib(join(self.contents_dir, 'MacOS', 'kitty'))
for f in glob.glob(join(self.contents_dir, '*.app', 'Contents', 'MacOS', '*')):
if not os.path.islink(f):
self.fix_dependencies_in_lib(f)
for f in walk(pdir):
if f.endswith('.so') or f.endswith('.dylib'):
self.fix_dependencies_in_lib(f)
@flush
def build_frozen_tools(self) -> None:
iv['build_frozen_tools'](join(self.contents_dir, 'MacOS', 'kitty'))
@flush
def add_site_packages(self) -> None:
print('\nAdding site-packages')
os.makedirs(self.site_packages)
sys_path = json.loads(subprocess.check_output([PYTHON, '-c', 'import sys, json; json.dump(sys.path, sys.stdout)']))
paths = reversed(tuple(map(abspath, [x for x in sys_path if x.startswith('/') and not x.startswith('/Library/')])))
upaths = []
for x in paths:
if x not in upaths and (x.endswith('.egg') or x.endswith('/site-packages')):
upaths.append(x)
for x in upaths:
print('\t', x)
tdir = None
try:
if not os.path.isdir(x):
zf = zipfile.ZipFile(x)
tdir = tempfile.mkdtemp()
zf.extractall(tdir)
x = tdir
self.add_modules_from_dir(x)
self.add_packages_from_dir(x)
finally:
if tdir is not None:
shutil.rmtree(tdir)
self.remove_bytecode(self.site_packages)
@flush
def add_modules_from_dir(self, src) -> None:
for x in glob.glob(join(src, '*.py')) + glob.glob(join(src, '*.so')):
shutil.copy2(x, self.site_packages)
if x.endswith('.so'):
self.fix_dependencies_in_lib(x)
@flush
def add_packages_from_dir(self, src) -> None:
for x in os.listdir(src):
x = join(src, x)
if os.path.isdir(x) and os.path.exists(join(x, '__init__.py')):
if self.filter_package(basename(x)):
continue
self.add_package_dir(x)
@flush
def filter_package(self, name):
return name in ('Cython', 'modulegraph', 'macholib', 'py2app', 'bdist_mpkg', 'altgraph')
@flush
def remove_bytecode(self, dest) -> None:
for x in os.walk(dest):
root = x[0]
for f in x[-1]:
if os.path.splitext(f) == '.pyc':
os.remove(join(root, f))
@flush
def compile_py_modules(self) -> None:
self.remove_bytecode(join(self.resources_dir, 'Python'))
py_compile(join(self.resources_dir, 'Python'))
@flush
def makedmg(self, d, volname, format='ULMO'):
"""Copy a directory d into a dmg named volname"""
print('\nMaking dmg...')
sys.stdout.flush()
destdir = join(SW, 'dist')
try:
shutil.rmtree(destdir)
except FileNotFoundError:
pass
os.mkdir(destdir)
dmg = join(destdir, f'{volname}.dmg')
if os.path.exists(dmg):
os.unlink(dmg)
tdir = tempfile.mkdtemp()
appdir = join(tdir, os.path.basename(d))
shutil.copytree(d, appdir, symlinks=True)
if self.sign_installers:
with timeit() as times:
sign_app(appdir, self.notarize)
print('Signing completed in {} minutes {} seconds'.format(*times))
os.symlink('/Applications', join(tdir, 'Applications'))
size_in_mb = int(subprocess.check_output(['du', '-s', '-k', tdir]).decode('utf-8').split()[0]) / 1024.0
cmd = ['/usr/bin/hdiutil', 'create', '-srcfolder', tdir, '-volname', volname, '-format', format]
if size_in_mb > 190:
# We need an explicit -size because of a bug in hdiutil. When the size of
# srcfolder is close to 200MB hdiutil fails with
# diskimages-helper: resize request is above maximum size allowed.
# Leave headroom for filesystem overhead, otherwise hdiutil fails
# with No space left on device.
cmd += ['-size', f'{max(255, int(size_in_mb * 1.2) + 32)}m']
print('\nCreating dmg...')
with timeit() as times:
subprocess.check_call(cmd + [dmg])
print('dmg created in {} minutes and {} seconds'.format(*times))
shutil.rmtree(tdir)
size = os.stat(dmg).st_size / (1024 * 1024.0)
print(f'\nInstaller size: {size:.2f}MB\n')
return dmg
def main() -> None:
args = globals()['args']
ext_dir = globals()['ext_dir']
Freeze(
join(ext_dir, f'{kitty_constants["appname"]}.app'),
dont_strip=args.dont_strip,
sign_installers=args.sign_installers,
notarize=args.notarize,
skip_tests=args.skip_tests,
)
if __name__ == '__main__':
main()
+1
View File
@@ -0,0 +1 @@
to_vm_excludes '/dependencies /build /dist /shaders /kitty/launcher/kitty* /.build-cache /.cache /.ruff_cache /tags __pycache__ /*_commands.json *.so *.pyd *.pyc *_generated.go'
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import _sitebuiltins
import builtins
import sys
def set_quit() -> None:
eof = 'Ctrl-D (i.e. EOF)'
builtins.quit = _sitebuiltins.Quitter('quit', eof)
builtins.exit = _sitebuiltins.Quitter('exit', eof)
def set_helper() -> None:
builtins.help = _sitebuiltins._Helper()
def main() -> None:
sys.argv[0] = sys.calibre_basename
set_helper()
set_quit()
mod = __import__(sys.calibre_module, fromlist=[1])
func = getattr(mod, sys.calibre_function)
return func()
if __name__ == '__main__':
main()
+310
View File
@@ -0,0 +1,310 @@
[
{
"name": "zlib 1.3.2",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:d7a0654783a4da529d1bb793b7ad9c3318020af77667bcae35f95d0e42a792f3",
"urls": ["https://zlib.net/{filename}"]
}
},
{
"name": "bzip2 1.0.8",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:ab5a03176ee106d3f0fa90e381da478ddae405918153cca248e682cd0c4a2269",
"urls": ["https://www.sourceware.org/pub/{name}/{filename}"]
}
},
{
"name": "pkg-config 0.29.2",
"type": "build",
"os": "macos",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:6fc69c01688c9458a57eb9a1664c9aba372ccda420a02bf4429fe610e7e7d591",
"urls": ["https://pkg-config.freedesktop.org/releases/{filename}"]
}
},
{
"name": "openssl 3.5.9",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a",
"urls": ["https://www.openssl.org/source/{filename}"]
}
},
{
"name": "cmake 3.29.3",
"type": "build",
"os": "macos",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:252aee1448d49caa04954fd5e27d189dd51570557313e7b281636716a238bccb",
"urls": ["https://cmake.org/files/v{version_except_last}/{filename}"]
}
},
{
"name": "expat 2.6.2",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:ee14b4c5d8908b1bec37ad937607eab183d4d9806a08adee472c3c3121d27364",
"urls": ["https://github.com/libexpat/libexpat/releases/download/R_{version_with_underscores}/{filename}"]
}
},
{
"name": "libxml2 2.15.4",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:98087fd181d9070724f3fbc65c7377db03038eb92bd882374daff44940138821",
"urls": ["https://download.gnome.org/sources/libxml2/{version_except_last}/{filename}"]
}
},
{
"name": "xkbcommon 1.7.0",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:65782f0a10a4b455af9c6baab7040e2f537520caa2ec2092805cdfd36863b247",
"urls": ["https://xkbcommon.org/download/lib{filename}"]
}
},
{
"name": "sqlite 3.54.0",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:134ec0802dda5795816e25d25872d20b312cb3973438c49b30bc40b7705ea9ed",
"urls": ["https://www.sqlite.org/2026/{name}-autoconf-3540000.{file_extension}"]
}
},
{
"name": "libffi 3.4.6",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:b0dea9df23c863a7a50e825440f3ebffabd65df1497108e5d437747843895a4e",
"urls": ["https://github.com/libffi/libffi/releases/download/v{version}/{filename}"]
}
},
{
"name": "ncurses 6.5",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:136d91bc269a9a5785e5f9e980bc76ab57428f604ce3e5a5a90cebc767971cc6",
"urls": ["https://ftp.gnu.org/gnu/ncurses/{filename}"]
}
},
{
"name": "readline 8.2",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:3feb7171f16a84ee82ca18a36d7b9be109a52c04f492a053331d7d1095007c35",
"urls": ["https://ftp.gnu.org/gnu/readline/{filename}"]
}
},
{
"name": "xz 5.8.3",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:3d3a1b973af218114f4f889bbaa2f4c037deaae0c8e815eec381c3d546b974a0",
"urls": ["https://tukaani.org/xz/{filename}"]
}
},
{
"name": "libxxhash 0.8.2",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:baee0c6afd4f03165de7a4e67988d16f0f2b257b51d0e3cb91909302a26a79c4",
"urls": ["https://github.com/Cyan4973/xxHash/archive/refs/tags/v{version}.{file_extension}"]
}
},
{
"name": "xcrypt 4.4.36",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:b979838d5f1f238869d467484793b72b8bca64c4eae696fdbba0a9e0b6c28453",
"urls": ["https://github.com/besser82/libxcrypt/archive/v{version}.{file_extension}"]
}
},
{
"name": "python 3.14.10",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:de414a57119abef52784d8993e341d53aed635fc2b05c2607d9f98a2c5b72032",
"urls": ["https://www.python.org/ftp/python/{version}/Python-{version}.{file_extension}"]
}
},
{
"name": "libpng 1.6.57",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:d10c20d7171569804cae8dfc13ba6dcd0662c41ed39d43d4d429314aafb10a80",
"urls": ["https://downloads.sourceforge.net/sourceforge/libpng/{filename}"]
}
},
{
"name": "lcms2 2.17",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:d11af569e42a1baa1650d20ad61d12e41af4fead4aa7964a01f93b08b53ab074",
"urls": ["https://github.com/mm2/Little-CMS/releases/download/lcms{version}/lcms2-{version}.{file_extension}"]
}
},
{
"name": "graphite 1.3.14",
"os": "linux",
"unix": {
"file_extension": "tgz",
"hash": "sha256:f99d1c13aa5fa296898a181dff9b82fb25f6cc0933dbaa7a475d8109bd54209d",
"urls": ["https://downloads.sourceforge.net/silgraphite/graphite2-{version}.{file_extension}"]
}
},
{
"name": "pcre 10.43",
"os": "linux",
"unix": {
"file_extension": "tar.bz2",
"hash": "sha256:e2a53984ff0b07dfdb5ae4486bbb9b21cca8e7df2434096cc9bf1b728c350bcb",
"urls": ["https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.43/pcre2-{version}.{file_extension}"]
}
},
{
"name": "iconv 1.17",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:8f74213b56238c85a50a5329f77e06198771e70dd9a739779f4c02f65d971313",
"urls": ["https://ftp.gnu.org/pub/gnu/libiconv/libiconv-{version}.{file_extension}"]
}
},
{
"name": "glib 2.89.0",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:205bf5dab175de68f11e33be7bb36d4ad4c5a5097d8c0c88a8682b257b6293dc",
"urls": ["https://ftp.gnome.org/pub/GNOME/sources/glib/{version_except_last}/{filename}"]
}
},
{
"name": "libbrotli 1.1.1",
"os": "linux",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:1a84dfaa740994d19254bf78aa7d74a4a8040d1638f3d5f2cdecb188fd520da8",
"urls": ["https://github.com/google/brotli/archive/v{version}/{filename}"]
}
},
{
"name": "pixman 0.44.2",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:50baf820dde0c5ff9714d03d2df4970f606a3d3b1024f5404c0398a9821cc4b0",
"urls": ["https://www.cairographics.org/releases/{filename}"]
}
},
{
"name": "freetype 2.15.0",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:93cd47eb719c325107f2d3cf087d06299e944c3b48a40b55537302304dea1dd5",
"urls": ["https://download.savannah.gnu.org/releases/freetype/{filename}"]
}
},
{
"name": "fontconfig 2.17.1",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:9f5cae93f4fffc1fbc05ae99cdfc708cd60dfd6612ffc0512827025c026fa541",
"urls": ["https://gitlab.freedesktop.org/api/v4/projects/890/packages/generic/fontconfig/{version}/{filename}"]
}
},
{
"name": "cairo 1.18.2",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:a62b9bb42425e844cc3d6ddde043ff39dbabedd1542eba57a2eb79f85889d45a",
"urls": ["https://www.cairographics.org/releases/{filename}"]
}
},
{
"name": "harfbuzz 15.0.0",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:968536e9abd782f07f7954044c0c4020199fcdd39b41d221ec42d2a3be4a44df",
"urls": ["https://github.com/harfbuzz/harfbuzz/releases/download/{version}/{filename}"]
}
},
{
"name": "simde 0.8.2",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:59068edc3420e75c5ff85ecfd80a77196fb3a151227a666cc20abb313a5360bf",
"urls": ["https://github.com/simd-everywhere/simde/releases/download/v{version}/simde-amalgamated-{version}.{file_extension}"]
}
},
{
"name": "slang 2026.14.1",
"unix": {
"file_extension": "tar.gz",
"hash": "sha256:20254026c218ac100ecd118c033f2843e11282152d0d2b6a6b744735674c40ea",
"urls": ["git-submodules://github.com/shader-slang/slang.git"]
}
},
{
"name": "wayland 1.26.0",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:64176eaa46e4969903e286f8e5ef8331affc17fdf03ac9b58381d2b23162b7a3",
"urls": ["https://gitlab.freedesktop.org/wayland/wayland/-/releases/{version}/downloads/{filename}"]
}
},
{
"name": "wayland-protocols 1.49",
"os": "linux",
"unix": {
"file_extension": "tar.xz",
"hash": "sha256:ec4c8f74942d6dff7ace8b4ce4764f0ef9ff618a935d974ea77edee2ad240b14",
"urls": ["https://gitlab.freedesktop.org/wayland/wayland-protocols/-/releases/{version}/downloads/{filename}"]
}
}
]