UNPKG

1.59 kBJavaScriptView Raw
1const { dirname, join, relative } = require('path')
2const { crossPlatformPath, titleize } = require('./string')
3const { exists, isDirectory } = require('./file')
4
5const COMPONENT_CONFNAME = 'component.config.js'
6const COMPONENT_DOCSNAME = 'README.md'
7
8const componentIdToTitle = (componentId) =>
9 titleize(componentId)
10
11const componentIdToFilePath = (componentPaths, componentId, fileName = COMPONENT_CONFNAME) => {
12 const componentPath = componentPaths.find(componentPath => exists(join(componentPath, componentId)))
13 const absolutePath = join(componentPath, componentId, fileName)
14
15 return absolutePath
16}
17
18const componentFilePathToId = (componentPaths, componentFilePath) => {
19 const relativePath = componentPathToId(componentPaths, componentFilePath)
20
21 if (relativePath) {
22 const dir = dirname(relativePath).split('/')[0]
23
24 if (dir === '.') {
25 return isDirectory(componentFilePath) ? crossPlatformPath(relativePath) : undefined
26 } else {
27 return crossPlatformPath(dir)
28 }
29 }
30
31 return undefined
32}
33
34const componentPathToId = (componentPaths, componentPath) => {
35 const relativePaths = componentPaths.map(basePath => relative(basePath, componentPath))
36
37 // paths starting with '..' are invalid: not a file/dir in the base dir
38 const relativePath = relativePaths.find(relPath => !relPath.startsWith('..') && relPath.length > 0)
39
40 return relativePath ? crossPlatformPath(relativePath) : undefined
41}
42
43module.exports = {
44 COMPONENT_CONFNAME,
45 COMPONENT_DOCSNAME,
46 componentIdToTitle,
47 componentIdToFilePath,
48 componentFilePathToId,
49 componentPathToId
50}