11cb0ef41Sopenharmony_ciconst { dirname, relative, join, resolve, basename } = require('path')
21cb0ef41Sopenharmony_ciconst linkGently = require('./link-gently.js')
31cb0ef41Sopenharmony_ciconst manTarget = require('./man-target.js')
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciconst linkMans = async ({ path, pkg, top, force }) => {
61cb0ef41Sopenharmony_ci  const target = manTarget({ path, top })
71cb0ef41Sopenharmony_ci  if (!target || !Array.isArray(pkg?.man) || !pkg.man.length) {
81cb0ef41Sopenharmony_ci    return []
91cb0ef41Sopenharmony_ci  }
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ci  const links = []
121cb0ef41Sopenharmony_ci  // `new Set` to filter out duplicates
131cb0ef41Sopenharmony_ci  for (let man of new Set(pkg.man)) {
141cb0ef41Sopenharmony_ci    if (!man || typeof man !== 'string') {
151cb0ef41Sopenharmony_ci      continue
161cb0ef41Sopenharmony_ci    }
171cb0ef41Sopenharmony_ci    // break any links to c:\\blah or /foo/blah or ../blah
181cb0ef41Sopenharmony_ci    man = join('/', man).replace(/\\|:/g, '/').slice(1)
191cb0ef41Sopenharmony_ci    const parseMan = man.match(/\.([0-9]+)(\.gz)?$/)
201cb0ef41Sopenharmony_ci    if (!parseMan) {
211cb0ef41Sopenharmony_ci      throw Object.assign(new Error('invalid man entry name\n' +
221cb0ef41Sopenharmony_ci        'Man files must end with a number, ' +
231cb0ef41Sopenharmony_ci        'and optionally a .gz suffix if they are compressed.'
241cb0ef41Sopenharmony_ci      ), {
251cb0ef41Sopenharmony_ci        code: 'EBADMAN',
261cb0ef41Sopenharmony_ci        path,
271cb0ef41Sopenharmony_ci        pkgid: pkg._id,
281cb0ef41Sopenharmony_ci        man,
291cb0ef41Sopenharmony_ci      })
301cb0ef41Sopenharmony_ci    }
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_ci    const section = parseMan[1]
331cb0ef41Sopenharmony_ci    const base = basename(man)
341cb0ef41Sopenharmony_ci    const absFrom = resolve(path, man)
351cb0ef41Sopenharmony_ci    /* istanbul ignore if - that unpossible */
361cb0ef41Sopenharmony_ci    if (absFrom.indexOf(path) !== 0) {
371cb0ef41Sopenharmony_ci      throw Object.assign(new Error('invalid man entry'), {
381cb0ef41Sopenharmony_ci        code: 'EBADMAN',
391cb0ef41Sopenharmony_ci        path,
401cb0ef41Sopenharmony_ci        pkgid: pkg._id,
411cb0ef41Sopenharmony_ci        man,
421cb0ef41Sopenharmony_ci      })
431cb0ef41Sopenharmony_ci    }
441cb0ef41Sopenharmony_ci
451cb0ef41Sopenharmony_ci    const to = resolve(target, 'man' + section, base)
461cb0ef41Sopenharmony_ci    const from = relative(dirname(to), absFrom)
471cb0ef41Sopenharmony_ci
481cb0ef41Sopenharmony_ci    links.push(linkGently({ from, to, path, absFrom, force }))
491cb0ef41Sopenharmony_ci  }
501cb0ef41Sopenharmony_ci  return Promise.all(links)
511cb0ef41Sopenharmony_ci}
521cb0ef41Sopenharmony_ci
531cb0ef41Sopenharmony_cimodule.exports = linkMans
54