refactor(util): slice the final filename segment (#46466)

This commit is contained in:
Kit Langton 2026-08-31 19:23:35 -04:00 committed by GitHub
parent e7d42f83e6
commit b31defc0a5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 17 additions and 2 deletions

View file

@ -18,6 +18,21 @@ describe("client paths", () => {
expect(getDirectory("")).toBe("")
})
test.each([
["/repo/src/index.ts///", "index.ts"],
["C:\\repo\\src\\index.ts", "index.ts"],
["C:\\repo/src\\file", "file"],
["C:/repo\\src/file/\\", "file"],
["/", ""],
["\\", ""],
["/\\/\\", ""],
["C:\\", "C:"],
["file", "file"],
["", ""],
])("reads the filename from %j", (path, filename) => {
expect(getFilename(path)).toBe(filename)
})
test("keeps filename truncation stable", () => {
expect(getFilenameTruncated("/repo/long-component-name.tsx", 16)).toBe("long-compon….tsx")
expect(truncateMiddle("abcdefghijklmnop", 9)).toBe("abcd…mnop")

View file

@ -1,8 +1,8 @@
export function getFilename(path: string | undefined) {
if (!path) return ""
const trimmed = path.replace(/[/\\]+$/, "")
const parts = trimmed.split(/[/\\]/)
return parts[parts.length - 1] ?? ""
const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"))
return trimmed.slice(index + 1)
}
export function getDirectory(path: string | undefined) {