package app import ( "os" "path/filepath" "sort" "strings" "sync" ) // 文件名索引与模糊匹配,供快速打开使用。 // indexState 是工作区文件索引。 type indexState struct { mu sync.Mutex root string files []string // 相对路径,正斜杠 ready bool } // buildIndex 在后台遍历工作区,收集可打开的文件。 func (a *App) buildIndex(root string) { go func() { var files []string _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { if err != nil { return nil } name := d.Name() if d.IsDir() { if p != root && skipDir(name) { return filepath.SkipDir } return nil } if skipFile(name) { return nil } rel, err := filepath.Rel(root, p) if err != nil { return nil } files = append(files, filepath.ToSlash(rel)) if len(files) > 20000 { return filepath.SkipAll } return nil }) sort.Strings(files) a.index.mu.Lock() if a.index.root == root { a.index.files = files a.index.ready = true } a.index.mu.Unlock() }() } // resetIndex 换工作区时清空索引。 func (a *App) resetIndex(root string) { a.index.mu.Lock() a.index.root = root a.index.files = nil a.index.ready = false a.index.mu.Unlock() } // indexSnapshot 取当前索引的快照。 func (a *App) indexSnapshot() ([]string, bool) { a.index.mu.Lock() defer a.index.mu.Unlock() return a.index.files, a.index.ready } // fuzzyScore 判断 query 是否为 path 的子序列,并给出一个分数(越大越靠前)。 // // 规则很朴素:连续匹配、匹配到文件名部分、匹配位置靠前,都会加分。 func fuzzyScore(path, query string) (int, bool) { if query == "" { return 0, true } lp := strings.ToLower(path) lq := strings.ToLower(query) score := 0 pi := 0 prev := -2 for qi := 0; qi < len(lq); qi++ { c := lq[qi] found := -1 for ; pi < len(lp); pi++ { if lp[pi] == c { found = pi break } } if found < 0 { return 0, false } // 连续匹配 if found == prev+1 { score += 8 } else { score += 2 } // 词边界(/ _ - . 之后)加分 if found == 0 || strings.ContainsRune("/_-.\\.", rune(lp[found-1])) { score += 6 } prev = found pi = found + 1 } // 文件名里命中比目录里命中更值钱 if base := lp[strings.LastIndexByte(lp, '/')+1:]; strings.Contains(base, lq) { score += 20 } // 路径越短越靠前 score -= len(path) / 4 return score, true } // quickResults 用索引算出快速打开的候选列表。 func (a *App) quickResults(query string, limit int) []paletteItem { files, _ := a.indexSnapshot() type scored struct { rel string score int } var hits []scored for _, rel := range files { if s, ok := fuzzyScore(rel, query); ok { hits = append(hits, scored{rel, s}) } } sort.Slice(hits, func(i, j int) bool { if hits[i].score != hits[j].score { return hits[i].score > hits[j].score } return hits[i].rel < hits[j].rel }) if len(hits) > limit { hits = hits[:limit] } out := make([]paletteItem, 0, len(hits)) for _, h := range hits { out = append(out, paletteItem{ Path: filepath.Join(a.root, filepath.FromSlash(h.rel)), Label: filepath.Base(h.rel), Hint: filepath.Dir(h.rel), Kind: itemFile, }) } return out }