Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standardise & simplify code #488

Merged
merged 7 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/env.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as fs from 'node:fs/promises';
import fs from 'node:fs/promises';

const envContent = `# env vars picked up by the ComfyUI executable on startup
COMFYUI_CPU_ONLY=true
Expand Down
8 changes: 4 additions & 4 deletions src/config/comfyConfigManager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import path from 'path';
import fs from 'node:fs';
import path from 'node:path';
import log from 'electron-log/main';

export type DirectoryStructure = (string | DirectoryStructure)[];
Expand Down Expand Up @@ -70,7 +70,7 @@ export class ComfyConfigManager {
}

static createNestedDirectories(basePath: string, structure: DirectoryStructure): void {
structure.forEach((item) => {
for (const item of structure) {
if (typeof item === 'string') {
const dirPath = path.join(basePath, item);
this.createDirIfNotExists(dirPath);
Expand All @@ -88,7 +88,7 @@ export class ComfyConfigManager {
} else {
log.warn(`Invalid directory structure item: ${JSON.stringify(item)}`);
}
});
}
}

/**
Expand Down
13 changes: 7 additions & 6 deletions src/config/comfyServerConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';
import fs from 'node:fs';
import fsPromises from 'node:fs/promises';
import log from 'electron-log/main';
import yaml, { type YAMLParseError } from 'yaml';
import path from 'node:path';
Expand Down Expand Up @@ -155,10 +155,11 @@ export class ComfyServerConfig {
}

public static getBaseModelPathsFromRepoPath(repoPath: string): ModelPaths {
return knownModelKeys.reduce((acc, key) => {
acc[key] = path.join(repoPath, 'models', key) + path.sep;
return acc;
}, {} as ModelPaths);
const paths: ModelPaths = {};
for (const key of knownModelKeys) {
paths[key] = path.join(repoPath, 'models', key) + path.sep;
}
return paths;
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/config/comfySettings.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as fs from 'fs/promises';
import * as path from 'path';
import fs from 'node:fs/promises';
import path from 'node:path';
import log from 'electron-log/main';

export const DEFAULT_SETTINGS: ComfySettingsData = {
Expand Down Expand Up @@ -40,7 +40,7 @@ export class ComfySettings {
return;
}
try {
const fileContent = await fs.readFile(this.filePath, 'utf-8');
const fileContent = await fs.readFile(this.filePath, 'utf8');
this.settings = JSON.parse(fileContent);
} catch (error) {
log.error(`Settings file cannot be loaded.`, error);
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/pathHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { IPC_CHANNELS } from '../constants';
import log from 'electron-log/main';
import { ComfyServerConfig } from '../config/comfyServerConfig';
import type { SystemPaths } from '../preload';
import fs from 'fs';
import fs from 'node:fs';
import si from 'systeminformation';
import { ComfyConfigManager } from '../config/comfyConfigManager';
import path from 'path';
import path from 'node:path';

export class PathHandlers {
static readonly REQUIRED_SPACE = 10 * 1024 * 1024 * 1024; // 10GB in bytes
Expand Down
4 changes: 2 additions & 2 deletions src/install/installWizard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'path';
import path from 'node:path';
import log from 'electron-log/main';
import fs from 'fs';
import fs from 'node:fs';
import { InstallOptions } from '../preload';
import { DEFAULT_SETTINGS } from '../config/comfySettings';
import { ComfyServerConfig, ModelPaths } from '../config/comfyServerConfig';
Expand Down
2 changes: 1 addition & 1 deletion src/install/installationValidator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { app, dialog, shell } from 'electron';
import fs from 'fs/promises';
import fs from 'node:fs/promises';
import log from 'electron-log/main';
import path from 'node:path';

Expand Down
2 changes: 1 addition & 1 deletion src/install/resourcePaths.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { app } from 'electron';
import path from 'path';
import path from 'node:path';

export function getAppResourcesPath(): string {
return app.isPackaged ? process.resourcesPath : path.join(app.getAppPath(), 'assets');
Expand Down
21 changes: 9 additions & 12 deletions src/main-process/comfyDesktopApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { ComfySettings } from '../config/comfySettings';
import { AppWindow } from './appWindow';
import { ComfyServer } from './comfyServer';
import { ComfyServerConfig } from '../config/comfyServerConfig';
import fs from 'fs';
import fs from 'node:fs';
import { InstallOptions, type ElectronContextMenuOptions, type TorchDeviceType } from '../preload';
import path from 'path';
import path from 'node:path';
import { ansiCodes, getModelsDirectory, validateHardware } from '../utils';
import { DownloadManager } from '../models/DownloadManager';
import { VirtualEnvironment } from '../virtualEnvironment';
Expand Down Expand Up @@ -86,8 +86,8 @@ export class ComfyDesktopApp {
const allGpuInfo = { ...gpuInfo };
// Set Sentry context with all GPU information
Sentry.setContext('gpus', allGpuInfo);
} catch (e) {
log.error('Error getting GPU info: ', e);
} catch (error) {
log.error('Error getting GPU info: ', error);
}
}

Expand Down Expand Up @@ -136,8 +136,8 @@ export class ComfyDesktopApp {
comfyorigin: 'core',
},
});
} catch (err) {
log.error('Failed to send error to Sentry:', err);
} catch (error_) {
log.error('Failed to send error to Sentry:', error_);
return null;
}
}
Expand Down Expand Up @@ -186,9 +186,7 @@ export class ComfyDesktopApp {
appWindow.maximize();
resolve(installWizard.basePath);
})
.catch((reason) => {
reject(reason);
});
.catch(reject);
});
});
}
Expand Down Expand Up @@ -290,9 +288,8 @@ export class ComfyDesktopApp {
return null;
case 'notFound':
return null;
case 'error':
default:
// Explain and quit
// 'error': Explain and quit
// TODO: Support link? Something?
await InstallationValidator.showInvalidFileAndQuit(ComfyServerConfig.configPath, {
message: `Unable to read the YAML configuration file. Please ensure this file is available and can be read:
Expand All @@ -304,7 +301,7 @@ If this problem persists, back up and delete the config file, then restart the a
defaultId: 0,
cancelId: 1,
});
throw new Error(/* Unreachable. */);
throw new Error('Unreachable');
}
}

