Skip to content

Commit

Permalink
feat: allow extending partials (#213)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukekarrys authored Sep 22, 2022
1 parent 88f8387 commit d4ddfca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
34 changes: 18 additions & 16 deletions lib/util/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,21 @@ const partialName = (s) => basename(s, extname(s)) // remove extension
.replace(/^_/, '') // remove leading underscore
.replace(/-([a-z])/g, (_, g) => g.toUpperCase()) // camelcase

const setupHandlebars = (...partialDirs) => {
const makePartials = (dir, setDefault) => {
const partials = fs.readdirSync(dir).reduce((acc, f) => {
const partial = fs.readFileSync(join(dir, f)).toString()
const name = partialName(f)
acc[name] = partial
if (setDefault && f.startsWith('_')) {
acc[partialName(`default-${name}`)] = partial
}
return acc
}, {})

Handlebars.registerPartial(partials)
}

const setupHandlebars = (baseDir, ...otherDirs) => {
Handlebars.registerHelper('obj', ({ hash }) => Object.fromEntries(safeValues(hash)))
Handlebars.registerHelper('join', (arr, sep) => arr.join(typeof sep === 'string' ? sep : ', '))
Handlebars.registerHelper('pluck', (arr, key) => arr.map(a => a[key]))
Expand All @@ -20,21 +34,9 @@ const setupHandlebars = (...partialDirs) => {
Handlebars.registerHelper('json', (c) => JSON.stringify(c))
Handlebars.registerHelper('del', () => JSON.stringify(DELETE))

// Load all files as camelcase partial names.
// all other content dirs only get special underscore leading
// files as partials. this prevents recursion loops when overwriting
// a filename to use as a enw file
let isBase = true
for (const dir of partialDirs) {
for (const f of fs.readdirSync(dir)) {
if (f.startsWith('_') || isBase) {
Handlebars.registerPartial(
partialName(f),
fs.readFileSync(join(dir, f)).toString()
)
}
}
isBase = false
makePartials(baseDir, true)
for (const dir of otherDirs) {
makePartials(dir)
}
}

Expand Down
3 changes: 3 additions & 0 deletions test/apply/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,16 @@ t.test('content can override partials', async (t) => {
testdir: {
content_dir: {
'_step-deps.yml': '- run: INSTALL\n',
'_step-test.yml': '- run: TEST\n{{> defaultStepTest }}\n',
},
},
})
await s.apply()
const ci = await s.readFile(join('.github', 'workflows', 'ci.yml'))
t.ok(ci.includes('- run: INSTALL'))
t.ok(ci.includes('- run: TEST'))
t.notOk(ci.includes('npm i --ignore-scripts --no-audit --no-fund'))
t.ok(ci.includes('npm test --ignore-scripts'))
})

t.test('content can extend files', async (t) => {
Expand Down

0 comments on commit d4ddfca

Please sign in to comment.