initial commit [141.14.140.180,mike]
This commit is contained in:
commit
156bb18c91
50 files changed
+13466
No files matched your search
@@ -0,0 +1,264 @@
|
||||
// Package ghostty talks to the installed Ghostty binary: it locates it,
|
||||
// reads documentation, defaults, themes, fonts and actions from it, and
|
||||
// validates config files with `ghostty +validate-config`.
|
||||
package ghostty
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Ghostty is an installed Ghostty binary.
|
||||
type Ghostty struct {
|
||||
Bin string
|
||||
Version string
|
||||
}
|
||||
|
||||
var (
|
||||
reVersion = regexp.MustCompile(`Ghostty (\d+\.\d+\.\d+\S*)`)
|
||||
reValidation = regexp.MustCompile(`^.+?:(\d+):(.*)$`)
|
||||
)
|
||||
|
||||
// Find locates the ghostty binary. An explicit path takes precedence, then
|
||||
// $PATH, then the usual macOS application locations.
|
||||
func Find(explicit string) (*Ghostty, error) {
|
||||
var candidates []string
|
||||
if explicit != "" {
|
||||
candidates = append(candidates, explicit)
|
||||
} else {
|
||||
if p, err := exec.LookPath("ghostty"); err == nil {
|
||||
candidates = append(candidates, p)
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
candidates = append(candidates,
|
||||
"/Applications/Ghostty.app/Contents/MacOS/ghostty",
|
||||
filepath.Join(os.Getenv("HOME"), "Applications/Ghostty.app/Contents/MacOS/ghostty"),
|
||||
)
|
||||
}
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if fi, err := os.Stat(c); err != nil || fi.IsDir() {
|
||||
continue
|
||||
}
|
||||
g := &Ghostty{Bin: c}
|
||||
out, err := g.run(5*time.Second, "+version")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if m := reVersion.FindStringSubmatch(out); m != nil {
|
||||
g.Version = m[1]
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
if explicit != "" {
|
||||
return nil, fmt.Errorf("%s is not a usable ghostty binary", explicit)
|
||||
}
|
||||
return nil, errors.New("ghostty binary not found")
|
||||
}
|
||||
|
||||
func (g *Ghostty) run(timeout time.Duration, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, g.Bin, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
// Keep Ghostty from treating our pipe as an interactive terminal.
|
||||
cmd.Stdin = nil
|
||||
err := cmd.Run()
|
||||
if err != nil && stdout.Len() == 0 {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return "", fmt.Errorf("ghostty %s: %s", strings.Join(args, " "), msg)
|
||||
}
|
||||
return stdout.String(), err
|
||||
}
|
||||
|
||||
// DefaultsWithDocs returns `ghostty +show-config --default --docs`.
|
||||
func (g *Ghostty) DefaultsWithDocs() (string, error) {
|
||||
out, err := g.run(10*time.Second, "+show-config", "--default", "--docs")
|
||||
if err != nil && out == "" {
|
||||
return "", err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Themes lists all available theme names.
|
||||
func (g *Ghostty) Themes() ([]string, error) {
|
||||
out, err := g.run(10*time.Second, "+list-themes", "--plain")
|
||||
if out == "" && err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
seen := map[string]bool{}
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
// Lines look like "Dracula (resources)" or "Mine (user)".
|
||||
if i := strings.LastIndex(line, " ("); i > 0 && strings.HasSuffix(line, ")") {
|
||||
line = line[:i]
|
||||
}
|
||||
if !seen[line] {
|
||||
seen[line] = true
|
||||
names = append(names, line)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// Fonts lists the font families Ghostty can find.
|
||||
func (g *Ghostty) Fonts() ([]string, error) {
|
||||
out, err := g.run(20*time.Second, "+list-fonts")
|
||||
if out == "" && err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var families []string
|
||||
seen := map[string]bool{}
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if line == "" || line[0] == ' ' || line[0] == '\t' {
|
||||
continue
|
||||
}
|
||||
line = strings.TrimSpace(line)
|
||||
if !seen[line] {
|
||||
seen[line] = true
|
||||
families = append(families, line)
|
||||
}
|
||||
}
|
||||
sort.Slice(families, func(i, j int) bool {
|
||||
return strings.ToLower(families[i]) < strings.ToLower(families[j])
|
||||
})
|
||||
return families, nil
|
||||
}
|
||||
|
||||
// Action is a keybinding action.
|
||||
type Action struct {
|
||||
Name string
|
||||
Summary string // first line of the documentation
|
||||
Doc string
|
||||
}
|
||||
|
||||
// Actions lists all keybinding actions with their documentation.
|
||||
func (g *Ghostty) Actions() ([]Action, error) {
|
||||
out, err := g.run(10*time.Second, "+list-actions", "--docs")
|
||||
if out == "" && err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseActions(out), nil
|
||||
}
|
||||
|
||||
func parseActions(out string) []Action {
|
||||
var actions []Action
|
||||
var cur *Action
|
||||
var doc []string
|
||||
flush := func() {
|
||||
if cur == nil {
|
||||
return
|
||||
}
|
||||
cur.Doc = strings.TrimSpace(strings.Join(doc, "\n"))
|
||||
if i := strings.Index(cur.Doc, "\n\n"); i >= 0 {
|
||||
cur.Summary = strings.ReplaceAll(cur.Doc[:i], "\n", " ")
|
||||
} else {
|
||||
cur.Summary = strings.ReplaceAll(cur.Doc, "\n", " ")
|
||||
}
|
||||
actions = append(actions, *cur)
|
||||
}
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if line != "" && line[0] != ' ' && strings.HasSuffix(line, ":") {
|
||||
flush()
|
||||
cur = &Action{Name: strings.TrimSuffix(line, ":")}
|
||||
doc = nil
|
||||
continue
|
||||
}
|
||||
if cur != nil {
|
||||
doc = append(doc, strings.TrimPrefix(line, " "))
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return actions
|
||||
}
|
||||
|
||||
// ValidationError is one problem reported by `ghostty +validate-config`.
|
||||
type ValidationError struct {
|
||||
Line int // 0 if unknown
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e ValidationError) String() string {
|
||||
if e.Line > 0 {
|
||||
return fmt.Sprintf("line %d: %s", e.Line, e.Message)
|
||||
}
|
||||
return e.Message
|
||||
}
|
||||
|
||||
// Validate runs `ghostty +validate-config` on path.
|
||||
func (g *Ghostty) Validate(path string) ([]ValidationError, error) {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, runErr := g.run(15*time.Second, "+validate-config", "--config-file="+abs)
|
||||
var errs []ValidationError
|
||||
sc := bufio.NewScanner(strings.NewReader(out))
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
// Lines look like "/path/to/config:3:font-size: invalid value".
|
||||
e := ValidationError{Message: line}
|
||||
if m := reValidation.FindStringSubmatch(line); m != nil {
|
||||
e.Line, _ = strconv.Atoi(m[1])
|
||||
e.Message = m[2]
|
||||
}
|
||||
errs = append(errs, e)
|
||||
}
|
||||
if runErr != nil && len(errs) == 0 {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(runErr, &exitErr) {
|
||||
return nil, runErr
|
||||
}
|
||||
errs = append(errs, ValidationError{Message: "ghostty reported an invalid configuration"})
|
||||
}
|
||||
return errs, nil
|
||||
}
|
||||
|
||||
// ResourcesDir returns Ghostty's resources directory (where the bundled
|
||||
// themes live), or "".
|
||||
func (g *Ghostty) ResourcesDir() string {
|
||||
if d := os.Getenv("GHOSTTY_RESOURCES_DIR"); d != "" {
|
||||
return d
|
||||
}
|
||||
if g == nil {
|
||||
return ""
|
||||
}
|
||||
bin, err := filepath.EvalSymlinks(g.Bin)
|
||||
if err != nil {
|
||||
bin = g.Bin
|
||||
}
|
||||
dir := filepath.Dir(bin)
|
||||
for _, c := range []string{
|
||||
filepath.Join(dir, "../Resources/ghostty"), // macOS app bundle
|
||||
filepath.Join(dir, "../share/ghostty"), // Linux prefix install
|
||||
} {
|
||||
if fi, err := os.Stat(filepath.Join(c, "themes")); err == nil && fi.IsDir() {
|
||||
return filepath.Clean(c)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package ghostty
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func xdgConfigDir() string {
|
||||
if d := os.Getenv("XDG_CONFIG_HOME"); d != "" {
|
||||
return filepath.Join(d, "ghostty")
|
||||
}
|
||||
return filepath.Join(os.Getenv("HOME"), ".config", "ghostty")
|
||||
}
|
||||
|
||||
func macConfigDir() string {
|
||||
return filepath.Join(os.Getenv("HOME"), "Library", "Application Support", "com.mitchellh.ghostty")
|
||||
}
|
||||
|
||||
// ConfigCandidates lists the files Ghostty loads by default, in load order.
|
||||
func ConfigCandidates() []string {
|
||||
xdg := xdgConfigDir()
|
||||
c := []string{filepath.Join(xdg, "config"), filepath.Join(xdg, "config.ghostty")}
|
||||
if runtime.GOOS == "darwin" {
|
||||
mac := macConfigDir()
|
||||
c = append(c, filepath.Join(mac, "config"), filepath.Join(mac, "config.ghostty"))
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// DefaultConfigPath picks the config file to edit: the last existing file
|
||||
// in Ghostty's load order (it has the final say), or the preferred location
|
||||
// for a new file.
|
||||
func DefaultConfigPath() string {
|
||||
c := ConfigCandidates()
|
||||
for i := len(c) - 1; i >= 0; i-- {
|
||||
if fi, err := os.Stat(c[i]); err == nil && !fi.IsDir() {
|
||||
return c[i]
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
return filepath.Join(macConfigDir(), "config.ghostty")
|
||||
}
|
||||
return filepath.Join(xdgConfigDir(), "config.ghostty")
|
||||
}
|
||||
|
||||
// ExistingConfigFiles returns all default config files that exist.
|
||||
func ExistingConfigFiles() []string {
|
||||
var out []string
|
||||
for _, c := range ConfigCandidates() {
|
||||
if fi, err := os.Stat(c); err == nil && !fi.IsDir() {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Theme holds the colors of a theme file, used for previews.
|
||||
type Theme struct {
|
||||
Name string
|
||||
Background string
|
||||
Foreground string
|
||||
Cursor string
|
||||
Selection string
|
||||
Palette [16]string
|
||||
}
|
||||
|
||||
// ThemeDirs returns the directories searched for themes, user dirs first.
|
||||
func (g *Ghostty) ThemeDirs() []string {
|
||||
dirs := []string{filepath.Join(xdgConfigDir(), "themes")}
|
||||
if runtime.GOOS == "darwin" {
|
||||
dirs = append(dirs, filepath.Join(macConfigDir(), "themes"))
|
||||
}
|
||||
if r := g.ResourcesDir(); r != "" {
|
||||
dirs = append(dirs, filepath.Join(r, "themes"))
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// LoadTheme reads a theme by name (or absolute path) for previewing.
|
||||
func (g *Ghostty) LoadTheme(name string) (*Theme, error) {
|
||||
var path string
|
||||
if filepath.IsAbs(name) {
|
||||
path = name
|
||||
} else {
|
||||
for _, d := range g.ThemeDirs() {
|
||||
p := filepath.Join(d, name)
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
path = p
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if path == "" {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
t := &Theme{Name: name}
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
key, value, ok := strings.Cut(sc.Text(), "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key, value = strings.TrimSpace(key), strings.TrimSpace(value)
|
||||
switch key {
|
||||
case "background":
|
||||
t.Background = value
|
||||
case "foreground":
|
||||
t.Foreground = value
|
||||
case "cursor-color":
|
||||
t.Cursor = value
|
||||
case "selection-background":
|
||||
t.Selection = value
|
||||
case "palette":
|
||||
idx, color, ok := strings.Cut(value, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var n int
|
||||
for _, c := range strings.TrimSpace(idx) {
|
||||
if c < '0' || c > '9' {
|
||||
n = -1
|
||||
break
|
||||
}
|
||||
n = n*10 + int(c-'0')
|
||||
}
|
||||
if n >= 0 && n < 16 {
|
||||
t.Palette[n] = strings.TrimSpace(color)
|
||||
}
|
||||
}
|
||||
}
|
||||
return t, sc.Err()
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package ghostty
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrNotRunning is returned by Reload when no Ghostty instance was found.
|
||||
var ErrNotRunning = errors.New("Ghostty is not running")
|
||||
|
||||
// ErrReloadUnsupported is returned by Reload on platforms where Ghostty
|
||||
// cannot be asked to reload from outside.
|
||||
var ErrReloadUnsupported = errors.New("automatic reload is not supported on this platform")
|
||||
|
||||
// Reload asks every running Ghostty instance to reload its configuration,
|
||||
// as if the reload_config action (⌘⇧, / ctrl+shift+,) had been triggered.
|
||||
//
|
||||
// On macOS this uses Ghostty's AppleScript "perform action" command, on
|
||||
// Linux the SIGUSR2 handler of the GTK app.
|
||||
func Reload() error {
|
||||
return reload()
|
||||
}
|
||||
|
||||
// isCLIAction reports whether a NUL-separated command line runs a Ghostty
|
||||
// CLI action ("ghostty +validate-config", …) rather than the app. Like
|
||||
// Ghostty, it only looks at arguments before "-e".
|
||||
func isCLIAction(cmdline []byte) bool {
|
||||
args := bytes.Split(bytes.TrimRight(cmdline, "\x00"), []byte{0})
|
||||
for _, a := range args[1:] {
|
||||
if string(a) == "-e" {
|
||||
break
|
||||
}
|
||||
if bytes.HasPrefix(a, []byte("+")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package ghostty
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The bundle id is used instead of the name so that the script never
|
||||
// launches a different app, and the "is running" check keeps it from
|
||||
// starting Ghostty when it is closed.
|
||||
const reloadScript = `
|
||||
if application id "com.mitchellh.ghostty" is running then
|
||||
tell application id "com.mitchellh.ghostty"
|
||||
if (count of terminals) is 0 then return "no terminals"
|
||||
return perform action "reload_config" on first terminal
|
||||
end tell
|
||||
else
|
||||
return "not running"
|
||||
end if`
|
||||
|
||||
func reload() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "osascript", "-e", reloadScript)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err := cmd.Run()
|
||||
out := strings.TrimSpace(stdout.String())
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
switch {
|
||||
case errors.Is(ctx.Err(), context.DeadlineExceeded):
|
||||
return errors.New("osascript timed out (is a permission dialog open?)")
|
||||
case strings.Contains(msg, "-1743"):
|
||||
return errors.New("not allowed to control Ghostty; allow it in System Settings → Privacy & Security → Automation")
|
||||
case strings.Contains(msg, "-1708"), strings.Contains(msg, "-10000"):
|
||||
return errors.New("Ghostty refused the AppleScript command (is macos-applescript = false set?)")
|
||||
case msg != "":
|
||||
return fmt.Errorf("osascript: %s", msg)
|
||||
}
|
||||
return fmt.Errorf("osascript: %w", err)
|
||||
}
|
||||
switch out {
|
||||
case "true":
|
||||
return nil
|
||||
case "not running":
|
||||
return ErrNotRunning
|
||||
case "no terminals":
|
||||
return errors.New("Ghostty has no open terminal to send the reload to")
|
||||
default:
|
||||
return fmt.Errorf("Ghostty did not perform reload_config (%s)", out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package ghostty
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// reload sends SIGUSR2 to the user's running Ghostty apps, which makes the
|
||||
// GTK app reload its configuration.
|
||||
func reload() error {
|
||||
pids := ghosttyApps("/proc", os.Getuid())
|
||||
if len(pids) == 0 {
|
||||
return ErrNotRunning
|
||||
}
|
||||
var errs []error
|
||||
for _, pid := range pids {
|
||||
if err := syscall.Kill(pid, syscall.SIGUSR2); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if len(errs) == len(pids) {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ghosttyApps finds Ghostty GUI processes owned by uid. CLI invocations
|
||||
// such as "ghostty +list-themes" are skipped: they do not handle SIGUSR2 and
|
||||
// would be terminated by it.
|
||||
func ghosttyApps(proc string, uid int) []int {
|
||||
entries, err := os.ReadDir(proc)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var pids []int
|
||||
for _, e := range entries {
|
||||
pid, err := strconv.Atoi(e.Name())
|
||||
if err != nil || pid == os.Getpid() {
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(proc, e.Name())
|
||||
comm, err := os.ReadFile(filepath.Join(dir, "comm"))
|
||||
if err != nil || strings.TrimSpace(string(comm)) != "ghostty" {
|
||||
continue
|
||||
}
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Stat(dir, &st); err != nil || int(st.Uid) != uid {
|
||||
continue
|
||||
}
|
||||
cmdline, err := os.ReadFile(filepath.Join(dir, "cmdline"))
|
||||
if err != nil || isCLIAction(cmdline) {
|
||||
continue
|
||||
}
|
||||
pids = append(pids, pid)
|
||||
}
|
||||
return pids
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !darwin && !linux
|
||||
|
||||
package ghostty
|
||||
|
||||
func reload() error {
|
||||
return ErrReloadUnsupported
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ghostty
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsCLIAction(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"/usr/bin/ghostty\x00": false,
|
||||
"ghostty\x00--gtk-single-instance=true\x00": false,
|
||||
"ghostty\x00+list-themes\x00": true,
|
||||
"ghostty\x00--config-file=x\x00+show-config\x00": true,
|
||||
"ghostty\x00-e\x00vim\x00+10\x00file\x00": false,
|
||||
}
|
||||
for cmdline, want := range cases {
|
||||
if got := isCLIAction([]byte(cmdline)); got != want {
|
||||
t.Errorf("isCLIAction(%q) = %v, want %v", cmdline, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user