feat(tui): --ui=next entry point and import guard (6.1.6)
main starts the new UI behind --ui=next with the jobs manager, the SSH pool and resolver in Deps, and tears them down after Program.Run. A test guard forbids os, io/fs, path/filepath, localfs and sftp imports in internal/tui (except deps.go and external.go) and raw key string matching outside the keys package. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
40b8722d58
commit
ebe3b56348
3 changed files with 238 additions and 12 deletions
|
|
@ -1,31 +1,41 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"vcom/internal/config"
|
||||
"vcom/internal/jobs"
|
||||
"vcom/internal/logx"
|
||||
"vcom/internal/paths"
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/ssh/sshconfig"
|
||||
"vcom/internal/tui"
|
||||
"vcom/internal/ui"
|
||||
)
|
||||
|
||||
func main() { os.Exit(run()) }
|
||||
|
||||
// run follows design §9.4: flags → log → config (not fatal) → run dir → UI;
|
||||
// teardown (session, temp files, run dir, log) happens after Program.Run in
|
||||
// every case: normal quit, signal, or a panic Bubble Tea recovered from.
|
||||
// teardown (session, jobs, connections, temp files, run dir, log) happens
|
||||
// after Program.Run in every case: normal quit, signal, or a panic Bubble
|
||||
// Tea recovered from.
|
||||
func run() int {
|
||||
configPath := flag.String("config", "", "path to vcom TOML config")
|
||||
logLevel := flag.String("log-level", "", "log level: debug, info, warn, error (default warn, or $VCOM_LOG)")
|
||||
debug := flag.Bool("debug", false, "shorthand for --log-level=debug")
|
||||
uiFlag := flag.String("ui", "old", "user interface: old (default) or next (the new UI, work in progress)")
|
||||
flag.Parse()
|
||||
|
||||
logger, logErr := openLog(*debug, *logLevel)
|
||||
|
|
@ -55,7 +65,7 @@ func run() int {
|
|||
for _, w := range info.Warnings {
|
||||
slog.Warn("config", "warning", w)
|
||||
}
|
||||
slog.Info("starting", "config", resolvedPath, "log", logger.Path)
|
||||
slog.Info("starting", "config", resolvedPath, "log", logger.Path, "ui", *uiFlag)
|
||||
|
||||
runDir, err := paths.CreateRunDir()
|
||||
if err != nil {
|
||||
|
|
@ -68,15 +78,27 @@ func run() int {
|
|||
}()
|
||||
}
|
||||
|
||||
model, err := ui.NewModel(cfg, resolvedPath)
|
||||
if err != nil {
|
||||
slog.Error("startup", "err", err)
|
||||
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
|
||||
return 1
|
||||
var (
|
||||
program *tea.Program
|
||||
teardown func()
|
||||
)
|
||||
switch *uiFlag {
|
||||
case "next":
|
||||
program, teardown = startNext(cfg, resolvedPath, notice)
|
||||
case "old", "":
|
||||
model, err := ui.NewModel(cfg, resolvedPath)
|
||||
if err != nil {
|
||||
slog.Error("startup", "err", err)
|
||||
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
model = model.WithStatus(notice)
|
||||
program = tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
|
||||
teardown = func() {}
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "vcom: unknown --ui=%s (old or next)\n", *uiFlag)
|
||||
return 2
|
||||
}
|
||||
model = model.WithStatus(notice)
|
||||
|
||||
program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
|
||||
|
||||
// SIGTERM/SIGINT are handled by Bubble Tea itself; SIGHUP (terminal
|
||||
// closed) is not. Either way the program quits and teardown runs below.
|
||||
|
|
@ -92,6 +114,7 @@ func run() int {
|
|||
|
||||
final, runErr := program.Run()
|
||||
shutdown(final)
|
||||
teardown()
|
||||
switch {
|
||||
case runErr == nil:
|
||||
slog.Info("exited cleanly")
|
||||
|
|
@ -122,7 +145,7 @@ func openLog(debug bool, flagLevel string) (*logx.Logger, error) {
|
|||
}
|
||||
|
||||
// shutdown saves the session of the final model (idempotent if the quit key
|
||||
// already did it).
|
||||
// already did it). The new UI saves its session in stage 6.6.
|
||||
func shutdown(final tea.Model) {
|
||||
switch m := final.(type) {
|
||||
case ui.Model:
|
||||
|
|
@ -131,3 +154,54 @@ func shutdown(final tea.Model) {
|
|||
m.Shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
// startNext wires the new UI (design §9.4): the jobs manager, the SSH
|
||||
// connection pool and the host resolver go into tui.Deps. The returned
|
||||
// teardown cancels jobs (giving them 3 s to remove temp files) and closes
|
||||
// every connection; it runs after Program.Run returns.
|
||||
func startNext(cfg config.Config, cfgPath, notice string) (*tea.Program, func()) {
|
||||
var prog atomic.Pointer[tea.Program]
|
||||
send := func(m tea.Msg) {
|
||||
if p := prog.Load(); p != nil {
|
||||
p.Send(m)
|
||||
}
|
||||
}
|
||||
readHome, _ := paths.ReadHome()
|
||||
deps := tui.DefaultDeps(cfg, cfgPath)
|
||||
deps.Notice = notice
|
||||
deps.Jobs = jobs.New(func(e jobs.Event) { send(tui.JobEvent(e)) }, cfg.Transfer.MaxParallelJobs)
|
||||
pool := conn.NewPool(conn.PoolOptions{
|
||||
DialOptions: conn.DialOptions{
|
||||
HandshakeTimeout: cfg.SSH.ConnectTimeout.Duration,
|
||||
Home: readHome,
|
||||
Warn: func(m string) { slog.Warn("ssh", "msg", m) },
|
||||
},
|
||||
KeepaliveInterval: cfg.SSH.KeepaliveInterval.Duration,
|
||||
})
|
||||
deps.Pool = pool
|
||||
var store *sshconfig.Store
|
||||
if f, err := paths.DefaultConfigFile(); err == nil {
|
||||
if s, err := sshconfig.OpenStore(filepath.Dir(f)); err == nil {
|
||||
store = s
|
||||
} else {
|
||||
slog.Warn("hosts store", "err", err)
|
||||
}
|
||||
}
|
||||
res, err := sshconfig.NewResolver(sshconfig.Options{Home: readHome, Store: store})
|
||||
if err != nil {
|
||||
slog.Warn("ssh config", "err", err)
|
||||
}
|
||||
deps.Resolver = res
|
||||
|
||||
p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion())
|
||||
prog.Store(p)
|
||||
return p, func() {
|
||||
prog.Store(nil)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := deps.Jobs.Shutdown(ctx); err != nil {
|
||||
slog.Warn("jobs shutdown", "err", err)
|
||||
}
|
||||
pool.Close()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
119
internal/tui/imports_test.go
Normal file
119
internal/tui/imports_test.go
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
package tui
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// forbidden imports in internal/tui/** (design §7.13): the UI reaches files
|
||||
// only through vfs.FS, so "forgot the remote case" cannot compile.
|
||||
var forbidden = map[string]bool{
|
||||
"os": true,
|
||||
"os/exec": true,
|
||||
"io/fs": true,
|
||||
"path/filepath": true,
|
||||
"syscall": true,
|
||||
"vcom/internal/vfs/localfs": true,
|
||||
"github.com/pkg/sftp": true,
|
||||
"vcom/internal/fs": true,
|
||||
"vcom/internal/fs/remote": true,
|
||||
"vcom/internal/ui": true,
|
||||
"vcom/internal/homedir": true,
|
||||
"github.com/atotto/clipboard": false, // allowed (clipboard.go, stage 6.3)
|
||||
}
|
||||
|
||||
// allowed files (relative to internal/tui): factories and external programs.
|
||||
var importAllow = map[string]bool{
|
||||
"deps.go": true,
|
||||
"external.go": true,
|
||||
}
|
||||
|
||||
func goFiles(t *testing.T) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
err := filepath.Walk(".", func(p string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fi.IsDir() && strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, "_test.go") {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestImportsGuard(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
files := goFiles(t)
|
||||
if len(files) < 10 {
|
||||
t.Fatalf("only %d files found", len(files))
|
||||
}
|
||||
for _, p := range files {
|
||||
f, err := parser.ParseFile(fset, p, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, imp := range f.Imports {
|
||||
path, _ := strconv.Unquote(imp.Path.Value)
|
||||
if forbidden[path] && !importAllow[filepath.ToSlash(p)] {
|
||||
t.Errorf("%s imports %s: go through vfs.FS / Deps instead", p, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Design §7.4: key strings are compared only in internal/tui/keys; elsewhere
|
||||
// keys are resolved to actions.
|
||||
func TestNoRawKeyMatching(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
for _, p := range goFiles(t) {
|
||||
if strings.HasPrefix(filepath.ToSlash(p), "keys/") {
|
||||
continue
|
||||
}
|
||||
f, err := parser.ParseFile(fset, p, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
switch x := n.(type) {
|
||||
case *ast.BinaryExpr:
|
||||
if x.Op == token.EQL || x.Op == token.NEQ {
|
||||
if isStringCall(x.X) && isStringLit(x.Y) || isStringCall(x.Y) && isStringLit(x.X) {
|
||||
t.Errorf("%s: msg.String() compared with a literal; use keys.Registry", fset.Position(x.Pos()))
|
||||
}
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Matches" {
|
||||
if id, ok := sel.X.(*ast.Ident); ok && id.Name == "key" {
|
||||
t.Errorf("%s: key.Matches; use keys.Registry", fset.Position(x.Pos()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func isStringCall(e ast.Expr) bool {
|
||||
c, ok := e.(*ast.CallExpr)
|
||||
if !ok || len(c.Args) != 0 {
|
||||
return false
|
||||
}
|
||||
sel, ok := c.Fun.(*ast.SelectorExpr)
|
||||
return ok && sel.Sel.Name == "String"
|
||||
}
|
||||
|
||||
func isStringLit(e ast.Expr) bool {
|
||||
b, ok := e.(*ast.BasicLit)
|
||||
return ok && b.Kind == token.STRING
|
||||
}
|
||||
|
|
@ -190,3 +190,36 @@
|
|||
прийти позже 1,5 с, и соединение будет признано потерянным после отмены (только после отмены — без отмены
|
||||
сторожок не работает). Последствие — reconnect при следующем действии, данные не страдают. Значения — переменные
|
||||
пакета, их легко поднять.
|
||||
|
||||
## 6.1 Каркас нового UI `internal/tui`
|
||||
|
||||
- **Пакеты:** `tui` (App), `tui/keys`, `tui/notify`, `tui/modal`, `tui/panel`, плюс два вспомогательных сверх плана:
|
||||
`tui/style` (все lipgloss-стили строятся один раз на тему, `Gen` входит в ключи кэшей — §7.10) и `tui/geom`
|
||||
(`Rect` — общий для layout, рендера и hit-test). `tui/viewer` в 6.1 — минимальная модель (Kind/Focus/Gen,
|
||||
прокрутка, построчный caret/visual), чтобы машина состояний и тесты 6.1 работали; 6.3 заменяет рендер.
|
||||
- **Контексты keys** сверх §7.4: `CtxModalConflict`, `CtxModalPrompt` (под 6.2/6.4; Prompt — текстовый). Клавиша
|
||||
Shift+F8 — это `f20` (так её шлёт xterm; у Bubble Tea v1 нет имени `shift+f8`), Shift+Delete в v1 не различается —
|
||||
остаётся `X`. Горячие клавиши кнопок Dialog матчатся самим Dialog (в т. ч. в ЙЦУКЕН через `keys.Translate`) и
|
||||
имеют приоритет над `q` = отмена, поэтому «q q» в диалоге выхода выходит.
|
||||
- **Modal API:** `Key(action, rawKey)` + `Mouse(msg, relX, relY, w, h, styles)` + `View`, без `ID()` — id выдаёт
|
||||
`Stack.Push`, `onClose func(Outcome) tea.Cmd` (замыкание на `*App` выполняется синхронно в Update, не в Cmd).
|
||||
- **Уведомления:** `Center` не считает время сам: `Push` → App планирует `tea.Tick(TTL, noteExpiredMsg{id})` →
|
||||
`Expire(id)` скрывает только свою заметку; Error дополнительно ждёт нажатия (`KeyPressed`).
|
||||
- **Panel:** история хранит снимки со стеком mount-ов, но без отдельного `Acquire` на каждый снимок: при выходе из
|
||||
mount-а (архив/хост) снимки, ссылающиеся на него, выбрасываются, и mount освобождается, когда его не держит ни
|
||||
текущее место, ни история (вперёд в закрытый архив не вернуться — проще и без утечек). Mirror (`MirrorOf`)
|
||||
делает `Acquire` у каждого mount-а. Размеры каталогов (`sizes`) и бейдж соединения — поля для 6.2/6.4.
|
||||
- **Точки расширения App** (чтобы 6.2–6.6 не трогали `app.go`): `register<Feature>(actionTable)` и
|
||||
`register<Feature>Hooks(*App)` в `register_*.go`; `a.handle(fn)` для своих сообщений; `a.onJob(fn)` для событий
|
||||
jobs; `a.openFile` — Enter на не-каталоге (6.5 архивы, 6.6 edit/run/open); `a.invalidate(locs)` после операций;
|
||||
`a.openModal`, `a.notify`, `a.navigate`, `a.req` (Tracker, `ReqFeature` + `Extra` для своих запросов). Действие
|
||||
без обработчика показывает «…: not available yet».
|
||||
- **Превью по умолчанию** (`Deps.Preview`, до 5B/6.3): голова текстового файла через `vfs.FS.Open`, иначе метаданные.
|
||||
- **Imports guard** проверяет не-тестовые файлы (`_test.go` пропускаются — тестам нужны `os`/`localfs` для стенда);
|
||||
allowlist `deps.go`, `external.go`. Дополнительно `TestNoRawKeyMatching`: вне `keys/` нет `x.String() == "…"` и
|
||||
`key.Matches` (§7.4).
|
||||
- **main:** `--ui=next` (по умолчанию `old`). Pool (keepalive/таймаут из `[ssh]`), jobs (`max_parallel_jobs`,
|
||||
notify → `program.Send(tui.JobEvent(e))` через atomic-указатель на программу), Resolver + Store в `Deps`;
|
||||
teardown после `Run`: `jobs.Shutdown(3 с)`, `pool.Close()`. SyncTTY и imgview — после 5C (их пакетов ещё нет).
|
||||
Сессия нового UI — 6.6. Ручной прогон в pty в этой среде невозможен (нет терминала, отвечающего на запрос цвета
|
||||
фона lipgloss); проверено драйвером.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue