1 | const { dirname, join, relative } = require('path')
|
2 | const { crossPlatformPath, titleize } = require('./string')
|
3 | const { exists, isDirectory } = require('./file')
|
4 |
|
5 | const COMPONENT_CONFNAME = 'component.config.js'
|
6 | const COMPONENT_DOCSNAME = 'README.md'
|
7 |
|
8 | const componentIdToTitle = (componentId) =>
|
9 | titleize(componentId)
|
10 |
|
11 | const 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 |
|
18 | const 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 |
|
34 | const componentPathToId = (componentPaths, componentPath) => {
|
35 | const relativePaths = componentPaths.map(basePath => relative(basePath, componentPath))
|
36 |
|
37 |
|
38 | const relativePath = relativePaths.find(relPath => !relPath.startsWith('..') && relPath.length > 0)
|
39 |
|
40 | return relativePath ? crossPlatformPath(relativePath) : undefined
|
41 | }
|
42 |
|
43 | module.exports = {
|
44 | COMPONENT_CONFNAME,
|
45 | COMPONENT_DOCSNAME,
|
46 | componentIdToTitle,
|
47 | componentIdToFilePath,
|
48 | componentFilePathToId,
|
49 | componentPathToId
|
50 | }
|