Skip to content

Commit

Permalink
Close sindresorhusGH-7: Add an asset manifest method.. Fixes sindreso…
Browse files Browse the repository at this point in the history
  • Loading branch information
bobthecow authored and sindresorhus committed Mar 8, 2014
1 parent f5cbcfc commit d62d5c2
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
35 changes: 34 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function md5(str) {
return crypto.createHash('md5').update(str, 'utf8').digest('hex');
}

module.exports = function () {
var plugin = function () {
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
Expand All @@ -20,6 +20,9 @@ module.exports = function () {
return cb();
}

// Save the old path for later...
file.revOrigPath = file.path;

var hash = md5(file.contents.toString()).slice(0, 8);
var ext = path.extname(file.path);
var filename = path.basename(file.path, ext) + '-' + hash + ext;
Expand All @@ -28,3 +31,33 @@ module.exports = function () {
cb();
});
};

plugin.manifest = function () {
var manifest = {};
var firstFile = null;

return through.obj(
function (file, enc, cb) {
// Ignore all non-rev'd files.
if (file.path && file.revOrigPath) {
firstFile = firstFile || file;
manifest[file.revOrigPath.replace(firstFile.base, '')] = file.path.replace(firstFile.base, '');
}
cb();
},

function (cb) {
if (firstFile) {
this.push(new gutil.File({
cwd: firstFile.cwd,
base: firstFile.base,
path: path.join(firstFile.base, 'rev-manifest.json'),
contents: new Buffer(JSON.stringify(manifest, null, ' '))
}));
}
cb();
}
);
};

module.exports = plugin;
29 changes: 29 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,35 @@ gulp.task('default', function () {
Options are intentionally missing as the default should work in most cases.


### Original path

Original file paths are stored at `file.revOrigPath`. This could come in handy for things like rewriting references to the assets.


### Asset manifest

```js
var gulp = require('gulp');
var rev = require('gulp-rev');

gulp.task('default', function () {
gulp.src('src/*.css')
.pipe(rev())
.pipe(gulp.dest('dist')) // write revisioned assets to /dist
.pipe(rev.manifest()) // generate a revision manifest file
.pipe(gulp.dest('dist')); // write it to /dist/rev-manifest.json
});
```

An asset manifest, mapping the original paths to the revisioned paths, will be written to `dist/rev-manifest.json`:

```json
{
"unicorn.css": "unicorn-098f6bcd.css"
}
```


## License

MIT © [Sindre Sorhus](http://sindresorhus.com)

0 comments on commit d62d5c2

Please sign in to comment.