Skip to content

Commit

Permalink
Merge pull request #9 from deltamualpha/master
Browse files Browse the repository at this point in the history
Don't attempt to parse a file if the key already exists in the metadata, even if the file is missing
  • Loading branch information
lambtron committed Nov 15, 2015
2 parents 4e421f4 + 6b0cf69 commit bbd198d
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,21 @@ function plugin(opts){
var file = opts[key];
var ext = extname(file);
if (!~exts.indexOf(ext)) throw new Error('unsupported metadata type "' + ext + '"');
if (!files[file]) throw new Error('file "' + file + '" not found');
if (!metadata[key] || files[file]) {
if (!files[file]) throw new Error('file "' + file + '" not found');

var parse = parsers[ext];
var str = files[file].contents.toString();
delete files[file];
var parse = parsers[ext];
var str = files[file].contents.toString();
delete files[file];

try {
var data = parse(str);
} catch (e) {
return done(new Error('malformed data in "' + file + '"'));
}
try {
var data = parse(str);
} catch (e) {
return done(new Error('malformed data in "' + file + '"'));
}

metadata[key] = data;
metadata[key] = data;
}
}

done();
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/duplicate/src/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"string": "string"
}
3 changes: 3 additions & 0 deletions test/fixtures/duplicate/src/data2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"string": "string2"
}
24 changes: 24 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ describe('metalsmith-metadata', function(){
});
});

it('should not parse a file if the key already exists in the metadata', function(done){
var m = Metalsmith('test/fixtures/json')
.use(metadata({ file: 'data.json' }))
.use(metadata({ file: 'missing.json' }));
m.build(function(err){
if (err) return done(err);
assert.deepEqual(m.metadata().file, { string: 'string' });
assert(!exists('test/fixtures/json/build'));
done();
});
});

it('should parse a file even if the key exists if the file is in the bundle', function(done){
var m = Metalsmith('test/fixtures/duplicate')
.use(metadata({ file: 'data.json' }))
.use(metadata({ file: 'data2.json' }));
m.build(function(err){
if (err) return done(err);
assert.deepEqual(m.metadata().file, { string: 'string2' });
assert(!exists('test/fixtures/json/build'));
done();
});
});

it('should parse YAML', function(done){
var m = Metalsmith('test/fixtures/yaml').use(metadata({ file: 'data.yaml' }));
m.build(function(err){
Expand Down

0 comments on commit bbd198d

Please sign in to comment.