Skip to content

Commit

Permalink
Intelligently hash asset files
Browse files Browse the repository at this point in the history
  • Loading branch information
rstacruz committed Oct 8, 2015
1 parent 313cfde commit 0e907c0
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
4 changes: 2 additions & 2 deletions data/layout.jade
Expand Up @@ -57,7 +57,7 @@ doctype html
html
head
meta(charset='utf-8')
link(rel='stylesheet' href=(base + 'assets/style.css?t=' + (+new Date())))
link(rel='stylesheet' href=(base + 'assets/style.css?t=' + hash.style))
title= title
body.-menu-visible
.doc-layout
Expand All @@ -67,4 +67,4 @@ html
!= contents
.menu.toc-menu
+menu(toc, 0)
script(src=(base + 'assets/script.js?t=' + (+new Date())))
script(src=(base + 'assets/script.js?t=' + hash.script))
8 changes: 7 additions & 1 deletion index.js
Expand Up @@ -8,6 +8,7 @@ const assign = Object.assign

const buildJs = require('./lib/build_js')
const buildCss = require('./lib/build_css')
const hash = require('./lib/hash')

/**
* Metalsmith middleware
Expand Down Expand Up @@ -78,9 +79,14 @@ function relayout (files, ms, done) {
const file = files[fname]
const base = Array(fname.split('/').length).join('../')
file.contents = layout(assign({}, file, {
base, toc, index, active: fname
base, toc, index, active: fname,
hash: {
style: hash(files['assets/style.css'].contents),
script: hash(files['assets/script.js'].contents)
}
}))
})

done()
}

7 changes: 7 additions & 0 deletions lib/hash.js
@@ -0,0 +1,7 @@
const crypto = require('crypto')

module.exports = function hash (data) {
const shasum = crypto.createHash('sha1')
shasum.update(data)
return shasum.digest('hex').substr(0, 8)
}
6 changes: 6 additions & 0 deletions test/fixture_test.js
Expand Up @@ -31,9 +31,15 @@ describe('fixture', function () {
it('highlights current menu item', function () {
expect(data).toMatch(/-active[^>]+>onmount/)
})

it('adds "link-slug" classes', function () {
expect(data).toMatch(/link-index[^>]+>onmount/)
})

it('adds hash to assets', function () {
expect(data).toMatch(/script\.js\?t=[a-f0-9]{8}/)
expect(data).toMatch(/style\.css\?t=[a-f0-9]{8}/)
})
})

describe('style.css', function () {
Expand Down

0 comments on commit 0e907c0

Please sign in to comment.