Skip to content

Commit

Permalink
Merge pull request #19 from tatang26/fix-assets-path-for
Browse files Browse the repository at this point in the history
fix(assets): fixing hashed assets mapping
  • Loading branch information
paganotoni committed Jun 18, 2024
2 parents ed46768 + e38b4d5 commit 45f4ab9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
13 changes: 5 additions & 8 deletions assets/fingerprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,14 @@ func (m *manager) PathFor(fname string) (string, error) {
hashString := hex.EncodeToString(hash[:])

// Add the hash to the filename
filename := path.Base(normalized)
ext := path.Ext(normalized)
newFilename := filename[:len(filename)-len(ext)] + "-" + hashString + ext
filename := strings.TrimSuffix(normalized, ext)
filename += "-" + hashString + ext

m.fmut.Lock()
defer m.fmut.Unlock()
m.fileToHash[normalized] = newFilename
m.HashToFile[newFilename] = normalized
m.fileToHash[normalized] = filename
m.HashToFile[filename] = normalized

result = path.Join(path.Dir(normalized), newFilename)
result = withPrefix(result)

return result, nil
return withPrefix(filename), nil
}
27 changes: 26 additions & 1 deletion assets/fingerprint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ func TestFingerprint(t *testing.T) {
if !strings.Contains(a, "/public/") {
t.Errorf("Expected %s to have /public/ prefix", a)
}

a, _ = m.PathFor("public/other/main.js")
b, _ = m.PathFor("public/other/main.js")
if a != b {
t.Errorf("Expected %s to equal %s", a, b)
}

if !strings.Contains(a, "/public/") {
t.Errorf("Expected %s to have /public/ prefix", a)
}
})

t.Run("adds starting slash", func(t *testing.T) {
Expand Down Expand Up @@ -51,18 +61,33 @@ func TestFingerprint(t *testing.T) {
})

t.Run("respects folders", func(t *testing.T) {
a, err := m.PathFor("public/main.js")
a, err := m.PathFor("main.js")
if err != nil {
t.Fatal(err)
}

if !strings.HasPrefix(a, "/public/main-") {
t.Errorf("Expected %s to contain /public/other/main-<hash>", a)
}

b, _ := m.PathFor("public/other/main.js")
if err != nil {
t.Fatal(err)
}

if !strings.HasPrefix(b, "/public/other/main-") {
t.Errorf("Expected %s to contain /public/other/main-<hash>", b)
}

if a == b {
t.Errorf("Expected %s to not equal %s", a, b)
}
})

t.Run("file does not exist", func(t *testing.T) {
a, err := m.PathFor("foo.js")
if err == nil {
t.Errorf("File must not exists: %s", a)
}
})
}

0 comments on commit 45f4ab9

Please sign in to comment.