Expand Down
18 changes: 9 additions & 9 deletions src/main-process/comfyServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { VirtualEnvironment } from '../virtualEnvironment';
import { ansiCodes, rotateLogFiles } from '../utils';
import { getAppResourcesPath } from '../install/resourcePaths';
import log from 'electron-log/main';
import path from 'path';
import path from 'node:path';
import { ComfyServerConfig } from '../config/comfyServerConfig';
import { AppWindow } from './appWindow';
import waitOn from 'wait-on';
import { ChildProcess } from 'child_process';
import { ChildProcess } from 'node:child_process';

export class ComfyServer {
/**
Expand Down Expand Up @@ -80,13 +80,13 @@ export class ComfyServer {
}

static buildLaunchArgs(mainScriptPath: string, args: Record<string, string>) {
return [mainScriptPath].concat(
Object.entries(args)
.map(([key, value]) => [`--${key}`, value])
.flat()
return [
mainScriptPath,
...Object.entries(args)
.flatMap(([key, value]) => [`--${key}`, value])
// Empty string values are ignored. e.g. { cpu: '' } => '--cpu'
.filter((value: string) => value !== '')
);
.filter((value: string) => value !== ''),
];
}

get launchArgs() {
Expand Down Expand Up @@ -164,7 +164,7 @@ export class ComfyServer {
// Set up a timeout in case the process doesn't exit
const timeout = setTimeout(() => {
reject(new Error('Timeout: Python server did not exit within 10 seconds'));
}, 10000);
}, 10_000);

// Listen for the 'exit' event
this.comfyServerProcess.once('exit', (code, signal) => {
Expand Down
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ if (!gotTheLock) {
app.on('ready', () => {
log.debug('App ready');

startApp().catch((reason) => {
log.error('Unhandled exception in app startup', reason);
startApp().catch((error) => {
log.error('Unhandled exception in app startup', error);
app.exit(2020);
});
});
Expand Down
6 changes: 3 additions & 3 deletions src/models/DownloadManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { session, DownloadItem, ipcMain } from 'electron';
import * as path from 'path';
import * as fs from 'fs';
import path from 'node:path';
import fs from 'node:fs';
import { IPC_CHANNELS } from '../constants';
import log from 'electron-log/main';
import type { AppWindow } from '../main-process/appWindow';
Expand Down Expand Up @@ -223,7 +223,7 @@ export class DownloadManager {
}

getAllDownloads(): DownloadState[] {
return Array.from(this.downloads.values())
return [...this.downloads.values()]
.filter((download) => download.item !== null)
.map((download) => ({
url: download.url,
Expand Down
2 changes: 1 addition & 1 deletion src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const electronAPI = {
return ipcRenderer.invoke(IPC_CHANNELS.IS_PACKAGED);
}, //Emulates app.ispackaged in renderer
restartApp: (customMessage?: string, delay?: number): void => {
console.log('Sending restarting app message to main process with custom message: ', customMessage);
console.log('Sending restarting app message to main process with custom message:', customMessage);
ipcRenderer.send(IPC_CHANNELS.RESTART_APP, { customMessage, delay });
},
reinstall: () => {
Expand Down
16 changes: 8 additions & 8 deletions src/services/backup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path';
import * as fs from 'fs';
import * as glob from 'glob';
import path from 'node:path';
import fs from 'node:fs';
import glob from 'glob';
import { app } from 'electron';
import { VirtualEnvironment } from '../virtualEnvironment';
import { getAppResourcesPath } from '../install/resourcePaths';
Expand All @@ -12,11 +12,11 @@ import { ansiCodes } from '../utils';
function parseLogFile(logPath: string): Set<string> {
console.log('Parsing log file:', logPath);
const customNodes = new Set<string>();
const content = fs.readFileSync(logPath, 'utf-8');
const content = fs.readFileSync(logPath, 'utf8');

const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
for (const rawLine of lines) {
const line = rawLine.trim();
// Match the exact format from Python's "{:6.1f} seconds"
const timeMatch = line.match(/\s*\d+\.\d+\s+seconds/);
if (timeMatch) {
Expand Down Expand Up @@ -92,9 +92,9 @@ export async function restoreCustomNodes(virtualEnvironment: VirtualEnvironment,
const customNodes = new Set<string>();
for (const logFile of logFiles) {
const nodes = parseLogFile(logFile);
nodes.forEach((node) => customNodes.add(node));
for (const node of nodes) customNodes.add(node);
}

log.info('Found custom nodes:', customNodes);
await installCustomNodes(Array.from(customNodes), virtualEnvironment, appWindow);
await installCustomNodes([...customNodes], virtualEnvironment, appWindow);
}
2 changes: 1 addition & 1 deletion src/shell/terminal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as pty from 'node-pty';
import pty from 'node-pty';
import { AppWindow } from '../main-process/appWindow';
import { IPC_CHANNELS } from '../constants';
import { getDefaultShell } from './util';
Expand Down
2 changes: 1 addition & 1 deletion src/shell/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import os from 'os';
import os from 'node:os';

export function getDefaultShell(): string {
switch (os.platform()) {
Expand Down
3 changes: 2 additions & 1 deletion src/store/desktopConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import log from 'electron-log/main';
import ElectronStore from 'electron-store';
import { app, dialog } from 'electron';
import path from 'node:path';
import fs from 'fs/promises';
import fs from 'node:fs/promises';
import type { DesktopSettings } from '.';

/** Backing ref for the singleton config instance. */
Expand Down Expand Up @@ -36,6 +36,7 @@ export class DesktopConfig {
* Static factory method. Loads the config from disk.
* @param shell Shell environment that can open file and folder views for the user
* @param options electron-store options to pass through to the backing store
* @returns The newly created instance, or `undefined` on error.
* @throws On unknown error
*/
static async load(
Expand Down
14 changes: 7 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import * as net from 'net';
import * as fsPromises from 'node:fs/promises';
import net from 'node:net';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import fs from 'fs';
import fs from 'node:fs';
import si from 'systeminformation';
import { exec } from 'child_process';
import { promisify } from 'util';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import log from 'electron-log/main';
import type { GpuType } from './preload';

export const ansiCodes = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
export const ansiCodes = /[\u001B\u009B][#();?[]*(?:\d{1,4}(?:;\d{0,4})*)?[\d<=>A-ORZcf-nqry]/g;

export async function pathAccessible(path: string): Promise<boolean> {
try {
Expand Down Expand Up @@ -82,7 +82,7 @@ export async function rotateLogFiles(logDir: string, baseName: string, maxFiles
}
}

const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const timestamp = new Date().toISOString().replaceAll(/[.:]/g, '-');
const newLogPath = path.join(logDir, `${baseName}_${timestamp}.log`);
await fsPromises.rename(currentLogPath, newLogPath);
}
Expand Down
Loading
Loading