feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+599
@@ -0,0 +1,599 @@
|
||||
// Package uimigrate migrates source syntax to the UI's checked value API.
|
||||
// It resolves the actual MyGo import alias and local declaration types;
|
||||
// it never performs global text replacements.
|
||||
package uimigrate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/format"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Result is a source migration and any changes requiring human review.
|
||||
type Result struct {
|
||||
Source []byte
|
||||
Changed bool
|
||||
Notes []string
|
||||
}
|
||||
|
||||
type migration struct {
|
||||
alias string
|
||||
kinds map[*ast.Object]string
|
||||
structs map[string]map[string]string
|
||||
objects map[*ast.Object]string
|
||||
returns map[string][]typeFact
|
||||
aliases map[string]string
|
||||
// declared holds the objects whose type is written in their declaration;
|
||||
// an assignment never overrides it.
|
||||
declared map[*ast.Object]bool
|
||||
notes []string
|
||||
}
|
||||
|
||||
type typeFact struct{ kind, object string }
|
||||
type packageFacts struct {
|
||||
structs map[string]map[string]string
|
||||
returns map[string][]typeFact
|
||||
// aliases maps the package's aliases of UI types, as type E =
|
||||
// *ui.Element, to the kind they stand for.
|
||||
aliases map[string]string
|
||||
}
|
||||
|
||||
// File transforms one file. Files adds declarations from sibling package files.
|
||||
func File(filename string, source []byte) (Result, error) {
|
||||
results, err := Files(map[string][]byte{filename: source})
|
||||
return results[filename], err
|
||||
}
|
||||
|
||||
// Files migrates a source set, sharing syntax facts within each directory and
|
||||
// package. It needs no successfully compiled old API or external Go tooling.
|
||||
func Files(sources map[string][]byte) (map[string]Result, error) {
|
||||
fs := token.NewFileSet()
|
||||
files := map[string]*ast.File{}
|
||||
groups := map[string]*packageFacts{}
|
||||
var names []string
|
||||
for name := range sources {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
// Aliases of UI types first, as declarations in any file of the
|
||||
// package may name them.
|
||||
for _, name := range names {
|
||||
f, err := parser.ParseFile(fs, name, sources[name], parser.ParseComments)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files[name] = f
|
||||
group := filepath.Dir(name) + "\x00" + f.Name.Name
|
||||
facts := groups[group]
|
||||
if facts == nil {
|
||||
facts = &packageFacts{structs: map[string]map[string]string{}, returns: map[string][]typeFact{}, aliases: map[string]string{}}
|
||||
groups[group] = facts
|
||||
}
|
||||
m := newMigration(importAlias(f), facts)
|
||||
ast.Inspect(f, func(node ast.Node) bool {
|
||||
if n, ok := node.(*ast.TypeSpec); ok && n.Assign.IsValid() {
|
||||
if kind := m.uiType(n.Type); kind != "" {
|
||||
facts.aliases[n.Name.Name] = kind
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
for _, name := range names {
|
||||
f := files[name]
|
||||
facts := groups[filepath.Dir(name)+"\x00"+f.Name.Name]
|
||||
m := newMigration(importAlias(f), facts)
|
||||
ast.Inspect(f, func(node ast.Node) bool {
|
||||
switch n := node.(type) {
|
||||
case *ast.TypeSpec:
|
||||
if structure, ok := n.Type.(*ast.StructType); ok {
|
||||
fields := map[string]string{}
|
||||
for _, field := range structure.Fields.List {
|
||||
if kind := m.uiType(field.Type); kind != "" {
|
||||
for _, id := range field.Names {
|
||||
fields[id.Name] = kind
|
||||
}
|
||||
}
|
||||
}
|
||||
facts.structs[n.Name.Name] = fields
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if n.Recv != nil || n.Type.Results == nil {
|
||||
return true
|
||||
}
|
||||
var results []typeFact
|
||||
for _, field := range n.Type.Results.List {
|
||||
fact := m.fact(field.Type)
|
||||
for range max(1, len(field.Names)) {
|
||||
results = append(results, fact)
|
||||
}
|
||||
}
|
||||
facts.returns[n.Name.Name] = results
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
results := map[string]Result{}
|
||||
for _, name := range names {
|
||||
f := files[name]
|
||||
alias := importAlias(f)
|
||||
if alias == "" || alias == "_" {
|
||||
results[name] = Result{Source: sources[name]}
|
||||
continue
|
||||
}
|
||||
if alias == "." {
|
||||
results[name] = Result{Source: sources[name], Notes: []string{"replace the dot import with an explicit MyGo UI alias before migrating"}}
|
||||
continue
|
||||
}
|
||||
m := newMigration(alias, groups[filepath.Dir(name)+"\x00"+f.Name.Name])
|
||||
m.collect(f)
|
||||
rewriteTypes(reflect.ValueOf(f), m)
|
||||
ast.Walk(visitor{m: m}, f)
|
||||
var out bytes.Buffer
|
||||
if err := format.Node(&out, fs, f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
formatted, err := format.Source(out.Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results[name] = Result{Source: formatted, Changed: !bytes.Equal(sources[name], formatted), Notes: m.notes}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func importAlias(f *ast.File) string {
|
||||
for _, im := range f.Imports {
|
||||
if strings.Trim(im.Path.Value, "\"") == "github.com/egoist/mygo/ui" {
|
||||
if im.Name != nil {
|
||||
return im.Name.Name
|
||||
}
|
||||
return "ui"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func newMigration(alias string, facts *packageFacts) *migration {
|
||||
return &migration{alias: alias, kinds: map[*ast.Object]string{}, objects: map[*ast.Object]string{}, declared: map[*ast.Object]bool{}, structs: facts.structs, returns: facts.returns, aliases: facts.aliases}
|
||||
}
|
||||
func (m *migration) fact(e ast.Expr) typeFact {
|
||||
if kind := m.uiType(e); kind != "" {
|
||||
return typeFact{kind: kind}
|
||||
}
|
||||
if star, ok := e.(*ast.StarExpr); ok {
|
||||
e = star.X
|
||||
}
|
||||
if name, ok := e.(*ast.Ident); ok {
|
||||
if kind := m.aliases[name.Name]; kind != "" {
|
||||
return typeFact{kind: kind}
|
||||
}
|
||||
return typeFact{object: name.Name}
|
||||
}
|
||||
return typeFact{}
|
||||
}
|
||||
func (m *migration) expressionFact(e ast.Expr) typeFact {
|
||||
if kind := m.kind(e); kind != "" {
|
||||
return typeFact{kind: kind}
|
||||
}
|
||||
switch e := e.(type) {
|
||||
case *ast.Ident:
|
||||
return typeFact{object: m.objects[e.Obj]}
|
||||
case *ast.UnaryExpr:
|
||||
return m.expressionFact(e.X)
|
||||
case *ast.CompositeLit:
|
||||
return m.fact(e.Type)
|
||||
case *ast.CallExpr:
|
||||
if name, ok := e.Fun.(*ast.Ident); ok && len(m.returns[name.Name]) == 1 {
|
||||
return m.returns[name.Name][0]
|
||||
}
|
||||
}
|
||||
return typeFact{}
|
||||
}
|
||||
func (m *migration) remember(object *ast.Object, fact typeFact) {
|
||||
if object == nil || m.declared[object] {
|
||||
return
|
||||
}
|
||||
if fact.kind != "" {
|
||||
m.kinds[object] = fact.kind
|
||||
}
|
||||
if fact.object != "" {
|
||||
m.objects[object] = fact.object
|
||||
}
|
||||
}
|
||||
|
||||
// declare records the type written in an object's declaration.
|
||||
func (m *migration) declare(object *ast.Object, typ ast.Expr) {
|
||||
if object == nil || typ == nil {
|
||||
return
|
||||
}
|
||||
m.remember(object, m.fact(typ))
|
||||
m.declared[object] = true
|
||||
}
|
||||
|
||||
func (m *migration) uiType(e ast.Expr) string {
|
||||
if star, ok := e.(*ast.StarExpr); ok {
|
||||
e = star.X
|
||||
}
|
||||
if ix, ok := e.(*ast.IndexExpr); ok {
|
||||
e = ix.X
|
||||
}
|
||||
if ix, ok := e.(*ast.IndexListExpr); ok {
|
||||
e = ix.X
|
||||
}
|
||||
if s, ok := e.(*ast.SelectorExpr); ok {
|
||||
if p, ok := s.X.(*ast.Ident); ok && p.Name == m.alias {
|
||||
if s.Sel.Name == "Context" || s.Sel.Name == "Element" || uiParts[s.Sel.Name] {
|
||||
return s.Sel.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *migration) collect(f *ast.File) {
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
switch n := n.(type) {
|
||||
case *ast.TypeSpec:
|
||||
if s, ok := n.Type.(*ast.StructType); ok {
|
||||
fields := map[string]string{}
|
||||
for _, field := range s.Fields.List {
|
||||
if k := m.uiType(field.Type); k != "" {
|
||||
for _, id := range field.Names {
|
||||
fields[id.Name] = k
|
||||
}
|
||||
advice := "Handle for persistent control identity"
|
||||
if k == "Context" {
|
||||
advice = "Services for retained window services"
|
||||
}
|
||||
m.notes = append(m.notes, fmt.Sprintf("review stored %s fields on %s; use %s", k, n.Name.Name, advice))
|
||||
}
|
||||
}
|
||||
m.structs[n.Name.Name] = fields
|
||||
}
|
||||
case *ast.Field:
|
||||
for _, id := range n.Names {
|
||||
m.declare(id.Obj, n.Type)
|
||||
}
|
||||
case *ast.ValueSpec:
|
||||
for _, id := range n.Names {
|
||||
m.declare(id.Obj, n.Type)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
for range 3 {
|
||||
ast.Inspect(f, func(node ast.Node) bool {
|
||||
if a, ok := node.(*ast.AssignStmt); ok {
|
||||
if len(a.Rhs) == 1 {
|
||||
if call, ok := a.Rhs[0].(*ast.CallExpr); ok {
|
||||
if name, ok := call.Fun.(*ast.Ident); ok {
|
||||
facts := m.returns[name.Name]
|
||||
if len(facts) == len(a.Lhs) {
|
||||
for i, lhs := range a.Lhs {
|
||||
if id, ok := lhs.(*ast.Ident); ok {
|
||||
m.remember(id.Obj, facts[i])
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The variables of a multi-valued call take its results, which
|
||||
// are never the call's single value: only pair equal sides.
|
||||
if len(a.Lhs) == len(a.Rhs) {
|
||||
for i, lhs := range a.Lhs {
|
||||
if id, ok := lhs.(*ast.Ident); ok {
|
||||
m.remember(id.Obj, m.expressionFact(a.Rhs[i]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if v, ok := node.(*ast.ValueSpec); ok && len(v.Names) == len(v.Values) {
|
||||
for i, name := range v.Names {
|
||||
m.remember(name.Obj, m.expressionFact(v.Values[i]))
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (m *migration) kind(e ast.Expr) string {
|
||||
switch e := e.(type) {
|
||||
case *ast.Ident:
|
||||
return m.kinds[e.Obj]
|
||||
case *ast.SelectorExpr:
|
||||
if kind := m.kind(e.X); kind == "Parts" || strings.HasSuffix(kind, "Parts") {
|
||||
switch e.Sel.Name {
|
||||
case "Trigger", "Input", "Track", "List", "Root":
|
||||
return "Element"
|
||||
}
|
||||
}
|
||||
if id, ok := e.X.(*ast.Ident); ok {
|
||||
return m.structs[m.objects[id.Obj]][e.Sel.Name]
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if name, ok := e.Fun.(*ast.Ident); ok && len(m.returns[name.Name]) == 1 {
|
||||
return m.returns[name.Name][0].kind
|
||||
}
|
||||
fn := e.Fun
|
||||
if ix, ok := fn.(*ast.IndexExpr); ok {
|
||||
fn = ix.X
|
||||
}
|
||||
if ix, ok := fn.(*ast.IndexListExpr); ok {
|
||||
fn = ix.X
|
||||
}
|
||||
if s, ok := fn.(*ast.SelectorExpr); ok {
|
||||
// Package ui's signatures decide (uiapi.go).
|
||||
if p, ok := s.X.(*ast.Ident); ok && p.Name == m.alias {
|
||||
return uiResults[s.Sel.Name]
|
||||
}
|
||||
if m.kind(s.X) == "Element" && elementChains[s.Sel.Name] {
|
||||
return "Element"
|
||||
}
|
||||
if m.kind(s.X) == "Context" && s.Sel.Name == "Root" {
|
||||
return "Element"
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var exprType = reflect.TypeOf((*ast.Expr)(nil)).Elem()
|
||||
|
||||
func rewriteTypes(v reflect.Value, m *migration) {
|
||||
if !v.IsValid() {
|
||||
return
|
||||
}
|
||||
if v.Kind() == reflect.Interface {
|
||||
if v.IsNil() {
|
||||
return
|
||||
}
|
||||
if v.Type() == exprType && v.CanSet() {
|
||||
if star, ok := v.Interface().(*ast.StarExpr); ok {
|
||||
if k := m.uiType(star); k != "" && k != "Context" {
|
||||
if s, ok := star.X.(*ast.SelectorExpr); ok {
|
||||
s.Sel.Name = k
|
||||
}
|
||||
v.Set(reflect.ValueOf(ast.Expr(star.X)))
|
||||
return
|
||||
}
|
||||
}
|
||||
if s, ok := v.Interface().(*ast.SelectorExpr); ok {
|
||||
if k := m.uiType(s); k != "" {
|
||||
s.Sel.Name = k
|
||||
}
|
||||
}
|
||||
}
|
||||
rewriteTypes(v.Elem(), m)
|
||||
return
|
||||
}
|
||||
if v.Kind() == reflect.Pointer {
|
||||
if v.IsNil() {
|
||||
return
|
||||
}
|
||||
// Object/scope links form cycles and are not syntax children.
|
||||
if v.Type() == reflect.TypeOf((*ast.Object)(nil)) || v.Type() == reflect.TypeOf((*ast.Scope)(nil)) {
|
||||
return
|
||||
}
|
||||
rewriteTypes(v.Elem(), m)
|
||||
return
|
||||
}
|
||||
if v.Kind() == reflect.Struct {
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
rewriteTypes(v.Field(i), m)
|
||||
}
|
||||
}
|
||||
if v.Kind() == reflect.Slice {
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
rewriteTypes(v.Index(i), m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type visitor struct {
|
||||
m *migration
|
||||
frame string
|
||||
returns []string
|
||||
}
|
||||
|
||||
func (v visitor) Visit(n ast.Node) ast.Visitor {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
switch n := n.(type) {
|
||||
case *ast.FuncDecl:
|
||||
return v.function(n.Type)
|
||||
case *ast.FuncLit:
|
||||
return v.function(n.Type)
|
||||
case *ast.BinaryExpr:
|
||||
if n.Op == token.EQL || n.Op == token.NEQ {
|
||||
var e ast.Expr
|
||||
if isNil(n.X) {
|
||||
e = n.Y
|
||||
} else if isNil(n.Y) {
|
||||
e = n.X
|
||||
}
|
||||
if e != nil && v.m.kind(e) != "" {
|
||||
// Parent rewriting handles replacement of the whole expression.
|
||||
}
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if sel, ok := n.Fun.(*ast.SelectorExpr); ok {
|
||||
if sel.Sel.Name == "Key" && v.m.kind(sel.X) == "Element" && len(n.Args) == 1 {
|
||||
if root := v.m.constructor(sel.X); root != nil && len(root.Args) > 0 && v.m.kind(root.Args[0]) == "Context" {
|
||||
root.Args[0] = &ast.CallExpr{Fun: &ast.SelectorExpr{X: root.Args[0], Sel: ast.NewIdent("Key")}, Args: n.Args}
|
||||
if before, ok := sel.X.(*ast.CallExpr); ok {
|
||||
*n = *before
|
||||
}
|
||||
} else {
|
||||
v.m.notes = append(v.m.notes, "move a stored element's Key to Context.Key before its constructor")
|
||||
}
|
||||
}
|
||||
if sel.Sel.Name == "Rows" && v.m.kind(sel.X) == "Element" && len(n.Args) == 1 {
|
||||
if _, ok := n.Args[0].(*ast.FuncLit); !ok {
|
||||
if id, ok := n.Args[0].(*ast.Ident); !ok || id.Obj == nil || id.Obj.Kind != ast.Fun {
|
||||
sel.Sel.Name = "GridRows"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case *ast.AssignStmt:
|
||||
for i, rhs := range n.Rhs {
|
||||
if i < len(n.Lhs) && isNil(rhs) {
|
||||
if k := v.m.kind(n.Lhs[i]); k == "Element" {
|
||||
n.Rhs[i] = v.zero(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
case *ast.ReturnStmt:
|
||||
for i, rhs := range n.Results {
|
||||
if i < len(v.returns) && isNil(rhs) && v.returns[i] != "" && v.returns[i] != "Context" {
|
||||
n.Results[i] = v.zero(v.returns[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
// Replace nil comparisons in expression fields without altering other
|
||||
// pointer comparisons. This pass uses collected declaration identities.
|
||||
replaceComparisons(reflect.ValueOf(n), v.m)
|
||||
return v
|
||||
}
|
||||
|
||||
func (v visitor) function(t *ast.FuncType) visitor {
|
||||
if t.Params != nil {
|
||||
for _, p := range t.Params.List {
|
||||
if v.m.uiType(p.Type) == "Context" && len(p.Names) > 0 {
|
||||
v.frame = p.Names[0].Name
|
||||
}
|
||||
}
|
||||
}
|
||||
v.returns = nil
|
||||
if t.Results != nil {
|
||||
for _, r := range t.Results.List {
|
||||
for range max(len(r.Names), 1) {
|
||||
v.returns = append(v.returns, v.m.uiType(r.Type))
|
||||
}
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func hasFrame(t *ast.FuncType, m *migration) bool {
|
||||
if t.Params != nil {
|
||||
for _, p := range t.Params.List {
|
||||
if m.uiType(p.Type) == "Context" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func buildCallback(t *ast.FuncType) bool {
|
||||
if t.Params != nil {
|
||||
for _, p := range t.Params.List {
|
||||
e := p.Type
|
||||
if s, ok := e.(*ast.StarExpr); ok {
|
||||
e = s.X
|
||||
}
|
||||
switch e := e.(type) {
|
||||
case *ast.Ident:
|
||||
if e.Name == "error" {
|
||||
return false
|
||||
}
|
||||
case *ast.SelectorExpr:
|
||||
if e.Sel.Name == "Menu" || e.Sel.Name == "Painter" || e.Sel.Name == "InputEvent" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (v visitor) zero(k string) ast.Expr {
|
||||
return &ast.CompositeLit{Type: &ast.SelectorExpr{X: ast.NewIdent(v.m.alias), Sel: ast.NewIdent(k)}}
|
||||
}
|
||||
func isNil(e ast.Expr) bool { id, ok := e.(*ast.Ident); return ok && id.Name == "nil" }
|
||||
|
||||
func replaceComparisons(v reflect.Value, m *migration) {
|
||||
if !v.IsValid() {
|
||||
return
|
||||
}
|
||||
if v.Kind() == reflect.Interface && v.Type() == exprType && v.CanSet() && !v.IsNil() {
|
||||
if b, ok := v.Interface().(*ast.BinaryExpr); ok && (b.Op == token.EQL || b.Op == token.NEQ) {
|
||||
var e ast.Expr
|
||||
if isNil(b.X) {
|
||||
e = b.Y
|
||||
} else if isNil(b.Y) {
|
||||
e = b.X
|
||||
}
|
||||
if e != nil && m.kind(e) == "Element" {
|
||||
var replacement ast.Expr = &ast.CallExpr{Fun: &ast.SelectorExpr{X: e, Sel: ast.NewIdent("Valid")}}
|
||||
if b.Op == token.EQL {
|
||||
replacement = &ast.UnaryExpr{Op: token.NOT, X: replacement}
|
||||
}
|
||||
v.Set(reflect.ValueOf(replacement))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only direct expression children are needed here; ast.Walk visits the rest.
|
||||
if v.Kind() == reflect.Pointer && !v.IsNil() {
|
||||
v = v.Elem()
|
||||
}
|
||||
if v.Kind() == reflect.Struct {
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
f := v.Field(i)
|
||||
if f.Kind() == reflect.Interface && f.Type() == exprType {
|
||||
replaceComparisons(f, m)
|
||||
} else if f.Kind() == reflect.Slice {
|
||||
for j := 0; j < f.Len(); j++ {
|
||||
if f.Index(j).Kind() == reflect.Interface && f.Index(j).Type() == exprType {
|
||||
replaceComparisons(f.Index(j), m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func callbackHasRow(t *ast.FuncType) bool {
|
||||
if t.Params != nil {
|
||||
for _, p := range t.Params.List {
|
||||
if s, ok := p.Type.(*ast.SelectorExpr); ok && s.Sel.Name == "ListRow" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// constructor finds the imported UI factory at the start of a fluent chain.
|
||||
func (m *migration) constructor(e ast.Expr) *ast.CallExpr {
|
||||
call, ok := e.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
fn := call.Fun
|
||||
if ix, ok := fn.(*ast.IndexExpr); ok {
|
||||
fn = ix.X
|
||||
}
|
||||
if ix, ok := fn.(*ast.IndexListExpr); ok {
|
||||
fn = ix.X
|
||||
}
|
||||
sel, ok := fn.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == m.alias && uiResults[sel.Sel.Name] != "" {
|
||||
return call
|
||||
}
|
||||
return m.constructor(sel.X)
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
package uimigrate
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/format"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"go/types"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMigrationPreservesLocalValuePolling(t *testing.T) {
|
||||
source := `package app
|
||||
import native "github.com/egoist/mygo/ui"
|
||||
var shared bool
|
||||
type app struct { checked bool }
|
||||
func (a *app) view(c *native.Context, persistent *bool) {
|
||||
checked := a.checked
|
||||
if native.Checkbox(c, &checked, "Derived").Disabled(false).Changed() {
|
||||
a.checked = checked
|
||||
return
|
||||
}
|
||||
var draft string
|
||||
input := native.TextInput(c, &draft)
|
||||
alias := input
|
||||
if alias.Submitted() { a.send(draft) }
|
||||
var choice = 0
|
||||
element := native.Segmented[int](c, &choice)
|
||||
if element.Changed() { a.choose(choice) }
|
||||
native.Checkbox(c, &checked, "Callback").OnChange(func() { a.checked = checked })
|
||||
if native.Checkbox(c, &a.checked, "Field").Changed() { a.save() }
|
||||
if native.Checkbox(c, &shared, "Global").Changed() { a.save() }
|
||||
if native.Checkbox(c, persistent, "Parameter").Changed() { a.save() }
|
||||
other := foreign()
|
||||
if other.Changed() { a.save() }
|
||||
}
|
||||
`
|
||||
formatted, err := format.Source([]byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := File("app.go", formatted)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Changed || string(r.Source) != string(formatted) {
|
||||
t.Fatalf("polling control flow was rewritten:\n%s", r.Source)
|
||||
}
|
||||
if len(r.Notes) != 0 {
|
||||
t.Fatalf("same-pass local-value polling needs no review notes: %q", r.Notes)
|
||||
}
|
||||
again, err := File("app.go", r.Source)
|
||||
if err != nil || again.Changed || strings.Join(again.Notes, "\n") != strings.Join(r.Notes, "\n") {
|
||||
t.Fatal("review notes were not stable on a repeated migration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationAliasesScopesAndNilValues(t *testing.T) {
|
||||
source := `package app
|
||||
import native "github.com/egoist/mygo/ui"
|
||||
type app struct { saved *native.Element; other *int }
|
||||
func (a *app) view(c *native.Context) {
|
||||
native.Column(c).Children(func() {
|
||||
e := native.Text(c, "Hello")
|
||||
if e != nil { e.Focus() }
|
||||
if a.saved == nil { a.saved = e }
|
||||
files := e.DroppedFiles()
|
||||
if files != nil { println(files) }
|
||||
if a.other != nil { println(*a.other) }
|
||||
})
|
||||
a.saved = nil
|
||||
}
|
||||
func missing() *native.Element { return nil }
|
||||
`
|
||||
r, err := File("app.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{"view(c *native.Context)", "Children(func()", "e.Valid()", "!a.saved.Valid()", "a.saved = native.Element{}", "return native.Element{}", "files != nil", "a.other != nil"} {
|
||||
if !strings.Contains(string(r.Source), want) {
|
||||
t.Fatalf("missing %q:\n%s", want, r.Source)
|
||||
}
|
||||
}
|
||||
if len(r.Notes) == 0 {
|
||||
t.Fatal("stored element fields were not reported")
|
||||
}
|
||||
if _, err := parser.ParseFile(token.NewFileSet(), "app.go", r.Source, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := File("app.go", r.Source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again.Changed {
|
||||
t.Fatalf("migration was not idempotent:\n%s", again.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationPreservesNonUIAliases(t *testing.T) {
|
||||
source := `package app
|
||||
import ui "example.org/other/ui"
|
||||
func render(c *ui.Context) *ui.Element { return nil }
|
||||
`
|
||||
r, err := File("app.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Changed || string(r.Source) != source {
|
||||
t.Fatal("an unrelated UI library was modified")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationBuilderCallbacks(t *testing.T) {
|
||||
source := `package app
|
||||
import "github.com/egoist/mygo/ui"
|
||||
func view(c *ui.Context) {
|
||||
ui.List(c, nil, 5, func(i int) { ui.Text(c, "row") })
|
||||
ui.Table(c, nil, nil, 5, func(row, col int) { ui.Text(c, "cell") })
|
||||
ui.Button(c, "menu").ContextMenu(func(m *ui.Menu) { m.Item("Open") })
|
||||
ui.Box(c).Rows(3)
|
||||
}
|
||||
`
|
||||
r, err := File("app.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{"func(i int)", "func(row, col int)", "func(m *ui.Menu)", "GridRows(3)"} {
|
||||
if !strings.Contains(string(r.Source), want) {
|
||||
t.Fatalf("missing %q:\n%s", want, r.Source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationDotImportRequiresReview(t *testing.T) {
|
||||
r, err := File("app.go", []byte("package app\nimport . \"github.com/egoist/mygo/ui\"\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Changed || len(r.Notes) != 1 {
|
||||
t.Fatal("dot import was guessed instead of reported")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationDoesNotChangeOtherBuilders(t *testing.T) {
|
||||
source := `package app
|
||||
import "github.com/egoist/mygo/ui"
|
||||
func render(c *ui.Context, foreign Other) {
|
||||
foreign.Children(func() { println("foreign") })
|
||||
ui.Column(c).Children(func() { ui.Text(c,"UI") })
|
||||
}
|
||||
`
|
||||
r, err := File("app.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(r.Source), "foreign.Children(func()") {
|
||||
t.Fatalf("unrelated builder changed:\n%s", r.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationKeysBeforeConstruction(t *testing.T) {
|
||||
source := `package app
|
||||
import native "github.com/egoist/mygo/ui"
|
||||
func view(c *native.Context,v *bool){
|
||||
native.Checkbox(c,v,"Done").Disabled(false).Key("done").OnChange(func(){})
|
||||
if c!=nil { println("context") }
|
||||
}
|
||||
`
|
||||
r, err := File("app.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(r.Source), `Checkbox(c.Key("done"), v, "Done").Disabled(false).OnChange`) {
|
||||
t.Fatal(string(r.Source))
|
||||
}
|
||||
if !strings.Contains(string(r.Source), "c != nil") {
|
||||
t.Fatal("context nil check changed")
|
||||
}
|
||||
again, err := File("app.go", r.Source)
|
||||
if err != nil || again.Changed {
|
||||
t.Fatal("key migration is not idempotent", err, string(again.Source))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationSharesPackageFieldsAndTupleHelpers(t *testing.T) {
|
||||
sources := map[string][]byte{
|
||||
"app/window.go": []byte(`package app
|
||||
import native "github.com/egoist/mygo/ui"
|
||||
type window struct { element *native.Element; other *int }
|
||||
`),
|
||||
"app/view.go": []byte(`package app
|
||||
import "github.com/egoist/mygo/ui"
|
||||
func(w *window)view(c *ui.Context){if w.element!=nil{w.element.Focus()};if w.other!=nil{println(*w.other)}}
|
||||
func newWindow()(*window,int){return &window{},0}
|
||||
func makeElement(c *ui.Context)*ui.Element{return ui.Text(c,"hello")}
|
||||
`),
|
||||
"app/view_test.go": []byte(`package app
|
||||
import "github.com/egoist/mygo/ui"
|
||||
func check(c *ui.Context){w,_:=newWindow();if w.element==nil{w.element=makeElement(c)};e:=makeElement(c);if e!=nil{e.Focus()}}
|
||||
`),
|
||||
}
|
||||
results, err := Files(sources)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(results["app/view.go"].Source), "w.element.Valid()") || !strings.Contains(string(results["app/view.go"].Source), "w.other != nil") {
|
||||
t.Fatal(string(results["app/view.go"].Source))
|
||||
}
|
||||
for _, want := range []string{"!w.element.Valid()", "e.Valid()"} {
|
||||
if !strings.Contains(string(results["app/view_test.go"].Source), want) {
|
||||
t.Fatal(string(results["app/view_test.go"].Source))
|
||||
}
|
||||
}
|
||||
migrated := map[string][]byte{}
|
||||
for name, r := range results {
|
||||
migrated[name] = r.Source
|
||||
}
|
||||
again, err := Files(migrated)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, r := range again {
|
||||
if r.Changed {
|
||||
t.Fatalf("second migration changed %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Values of package ui that are not elements keep their nil checks, whatever
|
||||
// assigned them; only elements become Valid, and the result compiles.
|
||||
func TestMigrationNilChecksFollowUISignatures(t *testing.T) {
|
||||
source := `package repro
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
func decode(data []byte) bool {
|
||||
var b ui.ImageSource
|
||||
b, _ = ui.DecodeImage(data)
|
||||
return b != nil
|
||||
}
|
||||
|
||||
func short(data []byte) bool {
|
||||
b, err := ui.DecodeImage(data)
|
||||
return err == nil && b != nil
|
||||
}
|
||||
|
||||
func player(d ui.VideoDecoder) {
|
||||
p, err := ui.NewVideoPlayer(d)
|
||||
if err == nil && p != nil {
|
||||
p.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func timeline(c *ui.Context) bool {
|
||||
var s, err = ui.DecodeImage(nil)
|
||||
t := ui.Text(c, "intro").Timeline("intro", ui.TimelineOptions{})
|
||||
return s != nil && err == nil && t != nil && ui.Text(c, "copy").SelectedTexts() != nil
|
||||
}
|
||||
|
||||
func declared(c *ui.Context) bool {
|
||||
var focuser interface{ AutoFocus() ui.Element }
|
||||
focuser = ui.Text(c, "focus")
|
||||
return focuser != nil
|
||||
}
|
||||
|
||||
func element(c *ui.Context) {
|
||||
var shown *ui.Element
|
||||
e := ui.Text(c, "hello").Padding(4)
|
||||
if e != nil && shown == nil {
|
||||
shown = ui.Button(c, "focus")
|
||||
shown.Focus()
|
||||
}
|
||||
}
|
||||
`
|
||||
r, err := File("repro.go", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(r.Source)
|
||||
for _, want := range []string{"return b != nil", "err == nil && b != nil", "err == nil && p != nil", "s != nil && err == nil && t != nil", "SelectedTexts() != nil", "return focuser != nil", "if e.Valid() && !shown.Valid()", "var shown ui.Element"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
fs := token.NewFileSet()
|
||||
f, err := parser.ParseFile(fs, "repro.go", r.Source, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := (&types.Config{Importer: uiImporter(t)}).Check("repro", fs, []*ast.File{f}, nil); err != nil {
|
||||
t.Fatalf("migrated source does not compile: %v\n%s", err, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A declared alias of a UI type, in the file or a sibling of it, is the
|
||||
// kind it stands for.
|
||||
func TestMigrationDeclaredUIAliases(t *testing.T) {
|
||||
sources := map[string][]byte{
|
||||
"types.go": []byte(`package repro
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
type E = *ui.Element
|
||||
`),
|
||||
"app.go": []byte(`package repro
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
func shown(c *ui.Context) bool {
|
||||
var e E = ui.Text(c, "hello")
|
||||
if e != nil {
|
||||
e = nil
|
||||
}
|
||||
return e != nil
|
||||
}
|
||||
`),
|
||||
}
|
||||
results, err := Files(sources)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(results["app.go"].Source)
|
||||
for _, want := range []string{"if e.Valid() {", "e = ui.Element{}", "return e.Valid()"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
fs := token.NewFileSet()
|
||||
var files []*ast.File
|
||||
for _, name := range []string{"types.go", "app.go"} {
|
||||
f, err := parser.ParseFile(fs, name, results[name].Source, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files = append(files, f)
|
||||
}
|
||||
if _, err := (&types.Config{Importer: uiImporter(t)}).Check("repro", fs, files, nil); err != nil {
|
||||
t.Fatalf("migrated source does not compile: %v\n%s%s", err, results["types.go"].Source, got)
|
||||
}
|
||||
}
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
// Code generated by go test ./internal/uimigrate -update from package ui; DO NOT EDIT.
|
||||
|
||||
package uimigrate
|
||||
|
||||
// uiResults maps each function of package ui that returns one Element or
|
||||
// custom parts value to that result's type. Other calls make neither.
|
||||
var uiResults = map[string]string{
|
||||
"Accordion": "Element",
|
||||
"AccordionBase": "AccordionParts",
|
||||
"AccordionItem": "Element",
|
||||
"Autocomplete": "Element",
|
||||
"Avatar": "Element",
|
||||
"BackButton": "Element",
|
||||
"Badge": "Element",
|
||||
"Box": "Element",
|
||||
"Breadcrumbs": "Element",
|
||||
"Button": "Element",
|
||||
"ButtonBase": "Element",
|
||||
"Calendar": "Element",
|
||||
"Checkbox": "Element",
|
||||
"CheckboxBase": "Element",
|
||||
"CheckboxGroup": "Element",
|
||||
"CheckboxState": "Element",
|
||||
"CheckboxStateBase": "Element",
|
||||
"Collapsible": "Element",
|
||||
"CollapsibleBase": "CollapsibleParts",
|
||||
"ColorPicker": "Element",
|
||||
"ColorWell": "Element",
|
||||
"Column": "Element",
|
||||
"Combobox": "Element",
|
||||
"ComboboxBase": "ComboboxParts",
|
||||
"ContextMenuBase": "MenuParts",
|
||||
"DateInput": "Element",
|
||||
"DecimalInput": "Element",
|
||||
"DialogBase": "Element",
|
||||
"Divider": "Element",
|
||||
"EditableText": "Element",
|
||||
"Field": "Element",
|
||||
"Fieldset": "Element",
|
||||
"FindBar": "Element",
|
||||
"Form": "Element",
|
||||
"ForwardButton": "Element",
|
||||
"Grid": "Element",
|
||||
"GridView": "Element",
|
||||
"Icon": "Element",
|
||||
"Image": "Element",
|
||||
"Link": "Element",
|
||||
"List": "Element",
|
||||
"MenuBase": "MenuParts",
|
||||
"MenuButton": "Element",
|
||||
"Meter": "Element",
|
||||
"Modal": "Element",
|
||||
"NativeView": "Element",
|
||||
"NumberInput": "Element",
|
||||
"Outline": "Element",
|
||||
"OutlineTable": "Element",
|
||||
"Popover": "Element",
|
||||
"PopoverBase": "Element",
|
||||
"PopoverMenuButton": "Element",
|
||||
"PrimaryButton": "Element",
|
||||
"PrimarySplitButton": "SplitButtonParts",
|
||||
"Progress": "Element",
|
||||
"Radio": "Element",
|
||||
"RadioBase": "Element",
|
||||
"RadioGroup": "Element",
|
||||
"RangeSlider": "Element",
|
||||
"Rating": "Element",
|
||||
"RichText": "Element",
|
||||
"Row": "Element",
|
||||
"Scroll": "Element",
|
||||
"ScrollBoth": "Element",
|
||||
"ScrollHorizontal": "Element",
|
||||
"SearchField": "Element",
|
||||
"Segmented": "Element",
|
||||
"SegmentedBase": "SegmentedParts",
|
||||
"Select": "Element",
|
||||
"SelectBase": "SelectParts",
|
||||
"SelectBaseOpen": "SelectParts",
|
||||
"Sidebar": "Element",
|
||||
"SidebarItem": "Element",
|
||||
"SidebarSection": "Element",
|
||||
"Slider": "Element",
|
||||
"SliderBase": "Element",
|
||||
"Spacer": "Element",
|
||||
"Spinner": "Element",
|
||||
"Split": "Element",
|
||||
"SplitButton": "SplitButtonParts",
|
||||
"SplitPercent": "Element",
|
||||
"SplitVertical": "Element",
|
||||
"SplitVerticalPercent": "Element",
|
||||
"StepSlider": "Element",
|
||||
"Stepper": "Element",
|
||||
"Switch": "Element",
|
||||
"SwitchBase": "Element",
|
||||
"Table": "Element",
|
||||
"Tabs": "Element",
|
||||
"TabsBase": "TabsParts",
|
||||
"Text": "Element",
|
||||
"TextArea": "Element",
|
||||
"TextAreaBase": "Element",
|
||||
"TextAreaBuffer": "Element",
|
||||
"TextAreaBufferBase": "Element",
|
||||
"TextInput": "Element",
|
||||
"TextInputBase": "Element",
|
||||
"TextInputBuffer": "Element",
|
||||
"TextInputBufferBase": "Element",
|
||||
"Textf": "Element",
|
||||
"Themed": "Element",
|
||||
"TimeInput": "Element",
|
||||
"ToastBase": "ToastParts",
|
||||
"ToastViewportBase": "Element",
|
||||
"Toggle": "Element",
|
||||
"ToggleBase": "Element",
|
||||
"ToggleGroup": "Element",
|
||||
"TokenField": "Element",
|
||||
"Toolbar": "Element",
|
||||
"TooltipBase": "Element",
|
||||
"Tree": "Element",
|
||||
"TreeBase": "TreeParts",
|
||||
"TreeItem": "Element",
|
||||
"Video": "Element",
|
||||
"WebView": "Element",
|
||||
}
|
||||
|
||||
// elementChains lists the methods of Element that return an Element.
|
||||
var elementChains = map[string]bool{
|
||||
"Absolute": true,
|
||||
"Access": true,
|
||||
"AccessChildren": true,
|
||||
"AccessDisabled": true,
|
||||
"AccessHidden": true,
|
||||
"AccessSelected": true,
|
||||
"ActiveDescendant": true,
|
||||
"AlignContent": true,
|
||||
"AlignItems": true,
|
||||
"AlignSelf": true,
|
||||
"AnimatePose": true,
|
||||
"AspectRatio": true,
|
||||
"Attach": true,
|
||||
"AttachEdgeMargin": true,
|
||||
"AttachTo": true,
|
||||
"AttachedOrigin": true,
|
||||
"AutoComplete": true,
|
||||
"AutoFocus": true,
|
||||
"Autocorrect": true,
|
||||
"Autofill": true,
|
||||
"BackfaceHidden": true,
|
||||
"Background": true,
|
||||
"Balance": true,
|
||||
"Basis": true,
|
||||
"BasisPercent": true,
|
||||
"Bind": true,
|
||||
"Blur": true,
|
||||
"Bold": true,
|
||||
"Border": true,
|
||||
"BorderColor": true,
|
||||
"BorderConicGradient": true,
|
||||
"BorderEndWidth": true,
|
||||
"BorderLinearGradient": true,
|
||||
"BorderStartWidth": true,
|
||||
"BorderStyle": true,
|
||||
"BorderWidth": true,
|
||||
"Bottom": true,
|
||||
"BottomPercent": true,
|
||||
"Browse": true,
|
||||
"Busy": true,
|
||||
"Cache": true,
|
||||
"Capitalize": true,
|
||||
"CaretColor": true,
|
||||
"CaretWidth": true,
|
||||
"Center": true,
|
||||
"Checked": true,
|
||||
"ChildExit": true,
|
||||
"Children": true,
|
||||
"Clip": true,
|
||||
"ClipInset": true,
|
||||
"ClipInsetPercent": true,
|
||||
"ClipX": true,
|
||||
"ClipY": true,
|
||||
"Column": true,
|
||||
"ColumnCount": true,
|
||||
"ColumnIndex": true,
|
||||
"ColumnSpan": true,
|
||||
"ColumnStart": true,
|
||||
"ColumnTracks": true,
|
||||
"Columns": true,
|
||||
"ConicGradient": true,
|
||||
"ContentTransition": true,
|
||||
"ContextMenu": true,
|
||||
"Controls": true,
|
||||
"CopyData": true,
|
||||
"Current": true,
|
||||
"Cursor": true,
|
||||
"Debug": true,
|
||||
"DecorationColor": true,
|
||||
"DecorationThickness": true,
|
||||
"DescribedBy": true,
|
||||
"Description": true,
|
||||
"DimDisabled": true,
|
||||
"Direction": true,
|
||||
"Disabled": true,
|
||||
"Dividers": true,
|
||||
"DottedUnderline": true,
|
||||
"Drag": true,
|
||||
"DragData": true,
|
||||
"DragDataFrom": true,
|
||||
"DragWindow": true,
|
||||
"Draggable": true,
|
||||
"Draw": true,
|
||||
"DrawObjects": true,
|
||||
"DrawOver": true,
|
||||
"Effect": true,
|
||||
"Ellipsis": true,
|
||||
"End": true,
|
||||
"EndPercent": true,
|
||||
"Error": true,
|
||||
"ErrorMessage": true,
|
||||
"Expanded": true,
|
||||
"Fill": true,
|
||||
"FillEqually": true,
|
||||
"FillHeight": true,
|
||||
"FillWidth": true,
|
||||
"Fit": true,
|
||||
"FixedLineHeight": true,
|
||||
"Focus": true,
|
||||
"FocusBind": true,
|
||||
"FocusGroup": true,
|
||||
"FocusRing": true,
|
||||
"FocusRingColor": true,
|
||||
"FocusRingOffset": true,
|
||||
"Focusable": true,
|
||||
"Font": true,
|
||||
"FontFeatures": true,
|
||||
"FontSize": true,
|
||||
"FontWeight": true,
|
||||
"Gap": true,
|
||||
"GapX": true,
|
||||
"GapY": true,
|
||||
"Gradient": true,
|
||||
"Grayscale": true,
|
||||
"Grid": true,
|
||||
"GridRows": true,
|
||||
"Grow": true,
|
||||
"HandleInput": true,
|
||||
"HandleTextInput": true,
|
||||
"HasPopup": true,
|
||||
"Height": true,
|
||||
"HeightPercent": true,
|
||||
"Hidden": true,
|
||||
"HitTest": true,
|
||||
"IgnoreInput": true,
|
||||
"InputMethod": true,
|
||||
"InsetShadow": true,
|
||||
"Invalid": true,
|
||||
"Invisible": true,
|
||||
"Italic": true,
|
||||
"ItemKey": true,
|
||||
"Justify": true,
|
||||
"JustifyItems": true,
|
||||
"JustifySelf": true,
|
||||
"KeepFocus": true,
|
||||
"KeepOpen": true,
|
||||
"KeepScrollbars": true,
|
||||
"Key": true,
|
||||
"KeyShortcuts": true,
|
||||
"Keyboard": true,
|
||||
"Label": true,
|
||||
"LabelledBy": true,
|
||||
"Lang": true,
|
||||
"Left": true,
|
||||
"LeftPercent": true,
|
||||
"LetterSpacing": true,
|
||||
"Level": true,
|
||||
"LineHeight": true,
|
||||
"LinearGradient": true,
|
||||
"Lines": true,
|
||||
"Margin": true,
|
||||
"MarginEnd": true,
|
||||
"MarginStart": true,
|
||||
"MarginX": true,
|
||||
"MarginY": true,
|
||||
"MaskConicGradient": true,
|
||||
"MaskLinearGradient": true,
|
||||
"MaskRadialGradient": true,
|
||||
"Masks": true,
|
||||
"Material": true,
|
||||
"MaxHeight": true,
|
||||
"MaxHeightPercent": true,
|
||||
"MaxLength": true,
|
||||
"MaxLines": true,
|
||||
"MaxWidth": true,
|
||||
"MaxWidthPercent": true,
|
||||
"MaximizeButton": true,
|
||||
"Menu": true,
|
||||
"MinHeight": true,
|
||||
"MinHeightPercent": true,
|
||||
"MinWidth": true,
|
||||
"MinWidthPercent": true,
|
||||
"Mixed": true,
|
||||
"Modal": true,
|
||||
"Multiline": true,
|
||||
"Multiselectable": true,
|
||||
"NoShadow": true,
|
||||
"NoWrap": true,
|
||||
"ObjectPosition": true,
|
||||
"ObserveInput": true,
|
||||
"OnChange": true,
|
||||
"OnClick": true,
|
||||
"OnPaste": true,
|
||||
"OnShortcut": true,
|
||||
"OnSubmit": true,
|
||||
"OnTextKey": true,
|
||||
"OnUnmount": true,
|
||||
"Opacity": true,
|
||||
"Orientation": true,
|
||||
"Padding": true,
|
||||
"PaddingEnd": true,
|
||||
"PaddingStart": true,
|
||||
"PaddingX": true,
|
||||
"PaddingY": true,
|
||||
"PassThrough": true,
|
||||
"Password": true,
|
||||
"Perspective": true,
|
||||
"Placeholder": true,
|
||||
"PlaceholderColor": true,
|
||||
"PopoverMenu": true,
|
||||
"PopoverMenuButton": true,
|
||||
"PositionInSet": true,
|
||||
"PreserveSpaces": true,
|
||||
"Pretty": true,
|
||||
"Query": true,
|
||||
"RadialGradient": true,
|
||||
"Radius": true,
|
||||
"Range": true,
|
||||
"ReadOnly": true,
|
||||
"Ref": true,
|
||||
"ReplaceText": true,
|
||||
"ReturnKey": true,
|
||||
"Reverse": true,
|
||||
"Right": true,
|
||||
"RightPercent": true,
|
||||
"Role": true,
|
||||
"RoleDescription": true,
|
||||
"Rotate": true,
|
||||
"RotateX": true,
|
||||
"RotateY": true,
|
||||
"Row": true,
|
||||
"RowCount": true,
|
||||
"RowIndex": true,
|
||||
"RowSpan": true,
|
||||
"RowStart": true,
|
||||
"RowTracks": true,
|
||||
"RowWidth": true,
|
||||
"Rows": true,
|
||||
"Scale": true,
|
||||
"ScrollIntoView": true,
|
||||
"ScrollSnap": true,
|
||||
"ScrollWith": true,
|
||||
"ScrollbarAxes": true,
|
||||
"ScrollbarInsets": true,
|
||||
"ScrollbarStyle": true,
|
||||
"Scrollbars": true,
|
||||
"Search": true,
|
||||
"Selectable": true,
|
||||
"Selected": true,
|
||||
"Selection": true,
|
||||
"SelectionColor": true,
|
||||
"SetChanged": true,
|
||||
"SetTextSelection": true,
|
||||
"Shadow": true,
|
||||
"Shrink": true,
|
||||
"SingleLine": true,
|
||||
"Size": true,
|
||||
"Skew": true,
|
||||
"SnapAlign": true,
|
||||
"SnapAlignX": true,
|
||||
"SnapAlignY": true,
|
||||
"Sort": true,
|
||||
"SplitReset": true,
|
||||
"Start": true,
|
||||
"StartPercent": true,
|
||||
"Step": true,
|
||||
"Sticky": true,
|
||||
"Strikethrough": true,
|
||||
"Stripes": true,
|
||||
"TabSize": true,
|
||||
"TabStop": true,
|
||||
"TextAlign": true,
|
||||
"TextBackground": true,
|
||||
"TextCaret": true,
|
||||
"TextColor": true,
|
||||
"TextRanges": true,
|
||||
"TextShadow": true,
|
||||
"TextStroke": true,
|
||||
"Tooltip": true,
|
||||
"Top": true,
|
||||
"TopPercent": true,
|
||||
"TrackLines": true,
|
||||
"TrackScroll": true,
|
||||
"Transform": true,
|
||||
"TransformOrigin": true,
|
||||
"Transition": true,
|
||||
"Translate": true,
|
||||
"TranslatePercent": true,
|
||||
"TranslateZ": true,
|
||||
"TruncateMiddle": true,
|
||||
"TruncateStart": true,
|
||||
"Underline": true,
|
||||
"UnderlineOffset": true,
|
||||
"Unselectable": true,
|
||||
"Value": true,
|
||||
"Vertical": true,
|
||||
"WavyUnderline": true,
|
||||
"Width": true,
|
||||
"WidthPercent": true,
|
||||
"Wrap": true,
|
||||
"WrapReverse": true,
|
||||
"ZIndex": true,
|
||||
}
|
||||
|
||||
// uiParts lists package ui's custom parts types.
|
||||
var uiParts = map[string]bool{
|
||||
"AccordionParts": true,
|
||||
"CollapsibleParts": true,
|
||||
"ComboboxParts": true,
|
||||
"MenuParts": true,
|
||||
"SegmentedParts": true,
|
||||
"SelectParts": true,
|
||||
"SplitButtonParts": true,
|
||||
"TabsParts": true,
|
||||
"ToastParts": true,
|
||||
"TreeItemParts": true,
|
||||
"TreeParts": true,
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package uimigrate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"go/importer"
|
||||
"go/token"
|
||||
"go/types"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var update = flag.Bool("update", false, "rewrite uiapi.go from package ui")
|
||||
|
||||
const uiPath = "github.com/egoist/mygo/ui"
|
||||
|
||||
// TestUIAPI derives uiapi.go from the compiled signatures of package ui, so
|
||||
// the migrator's facts about its functions and methods cannot drift.
|
||||
func TestUIAPI(t *testing.T) {
|
||||
pkg, err := uiImporter(t).Import(uiPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scope := pkg.Scope()
|
||||
element := scope.Lookup("Element").Type()
|
||||
parts := map[string]bool{}
|
||||
for _, name := range scope.Names() {
|
||||
if obj, ok := scope.Lookup(name).(*types.TypeName); ok && obj.Exported() && strings.HasSuffix(name, "Parts") {
|
||||
if _, ok := obj.Type().Underlying().(*types.Struct); ok {
|
||||
parts[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// kind names a result that the migrator converts: Element or parts.
|
||||
kind := func(results *types.Tuple) string {
|
||||
if results.Len() != 1 {
|
||||
return ""
|
||||
}
|
||||
named, ok := results.At(0).Type().(*types.Named)
|
||||
if !ok || named.Obj().Pkg() != pkg {
|
||||
return ""
|
||||
}
|
||||
if name := named.Origin().Obj().Name(); name == "Element" || parts[name] {
|
||||
return name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
results := map[string]string{}
|
||||
for _, name := range scope.Names() {
|
||||
if fn, ok := scope.Lookup(name).(*types.Func); ok && fn.Exported() {
|
||||
if k := kind(fn.Signature().Results()); k != "" {
|
||||
results[name] = k
|
||||
}
|
||||
}
|
||||
}
|
||||
chains := map[string]bool{}
|
||||
methods := types.NewMethodSet(types.NewPointer(element))
|
||||
for i := range methods.Len() {
|
||||
fn := methods.At(i).Obj().(*types.Func)
|
||||
if fn.Exported() && kind(fn.Signature().Results()) == "Element" {
|
||||
chains[fn.Name()] = true
|
||||
}
|
||||
}
|
||||
|
||||
var src bytes.Buffer
|
||||
src.WriteString("// Code generated by go test ./internal/uimigrate -update from package ui; DO NOT EDIT.\n\npackage uimigrate\n\n")
|
||||
src.WriteString("// uiResults maps each function of package ui that returns one Element or\n// custom parts value to that result's type. Other calls make neither.\nvar uiResults = map[string]string{\n")
|
||||
for _, name := range sorted(results) {
|
||||
fmt.Fprintf(&src, "%q: %q,\n", name, results[name])
|
||||
}
|
||||
src.WriteString("}\n\n// elementChains lists the methods of Element that return an Element.\nvar elementChains = map[string]bool{\n")
|
||||
for _, name := range sorted(chains) {
|
||||
fmt.Fprintf(&src, "%q: true,\n", name)
|
||||
}
|
||||
src.WriteString("}\n\n// uiParts lists package ui's custom parts types.\nvar uiParts = map[string]bool{\n")
|
||||
for _, name := range sorted(parts) {
|
||||
fmt.Fprintf(&src, "%q: true,\n", name)
|
||||
}
|
||||
src.WriteString("}\n")
|
||||
got, err := format.Source(src.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *update {
|
||||
if err := os.WriteFile("uiapi.go", got, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if want, err := os.ReadFile("uiapi.go"); err != nil || !bytes.Equal(want, got) {
|
||||
t.Fatalf("uiapi.go differs from package ui's signatures; go test ./internal/uimigrate -run TestUIAPI -update rewrites it:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// uiImporter imports package ui from its compiled export data.
|
||||
func uiImporter(t *testing.T) types.Importer {
|
||||
t.Helper()
|
||||
out, err := exec.Command("go", "list", "-export", "-f", "{{.Export}}", uiPath).Output()
|
||||
if err != nil {
|
||||
t.Fatal("export data of package ui:", err)
|
||||
}
|
||||
export := strings.TrimSpace(string(out))
|
||||
return importer.ForCompiler(token.NewFileSet(), "gc", func(path string) (io.ReadCloser, error) {
|
||||
if path != uiPath {
|
||||
return nil, fmt.Errorf("unexpected import %s", path)
|
||||
}
|
||||
return os.Open(export)
|
||||
})
|
||||
}
|
||||
|
||||
func sorted[V any](m map[string]V) []string {
|
||||
var names []string
|
||||
for name := range m {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
Reference in new issue
Block a user