chore: drop GitHub workflows and templates

The vendored copy does not run upstream CI: remove the Actions workflows, security scanners and issue templates so nothing is triggered from this repository. The dependency bundle URL is pinned in bypy so setup no longer reads the removed CI script.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
1 parent 3f23d6e065
commit 3769c5d08d
11 files changed
+4 -1362

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
github: kovidgoyal
patreon: kovidgoyal
liberapay: kovidgoyal
custom: https://sw.kovidgoyal.net/kitty/support.html
-32
View File
@@ -1,32 +0,0 @@
---
name: Bug report
about: Create a bug report
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. XXX
2. YYY
3. ZZZ
4. See error
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment details**
```
Press Ctrl+Shift+F6 (cmd+option+comma on macOS) in kitty, to copy debug output about kitty and its
configuration to the clipboard and paste it here.
On older versions of kitty, run kitty --debug-config instead
```
**Additional context**
Try to reproduce the problem with `kitty --config NONE` if you cannot then post a minimal kitty.conf that reproduces the problem. If the problem involves interaction with some other terminal program post a minimal config for that program to reproduce the problem as well.
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
-35
View File
@@ -1,35 +0,0 @@
Before implementing any code changes or responding to a request, run the
following command:
python3 .github/workflows/ci.py build
This will download needed dependencies, then create all generated files
and build the project, making it ready for inspection.
# Repository Build & Test Instructions
## Build Procedures
- **Build command:** Run `./dev.sh build` to build the project
- Run `gen/config.py` to update generated config parsing code for both kitty
and kitten. The `gen/go_code.py` generator is run automatically by the build
command to keep generated Go code files up to date.
- To build individual kittens use the build command above **do not** try to run go build
yourself.
Once a build is done, the kitty and kitten binaries will be in the `kitty/launcher` directory.
Note that the kitty binary can run python files using `kitty +launch file.py`.
When it does so the kitty fast_data_types module is available to the python
code.
## Test Procedures
- To run the complete test suite, run `./test.py`
- To run a specific test, run `./test.py test_name` where `test_name` is the name of the test without the
leading `test_` for Python tests and without the leading `Test` for Go tests.
- Do not use go test or ./setup.py test to run tests
## PR guidance
When creating a pull request, if the changes in the pull request are user
visible compared to the previous kitty release, add an entry in the file docs/changelog.rst
describing the change. If the changes include changes to Go code, run gofmt on
the changed Go files to ensure they are formatted correctly, before submitting
your changes.
-27
View File
@@ -1,27 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "gomod" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
groups:
all-go-deps:
patterns:
- "*" # group all non-security update PRs
cooldown:
default-days: 7
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
groups:
actions:
patterns:
- "*"
cooldown:
default-days: 7
-378
View File
@@ -1,378 +0,0 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import glob
import io
import json
import lzma
import os
import platform
import shlex
import shutil
import subprocess
import sys
import tarfile
import time
from urllib.request import Request, urlopen
BUNDLE_URL = 'https://download.calibre-ebook.com/ci/kitty/{}-64.tar.xz'
FONTS_URL = 'https://download.calibre-ebook.com/ci/fonts.tar.xz'
NERD_URL = 'https://github.com/ryanoasis/nerd-fonts/releases/latest/download/NerdFontsSymbolsOnly.tar.xz'
is_bundle = os.environ.get('KITTY_BUNDLE') == '1'
is_codeql = os.environ.get('KITTY_CODEQL') == '1'
is_macos = 'darwin' in sys.platform.lower()
running_under_sanitizer = os.environ.get('KITTY_SANITIZE') == '1'
SW = ''
SLANG_INSTALL_DIR = '/tmp/slang'
def do_print_crash_reports() -> None:
sys.stdout.flush()
sys.stderr.flush()
time.sleep(2)
print('Printing available crash reports...')
if is_macos:
end_time = time.monotonic() + 90
while time.monotonic() < end_time:
time.sleep(1)
items = glob.glob(os.path.join(os.path.expanduser('~/Library/Logs/DiagnosticReports'), 'kitty-*.ips'))
if items:
break
if items:
time.sleep(1)
print(os.path.basename(items[0]))
sdir = os.path.dirname(os.path.abspath(__file__))
subprocess.check_call([sys.executable, os.path.join(sdir, 'macos_crash_report.py'), items[0]])
else:
run('sh -c "echo bt | coredumpctl debug"')
print(flush=True)
def run(*a: str, print_crash_reports: bool = False) -> None:
if len(a) == 1:
a = tuple(shlex.split(a[0]))
cmd = ' '.join(map(shlex.quote, a))
print(cmd)
sys.stdout.flush()
ret = subprocess.Popen(a).wait()
if ret != 0:
if ret < 0:
import signal
try:
sig = signal.Signals(-ret)
except ValueError:
pass
else:
if print_crash_reports:
do_print_crash_reports()
raise SystemExit(f'The following process was killed by signal: {sig.name}:\n{cmd}')
raise SystemExit(f'The following process failed with exit code: {ret}:\n{cmd}')
def download_with_retry(url: str | Request, count: int = 5) -> bytes:
for i in range(count):
try:
print('Downloading', getattr(url, 'full_url', url), flush=True)
with urlopen(url) as f:
ans: bytes = f.read()
return ans
except Exception as err:
if getattr(err, 'code', -1) == 403:
raise
if i >= count - 1:
raise
print(f'Download failed with error {err} retrying...', file=sys.stderr)
time.sleep(1)
return b''
def install_fonts() -> None:
data = download_with_retry(FONTS_URL)
fonts_dir = os.path.expanduser('~/Library/Fonts' if is_macos else '~/.local/share/fonts')
os.makedirs(fonts_dir, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
try:
tf.extractall(fonts_dir, filter='fully_trusted')
except TypeError:
tf.extractall(fonts_dir)
data = download_with_retry(NERD_URL)
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
try:
tf.extractall(fonts_dir, filter='fully_trusted')
except TypeError:
tf.extractall(fonts_dir)
def install_slang_compiler() -> None:
os_name = 'macos' if is_macos else 'linux'
machine = platform.machine().lower()
arch = 'aarch64' if machine in ('aarch64', 'arm64') else 'x86_64'
with open('bypy/sources.json') as f:
data = json.loads(f.read())
for dep in data:
if dep['name'].startswith('slang '):
version = dep['name'].split()[-1]
break
url = f'https://github.com/shader-slang/slang/releases/download/v{version}/slang-{version}-{os_name}-{arch}.tar.gz'
install_dir = SLANG_INSTALL_DIR
os.makedirs(install_dir, exist_ok=True)
data = download_with_retry(url)
with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as tf:
try:
tf.extractall(install_dir, filter='fully_trusted')
except TypeError:
# filter parameter not supported on older Python versions
tf.extractall(install_dir)
pc_dir = os.path.join(install_dir, 'lib', 'pkgconfig')
pp = os.environ.get('PKG_CONFIG_PATH', '')
os.environ['PKG_CONFIG_PATH'] = f'{pc_dir}:{pp}' if pp else pc_dir
def install_deps() -> None:
print('Installing kitty dependencies...')
sys.stdout.flush()
if is_macos:
if not is_codeql: # for some reason brew fails on CodeQL we dont need it anyway
items = [x.split()[1].strip('"') for x in open('Brewfile').readlines() if x.strip().startswith('brew ')]
openssl = 'openssl'
items.remove('go') # already installed by ci.yml
import ssl
if ssl.OPENSSL_VERSION_INFO[0] == 1:
openssl += '@1.1'
run('brew', 'install', 'fish', openssl, *items)
else:
run('sudo apt-get update')
run(
'sudo apt-get install -y --fix-missing libgl1-mesa-dev libxi-dev libxrandr-dev libxinerama-dev ca-certificates'
' libxcursor-dev libxcb-xkb-dev libdbus-1-dev libxkbcommon-dev libharfbuzz-dev libx11-xcb-dev zsh'
' libpng-dev liblcms2-dev libfontconfig-dev libxkbcommon-x11-dev libcanberra-dev libxxhash-dev uuid-dev'
' libsimde-dev libsystemd-dev libcairo2-dev zsh bash dash systemd-coredump gdb'
' libwayland-dev wayland-protocols glslang-tools'
)
# for some reason these directories are world writable which causes zsh
# compinit to break
run('sudo chmod -R og-w /usr/share/zsh')
if is_bundle:
install_bundle()
else:
cmd = 'python3 -m pip install Pillow pygments'
if sys.version_info[:2] < (3, 7):
cmd += ' importlib-resources dataclasses'
run(cmd)
install_slang_compiler()
install_fonts()
def set_slangc() -> None:
slangc = os.path.join(SW if is_bundle else SLANG_INSTALL_DIR, 'bin', 'slangc')
os.environ['SLANGC'] = slangc
def build_kitty() -> None:
python = shutil.which('python3') if is_bundle else sys.executable
cmd = f'{python} setup.py build --verbose'
if running_under_sanitizer:
cmd += ' --debug --sanitize'
set_slangc()
run(cmd)
def test_kitty() -> None:
if is_macos:
run('ulimit -c unlimited')
run('sudo chmod -R 777 /cores')
if running_under_sanitizer:
os.environ['MallocNanoZone'] = '0'
set_slangc()
run('./test.py', print_crash_reports=True)
def package_kitty() -> None:
set_slangc()
python = 'python3' if is_macos else 'python'
run(f'{python} setup.py linux-package --update-check-interval=0 --verbose')
run('make FAIL_WARN=1 docs')
if is_macos:
run('python3 setup.py kitty.app --update-check-interval=0 --verbose')
run('kitty.app/Contents/MacOS/kitty +runpy "from kitty.constants import *; print(kitty_exe())"')
def replace_in_file(path: str, src: str, dest: str) -> None:
with open(path, 'r+') as f:
n = f.read().replace(src, dest)
f.seek(0), f.truncate()
f.write(n)
def setup_bundle_env() -> None:
global SW
os.environ['SW'] = SW = '/Users/Shared/kitty-build/sw/sw' if is_macos else os.path.join(os.environ['GITHUB_WORKSPACE'], 'sw')
os.environ['PKG_CONFIG_PATH'] = os.path.join(SW, 'lib', 'pkgconfig')
if is_macos:
os.environ['PATH'] = '{}:{}'.format('/usr/local/opt/sphinx-doc/bin', os.environ['PATH'])
else:
os.environ['LD_LIBRARY_PATH'] = os.path.join(SW, 'lib')
os.environ['PYTHONHOME'] = SW
os.environ['PATH'] = '{}:{}'.format(os.path.join(SW, 'bin'), os.environ['PATH'])
def install_bundle(dest: str = '', which: str = '') -> None:
dest = dest or SW
cwd = os.getcwd()
os.makedirs(dest, exist_ok=True)
os.chdir(dest)
which = which or ('macos' if is_macos else 'linux')
data = download_with_retry(BUNDLE_URL.format(which))
with tarfile.open(fileobj=io.BytesIO(data), mode='r:xz') as tf:
try:
tf.extractall(filter='fully_trusted')
except TypeError:
tf.extractall()
if not is_macos:
replaced = 0
for dirpath, dirnames, filenames in os.walk('.'):
for f in filenames:
if f.endswith('.pc') or (f.endswith('.py') and f.startswith('_sysconfig')):
replace_in_file(os.path.join(dirpath, f), '/sw/sw', dest)
replaced += 1
if replaced < 2:
raise SystemExit('Failed to replace path to SW in bundle')
os.chdir(cwd)
def install_grype(exe: str = '/tmp/grype') -> str:
raw = download_with_retry('https://download.calibre-ebook.com/ci/grype.xz')
raw = lzma.decompress(raw)
with open(exe, 'wb') as f:
f.write(raw)
os.fchmod(f.fileno(), 0o755)
subprocess.check_call([exe, 'db', 'update'])
return exe
IGNORED_DEPENDENCY_CVES = [
# Python stdlib
'CVE-2025-8194', # DoS in tarfile
'CVE-2025-6069', # DoS in HTMLParser
'CVE-2025-13836', # DoS in http client reading from malicious server
'CVE-2025-12084', # DoS in xml.dom.minidom unused in kitty
'CVE-2025-13837', # DoS in plistlib reading plist. We only use plistlib for writing
'CVE-2025-6075', # Quadratic complexity in os.path.expandvars()
# python stdlib all these are erroneously marked as fixed in python 3.15
# when it hasnt even been released. Sigh.
'CVE-2026-1299',
'CVE-2026-0865',
'CVE-2025-15282',
'CVE-2026-0672',
'CVE-2025-15366',
'CVE-2025-15367',
'CVE-2025-12781',
'CVE-2025-11468',
'CVE-2026-2297',
'CVE-2026-3644',
'CVE-2026-4224',
'CVE-2026-4519',
'CVE-2026-1502',
'CVE-2026-7210', # DoS in unused XML parser
'CVE-2026-3276', # DoS in unicodedata.normalize()
'CVE-2026-7774', # tarfile.data_filter path traversal bypass
'CVE-2026-12003', # bug in release builds irrelevant to us
'CVE-2026-15308', # bug in stdlib html parser irrelevant to us
'CVE-2026-11940', # tarfile, unused
'CVE-2026-11972', # tarfile, unused
'CVE-2026-0864', # configparser unused
'CVE-2026-17084', # idna encoding, unused
'CVE-2026-15806', # HTTPPasswordMgr unused
'CVE-2026-15310', # DoS in unzip
'CVE-2026-87910', # tarfile extract on systems without links irrelevant
'CVE-2026-12345', # tempfile.TemporaryDirectory cleanup symlink attack
'CVE-2026-103995', # http response header parsing in stdlib, inapplicable
# github.com/nwaples/rardecode/v2
'CVE-2025-11579', # rardecode is version 2.2.1, not vulnerable
]
def check_dependencies() -> None:
grype = install_grype()
with open((gc := os.path.expanduser('~/.grype.yml')), 'w') as f:
print('ignore:', file=f)
for x in IGNORED_DEPENDENCY_CVES:
print(' - vulnerability:', x, file=f)
dest = os.path.join(SW, 'linux')
os.makedirs(dest, exist_ok=True)
install_bundle(dest, os.path.basename(dest))
dest = os.path.join(SW, 'macos')
os.makedirs(dest, exist_ok=True)
install_bundle(dest, os.path.basename(dest))
cmdline = [grype, '--by-cve', '--config', gc, '--fail-on', 'medium', '--only-fixed', '--add-cpes-if-none']
if (subprocess.run(cmdline + ['dir:' + SW])).returncode != 0:
raise SystemExit('grype found problems during filesystem scan')
# Now test against the SBOM
import runpy
orig = sys.argv, sys.stdout
sys.argv = ['bypy', 'sbom', 'kovidgoyal/kitty', '1.0.0']
buf = io.StringIO()
sys.stdout = buf
runpy.run_path('bypy-src')
sys.argv, sys.stdout = orig
print(buf.getvalue())
if (subprocess.run(cmdline, input=buf.getvalue().encode())).returncode != 0:
raise SystemExit('grype found problems during SBOM scan')
def main() -> None:
if is_bundle:
setup_bundle_env()
else:
if not is_macos and 'pythonLocation' in os.environ:
os.environ['LD_LIBRARY_PATH'] = os.path.join(os.environ['pythonLocation'], 'lib')
action = sys.argv[-1]
if action in ('build', 'package'):
install_deps()
if action == 'build':
build_kitty()
elif action == 'package':
build_kitty()
test_kitty()
package_kitty()
elif action == 'test':
test_kitty()
elif action == 'govulncheck':
subprocess.check_call(['go', 'install', 'golang.org/x/vuln/cmd/govulncheck@latest'])
subprocess.check_call(['govulncheck', '-mode=binary', 'kitty/launcher/kitten'])
subprocess.check_call(['govulncheck', './...'])
elif action == 'check_code_formatting':
q = subprocess.check_output('gofmt -s -l tools kittens'.split()).decode()
if q.strip():
q = '\n'.join(filter(lambda x: not x.rstrip().endswith(('_generated.go', '_generated_test.go')), q.strip().splitlines())).strip()
if q:
raise SystemExit(q)
if subprocess.run(['ruff', 'format', '--check']).returncode != 0:
raise SystemExit('Some Python files are not formatted correctly')
c_files = subprocess.check_output(['git', 'ls-files', '*.c', '*.h', '*.m']).decode().split()
if c_files and subprocess.run(['clang-format', '--dry-run', '--Werror'] + c_files).returncode != 0:
raise SystemExit('Some C/ObjC files are not formatted correctly')
slang_files = subprocess.check_output(['git', 'ls-files', '*.slang']).decode().split()
badly_formatted_slang = []
for sf in slang_files:
assume_name = os.path.basename(sf) + '.cs'
with open(sf, 'rb') as f:
result = subprocess.run(['clang-format', '--style=file:.clang-format-for-slang', '--Werror', '-n', f'--assume-filename={assume_name}'], stdin=f)
if result.returncode != 0:
badly_formatted_slang.append(sf)
if badly_formatted_slang:
raise SystemExit('Some .slang files are not formatted correctly:\n' + '\n'.join(badly_formatted_slang))
elif action == 'check-dependencies':
check_dependencies()
else:
raise SystemExit(f'Unknown action: {action}')
if __name__ == '__main__':
main()
-207
View File
@@ -1,207 +0,0 @@
name: CI
on: [pull_request]
env:
CI: 'true'
ASAN_OPTIONS: detect_leaks=0
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
permissions:
contents: read # to fetch code (actions/checkout)
jobs:
linux:
name: Linux (python=${{ matrix.pyver }} cc=${{ matrix.cc }} sanitize=${{ matrix.sanitize }})
runs-on: ubuntu-latest
env:
CC: ${{ matrix.cc }}
KITTY_SANITIZE: ${{ matrix.sanitize }}
strategy:
matrix:
python: [a, b, c]
cc: [gcc, clang]
include:
- python: a
pyver: "3.12"
sanitize: 0
- python: b
pyver: "3.13"
sanitize: 1
- python: c
pyver: "3.14"
sanitize: 1
exclude:
- python: a
cc: clang
- python: b
cc: clang
- python: c
cc: gcc
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 10
persist-credentials: false
- name: Set up Python ${{ matrix.pyver }}
uses: actions/setup-python@v7.1.0
with:
python-version: ${{ matrix.pyver }}
- name: Install Go
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
- name: Build kitty
run: python .github/workflows/ci.py build
- name: Test kitty
run: python .github/workflows/ci.py test
linux-package:
name: Linux package
runs-on: ubuntu-latest
env:
CFLAGS: -funsigned-char
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0 # needed for :commit: docs role
persist-credentials: false
- name: Test for trailing whitespace
run: if grep -Inr '\s$' kitty kitty_tests kittens docs *.py *.asciidoc *.rst *.go .gitattributes .gitignore; then echo Trailing whitespace found, aborting.; exit 1; fi
- name: Test for bad code block formatting
run: if grep -Inr ':code:`\s' kitty kitty_tests kittens docs *.py *.asciidoc *.rst *.go .gitattributes .gitignore; then echo Space at code block start found, aborting.; exit 1; fi
- name: Set up Python
uses: actions/setup-python@v7.1.0
with:
python-version: "3.14"
- name: Install Go
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
cache: false
- name: Cache Go build artifacts for static kittens
uses: actions/cache@v6.1.0
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-golang-static-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-golang-static-
- name: Install build-only deps
run: python -m pip install -r docs/requirements.txt ruff ty types-requests types-docutils types-Pygments clang-format
- name: Run ruff
run: ruff check .
- name: Check code formatting
run: go version && python .github/workflows/ci.py check_code_formatting
- name: Build kitty package
run: python .github/workflows/ci.py package
- name: Run type checking
run: which python && ./test.py type-check
- name: Run go vet
run: go version && go vet -tags testing ./...
- name: Build static kittens
run: python setup.py build-static-binaries
bundle:
name: Bundle test (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
env:
KITTY_BUNDLE: 1
KITTY_SANITIZE: 1
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 10
persist-credentials: false
- name: Install Go
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
- name: Build kitty
run: which python3 && python3 .github/workflows/ci.py build
- name: Test kitty
run: python3 .github/workflows/ci.py test
brew:
name: macOS Brew
runs-on: macos-latest
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0 # needed for :commit: docs role
persist-credentials: false
- name: Set up Python
uses: actions/setup-python@v7.1.0
with:
python-version: "3.14"
- name: Install Go
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
- name: Install deps for docs
run: python3 -m pip install -r docs/requirements.txt
- name: Build kitty package
run: python3 .github/workflows/ci.py package
- name: Run benchmarks
run: ./benchmark.py
linux-dev:
name: Test ./dev.sh and benchmark
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 10
persist-credentials: false
- name: Install build deps
run: sudo apt-get update && sudo apt-get install -y curl xz-utils build-essential git pkg-config libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl1-mesa-dev libxkbcommon-x11-dev libfontconfig-dev libx11-xcb-dev libdbus-1-dev
- name: Install Go
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
- name: Build kitty
run: ./dev.sh build
- name: Run benchmarks
run: ./benchmark.py
-69
View File
@@ -1,69 +0,0 @@
name: "CodeQL"
on:
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 22 * * 5'
jobs:
CodeQL-Build:
permissions:
contents: read # to fetch code (actions/checkout)
security-events: write # to upload SARIF results (github/codeql-action/analyze)
strategy:
fail-fast: false
matrix:
include:
- language: python
os: ubuntu-latest
- language: c
os: ubuntu-latest
- language: c
os: macos-latest
- language: go
os: ubuntu-latest
- language: actions
os: ubuntu-latest
runs-on: ${{ matrix.os }}
env:
KITTY_BUNDLE: 1
KITTY_CODEQL: 1
steps:
- name: Checkout repository
uses: actions/checkout@v7.0.1
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
persist-credentials: false
- name: Install Go
if: matrix.language == 'c' || matrix.language == 'go'
uses: actions/setup-go@v7.0.0
with:
go-version-file: go.mod
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.1
with:
languages: ${{ matrix.language }}
trap-caching: false
- name: Build kitty
if: matrix.language == 'c' || matrix.language == 'go'
run: python3 .github/workflows/ci.py build
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.1
- name: Run govulncheck
if: matrix.language == 'go'
run: python3 .github/workflows/ci.py govulncheck
-37
View File
@@ -1,37 +0,0 @@
name: Depscan
on:
schedule:
- cron: '0 12 * * 5'
env:
CI: 'true'
ASAN_OPTIONS: detect_leaks=0
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
permissions:
contents: read # to fetch code (actions/checkout)
jobs:
dependecy-scanner:
name: Scan dependencies for vulnerabilities
runs-on: ubuntu-latest
env:
KITTY_BUNDLE: 1
steps:
- name: Checkout source code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 10
persist-credentials: false
- name: Checkout bypy
uses: actions/checkout@v7.0.1
with:
fetch-depth: 1
persist-credentials: false
repository: kovidgoyal/bypy
path: bypy-src
- name: Check dependencies
run: python3 .github/workflows/ci.py check-dependencies
-541
View File
@@ -1,541 +0,0 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import posixpath
import re
import subprocess
import sys
from collections import defaultdict, namedtuple
from datetime import datetime
from enum import Enum
from functools import cached_property
from typing import IO, Mapping, Optional
Frame = namedtuple('Frame', 'image_name image_base image_offset symbol symbol_offset')
Register = namedtuple('Register', 'name value')
# Cache mapping filename (basename) -> absolute path, built once on first use.
_build_file_cache: Optional[dict[str, str]] = None
def _build_filename_cache() -> dict[str, str]:
"""Walk the repo build tree and map each filename to its absolute path.
The script lives at <repo>/.github/workflows/, so the repo root is two
levels up. We scan the whole repo tree so we find both in-tree build
artefacts (e.g. kitty/fast_data_types.so) and those under build/.
"""
cache: dict[str, str] = {}
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
for dirpath, _dirnames, filenames in os.walk(repo_root):
for fname in filenames:
# Keep the first occurrence (shallowest path wins).
if fname not in cache:
cache[fname] = os.path.join(dirpath, fname)
return cache
def _resolve_image_path(image_path: str) -> str:
"""Return the real filesystem path for *image_path*.
Crash reports on macOS redact parts of paths for privacy, replacing
directory components with ``*`` (e.g. ``/Users/USER/*/fast_data_types.so``).
These are *not* glob patterns — the ``*`` is a literal privacy placeholder.
When such a path is detected, look up the basename in the build-file cache.
"""
if '*' not in image_path and '?' not in image_path:
return image_path
global _build_file_cache
if _build_file_cache is None:
_build_file_cache = _build_filename_cache()
basename = os.path.basename(image_path)
return _build_file_cache.get(basename, image_path)
def _get_source_locations(frames: list[Frame]) -> dict[int, str]:
"""Use atos to look up source file and line number for each frame.
Returns a mapping of frame index -> 'source_file:line_number' string.
Only frames with a known image path and base address are processed.
"""
# Group frames by (image_path, load_address) so we can batch atos calls.
by_image: dict[tuple[str, int], list[tuple[int, int]]] = defaultdict(list) # (path, base) -> [(address, frame_idx)]
for i, frame in enumerate(frames):
if frame.image_name and frame.image_base is not None and frame.image_offset is not None:
addr = frame.image_base + frame.image_offset
by_image[(frame.image_name, frame.image_base)].append((addr, i))
result: dict[int, str] = {}
for (image_path, load_addr), addr_frame_pairs in by_image.items():
addresses = [addr for addr, _ in addr_frame_pairs]
frame_indices = [idx for _, idx in addr_frame_pairs]
# Paths in crash reports may have privacy-redacted components (e.g.
# /Users/USER/*/fast_data_types.so). Resolve to a real path using the
# cached build-file index before passing to atos.
resolved_path = _resolve_image_path(image_path)
try:
cmd = ['atos', '-o', resolved_path, '-l', hex(load_addr)] + [hex(a) for a in addresses]
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if proc.returncode == 0:
lines = proc.stdout.splitlines()
for frame_idx, line in zip(frame_indices, lines):
# atos output: "func_name (in binary) (source_file:line)"
# Extract the trailing "(file:line)" part. Use [^:]+ for the
# file portion since colons in filenames are rare/invalid on
# macOS, and this avoids false-matches with parentheses in paths.
m = re.search(r'\(([^:()]+:\d+)\)\s*$', line)
if m:
result[frame_idx] = m.group(1)
except (OSError, subprocess.SubprocessError):
pass
return result
def surround(x: str, start: int, end: int) -> str:
if sys.stdout.isatty():
x = f'\033[{start}m{x}\033[{end}m'
return x
def cyan(x: str) -> str:
return surround(x, 96, 39)
def bold(x: str) -> str:
return surround(x, 1, 22)
class BugType(Enum):
WatchdogTimeout = '28'
BasebandStats = '195'
GPUEvent = '284'
Sandbox = '187'
TerminatingStackshot = '509'
ServiceWatchdogTimeout = '29'
Session = '179'
LegacyStackshot = '188'
MACorrelation = '197'
iMessages = '189'
log_power = '278'
PowerLog = 'powerlog'
DuetKnowledgeCollector2 = '58'
BridgeRestore = '83'
LegacyJetsam = '198'
ExcResource_385 = '385'
Modem = '199'
Stackshot = '288'
SystemInformation = 'system_profile'
Jetsam_298 = '298'
MemoryResource = '30'
Bridge = '31'
DifferentialPrivacy = 'diff_privacy'
FirmwareIntegrity = '32'
CoreAnalytics_33 = '33'
AutoBugCapture = '34'
EfiFirmwareIntegrity = '35'
SystemStats = '36'
AnonSystemStats = '37'
Crash_9 = '9'
Jetsam_98 = '98'
LDCM = '100'
Panic_10 = '10'
Spin = '11'
CLTM = '101'
Hang = '12'
Panic_110 = '110'
ConnectionFailure = '13'
MessageTracer = '14'
LowBattery = '120'
Siri = '201'
ShutdownStall = '17'
Panic_210 = '210'
SymptomsCPUUsage = '202'
AssumptionViolation = '18'
CoreHandwriting = 'chw'
IOMicroStackShot = '44'
CoreAnalytics_211 = '211'
SiriAppPrediction = '203'
spin_45 = '45'
PowerMicroStackshots = '220'
BTMetadata = '212'
SystemMemoryReset = '301'
ResetCount = '115'
AutoBugCapture_204 = '204'
WifiCrashBinary = '221'
MicroRunloopHang = '310'
Rosetta = '213'
glitchyspin = '302'
System = '116'
IOPowerSources = '141'
PanicStats = '205'
PowerLog_230 = '230'
LongRunloopHang = '222'
HomeProductsAnalytics = '311'
DifferentialPrivacy_150 = '150'
Rhodes = '214'
ProactiveEventTrackerTransparency = '303'
WiFi = '117'
SymptomsCPUWakes = '142'
SymptomsCPUUsageFatal = '206'
Crash_109 = '109'
ShortRunloopHang = '223'
CoreHandwriting_231 = '231'
ForceReset = '151'
SiriAppSelection = '215'
PrivateFederatedLearning = '304'
Bluetooth = '118'
SCPMotion = '143'
HangSpin = '207'
StepCount = '160'
RTCTransparency = '224'
DiagnosticRequest = '312'
MemorySnapshot = '152'
Rosetta_B = '216'
AudioAccessory = '305'
General = '119'
HotSpotIOMicroSS = '144'
GeoServicesTransparency = '233'
MotionState = '161'
AppStoreTransparency = '225'
SiriSearchFeedback = '313'
BearTrapReserved = '153'
Portrait = '217'
AWDMetricLog = 'metriclog'
SymptomsIO = '145'
SubmissionReserved = '170'
WifiCrash = '209'
Natalies = '162'
SecurityTransparency = '226'
BiomeMapReduce = '234'
MemoryGraph = '154'
MultichannelAudio = '218'
honeybee_payload = '146'
MesaReserved = '171'
WifiSensing = '235'
SiriMiss = '163'
ExcResourceThreads_227 = '227'
TestA = 'T01'
NetworkUsage = '155'
WifiReserved = '180'
SiriActionPrediction = '219'
honeybee_heartbeat = '147'
ECCEvent = '172'
KeyTransparency = '236'
SubDiagHeartBeat = '164'
ThirdPartyHang = '228'
OSFault = '308'
CoreTime = '156'
WifiDriverReserved = '181'
Crash_309 = '309'
honeybee_issue = '148'
CellularPerfReserved = '173'
TestB = 'T02'
StorageStatus = '165'
SiriNotificationTransparency = '229'
TestC = 'T03'
CPUMicroSS = '157'
AccessoryUpdate = '182'
xprotect = '20'
MultitouchFirmware = '149'
MicroStackshot = '174'
AppLaunchDiagnostics = '238'
KeyboardAccuracy = '166'
GPURestart = '21'
FaceTime = '191'
DuetKnowledgeCollector = '158'
OTASUpdate = '183'
ExcResourceThreads_327 = '327'
ExcResource_22 = '22'
DuetDB = '175'
ThirdPartyHangDeveloper = '328'
PrivacySettings = '167'
GasGauge = '192'
MicroStackShots = '23'
BasebandCrash = '159'
GPURestart_184 = '184'
SystemWatchdogCrash = '409'
FlashStatus = '176'
SleepWakeFailure = '24'
CarouselEvent = '168'
AggregateD = '193'
WakeupsMonitorViolation = '25'
DifferentialPrivacy_50 = '50'
ExcResource_185 = '185'
UIAutomation = '177'
ping = '26'
SiriTransaction = '169'
SURestore = '194'
KtraceStackshot = '186'
WirelessDiagnostics = '27'
PowerLogLite = '178'
SKAdNetworkAnalytics = '237'
HangWorkflowResponsiveness = '239'
CompositorClientHang = '243'
class CrashReportBase:
def __init__(self, metadata: Mapping, data: str, filename: str = None):
self.filename = filename
self._metadata = metadata
self._data = data
self._parse()
def _parse(self) -> None:
self._is_json = False
try:
modified_data = self._data
if '\n \n' in modified_data:
modified_data, rest = modified_data.split('\n \n', 1)
rest = '",' + rest.split('",', 1)[1]
modified_data += rest
self._data = json.loads(modified_data)
self._is_json = True
except json.decoder.JSONDecodeError:
pass
@cached_property
def bug_type(self) -> BugType:
return BugType(self.bug_type_str)
@cached_property
def bug_type_str(self) -> str:
return self._metadata['bug_type']
@cached_property
def incident_id(self) -> str:
return self._metadata.get('incident_id')
@cached_property
def timestamp(self) -> datetime:
timestamp = self._metadata.get('timestamp')
timestamp_without_timezone = timestamp.rsplit(' ', 1)[0]
return datetime.strptime(timestamp_without_timezone, '%Y-%m-%d %H:%M:%S.%f')
@cached_property
def name(self) -> str:
return self._metadata.get('name')
def __repr__(self) -> str:
filename = ''
if self.filename:
filename = f'FILENAME:{posixpath.basename(self.filename)} '
return f'<{self.__class__} {filename}TIMESTAMP:{self.timestamp}>'
def __str__(self) -> str:
filename = ''
if self.filename:
filename = self.filename
return cyan(f'{self.incident_id} {self.timestamp}\n{filename}\n\n')
class UserModeCrashReport(CrashReportBase):
def _parse_field(self, name: str) -> str:
name += ':'
for line in self._data.split('\n'):
if line.startswith(name):
field = line.split(name, 1)[1]
field = field.strip()
return field
@cached_property
def faulting_thread(self) -> int:
if self._is_json:
return self._data['faultingThread']
else:
return int(self._parse_field('Triggered by Thread'))
@cached_property
def frames(self) -> list[Frame]:
result = []
if self._is_json:
thread_index = self.faulting_thread
images = self._data['usedImages']
for frame in self._data['threads'][thread_index]['frames']:
image = images[frame['imageIndex']]
result.append(
Frame(
image_name=image.get('path'),
image_base=image.get('base'),
symbol=frame.get('symbol'),
image_offset=frame.get('imageOffset'),
symbol_offset=frame.get('symbolLocation'),
)
)
else:
in_frames = False
for line in self._data.split('\n'):
if in_frames:
splitted = line.split()
if len(splitted) == 0:
break
assert splitted[-2] == '+'
image_base = splitted[-3]
if image_base.startswith('0x'):
result.append(
Frame(image_name=splitted[1], image_base=int(image_base, 16), symbol=None, image_offset=int(splitted[-1]), symbol_offset=None)
)
else:
# symbolicated
result.append(Frame(image_name=splitted[1], image_base=None, symbol=image_base, image_offset=None, symbol_offset=int(splitted[-1])))
if line.startswith(f'Thread {self.faulting_thread} Crashed:'):
in_frames = True
return result
@cached_property
def registers(self) -> list[Register]:
result = []
if self._is_json:
thread_index = self._data['faultingThread']
thread_state = self._data['threads'][thread_index]['threadState']
if 'x' in thread_state:
for i, reg_x in enumerate(thread_state['x']):
result.append(Register(name=f'x{i}', value=reg_x['value']))
for i, (name, value) in enumerate(thread_state.items()):
if name == 'x':
for j, reg_x in enumerate(value):
result.append(Register(name=f'x{j}', value=reg_x['value']))
else:
if isinstance(value, dict):
result.append(Register(name=name, value=value['value']))
else:
in_frames = False
for line in self._data.split('\n'):
if in_frames:
splitted = line.split()
if len(splitted) == 0:
break
for i in range(0, len(splitted), 2):
register_name = splitted[i]
if not register_name.endswith(':'):
break
register_name = register_name[:-1]
register_value = int(splitted[i + 1], 16)
result.append(Register(name=register_name, value=register_value))
if line.startswith(f'Thread {self.faulting_thread} crashed with ARM Thread State'):
in_frames = True
return result
@cached_property
def exception_type(self) -> str:
if self._is_json:
return self._data['exception'].get('type')
else:
return self._parse_field('Exception Type')
@cached_property
def exception_subtype(self) -> Optional[str]:
if self._is_json:
return self._data['exception'].get('subtype')
else:
return self._parse_field('Exception Subtype')
@cached_property
def application_specific_information(self) -> Optional[str]:
result = ''
if self._is_json:
asi = self._data.get('asi')
if asi is None:
return None
return asi
else:
in_frames = False
for line in self._data.split('\n'):
if in_frames:
line = line.strip()
if len(line) == 0:
break
result += line + '\n'
if line.startswith('Application Specific Information:'):
in_frames = True
result = result.strip()
if not result:
return None
return result
def __str__(self) -> str:
result = super().__str__()
result += bold(f'Exception: {self.exception_type}\n')
if self.exception_subtype:
result += bold('Exception Subtype: ')
result += f'{self.exception_subtype}\n'
if self.application_specific_information:
result += bold('Application Specific Information: ')
result += str(self.application_specific_information)
result += '\n'
result += bold('Registers:')
for i, register in enumerate(self.registers):
if i % 4 == 0:
result += '\n'
result += f'{register.name} = 0x{register.value:016x} '.rjust(30)
result += '\n\n'
source_locations = _get_source_locations(self.frames)
result += bold('Frames:\n')
for i, frame in enumerate(self.frames):
image_base = '_HEADER'
if frame.image_base is not None:
image_base = f'0x{frame.image_base:x}'
result += f'\t[{frame.image_name}] {image_base}'
if frame.image_offset:
result += f' + 0x{frame.image_offset:x}'
if frame.symbol is not None:
result += f' ({frame.symbol} + 0x{frame.symbol_offset:x})'
if i in source_locations:
result += f' [{source_locations[i]}]'
result += '\n'
return result
def get_crash_report_from_file(crash_report_file: IO[str]) -> CrashReportBase:
metadata = json.loads(crash_report_file.readline())
try:
bug_type = BugType(metadata['bug_type'])
except ValueError:
return CrashReportBase(metadata, crash_report_file.read(), crash_report_file.name)
bug_type_parsers = {
BugType.Crash_109: UserModeCrashReport,
BugType.Crash_309: UserModeCrashReport,
BugType.ExcResourceThreads_327: UserModeCrashReport,
BugType.ExcResource_385: UserModeCrashReport,
}
parser = bug_type_parsers.get(bug_type)
if parser is None:
return CrashReportBase(metadata, crash_report_file.read(), crash_report_file.name)
return parser(metadata, crash_report_file.read(), crash_report_file.name)
if __name__ == '__main__':
with open(sys.argv[-1]) as f:
print(get_crash_report_from_file(f))
+4 -12
View File
@@ -14,7 +14,6 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
@@ -269,18 +268,11 @@ func dependencies(args []string) {
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 = '(.+?)'")
// The upstream CI scripts are not vendored here, so pin the bundle URL
// instead of scraping it from .github/workflows/ci.py.
const bundle_url = "https://download.calibre-ebook.com/ci/kitty/{}-64.tar.xz"
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]
}
url := bundle_url
var which string
switch runtime.GOOS {
case "darwin":