1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-06-04 08:34:55 +02:00

refactor logic for existing file check based on paths

This commit is contained in:
Kushagra Gour 2018-10-15 01:11:38 +05:30
parent 6d6fe6773e
commit b91028532f
3 changed files with 36 additions and 8 deletions

View File

@ -1,5 +1,6 @@
import { h, Component } from 'preact';
import { FileIcon } from './FileIcon';
import { getParentPath, getFileFromPath } from '../fileUtils';
const ENTER_KEY = 13;
const ESCAPE_KEY = 27;
@ -136,13 +137,15 @@ export class SidePane extends Component {
*/
warnForExistingFileName(newFileName) {
// We also check for fileBeingRenamed !== file because when a file being renamed is
// asked to be set same name, then that should not match and warn here.
if (
this.props.files.some(
file =>
file.name === newFileName && this.state.fileBeingRenamed !== file
)
) {
// asked to be set as same name, then that should not match and warn here.
let newPath = this.state.fileBeingRenamed
? `${getParentPath(this.state.fileBeingRenamed.path)}/${newFileName}`
: newFileName;
// remove first slash
newPath = newPath.replace(/^\//, '');
const match = getFileFromPath(this.props.files, newPath);
if (match.file && this.state.fileBeingRenamed !== match.file) {
alert(`A file with name ${newFileName} already exists.`);
return false;
}

View File

@ -95,3 +95,15 @@ export function doesFileExistInFolder(folder, fileName) {
const details = getChildFileFromName(folder.children, fileName);
return !!details.file;
}
/**
* Returns parent path of passed path
* @param {string} path Path of file to find parent of
*/
export function getParentPath(path) {
const pathPieces = path.split('/');
if (pathPieces.length > 1) {
return pathPieces.slice(0, -1).join('/');
}
return '';
}

View File

@ -3,7 +3,8 @@ import { shallow, deep } from 'preact-render-spy';
import {
assignFilePaths,
getFileFromPath,
removeFileAtPath
removeFileAtPath,
getParentPath
} from '../fileUtils';
function getNestedFiles() {
@ -81,3 +82,15 @@ describe('removeFileAtPath', () => {
expect(files[2].name).toBe('script.js');
});
});
describe('getParentPath', () => {
test('should return correct parent path for root file', () => {
expect(getParentPath('style.css')).toBe('');
});
test('should return correct parent path for nested file', () => {
expect(getParentPath('styles/style.css')).toBe('styles');
expect(getParentPath('js/plugins/main.js')).toBe('js/plugins');
expect(getParentPath('js/plugins/readme')).toBe('js/plugins');
});
});