Open History to see the last commit
1import * as fs from 'node:fs'
2import * as path from 'node:path'
3import { format } from 'oxfmt'
4import oxfmtConfig from '../oxfmt.config.ts'
5β
6/** Pairs of package labels and their corresponding paths */
7type LabelerPair = [string, string]
8β
9function readPairsFromFs(): Array<LabelerPair> {
10 const ignored = new Set(['.DS_Store'])
11β
12 const pairs: Array<LabelerPair> = []
13β
14 // Add subfolders in the packages folder, i.e. packages/**
15 fs.readdirSync(path.resolve('packages'))
16 .filter((folder) => !ignored.has(folder))
17 .forEach((folder) => {
18 // Check if package.json exists for the folder before adding it
19 if (
20 fs.existsSync(
21 path.resolve(path.join('packages', folder, 'package.json')),
22 )
23 ) {
24 pairs.push([`package: ${folder}`, `packages/${folder}/**/*`])
25 } else {
26 console.info(
27 `Skipping \`${folder}\` as it does not have a \`package.json\` file.`,
28 )
29 }
30 })
31β
32 // Sort by package name in alphabetical order
33 pairs.sort((a, b) => a[0].localeCompare(b[0]))
34β
35 return pairs
36}
37β
38async function generateLabelerYaml(pairs: Array<LabelerPair>): Promise<string> {
39 function s(n = 1) {
40 return ' '.repeat(n)
41 }
42β
43 // Convert the pairs into valid yaml
44 const formattedPairs = pairs
45 .map(([packageLabel, packagePath]) => {
46 const result = [
47 `'${packageLabel}':`,
48 `${s(2)}-${s(1)}changed-files:`,
49 `${s(4)}-${s(1)}any-glob-to-any-file:${s(1)}'${packagePath}'`,
50 ].join('\n')
51β
52 return result
53 })
54 .join('\n')
55β
56 // `format()` does not discover config files itself, so pass the config explicitly.
57 console.info('using resolved oxfmt config:', oxfmtConfig)
58β
59 // Format the YAML string using oxfmt
60 const { code: formattedStr, errors } = await format(
61 'labeler-config.yml',
62 formattedPairs,
63 oxfmtConfig,
64 )
65 if (errors.length > 0) {
66 throw new Error(
67 `Failed to format labeler config: ${errors.map((e) => e.message).join(', ')}`,
68 )
69 }
70β
71 return formattedStr
72}
73β
74async function run() {
75 console.info('Generating labeler config...')
76β
77 // Generate the pairs of package labels and their corresponding paths
78 const pairs = readPairsFromFs()
79β
80 // Always add the docs folder
81 pairs.push(['documentation', 'docs/**/*'])
82β
83 // Convert the pairs into valid yaml
84 const yamlStr = await generateLabelerYaml(pairs)
85β
86 // Write to 'labeler-config.yml'
87 const configPath = path.resolve('labeler-config.yml')
88 fs.writeFileSync(configPath, yamlStr, {
89 encoding: 'utf-8',
90 })
91β
92 console.info(`Generated labeler config at \`${configPath}\`!`)
93 return
94}
95β
96try {
97 run().then(() => {
98 process.exit(0)
99 })
100} catch (error) {
101 console.error('Error generating labeler config:', error)
102 process.exit(1)
103}