UNPKG

1.43 kBJavaScriptView Raw
1const { parse, basename } = require('path')
2const { debuglog } = require('util')
3
4const debug = debuglog('metalsmith-paths')
5const defaults = {
6 property: 'path',
7 directoryIndex: false,
8 hrefIndex: false,
9 winToUnix: true
10}
11
12/**
13 * @param {Object} options
14 * @return {Function}
15 */
16module.exports = function (options) {
17 options = Object.assign({}, defaults, options)
18
19 return function (files, metalsmith, done) {
20 setImmediate(done)
21
22 Object.keys(files).forEach((file) => {
23 let filename = file
24
25 // manage windows paths
26 if (options.winToUnix && process.platform === 'win32') {
27 const driveRegex = /^[a-z]:\\{0,2}/i
28 filename = file.replace(driveRegex, '/').replace(/\\{1,2}/g, '/')
29 }
30
31 debug('process file: %s (%s)', file, filename)
32
33 files[file][options.property] = parse(filename)
34
35 // generate href based on whether the file already has a leading slash or not
36 let href = files[file][options.property].dir.startsWith('/') ? '' : '/'
37
38 if (files[file][options.property].dir && files[file][options.property].dir !== '.') {
39 href += files[file][options.property].dir + '/'
40 }
41
42 const dhref = href
43
44 if (!options.directoryIndex || basename(filename) !== options.directoryIndex) {
45 href += basename(filename)
46 }
47
48 files[file][options.property].href = href
49 files[file][options.property].dhref = dhref
50 })
51 }
52}