1 | const { parse, basename } = require('path')
|
2 | const { debuglog } = require('util')
|
3 |
|
4 | const debug = debuglog('metalsmith-paths')
|
5 | const defaults = {
|
6 | property: 'path',
|
7 | directoryIndex: false,
|
8 | hrefIndex: false,
|
9 | winToUnix: true
|
10 | }
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | module.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 |
|
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 |
|
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 | }
|