|
| 1 | +// Copyright (c) - 2025+ the lowlighter/esquie authors. AGPL-3.0-or-later |
| 2 | +import type { Nullable } from "@libs/typing" |
| 3 | +import { expandGlob } from "@std/fs" |
| 4 | +export type { Nullable } |
| 5 | + |
| 6 | +/** Gets the current working directory. */ |
| 7 | +export function cwd(): string { |
| 8 | + return Deno.cwd().replaceAll("\\", "/") |
| 9 | +} |
| 10 | + |
| 11 | +/** Gets the file type of a file path. */ |
| 12 | +export function filetype(path: string): Nullable<"file" | "directory"> { |
| 13 | + try { |
| 14 | + const lstat = Deno.lstatSync(path) |
| 15 | + if (lstat.isFile) { |
| 16 | + return "file" |
| 17 | + } |
| 18 | + if (lstat.isDirectory) { |
| 19 | + return "directory" |
| 20 | + } |
| 21 | + } catch { |
| 22 | + // Ignore errors |
| 23 | + } |
| 24 | + return null |
| 25 | +} |
| 26 | + |
| 27 | +/** Options for {@linkcode list()}. */ |
| 28 | +export type ListOptions = { |
| 29 | + /** Root directory to search in. Defaults to the current working directory. */ |
| 30 | + root?: string |
| 31 | + /** Whether to return relative paths. */ |
| 32 | + relative?: boolean |
| 33 | + /** Whether to include files in the results. */ |
| 34 | + files?: boolean |
| 35 | + /** Whether to include directories in the results. */ |
| 36 | + directories?: boolean |
| 37 | +} |
| 38 | + |
| 39 | +/** Lists all files matching the given glob pattern in the specified root directory. */ |
| 40 | +export async function list(glob: string, { root = cwd(), relative = true, files = false, directories = false }: ListOptions = {}): Promise<string[]> { |
| 41 | + if (!root.endsWith("/")) { |
| 42 | + root += "/" |
| 43 | + } |
| 44 | + const entries = await Array.fromAsync(expandGlob(glob, { root, canonicalize: true, includeDirs: directories })) |
| 45 | + return entries |
| 46 | + .filter(({ path }) => [files ? "file" : "", directories ? "directory" : ""].filter(Boolean).includes(filetype(path) as string)) |
| 47 | + .map(({ path }) => path.replaceAll("\\", "/").replace(root, relative ? "" : root)) |
| 48 | +} |
0 commit comments