Emulate basename and dirname

This commit is contained in:
Manav Rathi 2024-04-18 14:37:04 +05:30
parent 4fd9ecba56
commit 9e35469bdc
No known key found for this signature in database
2 changed files with 25 additions and 10 deletions

View file

@ -1,4 +1,4 @@
import { directoryNameFromPOSIXPath, fileNameFromPOSIXPath } from "@/next/file";
import { basename, dirname } from "@/next/file";
import { FILE_TYPE } from "constants/file";
import {
A_SEC_IN_MICROSECONDS,
@ -118,7 +118,7 @@ export function areFileWithCollectionsSame(
* Empty list of paths is considered to be in the same directory.
*/
export const areAllInSameDirectory = (paths: string[]) =>
new Set(paths.map(directoryNameFromPOSIXPath)).size == 1;
new Set(paths.map(dirname)).size == 1;
export function getImportSuggestion(
uploadType: PICKED_UPLOAD_TYPE,
@ -225,5 +225,4 @@ export function isSystemFile(file: File | ElectronFile) {
*
* Hidden files are those whose names begin with a "." (dot).
*/
export const isHiddenFile = (path: string) =>
fileNameFromPOSIXPath(path).startsWith(".");
export const isHiddenFile = (path: string) => basename(path).startsWith(".");

View file

@ -34,19 +34,35 @@ export const fileNameFromComponents = (components: FileNameComponents) =>
components.filter((x) => !!x).join(".");
/**
* Extract the fileName from the given path.
* Return the file name portion from the given {@link path}.
*
* This tries to emulate the UNIX `basename` command. In particular, any
* trailing slashes on the path are trimmed, so this function can be used to get
* the name of the directory too.
*
* The path is assumed to use POSIX separators ("/").
*/
export const fileNameFromPOSIXPath = (path: string) => {
export const basename = (path: string) => {
const pathComponents = path.split("/");
return pathComponents[pathComponents.length - 1] ?? path;
for (let i = pathComponents.length - 1; i >= 0; i--)
if (pathComponents[i] !== "") return pathComponents[i];
return path;
};
/**
* Extract the directory path (leading up to the item) from the given path.
* Return the directory portion from the given {@link path}.
*
* This tries to emulate the UNIX `dirname` command. In particular, any trailing
* slashes on the path are trimmed, so this function can be used to get the path
* leading up to a directory too.
*
* The path is assumed to use POSIX separators ("/").
*/
export const directoryNameFromPOSIXPath = (path: string) => {
export const dirname = (path: string) => {
const pathComponents = path.split("/");
pathComponents.pop();
while (pathComponents.pop() == "") {
/* no-op */
}
return pathComponents.join("/");
};