mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
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:
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
+2
-17
@@ -6,7 +6,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -532,7 +531,7 @@ func ScanMarkdownContentWithRules(content []byte, filename string, activeRules [
|
||||
// isScannable returns true if the file should be scanned.
|
||||
func isScannable(name string) bool {
|
||||
// Skip skillshare's own metadata files
|
||||
if name == ".skillshare-meta.json" {
|
||||
if name == ".skillshare-meta.json" { // install.MetaFileName (cycle prevents import)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1233,7 +1232,7 @@ func checkContentIntegrity(skillPath string, cache map[string][]byte) []Finding
|
||||
actual = hex.EncodeToString(sum[:])
|
||||
} else {
|
||||
var hashErr error
|
||||
actual, hashErr = fileHash(absPath)
|
||||
actual, hashErr = utils.FileHash(absPath)
|
||||
if hashErr != nil {
|
||||
continue
|
||||
}
|
||||
@@ -1283,20 +1282,6 @@ func checkContentIntegrity(skillPath string, cache map[string][]byte) []Finding
|
||||
return findings
|
||||
}
|
||||
|
||||
// fileHash returns the hex-encoded SHA-256 digest of a file.
|
||||
func fileHash(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// stripFragment removes #fragment and ?query from a link target.
|
||||
func stripFragment(target string) string {
|
||||
if i := strings.IndexByte(target, '#'); i >= 0 {
|
||||
|
||||
@@ -26,7 +26,7 @@ func getUpdatableSkillsImpl(sourceDir string) ([]string, error) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
// Look for metadata files
|
||||
if !info.IsDir() && info.Name() == metaFileName {
|
||||
if !info.IsDir() && info.Name() == MetaFileName {
|
||||
skillDir := filepath.Dir(path)
|
||||
relPath, relErr := filepath.Rel(sourceDir, skillDir)
|
||||
if relErr != nil || relPath == "." {
|
||||
@@ -65,7 +65,7 @@ func FindRepoInstalls(sourceDir, cloneURL string) []string {
|
||||
if info.IsDir() && len(info.Name()) > 0 && info.Name()[0] == '_' {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if !info.IsDir() && info.Name() == metaFileName {
|
||||
if !info.IsDir() && info.Name() == MetaFileName {
|
||||
skillDir := filepath.Dir(path)
|
||||
relPath, relErr := filepath.Rel(sourceDir, skillDir)
|
||||
if relErr != nil || relPath == "." {
|
||||
|
||||
+10
-23
@@ -1,18 +1,18 @@
|
||||
package install
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/utils"
|
||||
)
|
||||
|
||||
const metaFileName = ".skillshare-meta.json"
|
||||
// MetaFileName is the name of the skillshare metadata file stored in each skill directory.
|
||||
const MetaFileName = ".skillshare-meta.json"
|
||||
|
||||
// SkillMeta contains metadata about an installed skill
|
||||
type SkillMeta struct {
|
||||
@@ -28,7 +28,7 @@ type SkillMeta struct {
|
||||
|
||||
// WriteMeta saves metadata to the skill directory
|
||||
func WriteMeta(skillPath string, meta *SkillMeta) error {
|
||||
metaPath := filepath.Join(skillPath, metaFileName)
|
||||
metaPath := filepath.Join(skillPath, MetaFileName)
|
||||
|
||||
data, err := json.MarshalIndent(meta, "", " ")
|
||||
if err != nil {
|
||||
@@ -44,7 +44,7 @@ func WriteMeta(skillPath string, meta *SkillMeta) error {
|
||||
|
||||
// ReadMeta loads metadata from the skill directory
|
||||
func ReadMeta(skillPath string) (*SkillMeta, error) {
|
||||
metaPath := filepath.Join(skillPath, metaFileName)
|
||||
metaPath := filepath.Join(skillPath, MetaFileName)
|
||||
|
||||
data, err := os.ReadFile(metaPath)
|
||||
if err != nil {
|
||||
@@ -64,7 +64,7 @@ func ReadMeta(skillPath string) (*SkillMeta, error) {
|
||||
|
||||
// HasMeta checks if a skill directory has metadata
|
||||
func HasMeta(skillPath string) bool {
|
||||
metaPath := filepath.Join(skillPath, metaFileName)
|
||||
metaPath := filepath.Join(skillPath, MetaFileName)
|
||||
_, err := os.Stat(metaPath)
|
||||
return err == nil
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func ComputeFileHashes(skillPath string) (map[string]string, error) {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if info.Name() == metaFileName {
|
||||
if info.Name() == MetaFileName {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -93,12 +93,12 @@ func ComputeFileHashes(skillPath string) (map[string]string, error) {
|
||||
return fmt.Errorf("relative path for %s: %w", path, relErr)
|
||||
}
|
||||
|
||||
h, hashErr := hashFile(path)
|
||||
formatted, hashErr := utils.FileHashFormatted(path)
|
||||
if hashErr != nil {
|
||||
return fmt.Errorf("hashing %s: %w", path, hashErr)
|
||||
}
|
||||
// Normalize path separators to /
|
||||
hashes[filepath.ToSlash(rel)] = "sha256:" + h
|
||||
hashes[filepath.ToSlash(rel)] = formatted
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -107,19 +107,6 @@ func ComputeFileHashes(skillPath string) (map[string]string, error) {
|
||||
return hashes, nil
|
||||
}
|
||||
|
||||
func hashFile(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// NewMetaFromSource creates a SkillMeta from a Source
|
||||
func NewMetaFromSource(source *Source) *SkillMeta {
|
||||
meta := &SkillMeta{
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestReadMeta_NoFile(t *testing.T) {
|
||||
|
||||
func TestReadMeta_InvalidJSON(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, metaFileName), []byte("{bad json"), 0644); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(dir, MetaFileName), []byte("{bad json"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// FileHash returns the hex-encoded SHA-256 digest of a file.
|
||||
func FileHash(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// FileHashFormatted returns the hash in "sha256:<hex>" format.
|
||||
func FileHashFormatted(path string) (string, error) {
|
||||
h, err := FileHash(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("sha256:%s", h), nil
|
||||
}
|
||||
@@ -239,8 +239,8 @@ targets:
|
||||
|
||||
// Items should only appear once (not duplicated)
|
||||
out := result.Stdout
|
||||
countA := strings.Count(out,"skill-a")
|
||||
countB := strings.Count(out,"skill-b")
|
||||
countA := strings.Count(out, "skill-a")
|
||||
countB := strings.Count(out, "skill-b")
|
||||
if countA != 1 {
|
||||
t.Errorf("expected skill-a to appear once, got %d times in:\n%s", countA, out)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user