Skip to content

Commit

Permalink
fix(utils/filename): handle files beginning with a period or without …
Browse files Browse the repository at this point in the history
…ext (#185)
  • Loading branch information
cjpearson authored Dec 30, 2024
1 parent 7534c0c commit e68f5cd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const pathSeparators = new Set(["/", "\\", undefined]);

const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");

const SLASH_RE = /[/\\]/;

/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
Expand Down Expand Up @@ -72,16 +74,26 @@ export function resolveAlias(path: string, aliases: Record<string, string>) {
return _path;
}

const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/;

/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
export function filename(path: string) {
return path.match(FILENAME_RE)?.[2];
const base = path.split(SLASH_RE).pop();

if (!base) {
return undefined;
}

const separatorIndex = base.lastIndexOf(".");

if (separatorIndex <= 0) {
return base;
}

return base.slice(0, separatorIndex);
}

// --- internals ---
Expand Down
12 changes: 12 additions & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,24 @@ describe("filename", () => {
"test.html": "test",
"/temp/myfile.html": "myfile",
"./myfile.html": "myfile",
"/Users/john.doe/foo/myFile.js": "myFile",
"/Users/john.doe/foo/myFile": "myFile",
"./.hidden/myFile.ts": "myFile",
"./.hidden/myFile": "myFile",
"/temp/.gitignore": ".gitignore",
"./foo.bar.baz.js": "foo.bar.baz",

// Windows
"C:\\temp\\": undefined,
"C:\\temp\\myfile.html": "myfile",
"\\temp\\myfile.html": "myfile",
".\\myfile.html": "myfile",
".\\john.doe\\myfile.js": "myfile",
".\\john.doe\\myfile": "myfile",
".\\.hidden\\myfile.js": "myfile",
".\\.hidden\\myfile": "myfile",
"C:\\temp\\.gitignore": ".gitignore",
"C:\\temp\\foo.bar.baz.js": "foo.bar.baz",
};
for (const file in files) {
it(file, () => {
Expand Down

0 comments on commit e68f5cd

Please sign in to comment.