From e1d55aec8efde8fa6815bd4df1059b56979c5bea Mon Sep 17 00:00:00 2001 From: Emma Litwa-Vulcu <80431903+reiniiriarios@users.noreply.github.com> Date: Mon, 22 Apr 2024 16:15:01 -0700 Subject: [PATCH] fix: default settings, env config --- electron/autoUpdate.ts | 5 ++--- electron/data/userData.ts | 35 ++++++++++++++++++++++++----------- electron/main.ts | 26 ++++++++++++-------------- electron/tsconfig.json | 2 +- env.cjs | 7 +++++++ package.json | 2 +- rollup.config.mjs | 12 ++++++------ 7 files changed, 53 insertions(+), 36 deletions(-) create mode 100644 env.cjs diff --git a/electron/autoUpdate.ts b/electron/autoUpdate.ts index fe854bb..17870b7 100644 --- a/electron/autoUpdate.ts +++ b/electron/autoUpdate.ts @@ -4,8 +4,7 @@ import log from "electron-log/main"; import packageJson from "../package.json"; import WyrmError from "./error"; import BUILD from "./build"; - -const DEV = process.env.WYRM_ENV === "dev"; +import ENV from "../env.cjs"; const GH_USER = "reiniiriarios"; const GH_REPO = "wordwyrm"; @@ -88,7 +87,7 @@ class AppUpdater { log.info(`Up to date, running ${latestVersion}`); return; } - if (DEV) { + if (ENV !== "prod") { log.info(`Version mismatch: latest is ${latestVersion}, running ${packageJson.version}`); } else { log.info(`Update available: ${latestVersion}, running ${packageJson.version}`); diff --git a/electron/data/userData.ts b/electron/data/userData.ts index 8a086aa..0b6e221 100644 --- a/electron/data/userData.ts +++ b/electron/data/userData.ts @@ -4,6 +4,7 @@ import * as path from "path"; import log from "electron-log/main"; import { UserSettings } from "../../types/global"; import WyrmError from "../error"; +import ENV from "../../env.cjs"; // Get platform-idiomatic user data directory. let dataPath: string; @@ -23,7 +24,7 @@ if (process.env.APPDATA) { } export const DATA_PATH = path.join(dataPath, dataDir); -const SCREENSHOT_MODE = process.env.WYRM_PREV === "true"; +const settingsFile = `settings${ENV ? `-${ENV}` : ""}.yaml`; /** * Create user data directories if not already present. @@ -136,14 +137,28 @@ export function isTypeBookGeneric(obj: unknown): obj is BookGeneric { export function loadSettings(args?: { migrateData?: boolean }): UserSettings { try { log.debug("Loading settings"); - const sf = path.join(DATA_PATH, "settings.yaml"); + const sf = path.join(DATA_PATH, settingsFile); + let settings: UserSettings; if (!fs.existsSync(sf)) { - saveYaml(sf, {}); - return {} as UserSettings; - } - const settings = readYaml(sf); - if (!isTypeUserSettings(settings)) { - throw new Error("Settings data invalid"); + // No settings file, set minimum defaults. + log.warn("No settings file found, creating."); + settings = { + booksDir: path.join(DATA_PATH, "books"), + } as UserSettings; + saveYaml(sf, settings); + } else { + // Read settings. + const yaml = readYaml(sf); + if (isTypeUserSettings(yaml)) { + settings = yaml; + } else { + // Reset settings. + log.error("Settings invalid. Backing up and setting defaults."); + fs.copyFileSync(sf, `${sf}.bak`); + settings = { + booksDir: path.join(DATA_PATH, "books"), + } as UserSettings; + } } // Defaults @@ -165,8 +180,6 @@ export function loadSettings(args?: { migrateData?: boolean }): UserSettings { } if (!settings.booksDir) { settings.booksDir = path.join(DATA_PATH, "books"); - } else if (SCREENSHOT_MODE) { - settings.booksDir = path.join(DATA_PATH, "DEV-screenshot-mode"); } else if (args?.migrateData) { // -- upgrade from 1.24.0 -- if (settings.booksDir.startsWith(path.join(dataPath, "me.reinii.wordwyrm"))) { @@ -195,7 +208,7 @@ export function saveSettings( callback: (error?: WyrmError) => void = () => {}, ) { log.debug("Saving settings"); - saveYaml(path.join(DATA_PATH, "settings.yaml"), settings); + saveYaml(path.join(DATA_PATH, settingsFile), settings); if (!options.moveData) { return callback(); } diff --git a/electron/main.ts b/electron/main.ts index 4bd44e0..e788204 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -7,23 +7,22 @@ import packageJson from "../package.json"; import { UserSettings } from "../types/global"; +import ENV from "../env.cjs"; import bridge from "./bridge"; import autoUpdate from "./autoUpdate"; import { DATA_PATH, initUserDirs, loadSettings, saveSettings } from "./data/userData"; const PORT = 5000; -const DEV_MODE = process.env.WYRM_ENV === "dev"; -const SCREENSHOT_MODE = process.env.WYRM_PREV === "true"; /** * Startup. */ app.on("ready", () => { // Setup logging - log.transports.file.level = DEV_MODE ? "debug" : "info"; + log.transports.file.level = ENV === "prod" ? "info" : "debug"; log.transports.file.format = "{h}:{i}:{s}.{ms} [{level}] {text}"; - log.transports.console.level = DEV_MODE ? "debug" : "info"; + log.transports.console.level = ENV === "prod" ? "info" : "debug"; log.transports.console.format = ({ message }: { message: LogMessage }): unknown[] => { const d = message.date || new Date(); const h = d.getHours().toString(10).padStart(2, "0"); @@ -40,10 +39,7 @@ app.on("ready", () => { log.initialize(); // Start - log.info(`Starting in ${DEV_MODE ? "DEV" : "PRODUCTION"} mode`); - if (SCREENSHOT_MODE) { - log.info("SCREENSHOT mode active"); - } + log.info(`Starting: env=${ENV}`); // Create user data directories if not already present. const migrateData = initUserDirs(); @@ -92,9 +88,9 @@ function createWindow(settings: UserSettings) { }); mainWindow.removeMenu(); - if (DEV_MODE) { + if (ENV !== "prod") { mainWindow.loadURL(`http://localhost:${PORT}`); - if (!SCREENSHOT_MODE) { + if (ENV !== "screenshot") { log.info("Opening dev tools"); mainWindow.webContents.openDevTools(); } @@ -102,15 +98,17 @@ function createWindow(settings: UserSettings) { mainWindow.loadFile(path.join(__dirname, "../../index.html")); } - if (!SCREENSHOT_MODE) { + if (ENV !== "screenshot") { mainWindow.setBounds(settings.bounds); } mainWindow.on("close", function () { // only if already loaded, thx - // use default size for screenshot mode - if (bridge.currentSettings && !SCREENSHOT_MODE) { - bridge.currentSettings.bounds = mainWindow.getBounds(); + if (bridge.currentSettings) { + // don't change screenshot bounds + if (ENV !== "screenshot") { + bridge.currentSettings.bounds = mainWindow.getBounds(); + } saveSettings(bridge.currentSettings, {}, (err: Error) => { if (err) { log.error(err); diff --git a/electron/tsconfig.json b/electron/tsconfig.json index c02677f..4038c21 100644 --- a/electron/tsconfig.json +++ b/electron/tsconfig.json @@ -11,6 +11,6 @@ "resolveJsonModule": true, "typeRoots": ["../types", "../node_modules/@types"] }, - "include": ["**/*.ts", "../types"], + "include": ["**/*.ts", "../types", "../env.cjs"], "exclude": ["../node_modules/*", "../dist/*", "../scripts/*"] } diff --git a/env.cjs b/env.cjs new file mode 100644 index 0000000..948b1e8 --- /dev/null +++ b/env.cjs @@ -0,0 +1,7 @@ +const valid = ["prod", "dev", "screenshot", "test"]; +const ENV = process.env.WYRM_ENV; +if (!valid.includes(ENV)) { + ENV = "prod"; +} + +module.exports = ENV; diff --git a/package.json b/package.json index ef4fe2a..6fe4b1b 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "dev": "cross-env WYRM_ENV=dev rollup -c -w", "dev:electron:build": "npm run set:build dev && cross-env WYRM_ENV=dev tsc -p ./electron/tsconfig.json", "dev:electron": "npm run dev:electron:build && cross-env WYRM_ENV=dev electron ./dist/electron/electron/main.js", - "dev:electron:ss": "npm run dev:electron:build && cross-env WYRM_ENV=dev WYRM_PREV=true electron ./dist/electron/electron/main.js", + "dev:electron:ss": "npm run dev:electron:build && cross-env WYRM_ENV=screenshot electron ./dist/electron/electron/main.js", "start": "sirv dist", "start:electron": "electron ./dist/electron/electron/main.js", "clean": "ts-node scripts/rmdist.ts", diff --git a/rollup.config.mjs b/rollup.config.mjs index c269e85..c27a9c1 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -14,9 +14,9 @@ import url from "url"; import { spawn } from "child_process"; import tsconfig from "./tsconfig.json" assert { type: "json" }; +import ENV from "./env.cjs"; const PORT = 5000; -const production = process.env.WYRM_ENV === "prod" ? true : false; const __filename = url.fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -88,12 +88,12 @@ export default { nodePolyfills(), svelte({ preprocess: sveltePreprocess({ - sourceMap: !production, + sourceMap: ENV !== "prod", scss: { includePaths: ["app/**/*.scss"] }, }), compilerOptions: { // enable run-time checks when not in production - dev: !production, + dev: ENV !== "prod", }, }), @@ -112,7 +112,7 @@ export default { commonjs(), typescript({ sourceMap: true, - inlineSources: !production, + inlineSources: ENV !== "prod", }), // we'll extract any component CSS out into // a separate file - better for performance @@ -120,11 +120,11 @@ export default { // In dev mode, call `npm run start` once // the bundle has been generated - !production && serve(), + ENV !== "prod" && serve(), // Watch the `public` directory and refresh the // browser on changes when not in production - !production && livereload({ watch: "dist", delay: 200 }), + ENV !== "prod" && livereload({ watch: "dist", delay: 200 }), ], watch: {