2024-04-09 08:04:36 -04:00
|
|
|
import { readFile, exists as tauriExists } from '@tauri-apps/plugin-fs'
|
2024-02-12 12:18:37 -08:00
|
|
|
import { isTauri } from 'lib/isTauri'
|
|
|
|
import { join } from '@tauri-apps/api/path'
|
2024-04-25 00:13:09 -07:00
|
|
|
import { readDirRecursive } from 'lib/tauri'
|
2024-02-12 12:18:37 -08:00
|
|
|
|
|
|
|
/// FileSystemManager is a class that provides a way to read files from the local file system.
|
|
|
|
/// It assumes that you are in a project since it is solely used by the std lib
|
|
|
|
/// when executing code.
|
|
|
|
class FileSystemManager {
|
|
|
|
private _dir: string | null = null
|
|
|
|
|
|
|
|
get dir() {
|
|
|
|
if (this._dir === null) {
|
|
|
|
throw new Error('current project dir is not set')
|
|
|
|
}
|
|
|
|
|
|
|
|
return this._dir
|
|
|
|
}
|
|
|
|
|
|
|
|
set dir(dir: string) {
|
|
|
|
this._dir = dir
|
|
|
|
}
|
|
|
|
|
|
|
|
readFile(path: string): Promise<Uint8Array | void> {
|
|
|
|
// Using local file system only works from Tauri.
|
|
|
|
if (!isTauri()) {
|
|
|
|
throw new Error(
|
|
|
|
'This function can only be called from a Tauri application'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return join(this.dir, path)
|
|
|
|
.catch((error) => {
|
|
|
|
throw new Error(`Error reading file: ${error}`)
|
|
|
|
})
|
|
|
|
.then((file) => {
|
2024-04-09 08:04:36 -04:00
|
|
|
return readFile(file)
|
2024-02-12 12:18:37 -08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
exists(path: string): Promise<boolean | void> {
|
|
|
|
// Using local file system only works from Tauri.
|
|
|
|
if (!isTauri()) {
|
|
|
|
throw new Error(
|
|
|
|
'This function can only be called from a Tauri application'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return join(this.dir, path)
|
|
|
|
.catch((error) => {
|
|
|
|
throw new Error(`Error checking file exists: ${error}`)
|
|
|
|
})
|
|
|
|
.then((file) => {
|
|
|
|
return tauriExists(file)
|
|
|
|
})
|
|
|
|
}
|
2024-02-19 12:33:16 -08:00
|
|
|
|
|
|
|
getAllFiles(path: string): Promise<string[] | void> {
|
|
|
|
// Using local file system only works from Tauri.
|
|
|
|
if (!isTauri()) {
|
|
|
|
throw new Error(
|
|
|
|
'This function can only be called from a Tauri application'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return join(this.dir, path)
|
|
|
|
.catch((error) => {
|
|
|
|
throw new Error(`Error joining dir: ${error}`)
|
|
|
|
})
|
|
|
|
.then((p) => {
|
2024-04-25 00:13:09 -07:00
|
|
|
readDirRecursive(p)
|
2024-02-19 12:33:16 -08:00
|
|
|
.catch((error) => {
|
|
|
|
throw new Error(`Error reading dir: ${error}`)
|
|
|
|
})
|
|
|
|
|
|
|
|
.then((files) => {
|
|
|
|
return files.map((file) => file.path)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2024-02-12 12:18:37 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
export const fileSystemManager = new FileSystemManager()
|