All files / src/lib/lang l10nManager.ts

35.9% Statements 14/39
0% Branches 0/3
22.22% Functions 2/9
34.21% Lines 13/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 891x 1x 1x 1x 1x 1x   1x             1x                             1x         1x 20x       20x   1x                                                                                              
import { getGlobalPluginsPath } from "lib/pluginManager/globalPlugins";
import glob from "glob";
import { promisify } from "util";
import { join, relative } from "path";
import { readJSON } from "fs-extra";
import { locales } from "./initElectronL10N";
 
const globAsync = promisify(glob);
 
interface L10NInterface {
  id: string;
  name: string;
}
 
export const loadL10NPlugin = async (
  path: string
): Promise<(JSON & { name: string; type: unknown }) | null> => {
  try {
    const l10n = await readJSON(path);
    Iif (!l10n.name) {
      throw new Error("L10N is missing name");
    }
    return l10n;
  } catch (e) {
    console.error("Unable to load l10n", e);
  }
  return null;
};
 
export class L10nManager {
  systemL10Ns: Record<string, L10NInterface>;
  pluginL10Ns: Record<string, L10NInterface>;
 
  constructor() {
    this.systemL10Ns = locales.reduce((memo, locale) => {
      memo[locale] = {
        id: locale,
        name: locale,
      };
      return memo;
    }, {} as Record<string, L10NInterface>);
    this.pluginL10Ns = {};
  }
 
  async loadPlugins() {
    this.pluginL10Ns = {};
    const globalPluginsPath = getGlobalPluginsPath();
    const pluginPaths = await globAsync(
      join(globalPluginsPath, "**/lang.json")
    );
 
    for (const path of pluginPaths) {
      const l10n = await loadL10NPlugin(path);
      Iif (l10n) {
        const id = relative(globalPluginsPath, path);
        this.pluginL10Ns[id] = { id, name: l10n.name };
      }
    }
  }
 
  async loadPlugin(path: string) {
    const globalPluginsPath = getGlobalPluginsPath();
    const l10n = await loadL10NPlugin(path);
    Iif (l10n) {
      const id = relative(globalPluginsPath, path);
      this.pluginL10Ns[id] = { id, name: l10n.name };
      return this.pluginL10Ns[id];
    }
  }
 
  getSystemL10Ns() {
    return Object.entries(this.systemL10Ns).map(([id, l10n]) => {
      return {
        id,
        name: l10n.name,
      };
    });
  }
 
  getPluginL10Ns() {
    return Object.entries(this.pluginL10Ns).map(([id, l10n]) => {
      return {
        id,
        name: l10n.name,
      };
    });
  }
}