Skip to content
Open
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
71 changes: 70 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,70 @@
// write code here
const fs = require('fs');
const path = require('path');

function renameFile() {
const [, , oldPath, newPath] = process.argv;

if (!oldPath || !newPath) {
// eslint-disable-next-line no-console
console.error('Please provide both source and destination.');

return;
}

if (!fs.existsSync(oldPath)) {
// eslint-disable-next-line no-console
console.error(`Source file does not exist: ${oldPath}`);
return;
}


const oldStats = fs.statSync(oldPath);
if (!oldStats.isFile()) {
// eslint-disable-next-line no-console
console.error(`Source path is not a file: ${oldPath}`);
return;
}

const endsWithSlash = newPath.endsWith('/') || newPath.endsWith('\\');

if (endsWithSlash && !fs.existsSync(newPath)) {
// eslint-disable-next-line no-console
console.error(`Destination directory does not exist: ${newPath}`);

return;
}

let finalDestination = newPath;

if (fs.existsSync(newPath)) {
const stats = fs.statSync(newPath);

if (stats.isDirectory()) {
finalDestination = path.join(newPath, path.basename(oldPath));
} else {
finalDestination = newPath;
}
} else {
const parentDir = path.dirname(newPath);

if (!fs.existsSync(parentDir)) {
// eslint-disable-next-line no-console
console.error(
`The directory for the new path does not exist: ${parentDir}`,
);

return;
}

finalDestination = newPath;
}
Comment on lines +39 to +60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic does not fully satisfy the requirement that "If a destination contains / in the end it must be considered as a directory." Specifically, when a given destination path ends with a / but does not exist (e.g., non-existent-dir/), your code doesn't treat it as a non-existent directory. Instead of reporting an error about the missing directory, it proceeds to the fs.renameSync call, which then fails with a generic system error.


try {
fs.renameSync(oldPath, finalDestination);
} catch (err) {
// eslint-disable-next-line no-console
console.error(`Operation failed: ${err.message}`);
}
}

renameFile();
Loading