|
| 1 | +import { CompilerPlugin, CompilerPluginRuntime, Logger } from 'commandkit'; |
| 2 | +import { DISCORD_LOCALES } from './constants'; |
| 3 | +import { Locale } from 'discord.js'; |
| 4 | +import { I18nPlugin } from './i18n'; |
| 5 | +import { existsSync, mkdirSync, writeFileSync } from 'fs'; |
| 6 | +import { join } from 'path'; |
| 7 | + |
| 8 | +export class I18nCliTemplatePlugin extends CompilerPlugin { |
| 9 | + public readonly name = 'I18nCliTemplatePlugin'; |
| 10 | + |
| 11 | + public async activate(ctx: CompilerPluginRuntime): Promise<void> { |
| 12 | + try { |
| 13 | + ctx.registerTemplate('locale', this.handleTemplate.bind(this)); |
| 14 | + } catch (e) { |
| 15 | + Logger.error(`Failed to register CLI template "locale": ${e}`); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + public async deactivate(ctx: CompilerPluginRuntime): Promise<void> { |
| 20 | + ctx.unregisterTemplate('locale'); |
| 21 | + } |
| 22 | + |
| 23 | + private panic(message: string): never { |
| 24 | + Logger.error(message); |
| 25 | + process.exit(1); |
| 26 | + } |
| 27 | + |
| 28 | + private async handleTemplate(args: string[]): Promise<void> { |
| 29 | + if (args.length < 2) { |
| 30 | + this.panic( |
| 31 | + `Invalid arguments for locale template. Expected: <locale> <commandName>`, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + const [locale, commandName] = args; |
| 36 | + |
| 37 | + if (!DISCORD_LOCALES.has(locale as Locale)) { |
| 38 | + this.panic( |
| 39 | + `Invalid locale ${locale}. Please use one of the followings:\n${Array.from( |
| 40 | + DISCORD_LOCALES, |
| 41 | + ) |
| 42 | + .map((l) => `- ${l}`) |
| 43 | + .join('\n')}`, |
| 44 | + ); |
| 45 | + } |
| 46 | + |
| 47 | + const localePath = I18nPlugin.getLoadPath('src', locale, commandName); |
| 48 | + |
| 49 | + if (existsSync(localePath)) { |
| 50 | + this.panic(`Locale file for "${locale}:${commandName}" already exists.`); |
| 51 | + } |
| 52 | + |
| 53 | + const localeDirSrc = join(localePath, '..', '..'); |
| 54 | + |
| 55 | + if (!existsSync(localeDirSrc)) { |
| 56 | + this.panic( |
| 57 | + `Could not locate source directory. Please make sure you are running this command from the location of your commandkit config file.`, |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + const localeDir = join(localePath, '..'); |
| 62 | + |
| 63 | + if (!existsSync(localeDir)) { |
| 64 | + mkdirSync(localeDir, { recursive: true }); |
| 65 | + } |
| 66 | + |
| 67 | + const data = { |
| 68 | + $command: { |
| 69 | + name: commandName, |
| 70 | + description: `${commandName} command`, |
| 71 | + }, |
| 72 | + }; |
| 73 | + |
| 74 | + writeFileSync(localePath, JSON.stringify(data, null, 2)); |
| 75 | + |
| 76 | + Logger.info( |
| 77 | + `Locale file for ${locale} and ${commandName} created at ${localePath}`, |
| 78 | + ); |
| 79 | + } |
| 80 | +} |
0 commit comments