colorSchemes.ts

 1import fs from "fs"
 2import path from "path"
 3import { ColorScheme, MetaAndLicense } from "./themes/common/colorScheme"
 4
 5const THEMES_DIRECTORY = path.resolve(`${__dirname}/themes`)
 6const STAFF_DIRECTORY = path.resolve(`${__dirname}/themes/staff`)
 7const IGNORE_ITEMS = ["staff", "common", "common.ts"]
 8const ACCEPT_EXTENSION = ".ts"
 9const LICENSE_FILE_NAME = "LICENSE"
10
11function getAllTsFiles(directoryPath: string) {
12    const files = fs.readdirSync(directoryPath)
13    const fileList: string[] = []
14
15    for (const file of files) {
16        if (!IGNORE_ITEMS.includes(file)) {
17            const filePath = path.join(directoryPath, file)
18
19            if (fs.statSync(filePath).isDirectory()) {
20                fileList.push(...getAllTsFiles(filePath))
21            } else if (path.extname(file) === ACCEPT_EXTENSION) {
22                fileList.push(filePath)
23            }
24        }
25    }
26
27    return fileList
28}
29
30function getAllColorSchemes(directoryPath: string) {
31    const files = getAllTsFiles(directoryPath)
32    return files.map((filePath) => ({
33        colorScheme: require(filePath),
34        filePath,
35        fileName: path.basename(filePath),
36        licenseFile: `${path.dirname(filePath)}/${LICENSE_FILE_NAME}`,
37    }))
38}
39
40function getColorSchemes(directoryPath: string) {
41    const colorSchemes: ColorScheme[] = []
42
43    for (const { colorScheme } of getAllColorSchemes(directoryPath)) {
44        if (colorScheme.dark) colorSchemes.push(colorScheme.dark)
45        else if (colorScheme.light) colorSchemes.push(colorScheme.light)
46    }
47
48    return colorSchemes
49}
50
51function getMetaAndLicense(directoryPath: string) {
52    const meta: MetaAndLicense[] = []
53
54    for (const { colorScheme, filePath, licenseFile } of getAllColorSchemes(
55        directoryPath
56    )) {
57        const licenseExists = fs.existsSync(licenseFile)
58        if (!licenseExists) {
59            throw Error(
60                `Public theme should have a LICENSE file ${licenseFile}`
61            )
62        }
63
64        if (!colorScheme.meta) {
65            throw Error(`Public theme ${filePath} must have a meta field`)
66        }
67
68        meta.push({
69            meta: colorScheme.meta,
70            licenseFile,
71        })
72    }
73
74    return meta
75}
76
77export const colorSchemes = getColorSchemes(THEMES_DIRECTORY)
78export const staffColorSchemes = getColorSchemes(STAFF_DIRECTORY)
79export const schemeMeta = getMetaAndLicense(THEMES_DIRECTORY)