更新若干功能
This commit is contained in:
275
app.go
275
app.go
@@ -1,19 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"view/platform"
|
||||
"view/service"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
"github.com/wailsapp/wails/v3/pkg/application"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/notifications"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
@@ -21,15 +25,52 @@ type App struct {
|
||||
store *Store
|
||||
bootstrapFile string
|
||||
bootstrap BootstrapStatus
|
||||
runtimeReady bool
|
||||
mu sync.Mutex
|
||||
tasks map[string]context.CancelFunc
|
||||
taskResults map[string]string
|
||||
aiStreams map[int64]context.CancelFunc
|
||||
shell *shellState
|
||||
notifier *notifications.NotificationService
|
||||
syncing atomic.Bool
|
||||
syncOnline atomic.Bool
|
||||
syncMu sync.Mutex
|
||||
syncLastErr string
|
||||
// 全局文件存储配置的实时读取缓存(见 filestorage.go currentFileStorage)。
|
||||
fsMu sync.Mutex
|
||||
fsCfg FileStorageConfig
|
||||
fsCfgAt time.Time
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
return &App{tasks: map[string]context.CancelFunc{}, taskResults: map[string]string{}, aiStreams: map[int64]context.CancelFunc{}}
|
||||
}
|
||||
|
||||
// emit 向前端广播事件;纯测试环境(无 Wails 应用实例)下静默忽略。
|
||||
func (a *App) emit(name string, data any) {
|
||||
if app := application.Get(); app != nil {
|
||||
app.Event.Emit(name, data)
|
||||
}
|
||||
}
|
||||
|
||||
// ServiceStartup 由 Wails v3 在应用启动时调用,执行数据库引导流程。
|
||||
func (a *App) ServiceStartup(ctx context.Context, _ application.ServiceOptions) error {
|
||||
a.startup(ctx)
|
||||
a.RefreshShell()
|
||||
go a.runAutoUpdateLoop()
|
||||
go a.runReminderLoop()
|
||||
go a.runSyncLoop()
|
||||
go a.runTeamDigestLoop()
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServiceShutdown 由 Wails v3 在应用退出时调用。
|
||||
func (a *App) ServiceShutdown() error {
|
||||
a.shutdown(context.Background())
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewApp() *App { return &App{tasks: map[string]context.CancelFunc{}} }
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
a.runtimeReady = true
|
||||
defaultPath, e := defaultDBPath()
|
||||
if e != nil {
|
||||
a.bootstrap = BootstrapStatus{State: BootstrapRecovery, ErrorCode: "DB_DEFAULT_PATH_FAILED", ErrorDetail: e.Error()}
|
||||
@@ -66,7 +107,6 @@ func (a *App) startup(ctx context.Context) {
|
||||
s, e := OpenStore(c.DatabasePath)
|
||||
if e != nil {
|
||||
a.bootstrap = bootstrapFailure(defaultPath, c.DatabasePath, e)
|
||||
runtime.LogError(ctx, e.Error())
|
||||
return
|
||||
}
|
||||
a.store = s
|
||||
@@ -80,7 +120,12 @@ func (a *App) SelectInitialDatabaseFile(defaultPath string) (string, error) {
|
||||
if strings.TrimSpace(defaultPath) == "" {
|
||||
defaultPath = a.bootstrap.DefaultPath
|
||||
}
|
||||
return runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{Title: "Initialize Code Count database", DefaultDirectory: filepath.Dir(defaultPath), DefaultFilename: filepath.Base(defaultPath), Filters: []runtime.FileFilter{{DisplayName: "SQLite Database", Pattern: "*.db"}}})
|
||||
return application.Get().Dialog.SaveFile().
|
||||
SetMessage("Initialize 年糕崽崽 PMS database").
|
||||
SetDirectory(filepath.Dir(defaultPath)).
|
||||
SetFilename(filepath.Base(defaultPath)).
|
||||
AddFilter("SQLite Database", "*.db").
|
||||
PromptForSingleSelection()
|
||||
}
|
||||
func (a *App) InitializeDatabase(path string) (BootstrapStatus, error) {
|
||||
a.mu.Lock()
|
||||
@@ -122,7 +167,12 @@ func (a *App) SelectDirectory() (string, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return "", e
|
||||
}
|
||||
return runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{Title: a.localized("选择代码目录", "Select code directory")})
|
||||
return application.Get().Dialog.OpenFile().
|
||||
SetTitle(a.localized("选择代码目录", "Select code directory")).
|
||||
CanChooseDirectories(true).
|
||||
CanChooseFiles(false).
|
||||
CanCreateDirectories(true).
|
||||
PromptForSingleSelection()
|
||||
}
|
||||
|
||||
// ListWSLDistros 返回本机可用的 WSL 发行版,供前端创建 UNC 项目路径。
|
||||
@@ -134,7 +184,12 @@ func (a *App) SelectWSLDirectory(distro string) (string, error) {
|
||||
return "", errors.New("WSL_DISTRO_REQUIRED")
|
||||
}
|
||||
root := "\\\\wsl.localhost\\" + distro + "\\"
|
||||
return runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{Title: a.localized("选择 WSL 代码目录", "Select WSL code directory"), DefaultDirectory: root})
|
||||
return application.Get().Dialog.OpenFile().
|
||||
SetTitle(a.localized("选择 WSL 代码目录", "Select WSL code directory")).
|
||||
SetDirectory(root).
|
||||
CanChooseDirectories(true).
|
||||
CanChooseFiles(false).
|
||||
PromptForSingleSelection()
|
||||
}
|
||||
|
||||
func (a *App) localized(zh, en string) string {
|
||||
@@ -146,7 +201,11 @@ func (a *App) localized(zh, en string) string {
|
||||
return zh
|
||||
}
|
||||
func (a *App) SelectDatabaseFile() (string, error) {
|
||||
return runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{Title: "Select database location", DefaultFilename: "code-count.db", Filters: []runtime.FileFilter{{DisplayName: "SQLite Database", Pattern: "*.db"}}})
|
||||
return application.Get().Dialog.SaveFile().
|
||||
SetMessage("Select database location").
|
||||
SetFilename("code-count.db").
|
||||
AddFilter("SQLite Database", "*.db").
|
||||
PromptForSingleSelection()
|
||||
}
|
||||
func (a *App) ListProjects() ([]Project, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
@@ -194,22 +253,14 @@ func (a *App) GetProject(id int64) (Project, error) {
|
||||
}
|
||||
func (a *App) SaveProject(id int64, in ProjectInput) (Project, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
if a.runtimeReady {
|
||||
runtime.LogError(a.ctx, "SaveProject: "+e.Error())
|
||||
}
|
||||
return Project{}, e
|
||||
}
|
||||
p, e := a.store.SaveProject(id, in)
|
||||
if e == nil {
|
||||
a.store.Log("info", "项目", "项目保存成功", p.Path)
|
||||
if a.runtimeReady {
|
||||
runtime.LogInfo(a.ctx, "Project saved: "+p.Path)
|
||||
}
|
||||
a.RefreshShell() // 托盘「打开项目」子菜单跟随项目列表
|
||||
} else {
|
||||
a.store.Log("error", "项目", "项目保存失败", in.Path+" | "+e.Error())
|
||||
if a.runtimeReady {
|
||||
runtime.LogError(a.ctx, "Project save failed: "+in.Path+" | "+e.Error())
|
||||
}
|
||||
}
|
||||
return p, e
|
||||
}
|
||||
@@ -218,9 +269,6 @@ func (a *App) ReportClientError(category, message, detail string) {
|
||||
if a.store != nil {
|
||||
a.store.Log("error", category, message, detail)
|
||||
}
|
||||
if a.runtimeReady {
|
||||
runtime.LogError(a.ctx, category+": "+message+" | "+detail)
|
||||
}
|
||||
}
|
||||
func (a *App) DeleteProject(id int64) error {
|
||||
if e := a.ready(); e != nil {
|
||||
@@ -229,6 +277,7 @@ func (a *App) DeleteProject(id int64) error {
|
||||
e := a.store.DeleteProject(id)
|
||||
if e == nil {
|
||||
a.store.Log("info", "项目", "项目删除成功", fmt.Sprint(id))
|
||||
a.RefreshShell() // 托盘「打开项目」子菜单跟随项目列表
|
||||
}
|
||||
return e
|
||||
}
|
||||
@@ -318,6 +367,9 @@ func (a *App) GetGitDiagnostics(id int64) (GitDiagnostics, error) {
|
||||
|
||||
// GetGitStatsForRef 只改变统计视图,不执行 checkout。
|
||||
func (a *App) GetGitStatsForRef(id int64, ref string) (GitStats, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return GitStats{}, e
|
||||
}
|
||||
p, e := a.store.GetProject(id)
|
||||
if e != nil {
|
||||
return GitStats{}, e
|
||||
@@ -332,6 +384,9 @@ func (a *App) GetGitStatsForRef(id int64, ref string) (GitStats, error) {
|
||||
|
||||
// GetCommitDetails 按需查询提交涉及的文件,避免 Git 首页一次加载所有明细。
|
||||
func (a *App) GetCommitDetails(id int64, hash string) (GitCommitDetail, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return GitCommitDetail{}, e
|
||||
}
|
||||
p, e := a.store.GetProject(id)
|
||||
if e != nil {
|
||||
return GitCommitDetail{}, e
|
||||
@@ -341,6 +396,9 @@ func (a *App) GetCommitDetails(id int64, hash string) (GitCommitDetail, error) {
|
||||
|
||||
// CheckoutBranch 安全切换工作区分支;服务层会拒绝任何脏工作区。
|
||||
func (a *App) CheckoutBranch(id int64, ref string) (CheckoutResult, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return CheckoutResult{}, e
|
||||
}
|
||||
p, e := a.store.GetProject(id)
|
||||
if e != nil {
|
||||
return CheckoutResult{}, e
|
||||
@@ -377,6 +435,81 @@ func (a *App) GetLogs(level string) ([]LogEntry, error) {
|
||||
}
|
||||
return a.store.Logs(level)
|
||||
}
|
||||
func (a *App) SearchLogs(query, level, category string, offset, limit int64) (LogPage, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return LogPage{}, e
|
||||
}
|
||||
return a.store.SearchLogs(query, level, category, offset, limit)
|
||||
}
|
||||
func (a *App) GetLogCategories() ([]string, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return a.store.LogCategories()
|
||||
}
|
||||
|
||||
// previewMaxBytes 是文件预览读取上限(1MB),超出部分截断。
|
||||
const previewMaxBytes = 1 << 20
|
||||
|
||||
// ReadProjectFile 读取项目内的相对路径文件用于预览:限制大小、检测二进制、阻止路径穿越。
|
||||
func (a *App) ReadProjectFile(projectID int64, relPath string) (FilePreview, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return FilePreview{}, e
|
||||
}
|
||||
p, e := a.store.GetProject(projectID)
|
||||
if e != nil {
|
||||
return FilePreview{}, e
|
||||
}
|
||||
rel := strings.TrimSpace(relPath)
|
||||
if rel == "" {
|
||||
return FilePreview{}, errors.New("FILE_PATH_REQUIRED")
|
||||
}
|
||||
desc, e := platform.ResolvePath(p.Path)
|
||||
if e != nil {
|
||||
return FilePreview{}, e
|
||||
}
|
||||
root := desc.WindowsPath
|
||||
full := filepath.Join(root, filepath.FromSlash(rel))
|
||||
if back, e := filepath.Rel(root, full); e != nil || back == ".." || strings.HasPrefix(back, ".."+string(filepath.Separator)) {
|
||||
return FilePreview{}, errors.New("FILE_PATH_INVALID")
|
||||
}
|
||||
st, e := os.Stat(full)
|
||||
if e != nil {
|
||||
if os.IsNotExist(e) {
|
||||
return FilePreview{}, coded("FILE_NOT_FOUND", e)
|
||||
}
|
||||
return FilePreview{}, coded("FILE_READ_FAILED", e)
|
||||
}
|
||||
if st.IsDir() {
|
||||
return FilePreview{}, errors.New("FILE_IS_DIRECTORY")
|
||||
}
|
||||
out := FilePreview{Path: filepath.ToSlash(rel), Name: st.Name(), Extension: strings.ToLower(filepath.Ext(st.Name())), Size: st.Size()}
|
||||
f, e := os.Open(full)
|
||||
if e != nil {
|
||||
return out, coded("FILE_READ_FAILED", e)
|
||||
}
|
||||
defer f.Close()
|
||||
buf := make([]byte, min(st.Size(), previewMaxBytes))
|
||||
n, e := io.ReadFull(f, buf)
|
||||
if e != nil && !errors.Is(e, io.ErrUnexpectedEOF) && !errors.Is(e, io.EOF) {
|
||||
return out, coded("FILE_READ_FAILED", e)
|
||||
}
|
||||
buf = buf[:n]
|
||||
out.Truncated = st.Size() > previewMaxBytes
|
||||
probe := buf
|
||||
if len(probe) > 8192 {
|
||||
probe = probe[:8192]
|
||||
}
|
||||
if bytes.IndexByte(probe, 0) >= 0 {
|
||||
out.Binary = true
|
||||
return out, nil
|
||||
}
|
||||
out.Content = string(buf)
|
||||
if out.Content != "" {
|
||||
out.Lines = strings.Count(out.Content, "\n") + 1
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (a *App) ClearLogs() error {
|
||||
if e := a.ready(); e != nil {
|
||||
return e
|
||||
@@ -393,13 +526,21 @@ func (a *App) SaveSettings(x AppSettings) error {
|
||||
if e := a.ready(); e != nil {
|
||||
return e
|
||||
}
|
||||
return a.store.SaveSettings(x)
|
||||
if e := a.store.SaveSettings(x); e != nil {
|
||||
return e
|
||||
}
|
||||
a.RefreshShell()
|
||||
return nil
|
||||
}
|
||||
func (a *App) ClearData(mode string, projectID int64) error {
|
||||
if e := a.ready(); e != nil {
|
||||
return e
|
||||
}
|
||||
return a.store.ClearData(mode, projectID)
|
||||
e := a.store.ClearData(mode, projectID)
|
||||
if e == nil {
|
||||
a.RefreshShell() // 托盘「打开项目」子菜单跟随项目列表
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func (a *App) MigrateDatabase(target string) error {
|
||||
@@ -483,18 +624,23 @@ func (a *App) StartAnalysis(projectID int64, kind string) (string, error) {
|
||||
a.tasks[taskID] = cancel
|
||||
a.mu.Unlock()
|
||||
go func() {
|
||||
finalStage := "completed"
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
detail := fmt.Sprintf("%v", recovered)
|
||||
finalStage = "error"
|
||||
a.store.Log("error", "代码分析", "后台分析异常", p.Name+" | "+detail)
|
||||
runtime.EventsEmit(a.ctx, "analysis:progress", TaskEvent{TaskID: taskID, ProjectID: projectID, Stage: "error", Progress: 100, MessageKey: "task.failed", Params: map[string]any{"project": p.Name}})
|
||||
a.emit("analysis:progress", TaskEvent{TaskID: taskID, ProjectID: projectID, Stage: "error", Progress: 100, MessageKey: "task.failed", Params: map[string]any{"project": p.Name}})
|
||||
}
|
||||
a.mu.Lock()
|
||||
if a.taskResults != nil {
|
||||
a.taskResults[taskID] = finalStage
|
||||
}
|
||||
delete(a.tasks, taskID)
|
||||
a.mu.Unlock()
|
||||
}()
|
||||
emit := func(stage string, progress int, messageKey string) {
|
||||
runtime.EventsEmit(a.ctx, "analysis:progress", TaskEvent{TaskID: taskID, ProjectID: projectID, Stage: stage, Progress: progress, MessageKey: messageKey, Params: map[string]any{"project": p.Name}})
|
||||
a.emit("analysis:progress", TaskEvent{TaskID: taskID, ProjectID: projectID, Stage: stage, Progress: progress, MessageKey: messageKey, Params: map[string]any{"project": p.Name}})
|
||||
}
|
||||
emit("start", 2, "task.start")
|
||||
a.store.Log("info", "代码分析", "开始分析项目", p.Name)
|
||||
@@ -510,10 +656,23 @@ func (a *App) StartAnalysis(projectID int64, kind string) (string, error) {
|
||||
}
|
||||
if err == nil && (kind == "all" || kind == "git") {
|
||||
emit("git", 80, "task.git")
|
||||
scopeAll := false
|
||||
if st, se := a.store.Settings(); se == nil && st.GitScope == "all" {
|
||||
scopeAll = true
|
||||
}
|
||||
var g GitStats
|
||||
g, err = (GitAnalyzer{}).Analyze(ctx, p.Path)
|
||||
var incremental bool
|
||||
g, incremental, err = (GitAnalyzer{}).AnalyzeWithOptions(ctx, p.Path, service.GitAnalyzeOptions{
|
||||
AllBranches: scopeAll,
|
||||
SinceHash: a.store.LatestCommitHash(projectID),
|
||||
})
|
||||
if err == nil {
|
||||
err = a.store.ReplaceGit(projectID, g)
|
||||
if incremental {
|
||||
err = a.store.MergeGit(projectID, g)
|
||||
a.store.Log("info", "Git分析", "增量分析完成", fmt.Sprintf("%s | 新增 %d 个提交", p.Name, len(g.Commits)))
|
||||
} else {
|
||||
err = a.store.ReplaceGit(projectID, g)
|
||||
}
|
||||
} else if kind == "all" && (err.Error() == "NOT_GIT_REPOSITORY" || err.Error() == "GIT_NOT_INSTALLED") {
|
||||
a.store.Log("warning", "Git分析", "已跳过 Git 分析", err.Error())
|
||||
err = nil
|
||||
@@ -524,12 +683,29 @@ func (a *App) StartAnalysis(projectID int64, kind string) (string, error) {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
level, stage = "warning", "cancelled"
|
||||
}
|
||||
finalStage = stage
|
||||
a.store.Log(level, "代码分析", "项目分析失败", p.Name+" | "+err.Error())
|
||||
emit(stage, 100, "task.failed")
|
||||
return
|
||||
}
|
||||
a.store.Log("info", "代码分析", "项目分析完成", p.Name)
|
||||
emit("completed", 100, "task.completed")
|
||||
// 数据就绪后异步生成各模块的 AI 分析(未配置 Key 时静默跳过)。
|
||||
// 代码数据变化会使洞察过期,先重算再交给 AI 解读。
|
||||
switch kind {
|
||||
case "code":
|
||||
go func() {
|
||||
a.RefreshProjectInsights(projectID)
|
||||
a.generateAISummaries(projectID, "project", "structure", "insights")
|
||||
}()
|
||||
case "git":
|
||||
go a.generateAISummaries(projectID, "git")
|
||||
default:
|
||||
go func() {
|
||||
a.RefreshProjectInsights(projectID)
|
||||
a.generateAISummaries(projectID, "project", "git", "structure", "insights")
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return taskID, nil
|
||||
}
|
||||
@@ -546,6 +722,9 @@ func (a *App) StartBatchAnalysis() ([]string, error) {
|
||||
return a.StartBatchAnalysisByGroup(0)
|
||||
}
|
||||
func (a *App) StartBatchAnalysisByGroup(groupID int64) ([]string, error) {
|
||||
if e := a.ready(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
ps, e := a.store.ListProjects(groupID)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
@@ -555,9 +734,12 @@ func (a *App) StartBatchAnalysisByGroup(groupID int64) ([]string, error) {
|
||||
ids = append(ids, fmt.Sprintf("%d-all", p.ID))
|
||||
}
|
||||
go func() {
|
||||
summary := BatchSummary{Total: len(ps), Failures: []string{}}
|
||||
for _, p := range ps {
|
||||
tid, e := a.StartAnalysis(p.ID, "all")
|
||||
if e != nil {
|
||||
summary.Failed++
|
||||
summary.Failures = append(summary.Failures, p.Name+": "+e.Error())
|
||||
continue
|
||||
}
|
||||
for {
|
||||
@@ -573,7 +755,46 @@ func (a *App) StartBatchAnalysisByGroup(groupID int64) ([]string, error) {
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
result := a.taskResults[tid]
|
||||
delete(a.taskResults, tid)
|
||||
a.mu.Unlock()
|
||||
switch result {
|
||||
case "cancelled":
|
||||
summary.Cancelled++
|
||||
case "error":
|
||||
summary.Failed++
|
||||
summary.Failures = append(summary.Failures, p.Name)
|
||||
default:
|
||||
summary.Completed++
|
||||
}
|
||||
}
|
||||
a.store.Log("info", "代码分析", "批量统计完成",
|
||||
fmt.Sprintf("共 %d 个 | 成功 %d | 失败 %d | 取消 %d | %s", summary.Total, summary.Completed, summary.Failed, summary.Cancelled, strings.Join(summary.Failures, ";")))
|
||||
a.emit("batch:done", summary)
|
||||
a.notifyBatchDone(summary)
|
||||
}()
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// notifyBatchDone 将批量统计结果写入消息中心,失败时附系统通知。
|
||||
func (a *App) notifyBatchDone(s BatchSummary) {
|
||||
locale := "zh-CN"
|
||||
if st, e := a.store.Settings(); e == nil {
|
||||
locale = st.Locale
|
||||
}
|
||||
title := "批量统计完成"
|
||||
body := fmt.Sprintf("共 %d 个项目:成功 %d,失败 %d,取消 %d", s.Total, s.Completed, s.Failed, s.Cancelled)
|
||||
if locale == "en" {
|
||||
title = "Batch analysis finished"
|
||||
body = fmt.Sprintf("%d projects: %d succeeded, %d failed, %d cancelled", s.Total, s.Completed, s.Failed, s.Cancelled)
|
||||
}
|
||||
if len(s.Failures) > 0 {
|
||||
sep := ";失败:"
|
||||
if locale == "en" {
|
||||
sep = "; failed: "
|
||||
}
|
||||
body += sep + strings.Join(s.Failures, ", ")
|
||||
}
|
||||
a.pushMessage("analysis", title, body, "", 0, s.Failed > 0)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user