Skip to content

Commit

Permalink
fix: default settings, env config
Browse files Browse the repository at this point in the history
  • Loading branch information
reiniiriarios committed Apr 22, 2024
1 parent bb9dd89 commit e1d55ae
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 36 deletions.
5 changes: 2 additions & 3 deletions electron/autoUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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}`);
Expand Down
35 changes: 24 additions & 11 deletions electron/data/userData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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"))) {
Expand Down Expand Up @@ -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();
}
Expand Down
26 changes: 12 additions & 14 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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();
Expand Down Expand Up @@ -92,25 +88,27 @@ 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();
}
} else {
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);
Expand Down
2 changes: 1 addition & 1 deletion electron/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
"resolveJsonModule": true,
"typeRoots": ["../types", "../node_modules/@types"]
},
"include": ["**/*.ts", "../types"],
"include": ["**/*.ts", "../types", "../env.cjs"],
"exclude": ["../node_modules/*", "../dist/*", "../scripts/*"]
}
7 changes: 7 additions & 0 deletions env.cjs
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 6 additions & 6 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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",
},
}),

Expand All @@ -112,19 +112,19 @@ 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
css({ output: "bundle.css" }),

// 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: {
Expand Down

0 comments on commit e1d55ae

Please sign in to comment.