MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/
This commit is contained in:
commit
a80c0f886a
220 files changed
+20784
No files matched your search
@@ -0,0 +1,417 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/json"
|
||||
"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"`
|
||||
}
|
||||
|
||||
// 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 给文件留一个历史点;内容没变时直接跳过。
|
||||
func saveSnapshot(path string, data []byte, reason string, dirty bool) error {
|
||||
if len(data) == 0 || len(data) > histMaxSize {
|
||||
return nil
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
if err := saveSnapshot(path, data, reason, dirty); 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
|
||||
}
|
||||
Reference in new issue
Block a user