2
0

antora-linked-worktree-patch.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict'
  2. /* Copyright (c) 2002-2022 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. const { promises: fsp } = require('fs')
  17. const ospath = require('path')
  18. /**
  19. * Rewrites local content sources to support the use of linked worktrees.
  20. *
  21. * @author Dan Allen <dan@opendevise.com>
  22. */
  23. module.exports.register = function () {
  24. this.once('playbookBuilt', async ({ playbook }) => {
  25. const expandPath = this.require('@antora/expand-path-helper')
  26. for (const contentSource of playbook.content.sources) {
  27. const { url, branches } = contentSource
  28. if (url.charAt() !== '.') continue
  29. const absdir = expandPath(url, { dot: playbook.dir })
  30. const gitfile = ospath.join(absdir, '.git')
  31. if (await fsp.stat(gitfile).then((stat) => !stat.isDirectory(), () => false)) {
  32. const worktreeGitdir = await fsp.readFile(gitfile, 'utf8')
  33. .then((contents) => contents.trimRight().substr(8))
  34. const worktreeBranch = await fsp.readFile(ospath.join(worktreeGitdir, 'HEAD'), 'utf8')
  35. .then((contents) => contents.trimRight().replace(/^ref: (?:refs\/heads\/)?/, ''))
  36. const reldir = ospath.relative(
  37. playbook.dir,
  38. await fsp.readFile(ospath.join(worktreeGitdir, 'commondir'), 'utf8')
  39. .then((contents) => {
  40. const gitdir = ospath.join(worktreeGitdir, contents.trimRight())
  41. return ospath.basename(gitdir) === '.git' ? ospath.dirname(gitdir) : gitdir
  42. })
  43. )
  44. contentSource.url = reldir ? `.${ospath.sep}${reldir}` : '.'
  45. if (!branches) continue
  46. contentSource.branches = (branches.constructor === Array ? branches : [branches])
  47. .map((pattern) => pattern.replaceAll('HEAD', worktreeBranch))
  48. }
  49. }
  50. })
  51. }