T1 移动包同步(internal/app/movepkg.go + renameentry.go)
gopls 不声明 willRename,改用 go/parser 精确定位 ImportSpec.Path,
目录移动改全仓 import 路径、单文件跨目录移动改 package 声明。
写盘失败整体恢复并回滚 rename;已打开且无改动的缓冲区用 Reset 同步。
集成测试在临时 Go 模块里移目录后直接跑 go build ./... 通过。
T2 输出/问题面板右键(panel_menu.go + output.go + popmenu.go)
新增 openPopAt 让菜单贴指针弹出;复制选中行/复制全部/清空输出。
真窗口截图确认位置正确、无裁切。
**范围缩窄**:终端从 mygo v0.7.4 起就自带原生 ContextMenu,原判断是误报。
T3 snippet 补全(completion_snippet.go + lsp/protocol.go)
snippetSupport 改 true;实测 gopls v0.23 返回 insertTextFormat=2、
textEdit.newText="Print(${1:})",接上 mygo v0.9.0 的 ParseSnippet。
解析失败降级成纯文本(支持嵌套占位/choices 剥离),结果按模板缓存。
端到端 Tester 验证接受补全后得到 fmt.Print() 且光标停在括号内。
T4 本地历史超限可见(history.go)
静默 return 改为返回 histSkipped,输出面板提示;每文件整个会话只提一次。
T5 全局搜索并发(palette.go)
NumCPU(上限 8)个 worker 并发读盘,结果按文件序合并保证顺序稳定;
命中上限停止派发;512KB 以上被跳过的文件数显示成面板底部提示。
T6 清理根目录残留;4 个 0 字节 .sock 被环境安全守卫拦住未删(已 gitignore)。
验证:gofmt 空、build/vet OK、go test -count=1 ./... 全绿(282 个测试)、
新增并发/剪贴板/回滚用例 go test -race 无数据竞争。
docs/MyGoland-待办与规划.md 已清空待办,只剩 6 项规划与完成索引。
457 lines
13 KiB
Go
457 lines
13 KiB
Go
package app
|
|
|
|
import (
|
|
"crypto/sha1"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// 本地历史:把文件内容按时间点存到本机,和 git 无关。
|
|
//
|
|
// 三个用途共用这一套存储:
|
|
// - 手动保存后留一个点(reason=save),误改能翻回去;
|
|
// - 有未保存改动时定时留点(reason=auto),崩溃后能捞回来;
|
|
// - 本地历史面板列出来给用户挑着恢复。
|
|
//
|
|
// 同一个内容只存一份:文件名就是内容的 sha1,重复内容直接跳过。
|
|
|
|
const (
|
|
// histKeep 是每个文件保留的快照条数。
|
|
histKeep = 60
|
|
// histMaxSize 是单文件快照的大小上限:超过就不存了,
|
|
// 免得把 40 MB 的日志每次保存都复制一份。
|
|
histMaxSize = 4 << 20
|
|
)
|
|
|
|
// histEntry 是历史索引里的一条。
|
|
type histEntry struct {
|
|
Time int64 `json:"time"` // 毫秒时间戳
|
|
Hash string `json:"hash"` // 内容 sha1 的前 12 位,也是快照文件名
|
|
Size int `json:"size"` // 字节数
|
|
Reason string `json:"reason"` // save / auto / close
|
|
Dirty bool `json:"dirty"` // 存的时候是否还有未保存改动
|
|
}
|
|
|
|
// histIndex 是某个文件的历史索引。
|
|
type histIndex struct {
|
|
Path string `json:"path"`
|
|
Entries []histEntry `json:"entries"`
|
|
}
|
|
|
|
// histSkipped 不是写失败,而是「这次故意没留历史点」,需要让用户知道原因。
|
|
// 用独立类型把它和真正的 IO 错误分开:前者进输出面板,后者进日志。
|
|
type histSkipped struct{ msg string }
|
|
|
|
func (e histSkipped) Error() string { return e.msg }
|
|
|
|
// histSkipMessage 说明为什么这个文件没被纳入本地历史。
|
|
// 单列成纯函数是为了能测:措辞里要带文件名、上限,别只说「失败」。
|
|
func histSkipMessage(path string, size int) string {
|
|
return fmt.Sprintf("本地历史:%s 超过 %d MB 上限(当前 %.1f MB),该文件不会有历史快照",
|
|
filepath.Base(path), histMaxSize/(1<<20), float64(size)/(1<<20))
|
|
}
|
|
|
|
// histMu 串行化索引读写:多个文档同时保存会并发进来。
|
|
var histMu sync.Mutex
|
|
|
|
// historyDir 返回某个文件的历史目录(按绝对路径散列)。
|
|
func historyDir(path string) string {
|
|
base := sessionDir()
|
|
if base == "" || path == "" {
|
|
return ""
|
|
}
|
|
sum := sha1.Sum([]byte(strings.ToLower(filepath.Clean(path))))
|
|
return filepath.Join(base, "history", fmt.Sprintf("%x", sum[:6]))
|
|
}
|
|
|
|
// saveSnapshot 给文件留一个历史点;内容没变时直接跳过。
|
|
//
|
|
// 超过 histMaxSize 时返回 histSkipped(不是 error 日志),调用方要把它
|
|
// 转成用户可见的说明——以前这里静默 return nil,大文件改坏后用户根本
|
|
// 不知道自己没有快照可回。
|
|
func saveSnapshot(path string, data []byte, reason string, dirty bool) error {
|
|
if len(data) == 0 {
|
|
return nil
|
|
}
|
|
if len(data) > histMaxSize {
|
|
return histSkipped{histSkipMessage(path, len(data))}
|
|
}
|
|
dir := historyDir(path)
|
|
if dir == "" {
|
|
return nil
|
|
}
|
|
|
|
histMu.Lock()
|
|
defer histMu.Unlock()
|
|
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
sum := sha1.Sum(data)
|
|
hash := fmt.Sprintf("%x", sum[:12])
|
|
snap := filepath.Join(dir, hash+".snap")
|
|
|
|
idx, err := readHistIndex(dir)
|
|
if err != nil {
|
|
idx = histIndex{Path: path}
|
|
}
|
|
// 内容没变就不重复记:同一个 hash 说明和上一次存的一模一样。
|
|
for _, e := range idx.Entries {
|
|
if e.Hash == hash {
|
|
return nil
|
|
}
|
|
}
|
|
if err := os.WriteFile(snap, data, 0o644); err != nil {
|
|
return err
|
|
}
|
|
idx.Path = path
|
|
idx.Entries = append(idx.Entries, histEntry{
|
|
Time: time.Now().UnixMilli(),
|
|
Hash: hash,
|
|
Size: len(data),
|
|
Reason: reason,
|
|
Dirty: dirty,
|
|
})
|
|
pruneHistory(dir, &idx)
|
|
return writeHistIndex(dir, idx)
|
|
}
|
|
|
|
// readHistIndex 读索引,损坏时当成空的(历史丢了也不能影响正常编辑)。
|
|
func readHistIndex(dir string) (histIndex, error) {
|
|
var idx histIndex
|
|
b, err := os.ReadFile(filepath.Join(dir, "index.json"))
|
|
if err != nil {
|
|
return idx, err
|
|
}
|
|
if err := json.Unmarshal(b, &idx); err != nil {
|
|
return histIndex{}, err
|
|
}
|
|
return idx, nil
|
|
}
|
|
|
|
func writeHistIndex(dir string, idx histIndex) error {
|
|
b, err := json.MarshalIndent(idx, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tmp := filepath.Join(dir, "index.json.tmp")
|
|
if err := os.WriteFile(tmp, b, 0o644); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, filepath.Join(dir, "index.json"))
|
|
}
|
|
|
|
// pruneHistory 只保留最近 histKeep 条,并把对应快照文件删掉。
|
|
// 调用方必须持有 histMu。
|
|
func pruneHistory(dir string, idx *histIndex) {
|
|
if len(idx.Entries) <= histKeep {
|
|
return
|
|
}
|
|
sort.Slice(idx.Entries, func(i, j int) bool { return idx.Entries[i].Time < idx.Entries[j].Time })
|
|
drop := idx.Entries[:len(idx.Entries)-histKeep]
|
|
for _, e := range drop {
|
|
_ = os.Remove(filepath.Join(dir, e.Hash+".snap"))
|
|
}
|
|
idx.Entries = idx.Entries[len(idx.Entries)-histKeep:]
|
|
}
|
|
|
|
// listHistory 返回某个文件的历史,最新的在前。
|
|
func listHistory(path string) []histEntry {
|
|
dir := historyDir(path)
|
|
if dir == "" {
|
|
return nil
|
|
}
|
|
histMu.Lock()
|
|
defer histMu.Unlock()
|
|
idx, err := readHistIndex(dir)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
out := append([]histEntry(nil), idx.Entries...)
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Time > out[j].Time })
|
|
return out
|
|
}
|
|
|
|
// readSnapshot 读出某条历史的内容。
|
|
func readSnapshot(path, hash string) ([]byte, error) {
|
|
dir := historyDir(path)
|
|
if dir == "" {
|
|
return nil, fmt.Errorf("没有历史目录")
|
|
}
|
|
return os.ReadFile(filepath.Join(dir, hash+".snap"))
|
|
}
|
|
|
|
// 崩溃恢复用:启动时如果发现上次是异常退出,把没存盘的内容捞回来。
|
|
|
|
// pendingPath 是「上次退出时有未保存改动」的标记文件。
|
|
func pendingPath() string {
|
|
base := sessionDir()
|
|
if base == "" {
|
|
return ""
|
|
}
|
|
return filepath.Join(base, "pending.json")
|
|
}
|
|
|
|
// pendingSnap 是待恢复的一条。
|
|
type pendingSnap struct {
|
|
Path string `json:"path"`
|
|
Hash string `json:"hash"`
|
|
Time int64 `json:"time"`
|
|
}
|
|
|
|
// markPending 记录「这些文件有未保存改动」,正常退出时清掉。
|
|
func markPending(items []pendingSnap) {
|
|
p := pendingPath()
|
|
if p == "" {
|
|
return
|
|
}
|
|
if len(items) == 0 {
|
|
_ = os.Remove(p)
|
|
return
|
|
}
|
|
b, err := json.Marshal(items)
|
|
if err != nil {
|
|
return
|
|
}
|
|
// 首次运行时 mygoland 目录可能还不存在,先建出来。
|
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
|
return
|
|
}
|
|
if err := os.WriteFile(p, b, 0o644); err != nil {
|
|
logf("写入恢复标记失败:%v", err)
|
|
}
|
|
}
|
|
|
|
// loadPending 读上次的未保存标记。
|
|
func loadPending() []pendingSnap {
|
|
p := pendingPath()
|
|
if p == "" {
|
|
return nil
|
|
}
|
|
b, err := os.ReadFile(p)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var items []pendingSnap
|
|
if err := json.Unmarshal(b, &items); err != nil {
|
|
return nil
|
|
}
|
|
return items
|
|
}
|
|
|
|
// shouldWarnHistory 判断这个文件的「超限」提示是否还没发过。
|
|
// LoadOrStore 保证并发自动快照里也只过一次。
|
|
func (a *App) shouldWarnHistory(path string) bool {
|
|
_, warned := a.histWarned.LoadOrStore(path, struct{}{})
|
|
return !warned
|
|
}
|
|
|
|
// snapshotAsync 在后台给文档留一个历史点,真正的写失败只记日志;
|
|
// 「故意跳过」要让用户看见,否则用户会以为自己有快照可回。
|
|
func (a *App) snapshotAsync(d *Doc, reason string, dirty bool) {
|
|
if d == nil || d.truncated || !a.set.History {
|
|
return
|
|
}
|
|
path := d.path
|
|
text := d.buf.String()
|
|
enc := d.enc
|
|
eol := d.buf.LineEnding()
|
|
d.lastSnapAt = time.Now().UnixMilli()
|
|
go func() {
|
|
data, err := encodeFile(applyEOL(text, eol), enc)
|
|
if err != nil {
|
|
return
|
|
}
|
|
err = saveSnapshot(path, data, reason, dirty)
|
|
var skipped histSkipped
|
|
if errors.As(err, &skipped) {
|
|
if a.win == nil || !a.shouldWarnHistory(path) {
|
|
return
|
|
}
|
|
msg := skipped.Error()
|
|
a.win.Update(func() { a.appendOut(msg) })
|
|
return
|
|
}
|
|
if err != nil {
|
|
logf("本地历史写入失败:%v", err)
|
|
}
|
|
}()
|
|
}
|
|
|
|
// applyEOL 按原文件的换行写回,和保存时保持一致。
|
|
func applyEOL(text, eol string) string {
|
|
if eol != "\r\n" {
|
|
return text
|
|
}
|
|
text = strings.ReplaceAll(text, "\r\n", "\n")
|
|
return strings.ReplaceAll(text, "\n", "\r\n")
|
|
}
|
|
|
|
// maybeAutoSnapshot 在有未保存改动、且停手几秒后自动留一个点。
|
|
//
|
|
// 只写历史、不动原文件:自动改磁盘风险更大,崩溃恢复靠 pending 兜底。
|
|
func (a *App) maybeAutoSnapshot(d *Doc) {
|
|
if d == nil || d.st == nil || d.truncated || !a.set.History || !a.set.AutoSnapshot {
|
|
return
|
|
}
|
|
ver := d.buf.Version()
|
|
now := time.Now().UnixMilli()
|
|
if !d.buf.Modified() {
|
|
d.dirtyAt = 0
|
|
d.dirtyVer = ver
|
|
return
|
|
}
|
|
if ver != d.dirtyVer {
|
|
d.dirtyVer = ver
|
|
d.dirtyAt = now
|
|
return
|
|
}
|
|
// 停手 4 秒以上、且距上次留点超过 1 分钟,才存一次。
|
|
if d.dirtyAt == 0 || now-d.dirtyAt < 4000 || now-d.lastSnapAt < 60000 {
|
|
return
|
|
}
|
|
a.snapshotAsync(d, "auto", true)
|
|
}
|
|
|
|
// snapshotDirtyOnExit 退出前把未保存的文档各存一份,并留下恢复标记。
|
|
func (a *App) snapshotDirtyOnExit() {
|
|
var pending []pendingSnap
|
|
for _, d := range a.docs {
|
|
if d == nil || !d.buf.Modified() || d.truncated || !a.set.History {
|
|
continue
|
|
}
|
|
text := d.buf.String()
|
|
data, err := encodeFile(applyEOL(text, d.buf.LineEnding()), d.enc)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if err := saveSnapshot(d.path, data, "close", true); err != nil {
|
|
continue
|
|
}
|
|
sum := sha1.Sum(data)
|
|
pending = append(pending, pendingSnap{
|
|
Path: d.path,
|
|
Hash: fmt.Sprintf("%x", sum[:12]),
|
|
Time: time.Now().UnixMilli(),
|
|
})
|
|
}
|
|
markPending(pending)
|
|
}
|
|
|
|
// collectPending 读上次没存盘的记录,只留当前工作区的。
|
|
//
|
|
// 这一步要在切工作区时做,但**不能在这里弹窗**:OpenFolder 期间窗口
|
|
// 还没就绪,模态框弹不出来。所以只记下来,等首帧之后再问。
|
|
func (a *App) collectPending() {
|
|
a.pendingRestore = nil
|
|
items := loadPending()
|
|
if len(items) == 0 {
|
|
return
|
|
}
|
|
for _, it := range items {
|
|
if a.root == "" || within(a.root, it.Path) {
|
|
a.pendingRestore = append(a.pendingRestore, it)
|
|
}
|
|
}
|
|
// 已经消费掉的标记要清掉,免得下次又弹一遍。
|
|
markPending(nil)
|
|
if len(a.pendingRestore) > 0 {
|
|
// 等窗口把第一帧画完再往里塞内容,否则编辑器还没建好。
|
|
time.AfterFunc(600*time.Millisecond, a.restorePendingNow)
|
|
}
|
|
}
|
|
|
|
// restorePendingNow 把上次没存盘的内容放回编辑器。
|
|
//
|
|
// 不弹模态框询问:模态在启动阶段弹不出来(窗口还没就绪,非 UI 线程调用会失败),
|
|
// 而这一步的价值就是「别丢东西」。所以直接恢复到缓冲区——**不写盘**,
|
|
// 标签上会显示未保存标记,用户在运行面板也能看到说明,不要就 Ctrl+Z 或直接关闭。
|
|
func (a *App) restorePendingNow() {
|
|
items := a.pendingRestore
|
|
a.pendingRestore = nil
|
|
if len(items) == 0 {
|
|
return
|
|
}
|
|
restored := 0
|
|
for _, it := range items {
|
|
if _, err := os.Stat(it.Path); err != nil {
|
|
continue
|
|
}
|
|
data, err := readSnapshot(it.Path, it.Hash)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
text, _, ok := decodeFile(data)
|
|
if !ok {
|
|
continue
|
|
}
|
|
d, err := a.loadDoc(it.Path)
|
|
if err != nil || d == nil {
|
|
continue
|
|
}
|
|
if d.buf.String() != text {
|
|
// 用 Set 而不是 Reset:Set 是「一次可撤销的编辑」,
|
|
// 缓冲区会处于已修改状态,用户能立刻看到「这段内容还没存盘」;
|
|
// Reset 会把它当成已保存文本,关掉就悄悄丢了。
|
|
d.buf.Set(text)
|
|
restored++
|
|
}
|
|
}
|
|
if restored == 0 {
|
|
return
|
|
}
|
|
a.appendOut(fmt.Sprintf("已恢复 %d 个上次未保存的文件(内容在编辑器里,尚未写盘,确认后请保存)。", restored))
|
|
a.refresh()
|
|
}
|
|
|
|
// histItem 是带文件路径的一条历史,目录聚合时用。
|
|
type histItem struct {
|
|
Path string
|
|
histEntry
|
|
}
|
|
|
|
// listHistoryUnder 列出某个目录下所有文件的历史,按时间倒序。
|
|
//
|
|
// history 目录是按文件路径散列的,没法从目录名反推,
|
|
// 所以遍历每个 index.json,读里面记的原路径来筛。
|
|
func listHistoryUnder(dir string) []histItem {
|
|
base := sessionDir()
|
|
if base == "" || dir == "" {
|
|
return nil
|
|
}
|
|
histRoot := filepath.Join(base, "history")
|
|
entries, err := os.ReadDir(histRoot)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
histMu.Lock()
|
|
defer histMu.Unlock()
|
|
|
|
var out []histItem
|
|
for _, e := range entries {
|
|
if !e.IsDir() {
|
|
continue
|
|
}
|
|
idx, err := readHistIndex(filepath.Join(histRoot, e.Name()))
|
|
if err != nil || idx.Path == "" {
|
|
continue
|
|
}
|
|
if !within(dir, idx.Path) {
|
|
continue
|
|
}
|
|
for _, en := range idx.Entries {
|
|
out = append(out, histItem{Path: idx.Path, histEntry: en})
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Time > out[j].Time })
|
|
return out
|
|
}
|