refactor: consolidate duplicated utilities and simplify diff API

- Extract shared applyDetailScroll into tui_helpers.go (was duplicated
  across diff_tui.go, log_tui.go, audit_tui.go)
- Create utils.FileHash and utils.FileHashFormatted, replacing private
  copies in install/meta.go and audit/audit.go
- Export install.MetaFileName constant, use from diff_file.go
- Replace double SHA-256 in fileContentsEqual with streaming byte compare
  for early-exit efficiency
- Add 1MB size cap to generateUnifiedDiff to prevent performance issues
- Move noTUI into diffRenderOpts struct, simplifying function signatures
This commit is contained in:
Willie
2026-03-02 02:23:50 +08:00
parent ada539603e
commit 13744f89a8
13 changed files with 158 additions and 197 deletions
+2 -44
View File
@@ -297,7 +297,7 @@ func (m auditTUIModel) View() string {
var detailStr string
if item, ok := m.list.SelectedItem().(auditItem); ok {
detailContent := m.renderDetailContent(item)
detailStr = m.applyDetailScroll(detailContent, panelHeight)
detailStr = applyDetailScroll(detailContent, m.detailScroll, panelHeight)
}
rightPanel := lipgloss.NewStyle().
Width(rightWidth).MaxWidth(rightWidth).
@@ -335,7 +335,7 @@ func (m auditTUIModel) viewVertical() string {
if item, ok := m.list.SelectedItem().(auditItem); ok {
detailContent := m.renderDetailContent(item)
detailHeight := m.termHeight - m.termHeight*2/5 - 7
b.WriteString(m.applyDetailScroll(detailContent, detailHeight))
b.WriteString(applyDetailScroll(detailContent, m.detailScroll, detailHeight))
}
b.WriteString(m.renderSummaryFooter())
@@ -513,48 +513,6 @@ func (m auditTUIModel) renderDetailContent(item auditItem) string {
return b.String()
}
// applyDetailScroll wraps a detail panel string with height limit and scroll offset.
func (m auditTUIModel) applyDetailScroll(content string, viewHeight int) string {
lines := strings.Split(content, "\n")
maxDetailLines := viewHeight
if maxDetailLines < 5 {
maxDetailLines = 5
}
totalLines := len(lines)
if totalLines <= maxDetailLines {
return content
}
// Clamp scroll offset
maxScroll := totalLines - maxDetailLines
offset := m.detailScroll
if offset > maxScroll {
offset = maxScroll
}
visible := lines[offset:]
if len(visible) > maxDetailLines {
visible = visible[:maxDetailLines]
}
var b strings.Builder
for _, line := range visible {
b.WriteString(line)
b.WriteString("\n")
}
// Scroll indicator
if offset > 0 || offset < maxScroll {
indicator := fmt.Sprintf("── Ctrl+d/u scroll (%d/%d) ──", offset+1, maxScroll+1)
b.WriteString(tc.Dim.Render(indicator))
b.WriteString("\n")
}
return b.String()
}
// auditListWidth returns the left panel width for horizontal layout.
// 25% of terminal, clamped to [25, 45].
func auditListWidth(termWidth int) int {
+12 -12
View File
@@ -19,8 +19,9 @@ import (
"skillshare/internal/utils"
)
// diffRenderOpts controls plain text rendering behavior.
// diffRenderOpts controls diff output behavior.
type diffRenderOpts struct {
noTUI bool
showPatch bool
showStat bool
}
@@ -56,31 +57,30 @@ func cmdDiff(args []string) error {
}
var targetName string
var noTUI, showPatch, showStat bool
var opts diffRenderOpts
for i := 0; i < len(rest); i++ {
switch rest[i] {
case "--help", "-h":
printDiffHelp()
return nil
case "--no-tui":
noTUI = true
opts.noTUI = true
case "--patch":
showPatch = true
noTUI = true // --patch implies no TUI
opts.showPatch = true
opts.noTUI = true // --patch implies no TUI
case "--stat":
showStat = true
noTUI = true
opts.showStat = true
opts.noTUI = true // --stat implies no TUI
default:
targetName = rest[i]
}
}
opts := diffRenderOpts{showPatch: showPatch, showStat: showStat}
var cmdErr error
if mode == modeProject {
cmdErr = cmdDiffProject(cwd, targetName, noTUI, opts)
cmdErr = cmdDiffProject(cwd, targetName, opts)
} else {
cmdErr = cmdDiffGlobal(targetName, noTUI, opts)
cmdErr = cmdDiffGlobal(targetName, opts)
}
logDiffOp(cfgPath, targetName, scope, 0, start, cmdErr)
return cmdErr
@@ -323,7 +323,7 @@ func (dp *diffProgress) stop() {
}
}
func cmdDiffGlobal(targetName string, noTUI bool, opts diffRenderOpts) error {
func cmdDiffGlobal(targetName string, opts diffRenderOpts) error {
cfg, err := config.Load()
if err != nil {
return err
@@ -412,7 +412,7 @@ func cmdDiffGlobal(targetName string, noTUI bool, opts diffRenderOpts) error {
progress.stop()
if !noTUI && ui.IsTTY() && len(results) > 0 {
if !opts.noTUI && ui.IsTTY() && len(results) > 0 {
return runDiffTUI(results)
}
renderGroupedDiffs(results, opts)
+46 -18
View File
@@ -1,7 +1,7 @@
package main
import (
"crypto/sha256"
"bytes"
"fmt"
"io"
"os"
@@ -11,6 +11,8 @@ import (
"time"
"github.com/sergi/go-diff/diffmatchpatch"
"skillshare/internal/install"
)
// fileDiffEntry represents a single file-level difference between source and destination.
@@ -97,7 +99,7 @@ func walkFiles(root string) map[string]os.FileInfo {
}
return nil
}
if info.Name() == ".skillshare-meta.json" {
if info.Name() == install.MetaFileName {
return nil
}
rel, relErr := filepath.Rel(root, path)
@@ -113,36 +115,52 @@ func walkFiles(root string) map[string]os.FileInfo {
return result
}
// fileContentsEqual compares two files by SHA-256 hash.
// Returns false if either file is unreadable.
// fileContentsEqual compares two files by streaming byte comparison.
// Returns false if either file is unreadable or contents differ.
func fileContentsEqual(pathA, pathB string) bool {
hashA := fileHash(pathA)
hashB := fileHash(pathB)
if hashA == "" || hashB == "" {
fA, err := os.Open(pathA)
if err != nil {
return false
}
return hashA == hashB
}
defer fA.Close()
// fileHash returns the SHA-256 hex hash of a file. Returns "" on error.
func fileHash(path string) string {
f, err := os.Open(path)
fB, err := os.Open(pathB)
if err != nil {
return ""
return false
}
defer f.Close()
defer fB.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return ""
const bufSize = 32 * 1024
bufA := make([]byte, bufSize)
bufB := make([]byte, bufSize)
for {
nA, errA := fA.Read(bufA)
nB, errB := fB.Read(bufB)
if nA != nB || !bytes.Equal(bufA[:nA], bufB[:nB]) {
return false
}
if errA == io.EOF && errB == io.EOF {
return true
}
if errA != nil || errB != nil {
return false
}
}
return fmt.Sprintf("%x", h.Sum(nil))
}
// maxDiffFileSize is the maximum file size for generating unified diffs.
// Files larger than this are skipped to avoid performance issues.
const maxDiffFileSize = 1_000_000 // 1MB
// generateUnifiedDiff produces a unified diff between two files.
// dstContent is treated as "old", srcContent as "new".
// Returns "(binary file differs)" if either file contains null bytes in the first 8000 chars.
// Returns "(file too large for diff)" if either file exceeds maxDiffFileSize.
func generateUnifiedDiff(srcPath, dstPath string) string {
if fileExceedsSize(srcPath, maxDiffFileSize) || fileExceedsSize(dstPath, maxDiffFileSize) {
return "(file too large for diff)"
}
srcContent := readFileString(srcPath)
dstContent := readFileString(dstPath)
@@ -170,6 +188,16 @@ func readFileString(path string) string {
return string(data)
}
// fileExceedsSize returns true if the file at path is larger than limit bytes.
// Returns false if the file doesn't exist or can't be stat'd.
func fileExceedsSize(path string, limit int64) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return info.Size() > limit
}
// isBinary checks whether a string contains null bytes in the first 8000 characters.
func isBinary(content string) bool {
limit := len(content)
+2 -2
View File
@@ -9,7 +9,7 @@ import (
"skillshare/internal/ui"
)
func cmdDiffProject(root, targetName string, noTUI bool, opts diffRenderOpts) error {
func cmdDiffProject(root, targetName string, opts diffRenderOpts) error {
if !projectConfigExists(root) {
if err := performProjectInit(root, projectInitOptions{}); err != nil {
return err
@@ -101,7 +101,7 @@ func cmdDiffProject(root, targetName string, noTUI bool, opts diffRenderOpts) er
progress.stop()
if !noTUI && ui.IsTTY() && len(results) > 0 {
if !opts.noTUI && ui.IsTTY() && len(results) > 0 {
return runDiffTUI(results)
}
renderGroupedDiffs(results, opts)
+2 -31
View File
@@ -387,7 +387,7 @@ func (m diffTUIModel) viewDiffHorizontal() string {
// Right panel: detail
detailContent := m.buildDiffDetail()
detailStr := m.applyDiffDetailScroll(detailContent, panelHeight)
detailStr := applyDetailScroll(detailContent, m.detailScroll, panelHeight)
rightPanel := lipgloss.NewStyle().
Width(rightWidth).MaxWidth(rightWidth).
@@ -420,7 +420,7 @@ func (m diffTUIModel) viewDiffVertical() string {
// Detail below list
detailContent := m.buildDiffDetail()
detailHeight := max(m.termHeight/3, 6)
b.WriteString(m.applyDiffDetailScroll(detailContent, detailHeight))
b.WriteString(applyDetailScroll(detailContent, m.detailScroll, detailHeight))
b.WriteString("\n")
b.WriteString(tc.Help.Render("↑↓ navigate / filter Enter expand Ctrl+d/u scroll q quit"))
@@ -607,35 +607,6 @@ func (m diffTUIModel) buildDiffDetail() string {
return b.String()
}
// applyDiffDetailScroll applies vertical scrolling to detail content.
func (m diffTUIModel) applyDiffDetailScroll(content string, viewHeight int) string {
lines := strings.Split(content, "\n")
if len(lines) <= viewHeight {
return content
}
maxScroll := len(lines) - viewHeight
offset := min(m.detailScroll, maxScroll)
end := min(offset+viewHeight, len(lines))
visible := lines[offset:end]
var b strings.Builder
for _, line := range visible {
b.WriteString(line)
b.WriteString("\n")
}
if offset > 0 || offset < maxScroll {
indicator := fmt.Sprintf("── Ctrl+d/u scroll (%d/%d) ──", offset+1, maxScroll+1)
b.WriteString(tc.Dim.Render(indicator))
b.WriteString("\n")
}
return b.String()
}
// --- Entry point ---
func runDiffTUI(results []targetDiffResult) error {
+2 -45
View File
@@ -573,7 +573,7 @@ func (m logTUIModel) View() string {
var detailStr string
if item, ok := m.list.SelectedItem().(logItem); ok {
detailContent := renderLogDetailPanel(item)
detailStr = m.applyDetailScroll(detailContent, panelHeight)
detailStr = applyDetailScroll(detailContent, m.detailScroll, panelHeight)
}
rightPanel := lipgloss.NewStyle().
Width(rightWidth).MaxWidth(rightWidth).
@@ -611,7 +611,7 @@ func (m logTUIModel) viewVertical() string {
detailContent := renderLogDetailPanel(item)
// Vertical: detail takes remaining space below the list
detailHeight := m.termHeight - m.termHeight*2/5 - 7
b.WriteString(m.applyDetailScroll(detailContent, detailHeight))
b.WriteString(applyDetailScroll(detailContent, m.detailScroll, detailHeight))
}
b.WriteString(m.renderStatsFooter())
@@ -680,49 +680,6 @@ func logDetailPanelWidth(termWidth int) int {
return w
}
// applyDetailScroll wraps a detail panel string with height limit and scroll offset.
// viewHeight is the maximum number of visible lines for the detail area.
func (m logTUIModel) applyDetailScroll(content string, viewHeight int) string {
lines := strings.Split(content, "\n")
maxDetailLines := viewHeight
if maxDetailLines < 5 {
maxDetailLines = 5
}
totalLines := len(lines)
if totalLines <= maxDetailLines {
return content // fits without scrolling
}
// Clamp scroll offset
maxScroll := totalLines - maxDetailLines
offset := m.detailScroll
if offset > maxScroll {
offset = maxScroll
}
visible := lines[offset:]
if len(visible) > maxDetailLines {
visible = visible[:maxDetailLines]
}
var b strings.Builder
for _, line := range visible {
b.WriteString(line)
b.WriteString("\n")
}
// Scroll indicator
if offset > 0 || offset < maxScroll {
indicator := fmt.Sprintf(" ── Ctrl+d/u scroll (%d/%d) ──", offset+1, maxScroll+1)
b.WriteString(tc.Dim.Render(indicator))
b.WriteString("\n")
}
return b.String()
}
// renderLogDetailPanel renders structured details for the selected log entry.
func renderLogDetailPanel(item logItem) string {
var b strings.Builder
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"fmt"
"strings"
)
// applyDetailScroll applies vertical scrolling to detail panel content.
// detailScroll is the current scroll offset; viewHeight is the visible line count.
// Returns the visible portion with a scroll indicator when needed.
func applyDetailScroll(content string, detailScroll, viewHeight int) string {
lines := strings.Split(content, "\n")
maxDetailLines := viewHeight
if maxDetailLines < 5 {
maxDetailLines = 5
}
totalLines := len(lines)
if totalLines <= maxDetailLines {
return content
}
maxScroll := totalLines - maxDetailLines
offset := min(detailScroll, maxScroll)
end := min(offset+maxDetailLines, totalLines)
visible := lines[offset:end]
var b strings.Builder
for _, line := range visible {
b.WriteString(line)
b.WriteString("\n")
}
if offset > 0 || offset < maxScroll {
indicator := fmt.Sprintf("── Ctrl+d/u scroll (%d/%d) ──", offset+1, maxScroll+1)
b.WriteString(tc.Dim.Render(indicator))
b.WriteString("\n")
}
return b.String()
}