From 55bbba329c0f4f3f6abc957d3a471929d08f2f93 Mon Sep 17 00:00:00 2001 From: Jens Oliver Meiert Date: Wed, 9 Oct 2024 13:12:48 +0200 Subject: [PATCH] feat: improve error handling and code readability Refactor error logging for consistency and simplify log messages. Introduce try-catch around file copy to handle errors and ensure process continuation. (This commit message was AI-generated.) Signed-off-by: Jens Oliver Meiert --- src/index.js | 4 ++-- src/utils.js | 23 +++++++++++------------ 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/index.js b/src/index.js index 9d0595d..cac0b2c 100644 --- a/src/index.js +++ b/src/index.js @@ -68,8 +68,8 @@ import { hideBin } from 'yargs/helpers' const status = await git.status() compressionFiles = status.staged.filter(filename => files.includes(filename)) await compress(compressionFiles, argv.dry) - } catch (err) { - console.error(err) + } catch (error) { + console.error(error) } } else { await compress(compressionFiles, argv.dry) diff --git a/src/utils.js b/src/utils.js index f88b299..6443ad5 100644 --- a/src/utils.js +++ b/src/utils.js @@ -9,16 +9,17 @@ import path from 'path' import sharp from 'sharp' const logMessage = (message, dry, color = 'yellow') => { - if (dry) { - console.info(chalk[color](`Dry run: ${message}`)) - } else { - console.info(chalk[color](message)) - } + console.info(chalk[color](`${dry ? 'Dry run: ' : ''}${message}`)) } const compression = async (filename, dry) => { const filenameBackup = `${filename}.bak` - fs.copyFileSync(filename, filenameBackup) + try { + fs.copyFileSync(filename, filenameBackup) + } catch (error) { + console.error(`Error creating backup for ${filename}:`, error) + return 0 + } const fileSizeBefore = await size(filename) @@ -71,9 +72,7 @@ const compression = async (filename, dry) => { color = 'green' status = 'Compressed' details = `${sizeReadable(fileSizeBefore)} → ${sizeReadable(fileSizeAfter)}` - } - - if (fileSizeAfter > fileSizeBefore) { + } else if (fileSizeAfter > fileSizeBefore) { color = 'blue' status = 'Skipped' details = 'already better compressed' @@ -90,12 +89,12 @@ const compression = async (filename, dry) => { fs.unlinkSync(tempFilePath) if (fileSizeAfter === 0) { - console.error(chalk.bold.red(`Something went wrong, new file size is ${sizeReadable(fileSizeAfter)}`)) + console.error(chalk.bold.red(`Error doing something meaningful here, new file size is ${sizeReadable(fileSizeAfter)}`)) } return fileSizeAfter < fileSizeBefore ? fileSizeBefore - fileSizeAfter : 0 - } catch (err) { - console.error(`Error compressing ${filename}:`, err) + } catch (error) { + console.error(`Error compressing ${filename}:`, error) fs.renameSync(filenameBackup, filename) return 0 } finally {