Skip to content
This repository was archived by the owner on May 20, 2025. It is now read-only.

Commit 427be0d

Browse files
committed
check for duplicate file names and error
1 parent f53b43e commit 427be0d

File tree

4 files changed

+24
-2
lines changed

4 files changed

+24
-2
lines changed

lib/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ function plugin (opts) {
4343
var theKey = fileName.replace(/\.[^/.]+$/, '')
4444
var theContents = fs.readFileSync(file, 'utf8')
4545

46+
// Error if the key already exists (duplicate file name)
47+
if (theKey in metadata) {
48+
return done(new Error('Duplicate file name: ' + fileName))
49+
}
50+
4651
// Ignore file if it is empty
4752
if (theContents.length === 0) {
4853
return done()
@@ -52,7 +57,7 @@ function plugin (opts) {
5257
try {
5358
var json = JSON.parse(theContents)
5459
} catch (error) {
55-
return done(new Error('Malformed data in ' + fileName))
60+
return done(new Error('Malformed data in: ' + fileName))
5661
}
5762

5863
// Debug information
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"text": "Text from a json file"
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"random": "same key but different text"
3+
}

test/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,18 @@ it('should error if a JSON file is malformed', function (done) {
4848
metalsmith.build(function(err) {
4949
errMessage = String(err);
5050
err.should.be.an('error')
51-
errMessage.should.equal('Error: Malformed data in example.json')
51+
errMessage.should.equal('Error: Malformed data in: example.json')
52+
53+
done() // don't return the error to metalsmith
54+
})
55+
})
56+
57+
it('should error if a key is already used', function (done) {
58+
var metalsmith = Metalsmith('test/fixtures/json-duplicate').use(metadata({ directory: 'test/fixtures/json-duplicate/src/**/*.json' }))
59+
metalsmith.build(function(err) {
60+
errMessage = String(err);
61+
err.should.be.an('error')
62+
errMessage.should.equal('Error: Duplicate file name: example.json')
5263

5364
done() // don't return the error to metalsmith
5465
})

0 commit comments

Comments
 (0)