Skip to content

mission control for agent skills

Update deps & add atomic file writes w/ improved ANSI handling

Alvin Unreal5f72bdb4732d
diff --git a/go.mod b/go.mod
index 6c67b66..a8a518d 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,9 @@ require (
github.com/charmbracelet/bubbles v1.0.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
- github.com/muesli/reflow v0.3.0
+ github.com/charmbracelet/x/ansi v0.11.7
+ golang.org/x/mod v0.17.0
+ golang.org/x/net v0.39.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -18,7 +20,6 @@ require (
github.com/aymerick/douceur v0.2.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20251205161215-1948445e3318 // indirect
- github.com/charmbracelet/x/ansi v0.11.7 // indirect
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
@@ -41,7 +42,6 @@ require (
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
- golang.org/x/net v0.39.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.24.0 // indirect
diff --git a/go.sum b/go.sum
index 6c0b650..6041b9d 100644
--- a/go.sum
+++ b/go.sum
@@ -56,7 +56,6 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
-github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
@@ -65,12 +64,8 @@ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
-github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
-github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
-github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
@@ -82,6 +77,8 @@ github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC
github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
+golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
+golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go
new file mode 100644
index 0000000..90edd5a
--- /dev/null
+++ b/internal/atomicfile/atomicfile.go
@@ -0,0 +1,48 @@
+package atomicfile
+
+import (
+ "os"
+ "path/filepath"
+)
+
+// WriteFile writes data to path by creating a temporary file in the same
+// directory, closing it, and renaming it into place. The parent directory is
+// created when needed. Temporary files are removed on errors.
+func WriteFile(path string, data []byte, perm os.FileMode) error {
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ if info, err := os.Stat(path); err == nil {
+ perm = info.Mode().Perm()
+ }
+
+ tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*")
+ if err != nil {
+ return err
+ }
+ tmpPath := tmp.Name()
+ cleanup := true
+ defer func() {
+ if cleanup {
+ _ = os.Remove(tmpPath)
+ }
+ }()
+
+ if err := tmp.Chmod(perm); err != nil {
+ _ = tmp.Close()
+ return err
+ }
+ if _, err := tmp.Write(data); err != nil {
+ _ = tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ if err := os.Rename(tmpPath, path); err != nil {
+ return err
+ }
+ cleanup = false
+ return nil
+}
diff --git a/internal/compat/compat.go b/internal/compat/compat.go
index ccf2da8..4f50ff8 100644
--- a/internal/compat/compat.go
+++ b/internal/compat/compat.go
@@ -5,6 +5,7 @@ import (
"strings"
"github.com/alvinunreal/lazyskills/internal/model"
+ xansi "github.com/charmbracelet/x/ansi"
)
var unsafeNameChars = regexp.MustCompile(`[^a-z0-9._]+`)
@@ -28,21 +29,26 @@ func NormalizeName(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
-var csiRE = regexp.MustCompile(`\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]`)
-var oscRE = regexp.MustCompile(`\x1b\][\s\S]*?(?:\x07|\x1b\\)`)
-var dcsPMAPCRE = regexp.MustCompile(`\x1b[P^_][\s\S]*?(?:\x1b\\)`)
-var simpleEscRE = regexp.MustCompile(`\x1b[\x20-\x7e]`)
-var c1RE = regexp.MustCompile(`[\x80-\x9f]`)
-var controlRE = regexp.MustCompile(`[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1b\x1c-\x1f\x7f]`)
var newlineRE = regexp.MustCompile(`[\r\n]+`)
func StripTerminalEscapes(str string) string {
- str = oscRE.ReplaceAllString(str, "")
- str = dcsPMAPCRE.ReplaceAllString(str, "")
- str = csiRE.ReplaceAllString(str, "")
- str = simpleEscRE.ReplaceAllString(str, "")
- str = c1RE.ReplaceAllString(str, "")
- return controlRE.ReplaceAllString(str, "")
+ return stripUnsafeControls(xansi.Strip(str))
+
+}
+
+func stripUnsafeControls(str string) string {
+ var b strings.Builder
+ for _, r := range str {
+ if r == '\n' || r == '\t' {
+ b.WriteRune(r)
+ continue
+ }
+ if r < 32 || r == 127 || (r >= 0x80 && r <= 0x9f) {
+ continue
+ }
+ b.WriteRune(r)
+ }
+ return b.String()
}
func SanitizeMetadata(str string) string {
diff --git a/internal/compat/compat_test.go b/internal/compat/compat_test.go
index 5393b5a..9c1565d 100644
--- a/internal/compat/compat_test.go
+++ b/internal/compat/compat_test.go
@@ -51,3 +51,24 @@ func TestStripTerminalEscapesRemovesBareEsc(t *testing.T) {
t.Fatalf("got %q", got)
}
}
+
+func TestStripTerminalEscapesRemovesControlSequences(t *testing.T) {
+ input := "a\x1b[31mred\x1b[0m" +
+ "\x1b]8;;https://example.com\x07link\x1b]8;;\x07" +
+ "\x1bPignored\x1b\\" +
+ "\x1b_ignored\x1b\\" +
+ "\x07\b\rc\x90d"
+ got := StripTerminalEscapes(input)
+ want := "aredlinkc"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestStripTerminalEscapesPreservesPreviewNewlinesAndTabs(t *testing.T) {
+ got := StripTerminalEscapes("one\n\ttwo\rthree")
+ want := "one\n\ttwothree"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
diff --git a/internal/locks/locks.go b/internal/locks/locks.go
index 2d3aed8..ecac2a8 100644
--- a/internal/locks/locks.go
+++ b/internal/locks/locks.go
@@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
+ "github.com/alvinunreal/lazyskills/internal/atomicfile"
"github.com/alvinunreal/lazyskills/internal/model"
)
@@ -77,7 +78,7 @@ func RemoveEntry(path, key string) error {
if err != nil {
return err
}
- return os.WriteFile(path, append(out, '\n'), 0o644)
+ return atomicfile.WriteFile(path, append(out, '\n'), 0o644)
}
// RemoveEntryIfExists deletes a lock entry when both the lock file and key are
@@ -108,5 +109,5 @@ func RemoveEntryIfExists(path, key string) (bool, error) {
if err != nil {
return false, err
}
- return true, os.WriteFile(path, append(out, '\n'), 0o644)
+ return true, atomicfile.WriteFile(path, append(out, '\n'), 0o644)
}
diff --git a/internal/locks/locks_test.go b/internal/locks/locks_test.go
index 84de1a5..1606912 100644
--- a/internal/locks/locks_test.go
+++ b/internal/locks/locks_test.go
@@ -1,6 +1,7 @@
package locks
import (
+ "encoding/json"
"os"
"path/filepath"
"strings"
@@ -14,6 +15,9 @@ func TestRemoveEntry(t *testing.T) {
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
+ if err := os.Chmod(path, 0o600); err != nil {
+ t.Fatal(err)
+ }
if err := RemoveEntry(path, "a"); err != nil {
t.Fatalf("RemoveEntry: %v", err)
@@ -34,6 +38,21 @@ func TestRemoveEntry(t *testing.T) {
if !strings.Contains(string(raw), `"extra"`) {
t.Errorf("expected unknown top-level field to be preserved, got %s", raw)
}
+ var root map[string]any
+ if err := json.Unmarshal(raw, &root); err != nil {
+ t.Fatalf("rewritten lock is invalid JSON: %v", err)
+ }
+ if root["extra"] != "keep" {
+ t.Fatalf("expected unknown top-level field value to be preserved, got %#v", root["extra"])
+ }
+ assertNoAtomicTemps(t, dir)
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("stat rewritten lock: %v", err)
+ }
+ if info.Mode().Perm() != 0o600 {
+ t.Fatalf("expected existing lock mode 0600 to be preserved, got %v", info.Mode().Perm())
+ }
if err := RemoveEntry(path, "missing"); err == nil {
t.Error("expected an error removing a missing key")
@@ -67,4 +86,25 @@ func TestRemoveEntryIfExistsIgnoresMissingFileAndKey(t *testing.T) {
if strings.Contains(string(raw), `"a"`) || !strings.Contains(string(raw), `"b"`) || !strings.Contains(string(raw), `"extra"`) {
t.Fatalf("expected a pruned while preserving b and extra, got %s", raw)
}
+ var root map[string]any
+ if err := json.Unmarshal(raw, &root); err != nil {
+ t.Fatalf("rewritten lock is invalid JSON: %v", err)
+ }
+ if root["extra"] != "keep" {
+ t.Fatalf("expected unknown top-level field value to be preserved, got %#v", root["extra"])
+ }
+ assertNoAtomicTemps(t, dir)
+}
+
+func assertNoAtomicTemps(t *testing.T, dir string) {
+ t.Helper()
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ if strings.Contains(entry.Name(), ".tmp-") {
+ t.Fatalf("unexpected leftover temp file %q", entry.Name())
+ }
+ }
}
diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.go
index f3e6e88..a53f77e 100644
--- a/internal/selfupdate/selfupdate.go
+++ b/internal/selfupdate/selfupdate.go
@@ -12,7 +12,9 @@ import (
"strings"
"time"
+ "github.com/alvinunreal/lazyskills/internal/atomicfile"
"github.com/alvinunreal/lazyskills/internal/buildinfo"
+ "golang.org/x/mod/semver"
)
type UpdateStatus string
@@ -112,19 +114,15 @@ func writeCache(rel *GitHubRelease) error {
if err != nil {
return err
}
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return err
- }
- f, err := os.Create(path)
- if err != nil {
- return err
- }
- defer f.Close()
cd := CacheData{
LastChecked: time.Now(),
Release: *rel,
}
- return json.NewEncoder(f).Encode(cd)
+ b, err := json.Marshal(cd)
+ if err != nil {
+ return err
+ }
+ return atomicfile.WriteFile(path, append(b, '\n'), 0o644)
}
func CleanVersion(v string) string {
@@ -136,65 +134,36 @@ func CleanVersion(v string) string {
}
func CompareVersions(v1, v2 string) int {
- v1 = CleanVersion(v1)
- v2 = CleanVersion(v2)
-
- if v1 == v2 {
+ s1, ok1 := normalizeSemver(v1)
+ s2, ok2 := normalizeSemver(v2)
+ if ok1 && ok2 {
+ return semver.Compare(s1, s2)
+ }
+ c1 := CleanVersion(v1)
+ c2 := CleanVersion(v2)
+ if c1 == c2 {
return 0
}
-
- parts1 := strings.SplitN(v1, "-", 2)
- parts2 := strings.SplitN(v2, "-", 2)
-
- main1 := parts1[0]
- main2 := parts2[0]
-
- nums1 := parseVersionComponents(main1)
- nums2 := parseVersionComponents(main2)
-
- for i := 0; i < len(nums1) || i < len(nums2); i++ {
- n1 := 0
- if i < len(nums1) {
- n1 = nums1[i]
- }
- n2 := 0
- if i < len(nums2) {
- n2 = nums2[i]
- }
- if n1 < n2 {
- return -1
- }
- if n1 > n2 {
- return 1
- }
- }
-
- if len(parts1) == 1 && len(parts2) > 1 {
- return 1
- }
- if len(parts1) > 1 && len(parts2) == 1 {
+ if c1 < c2 {
return -1
}
- if len(parts1) > 1 && len(parts2) > 1 {
- if parts1[1] < parts2[1] {
- return -1
- }
- if parts1[1] > parts2[1] {
- return 1
- }
- }
- return 0
+ return 1
}
-func parseVersionComponents(v string) []int {
- parts := strings.Split(v, ".")
- res := make([]int, len(parts))
- for i, p := range parts {
- var n int
- fmt.Sscanf(p, "%d", &n)
- res[i] = n
+func normalizeSemver(v string) (string, bool) {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return "", false
+ }
+ if v[0] == 'V' {
+ v = "v" + v[1:]
+ } else if v[0] != 'v' {
+ v = "v" + v
+ }
+ if semver.IsValid(v) {
+ return v, true
}
- return res
+ return "", false
}
func isManagedByDpkg(path string) bool {
diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.go
index d94b306..a8ecfb8 100644
--- a/internal/selfupdate/selfupdate_test.go
+++ b/internal/selfupdate/selfupdate_test.go
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -37,6 +38,11 @@ func TestCompareVersions(t *testing.T) {
{"v1.0.0-alpha", "v1.0.0", -1},
{"v1.0.0", "v1.0.0-beta", 1},
{"v1.0.0-alpha", "v1.0.0-beta", -1},
+ {"v1.0.0-alpha.2", "v1.0.0-alpha.10", -1},
+ {"v1.0.0-rc.1", "v1.0.0", -1},
+ {"V1.0.0", "v1.0.0", 0},
+ {"dev", "dev", 0},
+ {"dev", "v1.0.0", 1},
}
for _, tt := range tests {
@@ -175,6 +181,49 @@ func TestPlanAndCacheTTL(t *testing.T) {
}
os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "")
}
+
+func TestWriteCacheReadCacheRoundTrip(t *testing.T) {
+ cacheRoot := t.TempDir()
+ t.Setenv("XDG_CACHE_HOME", cacheRoot)
+
+ rel := &GitHubRelease{
+ TagName: "v1.2.3",
+ HTMLURL: "https://github.com/alvinunreal/lazyskills/releases/tag/v1.2.3",
+ Body: "cache body",
+ }
+ if err := writeCache(rel); err != nil {
+ t.Fatalf("writeCache: %v", err)
+ }
+
+ got, err := readCache(time.Hour)
+ if err != nil {
+ t.Fatalf("readCache: %v", err)
+ }
+ if got.TagName != rel.TagName || got.HTMLURL != rel.HTMLURL || got.Body != rel.Body {
+ t.Fatalf("readCache = %+v; want %+v", got, rel)
+ }
+
+ cachePath, err := getCachePath()
+ if err != nil {
+ t.Fatalf("getCachePath: %v", err)
+ }
+ info, err := os.Stat(cachePath)
+ if err != nil {
+ t.Fatalf("stat cache file: %v", err)
+ }
+ if info.Mode().Perm() != 0o644 {
+ t.Fatalf("expected new cache file mode 0644, got %v", info.Mode().Perm())
+ }
+ entries, err := os.ReadDir(filepath.Dir(cachePath))
+ if err != nil {
+ t.Fatalf("ReadDir cache dir: %v", err)
+ }
+ for _, entry := range entries {
+ if strings.Contains(entry.Name(), ".tmp-") {
+ t.Fatalf("unexpected leftover temp file %q", entry.Name())
+ }
+ }
+}
func TestRecoveryAdvice(t *testing.T) {
tests := []struct {
channel string
diff --git a/internal/tui/discovery.go b/internal/tui/discovery.go
index 97ba8d7..d20b112 100644
--- a/internal/tui/discovery.go
+++ b/internal/tui/discovery.go
@@ -7,6 +7,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "sync"
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/alvinunreal/lazyskills/internal/frontmatter"
@@ -350,6 +351,18 @@ func isGitRepo(dir string) bool {
return err == nil && st.IsDir()
}
+type cloneFlight struct {
+ wg sync.WaitGroup
+ dir string
+ cleanup func()
+ err error
+}
+
+var cachedSourceCloneFlights = struct {
+ sync.Mutex
+ m map[string]*cloneFlight
+}{m: make(map[string]*cloneFlight)}
+
// cachedSourceClone returns a directory holding a shallow clone of the remote
// source. A cached clone is reused unless force is set; on a cache miss (or
// force) it clones fresh. The returned cleanup removes throwaway directories
@@ -368,6 +381,10 @@ func cachedSourceClone(url, ref string, force bool) (dir string, cleanup func(),
os.RemoveAll(tmp)
return "", noop, cloneErr
}
+ if !isGitRepo(tmp) {
+ os.RemoveAll(tmp)
+ return "", noop, fmt.Errorf("clone did not produce a git repository")
+ }
return tmp, func() { os.RemoveAll(tmp) }, nil
}
@@ -376,46 +393,78 @@ func cachedSourceClone(url, ref string, force bool) (dir string, cleanup func(),
return dir, noop, nil
}
- os.RemoveAll(dir)
- if mkErr := os.MkdirAll(dir, 0o755); mkErr != nil {
+ if !force {
+ key := cloneCacheKey(url, ref)
+ cachedSourceCloneFlights.Lock()
+ if inFlight := cachedSourceCloneFlights.m[key]; inFlight != nil {
+ cachedSourceCloneFlights.Unlock()
+ inFlight.wg.Wait()
+ return inFlight.dir, inFlight.cleanup, inFlight.err
+ }
+ flight := &cloneFlight{cleanup: noop}
+ flight.wg.Add(1)
+ cachedSourceCloneFlights.m[key] = flight
+ cachedSourceCloneFlights.Unlock()
+
+ defer func() {
+ flight.dir = dir
+ flight.cleanup = cleanup
+ flight.err = err
+ flight.wg.Done()
+
+ cachedSourceCloneFlights.Lock()
+ delete(cachedSourceCloneFlights.m, key)
+ cachedSourceCloneFlights.Unlock()
+ }()
+ }
+
+ if !force && isGitRepo(dir) {
+ return dir, noop, nil
+ }
+ if mkErr := os.MkdirAll(root, 0o755); mkErr != nil {
return "", noop, mkErr
}
- if cloneErr := gitClone(url, ref, dir); cloneErr != nil {
- os.RemoveAll(dir)
+ tmp, tmpErr := os.MkdirTemp(root, ".clone-*")
+ if tmpErr != nil {
+ return "", noop, tmpErr
+ }
+ removeTmp := func() { os.RemoveAll(tmp) }
+ if cloneErr := gitClone(url, ref, tmp); cloneErr != nil {
+ removeTmp()
return "", noop, cloneErr
}
- return dir, noop, nil
-}
-
-func parseRemoteGitHubSource(source string) (url string, ref string, ok bool) {
- repoPart := source
- if idx := strings.Index(source, "#"); idx != -1 {
- repoPart = source[:idx]
- ref = source[idx+1:]
+ if !isGitRepo(tmp) {
+ removeTmp()
+ return "", noop, fmt.Errorf("clone did not produce a git repository")
}
- if strings.HasPrefix(repoPart, "https://github.com/") {
- repoPart = strings.TrimPrefix(repoPart, "https://github.com/")
- } else if strings.HasPrefix(repoPart, "github:") {
- repoPart = strings.TrimPrefix(repoPart, "github:")
+ if force {
+ return tmp, removeTmp, nil
}
- repoPart = strings.TrimSuffix(repoPart, ".git")
+ if renameErr := os.Rename(tmp, dir); renameErr == nil {
+ return dir, noop, nil
+ }
+ if isGitRepo(dir) {
+ removeTmp()
+ return dir, noop, nil
+ }
+ removeTmp()
+ return "", noop, fmt.Errorf("failed to publish clone to cache")
+}
- parts := strings.Split(repoPart, "/")
- if len(parts) != 2 {
+func parseRemoteGitHubSource(source string) (url string, ref string, ok bool) {
+ parsed, ok := parseSource(source)
+ if !ok || parsed.Folder != "" {
return "", "", false
}
- owner, repo := parts[0], parts[1]
- if !isSafeGitHubToken(owner) || !isSafeGitHubToken(repo) {
+ if parsed.Host != "" && parsed.Host != "github.com" {
return "", "", false
}
-
- if ref != "" && !isSafeGitHubRef(ref) {
+ if !parsed.validRepo() || !parsed.validRef() {
return "", "", false
}
-
- return fmt.Sprintf("https://github.com/%s/%s", owner, repo), ref, true
+ return fmt.Sprintf("https://github.com/%s/%s", parsed.Owner, parsed.Repo), parsed.Ref, true
}
func isSafeGitHubToken(s string) bool {
diff --git a/internal/tui/discovery_cache_test.go b/internal/tui/discovery_cache_test.go
new file mode 100644
index 0000000..76b2e82
--- /dev/null
+++ b/internal/tui/discovery_cache_test.go
@@ -0,0 +1,196 @@
+package tui
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func withDiscoveryCloneCache(t *testing.T, clone func(url, ref, dir string) error) string {
+ t.Helper()
+ oldRoot := discoveryCacheRoot
+ oldClone := gitClone
+ root := t.TempDir()
+ discoveryCacheRoot = func() (string, error) { return root, nil }
+ gitClone = clone
+ t.Cleanup(func() {
+ discoveryCacheRoot = oldRoot
+ gitClone = oldClone
+ })
+ return root
+}
+
+func makeGitRepo(t *testing.T, dir string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestCachedSourceCloneConcurrentCallsCloneOnce(t *testing.T) {
+ var clones int32
+ root := withDiscoveryCloneCache(t, func(url, ref, dir string) error {
+ atomic.AddInt32(&clones, 1)
+ time.Sleep(25 * time.Millisecond)
+ makeGitRepo(t, dir)
+ return nil
+ })
+
+ const callers = 8
+ var wg sync.WaitGroup
+ errs := make(chan error, callers)
+ dirs := make(chan string, callers)
+ for i := 0; i < callers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ dir, cleanup, err := cachedSourceClone("https://github.com/owner/repo", "main", false)
+ if err == nil {
+ cleanup()
+ dirs <- dir
+ }
+ errs <- err
+ }()
+ }
+ wg.Wait()
+ close(errs)
+ close(dirs)
+
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("cachedSourceClone failed: %v", err)
+ }
+ }
+ if got := atomic.LoadInt32(&clones); got != 1 {
+ t.Fatalf("expected one clone, got %d", got)
+ }
+ want := filepath.Join(root, cloneCacheKey("https://github.com/owner/repo", "main"))
+ for dir := range dirs {
+ if dir != want {
+ t.Fatalf("expected cached dir %q, got %q", want, dir)
+ }
+ }
+}
+
+func TestCachedSourceCloneForceFailurePreservesOldCache(t *testing.T) {
+ root := withDiscoveryCloneCache(t, func(url, ref, dir string) error {
+ return errors.New("clone failed")
+ })
+ target := filepath.Join(root, cloneCacheKey("https://github.com/owner/repo", "main"))
+ makeGitRepo(t, target)
+
+ if _, _, err := cachedSourceClone("https://github.com/owner/repo", "main", true); err == nil {
+ t.Fatal("expected forced clone failure")
+ }
+ if !isGitRepo(target) {
+ t.Fatalf("expected existing cache to remain valid at %q", target)
+ }
+}
+
+func TestCachedSourceCloneMissFailureLeavesNoTargetDir(t *testing.T) {
+ root := withDiscoveryCloneCache(t, func(url, ref, dir string) error {
+ if err := os.WriteFile(filepath.Join(dir, "partial"), []byte("partial"), 0o644); err != nil {
+ return err
+ }
+ return errors.New("clone failed")
+ })
+ target := filepath.Join(root, cloneCacheKey("https://github.com/owner/repo", "main"))
+
+ if _, _, err := cachedSourceClone("https://github.com/owner/repo", "main", false); err == nil {
+ t.Fatal("expected clone failure")
+ }
+ if _, err := os.Stat(target); !os.IsNotExist(err) {
+ t.Fatalf("expected no half-valid target dir, stat err=%v", err)
+ }
+}
+
+func TestCachedSourceCloneForceReturnsTempWithoutDestroyingCache(t *testing.T) {
+ root := withDiscoveryCloneCache(t, func(url, ref, dir string) error {
+ makeGitRepo(t, dir)
+ return os.WriteFile(filepath.Join(dir, "fresh"), []byte("fresh"), 0o644)
+ })
+ target := filepath.Join(root, cloneCacheKey("https://github.com/owner/repo", "main"))
+ makeGitRepo(t, target)
+ if err := os.WriteFile(filepath.Join(target, "old"), []byte("old"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ dir, cleanup, err := cachedSourceClone("https://github.com/owner/repo", "main", true)
+ if err != nil {
+ t.Fatalf("forced clone failed: %v", err)
+ }
+ if dir == target {
+ t.Fatalf("expected force clone to return temp dir, got target %q", dir)
+ }
+ if !isGitRepo(target) {
+ t.Fatalf("expected existing cache to remain valid at %q", target)
+ }
+ if _, err := os.Stat(filepath.Join(target, "old")); err != nil {
+ t.Fatalf("expected old cache contents preserved: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "fresh")); err != nil {
+ t.Fatalf("expected temp clone contents: %v", err)
+ }
+ cleanup()
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatalf("expected cleanup to remove temp clone, stat err=%v", err)
+ }
+}
+
+func TestCachedSourceCloneConcurrentForceCallsUseSeparateTempDirs(t *testing.T) {
+ var clones int32
+ withDiscoveryCloneCache(t, func(url, ref, dir string) error {
+ atomic.AddInt32(&clones, 1)
+ time.Sleep(25 * time.Millisecond)
+ makeGitRepo(t, dir)
+ return nil
+ })
+
+ const callers = 2
+ var wg sync.WaitGroup
+ errs := make(chan error, callers)
+ dirs := make(chan string, callers)
+ cleanups := make(chan func(), callers)
+ for i := 0; i < callers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ dir, cleanup, err := cachedSourceClone("https://github.com/owner/repo", "main", true)
+ if err == nil {
+ dirs <- dir
+ cleanups <- cleanup
+ }
+ errs <- err
+ }()
+ }
+ wg.Wait()
+ close(errs)
+ close(dirs)
+ close(cleanups)
+
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("forced cachedSourceClone failed: %v", err)
+ }
+ }
+ if got := atomic.LoadInt32(&clones); got != callers {
+ t.Fatalf("expected %d independent force clones, got %d", callers, got)
+ }
+ seen := map[string]bool{}
+ for dir := range dirs {
+ if seen[dir] {
+ t.Fatalf("force clone temp dir was shared: %q", dir)
+ }
+ seen[dir] = true
+ if !isGitRepo(dir) {
+ t.Fatalf("expected temp dir to remain valid before cleanup: %q", dir)
+ }
+ }
+ for cleanup := range cleanups {
+ cleanup()
+ }
+}
diff --git a/internal/tui/helpers.go b/internal/tui/helpers.go
index eb81d61..99bb625 100644
--- a/internal/tui/helpers.go
+++ b/internal/tui/helpers.go
@@ -8,7 +8,6 @@ import (
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/charmbracelet/lipgloss"
xansi "github.com/charmbracelet/x/ansi"
- "github.com/muesli/reflow/wordwrap"
)
// humanizeSince renders a coarse, git-style relative age ("just now", "5m ago").
@@ -29,26 +28,10 @@ func humanizeSince(t time.Time) string {
}
func wrap(s string, width int) string {
- if width <= 8 || len(s) <= width {
+ if width <= 8 || xansi.StringWidth(s) <= width {
return s
}
- words := strings.Fields(s)
- lines := []string{}
- current := ""
- for _, word := range words {
- if len(current)+len(word)+1 > width {
- lines = append(lines, current)
- current = word
- } else if current == "" {
- current = word
- } else {
- current += " " + word
- }
- }
- if current != "" {
- lines = append(lines, current)
- }
- return strings.Join(lines, "\n")
+ return xansi.Wrap(strings.Join(strings.Fields(s), " "), width, " ")
}
func wrapText(s string, width int) string {
@@ -56,7 +39,7 @@ func wrapText(s string, width int) string {
return ""
}
s = strings.ReplaceAll(s, "\t", " ")
- return wordwrap.String(s, width)
+ return xansi.Wrap(s, width, " ")
}
func indent(s string, prefix string) string {
@@ -325,14 +308,13 @@ func decoratePane(rendered string, p paneLayout, focused bool, title string) str
}
func truncateTitle(s string, width int) string {
- runes := []rune(s)
- if len(runes) <= width {
+ if xansi.StringWidth(s) <= width {
return s
}
if width <= 1 {
return "…"
}
- return string(runes[:width-1]) + "…"
+ return xansi.Truncate(s, width, "…")
}
func (m appModel) installedSkillNames(group string) map[string]bool {
diff --git a/internal/tui/helpers_test.go b/internal/tui/helpers_test.go
new file mode 100644
index 0000000..0831ef1
--- /dev/null
+++ b/internal/tui/helpers_test.go
@@ -0,0 +1,101 @@
+package tui
+
+import (
+ "strings"
+ "testing"
+
+ xansi "github.com/charmbracelet/x/ansi"
+)
+
+func assertDisplayWidths(t *testing.T, got string, width int) {
+ t.Helper()
+ for _, line := range strings.Split(got, "\n") {
+ if lineWidth := xansi.StringWidth(line); lineWidth > width {
+ t.Fatalf("line %q has display width %d, want <= %d in %q", line, lineWidth, width, got)
+ }
+ }
+}
+
+func TestWrapTextPreservesStyledANSIAndDisplayWidth(t *testing.T) {
+ styled := "\x1b[38;5;205malpha beta gamma\x1b[0m"
+ got := wrapText(styled, 10)
+
+ if !strings.Contains(got, "\x1b[") {
+ t.Fatalf("expected styled ANSI sequences to be preserved, got %q", got)
+ }
+ if strings.Count(got, "\n") == 0 {
+ t.Fatalf("expected wrapped output, got %q", got)
+ }
+ assertDisplayWidths(t, got, 10)
+ if stripped := strings.ReplaceAll(xansi.Strip(got), "\n", " "); stripped != "alpha beta gamma" {
+ t.Fatalf("unexpected stripped wrapped text %q", stripped)
+ }
+}
+
+func TestWrapUsesDisplayWidthForWideGlyphsAndEmoji(t *testing.T) {
+ got := wrap("漢字 emoji 😊 wrap here", 10)
+
+ if strings.Count(got, "\n") == 0 {
+ t.Fatalf("expected wrapped output, got %q", got)
+ }
+ assertDisplayWidths(t, got, 10)
+ if !strings.Contains(got, "漢字") || !strings.Contains(got, "😊") {
+ t.Fatalf("expected wide glyphs and emoji to be preserved, got %q", got)
+ }
+}
+
+func TestFormatMetaLineWrapsValueUsingDisplayWidth(t *testing.T) {
+ got := formatMetaLine("Author", "alpha 漢字 beta 😊 gamma", 20)
+ lines := strings.Split(got, "\n")
+ if len(lines) < 2 {
+ t.Fatalf("expected metadata value to wrap, got %q", got)
+ }
+
+ assertDisplayWidths(t, got, 20)
+ strippedFirst := xansi.Strip(lines[0])
+ if !strings.HasPrefix(strippedFirst, "Author ") {
+ t.Fatalf("expected padded metadata key, got %q", strippedFirst)
+ }
+ if !strings.HasPrefix(xansi.Strip(lines[1]), strings.Repeat(" ", 13)) {
+ t.Fatalf("expected continuation line indentation, got %q", xansi.Strip(lines[1]))
+ }
+}
+
+func TestFormatMetaLineWrapsStyledValueUsingDisplayWidth(t *testing.T) {
+ value := "\x1b[31malpha beta gamma delta epsilon\x1b[0m"
+ got := formatMetaLine("Status", value, 22)
+ lines := strings.Split(got, "\n")
+ if len(lines) < 2 {
+ t.Fatalf("expected styled metadata value to wrap, got %q", got)
+ }
+
+ assertDisplayWidths(t, got, 22)
+ if !strings.Contains(got, "\x1b[") {
+ t.Fatalf("expected styled ANSI sequences to be preserved, got %q", got)
+ }
+ if strings.ContainsRune(got, '\uFFFD') {
+ t.Fatalf("wrapped styled metadata contains replacement characters: %q", got)
+ }
+ stripped := strings.Join(strings.Fields(xansi.Strip(got)), " ")
+ if stripped != "Status alpha beta gamma delta epsilon" {
+ t.Fatalf("unexpected stripped metadata text %q from %q", stripped, got)
+ }
+ if !strings.HasPrefix(xansi.Strip(lines[1]), strings.Repeat(" ", 13)) {
+ t.Fatalf("expected continuation line indentation, got %q", xansi.Strip(lines[1]))
+ }
+}
+
+func TestTruncateTitleUsesDisplayWidth(t *testing.T) {
+ styled := "\x1b[38;5;39mSkill 漢字 😊 Title\x1b[0m"
+ got := truncateTitle(styled, 10)
+
+ if !strings.Contains(got, "…") {
+ t.Fatalf("expected ellipsis, got %q", got)
+ }
+ if !strings.Contains(got, "\x1b[") {
+ t.Fatalf("expected ANSI sequences to be preserved, got %q", got)
+ }
+ if width := xansi.StringWidth(got); width > 10 {
+ t.Fatalf("truncated title width = %d, want <= 10 for %q", width, got)
+ }
+}
diff --git a/internal/tui/registry_preview_sanitize_test.go b/internal/tui/registry_preview_sanitize_test.go
new file mode 100644
index 0000000..a662a1a
--- /dev/null
+++ b/internal/tui/registry_preview_sanitize_test.go
@@ -0,0 +1,64 @@
+package tui
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSanitizeRegistryPreviewContentRemovesScriptsAndEventAttributes(t *testing.T) {
+ input := `<div onclick="alert('attr')">Safe<script>alert('script')</script><span onmouseover="bad()"> text</span></div>`
+
+ got := sanitizeRegistryPreviewContent(input)
+
+ if got != "Safe text" {
+ t.Fatalf("expected safe text only, got %q", got)
+ }
+ for _, forbidden := range []string{"script", "alert", "onclick", "onmouseover"} {
+ if strings.Contains(got, forbidden) {
+ t.Fatalf("expected %q to be removed from %q", forbidden, got)
+ }
+ }
+}
+
+func TestSanitizeRegistryPreviewContentPreservesBlockLineBreaks(t *testing.T) {
+ input := "<h1>Title</h1><p>First</p><div>Second<br>line</div><ul><li>One</li><li>Two</li></ul>"
+
+ got := sanitizeRegistryPreviewContent(input)
+ want := "Title\nFirst\nSecond\nline\nOne\nTwo"
+
+ if got != want {
+ t.Fatalf("expected %q, got %q", want, got)
+ }
+}
+
+func TestSanitizeRegistryPreviewContentDecodesEntities(t *testing.T) {
+ input := "Tom &amp; Jerry &lt;3&nbsp;forever"
+
+ got := sanitizeRegistryPreviewContent(input)
+ want := "Tom & Jerry <3\u00a0forever"
+
+ if got != want {
+ t.Fatalf("expected %q, got %q", want, got)
+ }
+}
+
+func TestSanitizeRegistryPreviewContentHandlesNestedTags(t *testing.T) {
+ input := "<div>Outer <strong>bold <em>inner</em></strong> tail</div>"
+
+ got := sanitizeRegistryPreviewContent(input)
+ want := "Outer bold inner tail"
+
+ if got != want {
+ t.Fatalf("expected %q, got %q", want, got)
+ }
+}
+
+func TestSanitizeRegistryPreviewContentKeepsMarkdownLiteralLessThan(t *testing.T) {
+ input := "# Usage\n\nUse `if a < b` and keep 1 < 2 in prose."
+
+ got := sanitizeRegistryPreviewContent(input)
+
+ if got != input {
+ t.Fatalf("expected markdown literal '<' to be preserved, got %q", got)
+ }
+}
diff --git a/internal/tui/source_parser.go b/internal/tui/source_parser.go
new file mode 100644
index 0000000..32607db
--- /dev/null
+++ b/internal/tui/source_parser.go
@@ -0,0 +1,150 @@
+package tui
+
+import (
+ "net/url"
+ "strings"
+)
+
+type parsedSource struct {
+ Host string
+ Owner string
+ Repo string
+ Folder string
+ Ref string
+}
+
+func parseSource(source string) (parsedSource, bool) {
+ src := strings.TrimSpace(source)
+ if src == "" {
+ return parsedSource{}, false
+ }
+
+ repoPart := src
+ ref := ""
+ if idx := strings.Index(repoPart, "#"); idx != -1 {
+ ref = repoPart[idx+1:]
+ repoPart = repoPart[:idx]
+ }
+
+ repoPart = strings.TrimPrefix(repoPart, "git+")
+ host := ""
+
+ if strings.HasPrefix(repoPart, "github:") {
+ host = "github.com"
+ repoPart = strings.TrimPrefix(repoPart, "github:")
+ } else if strings.HasPrefix(repoPart, "git@") {
+ ssh := strings.TrimPrefix(repoPart, "git@")
+ if i := strings.Index(ssh, ":"); i != -1 {
+ host = strings.ToLower(ssh[:i])
+ if !knownSourceHost(host) {
+ return parsedSource{}, false
+ }
+ repoPart = ssh[i+1:]
+ } else {
+ repoPart = ssh
+ }
+ } else if u, err := url.Parse(repoPart); err == nil && u.Scheme != "" && u.Host != "" {
+ host = strings.ToLower(u.Host)
+ if !knownSourceHost(host) {
+ return parsedSource{}, false
+ }
+ repoPart = strings.TrimPrefix(u.Path, "/")
+ }
+
+ if decoded, err := url.PathUnescape(repoPart); err == nil {
+ repoPart = decoded
+ }
+ repoPart = strings.TrimRight(repoPart, "/")
+ repoPart = strings.ReplaceAll(repoPart, ":", "/")
+
+ for _, knownHost := range []string{"github.com/", "gitlab.com/"} {
+ if strings.HasPrefix(strings.ToLower(repoPart), knownHost) {
+ host = strings.TrimSuffix(knownHost, "/")
+ repoPart = repoPart[len(knownHost):]
+ break
+ }
+ }
+
+ parts := strings.Split(repoPart, "/")
+ if len(parts) < 2 {
+ return parsedSource{}, false
+ }
+ owner := parts[0]
+ repo := strings.TrimSuffix(parts[1], ".git")
+ folder := ""
+ if host == "github.com" && len(parts) >= 4 && parts[2] == "tree" {
+ if ref == "" {
+ ref = parts[3]
+ }
+ if len(parts) > 4 {
+ folder = strings.Join(parts[4:], "/")
+ }
+ } else if len(parts) > 2 {
+ folder = strings.Join(parts[2:], "/")
+ }
+
+ return parsedSource{Host: host, Owner: owner, Repo: repo, Folder: folder, Ref: ref}, true
+}
+
+func knownSourceHost(host string) bool {
+ switch strings.ToLower(host) {
+ case "github.com", "gitlab.com":
+ return true
+ default:
+ return false
+ }
+}
+
+func (s parsedSource) repoSlug() string {
+ if s.Owner == "" || s.Repo == "" {
+ return ""
+ }
+ return s.Owner + "/" + s.Repo
+}
+
+func (s parsedSource) validRepo() bool {
+ return isSafeGitHubToken(s.Owner) && isSafeGitHubToken(s.Repo)
+}
+
+func (s parsedSource) validRef() bool {
+ return s.Ref == "" || isSafeGitHubRef(s.Ref)
+}
+
+func legacySourceURLDetails(source string) (repo string, folder string) {
+ src := source
+ src = strings.TrimPrefix(src, "git+https://")
+ src = strings.TrimPrefix(src, "https://")
+ src = strings.TrimPrefix(src, "http://")
+ src = strings.TrimPrefix(src, "git@")
+ src = strings.ReplaceAll(src, ":", "/")
+ src = strings.TrimSuffix(src, ".git")
+ src = strings.TrimRight(src, "/")
+ for _, host := range []string{"github.com/", "gitlab.com/"} {
+ src = strings.TrimPrefix(src, host)
+ }
+ parts := strings.Split(src, "/")
+ if len(parts) >= 2 {
+ repo = parts[0] + "/" + parts[1]
+ if len(parts) > 2 {
+ folder = strings.Join(parts[2:], "/")
+ }
+ } else {
+ repo = src
+ }
+ return repo, folder
+}
+
+func escapedSourceFolder(folder string) (string, bool) {
+ if folder == "" {
+ return "", true
+ }
+ parts := strings.Split(folder, "/")
+ escaped := make([]string, 0, len(parts))
+ for _, part := range parts {
+ if part == "" || part == "." || part == ".." || strings.Contains(part, "\\") {
+ return "", false
+ }
+ escaped = append(escaped, url.PathEscape(part))
+ }
+ return strings.Join(escaped, "/"), true
+}
diff --git a/internal/tui/source_parser_test.go b/internal/tui/source_parser_test.go
new file mode 100644
index 0000000..e55bb6b
--- /dev/null
+++ b/internal/tui/source_parser_test.go
@@ -0,0 +1,127 @@
+package tui
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestSourceParserMatrix(t *testing.T) {
+ cases := []struct {
+ name string
+ source string
+ wantRepo string
+ wantFolder string
+ wantNorm string
+ remoteOK bool
+ wantRemote string
+ wantRef string
+ }{
+ {name: "slug", source: "owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "github shorthand", source: "github:owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "https", source: "https://github.com/owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "http", source: "http://github.com/owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "git https", source: "git+https://github.com/owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "ssh", source: "[email protected]:owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "dot git", source: "https://github.com/owner/repo.git", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo"},
+ {name: "ref", source: "owner/repo#feature/ref", wantRepo: "owner/repo", wantNorm: "owner/repo", remoteOK: true, wantRemote: "https://github.com/owner/repo", wantRef: "feature/ref"},
+ {name: "folder", source: "owner/repo/skills/build", wantRepo: "owner/repo", wantFolder: "skills/build", wantNorm: "owner/repo/skills/build"},
+ {name: "host folder", source: "https://github.com/owner/repo/skills/build", wantRepo: "owner/repo", wantFolder: "skills/build", wantNorm: "owner/repo/skills/build"},
+ {name: "github tree folder", source: "https://github.com/owner/repo/tree/main/packages/skill", wantRepo: "owner/repo", wantFolder: "packages/skill", wantNorm: "owner/repo/packages/skill"},
+ {name: "gitlab display only", source: "https://gitlab.com/owner/repo", wantRepo: "owner/repo", wantNorm: "owner/repo"},
+ {name: "unknown host keeps host context", source: "https://example.com/owner/repo", wantRepo: "example.com/owner", wantFolder: "repo", wantNorm: "example.com/owner/repo"},
+ {name: "unknown ssh host keeps host context", source: "[email protected]:owner/repo", wantRepo: "example.com/owner", wantFolder: "repo", wantNorm: "example.com/owner/repo"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ repo, folder := parseSourceURLDetails(tc.source)
+ if repo != tc.wantRepo || folder != tc.wantFolder {
+ t.Fatalf("parseSourceURLDetails() = %q, %q; want %q, %q", repo, folder, tc.wantRepo, tc.wantFolder)
+ }
+ if got := normalizeSource(tc.source); got != tc.wantNorm {
+ t.Fatalf("normalizeSource() = %q; want %q", got, tc.wantNorm)
+ }
+ remote, ref, ok := parseRemoteGitHubSource(tc.source)
+ if ok != tc.remoteOK || remote != tc.wantRemote || ref != tc.wantRef {
+ t.Fatalf("parseRemoteGitHubSource() = %q, %q, %v; want %q, %q, %v", remote, ref, ok, tc.wantRemote, tc.wantRef, tc.remoteOK)
+ }
+ })
+ }
+}
+
+func TestSourceParserRejectsInvalidRemoteDiscovery(t *testing.T) {
+ cases := []string{
+ "-owner/repo",
+ "owner/-repo",
+ "owner/repo#--ref",
+ "owner/repo#branch..name",
+ "owner/repo;-somecmd",
+ "owner/repo/sub",
+ "https://gitlab.com/owner/repo",
+ }
+ for _, source := range cases {
+ if remote, ref, ok := parseRemoteGitHubSource(source); ok {
+ t.Fatalf("parseRemoteGitHubSource(%q) = %q, %q, true; want rejected", source, remote, ref)
+ }
+ }
+}
+
+func TestDeriveRawGitHubURLsUsesParsedSource(t *testing.T) {
+ got := deriveRawGitHubURLs("git+https://github.com/owner/repo.git/skills/build")
+ want := []string{
+ "https://raw.githubusercontent.com/owner/repo/main/skills/build/SKILL.md",
+ "https://raw.githubusercontent.com/owner/repo/main/skills/build/README.md",
+ "https://raw.githubusercontent.com/owner/repo/main/skills/build/README",
+ "https://raw.githubusercontent.com/owner/repo/master/skills/build/SKILL.md",
+ "https://raw.githubusercontent.com/owner/repo/master/skills/build/README.md",
+ "https://raw.githubusercontent.com/owner/repo/master/skills/build/README",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("deriveRawGitHubURLs() = %#v; want %#v", got, want)
+ }
+
+ if got := deriveRawGitHubURLs("https://gitlab.com/owner/repo"); got != nil {
+ t.Fatalf("expected GitLab raw preview unsupported, got %#v", got)
+ }
+}
+
+func TestDeriveRawGitHubURLsEscapesFolderSegments(t *testing.T) {
+ got := deriveRawGitHubURLs("https://github.com/owner/repo/skills/a%23b/folder with spaces")
+ if len(got) == 0 {
+ t.Fatal("expected raw preview URLs for escaped folder")
+ }
+ for _, u := range got {
+ if strings.Contains(u, "#") || strings.Contains(u, " ") {
+ t.Fatalf("raw URL should escape fragments and spaces, got %q", u)
+ }
+ if !strings.Contains(u, "/skills/a%23b/folder%20with%20spaces/") {
+ t.Fatalf("raw URL missing escaped folder path, got %q", u)
+ }
+ }
+
+ for _, source := range []string{
+ "https://github.com/owner/repo/../secret",
+ "https://github.com/owner/repo/skills/../secret",
+ "https://github.com/owner/repo/skills\\secret",
+ "owner/repo#--ref",
+ "owner/repo#bad ref",
+ "https://github.com/owner/repo/tree/--ref/packages/skill",
+ } {
+ if got := deriveRawGitHubURLs(source); got != nil {
+ t.Fatalf("expected unsafe source %q to be rejected, got %#v", source, got)
+ }
+ }
+}
+
+func TestDeriveRawGitHubURLsUsesTreeRefAndFolder(t *testing.T) {
+ got := deriveRawGitHubURLs("https://github.com/owner/repo/tree/dev/packages/skill")
+ want := []string{
+ "https://raw.githubusercontent.com/owner/repo/dev/packages/skill/SKILL.md",
+ "https://raw.githubusercontent.com/owner/repo/dev/packages/skill/README.md",
+ "https://raw.githubusercontent.com/owner/repo/dev/packages/skill/README",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("deriveRawGitHubURLs() = %#v; want %#v", got, want)
+ }
+}
diff --git a/internal/tui/state.go b/internal/tui/state.go
index 0fd6797..5a97454 100644
--- a/internal/tui/state.go
+++ b/internal/tui/state.go
@@ -651,12 +651,24 @@ func (m appModel) checkRegistrySkillStatus(s registry.Skill) (RegistryMatchStatu
}
func normalizeSource(src string) string {
+ parsed, ok := parseSource(src)
+ if !ok {
+ return normalizeSourceFallback(src)
+ }
+ out := strings.ToLower(parsed.repoSlug())
+ if parsed.Folder != "" {
+ out += "/" + strings.ToLower(parsed.Folder)
+ }
+ return out
+}
+
+func normalizeSourceFallback(src string) string {
src = strings.ToLower(strings.TrimSpace(src))
src = strings.TrimPrefix(src, "git+https://")
src = strings.TrimPrefix(src, "https://")
src = strings.TrimPrefix(src, "http://")
- src = strings.TrimPrefix(src, "git@") // for ssh URLs
- src = strings.ReplaceAll(src, ":", "/") // normalize [email protected]:foo/bar
+ src = strings.TrimPrefix(src, "git@")
+ src = strings.ReplaceAll(src, ":", "/")
src = strings.TrimSuffix(src, ".git")
src = strings.TrimRight(src, "/")
for _, host := range []string{"github.com/", "gitlab.com/"} {
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index 94a8fa3..feb325f 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -2345,6 +2345,9 @@ func TestRemoteDiscoverySuccess(t *testing.T) {
gitClone = func(url, ref, tempDir string) error {
capturedURL = url
capturedRef = ref
+ if err := os.MkdirAll(filepath.Join(tempDir, ".git"), 0o755); err != nil {
+ return err
+ }
skillPath := filepath.Join(tempDir, "SKILL.md")
skillContent := "---\nname: \"Remote Skill\"\ndescription: \"Remote description\"\n---\nRemote preview content"
if err := os.WriteFile(skillPath, []byte(skillContent), 0o644); err != nil {
@@ -2408,11 +2411,11 @@ func TestRemoteDiscoveryFailure(t *testing.T) {
width: 120, height: 32, selected: 0,
result: model.ScanResult{
Skills: []*model.Skill{
- {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo-fail"}},
},
},
}
- updated, cmd := m.startDiscovery("owner/repo", false)
+ updated, cmd := m.startDiscovery("owner/repo-fail", false)
if cmd == nil {
t.Fatal("expected discovery cmd")
}
@@ -2420,7 +2423,7 @@ func TestRemoteDiscoveryFailure(t *testing.T) {
updated, _ = updated.Update(msg)
next := updated.(appModel)
- disc := next.discovery["owner/repo"]
+ disc := next.discovery["owner/repo-fail"]
if disc.Status != DiscoveryFailed {
t.Fatalf("expected status failed, got %s", disc.Status)
}
@@ -2488,6 +2491,9 @@ func TestRemoteDiscoverySanitization(t *testing.T) {
defer func() { gitClone = oldGitClone }()
gitClone = func(url, ref, tempDir string) error {
+ if err := os.MkdirAll(filepath.Join(tempDir, ".git"), 0o755); err != nil {
+ return err
+ }
skillPath := filepath.Join(tempDir, "SKILL.md")
skillContent := "---\nname: \"Bad\\u001b[31m Skill\"\ndescription: \"Bad\\u001b[31m Description\"\n---\nBad\x1b[31m preview content"
if err := os.WriteFile(skillPath, []byte(skillContent), 0o644); err != nil {
diff --git a/internal/tui/update.go b/internal/tui/update.go
index cd9b123..23333b7 100644
--- a/internal/tui/update.go
+++ b/internal/tui/update.go
@@ -1982,15 +1982,20 @@ type registryPreviewMsg struct {
}
func deriveRawGitHubURLs(source string) []string {
- repo, folder := parseSourceURLDetails(source)
- parts := strings.Split(repo, "/")
- if len(parts) < 2 {
+ parsed, ok := parseSource(source)
+ if !ok || (parsed.Host != "" && parsed.Host != "github.com") || !parsed.validRepo() || !parsed.validRef() {
+ return nil
+ }
+ folder, ok := escapedSourceFolder(parsed.Folder)
+ if !ok {
return nil
}
- owner, name := parts[0], parts[1]
var urls []string
branches := []string{"main", "master"}
+ if parsed.Ref != "" {
+ branches = []string{parsed.Ref}
+ }
files := []string{"SKILL.md", "README.md", "README"}
for _, branch := range branches {
@@ -2001,7 +2006,7 @@ func deriveRawGitHubURLs(source string) []string {
} else {
path = file
}
- urls = append(urls, fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/%s", owner, name, branch, path))
+ urls = append(urls, fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/%s", parsed.Owner, parsed.Repo, branch, path))
}
}
return urls
diff --git a/internal/tui/view.go b/internal/tui/view.go
index 7f1a578..49ab5bb 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -2,8 +2,7 @@ package tui
import (
"fmt"
- "html"
- "regexp"
+ "io"
"strings"
"sync"
"time"
@@ -17,11 +16,9 @@ import (
"github.com/alvinunreal/lazyskills/internal/model"
"github.com/alvinunreal/lazyskills/internal/selfupdate"
"github.com/charmbracelet/lipgloss"
+ xhtml "golang.org/x/net/html"
)
-var htmlBlockTagRE = regexp.MustCompile(`(?i)</?(?:br|p|div|li|h1|h2|h3|h4)\b[^>]*>`)
-var htmlTagRE = regexp.MustCompile(`<[^>]+>`)
-
func (m appModel) View() string {
viewStart := time.Now()
defer func() {
@@ -780,9 +777,7 @@ func sanitizeRegistryPreviewContent(markdown string) string {
markdown = compat.SanitizePreviewContent(markdown)
markdown = strings.ReplaceAll(markdown, "\r\n", "\n")
markdown = strings.ReplaceAll(markdown, "\r", "\n")
- markdown = htmlBlockTagRE.ReplaceAllString(markdown, "\n")
- markdown = htmlTagRE.ReplaceAllString(markdown, "")
- markdown = html.UnescapeString(markdown)
+ markdown = registryPreviewPlainText(markdown)
lines := strings.Split(markdown, "\n")
for i, line := range lines {
lines[i] = strings.TrimRight(line, " \t")
@@ -790,6 +785,75 @@ func sanitizeRegistryPreviewContent(markdown string) string {
return strings.TrimSpace(strings.Join(lines, "\n"))
}
+func registryPreviewPlainText(markdown string) string {
+ var b strings.Builder
+ z := xhtml.NewTokenizer(strings.NewReader(markdown))
+ skipDepth := 0
+ lastWasNewline := false
+
+ for {
+ tt := z.Next()
+ switch tt {
+ case xhtml.ErrorToken:
+ if z.Err() == io.EOF {
+ return b.String()
+ }
+ return b.String()
+ case xhtml.TextToken:
+ if skipDepth == 0 {
+ text := z.Token().Data
+ b.WriteString(text)
+ lastWasNewline = strings.HasSuffix(text, "\n")
+ }
+ case xhtml.StartTagToken, xhtml.SelfClosingTagToken:
+ tag := z.Token().DataAtom.String()
+ if tag == "" {
+ tag = strings.ToLower(z.Token().Data)
+ }
+ if tag == "script" || tag == "style" {
+ if tt == xhtml.StartTagToken {
+ skipDepth++
+ }
+ continue
+ }
+ if skipDepth == 0 && registryPreviewBlockTag(tag) {
+ writeRegistryPreviewNewline(&b, &lastWasNewline)
+ }
+ case xhtml.EndTagToken:
+ tag := z.Token().DataAtom.String()
+ if tag == "" {
+ tag = strings.ToLower(z.Token().Data)
+ }
+ if tag == "script" || tag == "style" {
+ if skipDepth > 0 {
+ skipDepth--
+ }
+ continue
+ }
+ if skipDepth == 0 && registryPreviewBlockTag(tag) {
+ writeRegistryPreviewNewline(&b, &lastWasNewline)
+ }
+ }
+ }
+}
+
+func writeRegistryPreviewNewline(b *strings.Builder, lastWasNewline *bool) {
+ if *lastWasNewline {
+ return
+ }
+ b.WriteByte('\n')
+ *lastWasNewline = true
+}
+
+func registryPreviewBlockTag(tag string) bool {
+ switch tag {
+ case "br", "p", "div", "li", "h1", "h2", "h3", "h4", "h5", "h6":
+ return true
+ default:
+ return false
+ }
+}
+
func appendRegistryPreviewLines(lines []string, title string, markdown string, width int, maxLines int) []string {
markdown = sanitizeRegistryPreviewContent(markdown)
if markdown == "" {
@@ -1781,31 +1845,11 @@ func truncateReleaseNotes(notes string, width int) string {
}
func parseSourceURLDetails(source string) (repo string, folder string) {
- src := source
- src = strings.TrimPrefix(src, "git+https://")
- src = strings.TrimPrefix(src, "https://")
- src = strings.TrimPrefix(src, "http://")
- src = strings.TrimPrefix(src, "git@")
- src = strings.ReplaceAll(src, ":", "/")
- src = strings.TrimSuffix(src, ".git")
- src = strings.TrimRight(src, "/")
-
- // Remove host prefix
- for _, host := range []string{"github.com/", "gitlab.com/"} {
- src = strings.TrimPrefix(src, host)
- }
-
- // Now src should look like "owner/repo/sub/folders" or just "owner/repo"
- parts := strings.Split(src, "/")
- if len(parts) >= 2 {
- repo = parts[0] + "/" + parts[1]
- if len(parts) > 2 {
- folder = strings.Join(parts[2:], "/")
- }
- } else {
- repo = src
+ parsed, ok := parseSource(source)
+ if !ok {
+ return legacySourceURLDetails(source)
}
- return repo, folder
+ return parsed.repoSlug(), parsed.Folder
}
func (m appModel) registrySelectedCount() int {