@samitouri / QOSami-HFS / commits / 9fd977d1

support platforms not supported by module fs-x-attributes

Massimo Melina committed Jun 6, 2024 at 17:34 UTC 9fd977d181c64d963e9d6dd6750eb91d15775ea4
1 file changed +15 -13
src/fileAttr.ts
+15 -13
@@ -5,28 +5,30 @@ import { access } from 'fs/promises'
5 import { tryJson } from './cross'
6 import { onProcessExit } from './first'
7 // @ts-ignore
8 -import fsx from 'fs-x-attributes'
8 +const fsx = import('fs-x-attributes').then(x => ({ set: promisify(x.set), get: promisify(x.get) }),
9 + () => console.log('fs-x-attributes not available') )
10
10 -let fileAttrDb = new KvStorage({ defaultPutDelay: 1000, maxPutDelay: 5000 })
11 +const fileAttrDb = new KvStorage({ defaultPutDelay: 1000, maxPutDelay: 5000 })
12 onProcessExit(() => fileAttrDb.flush())
13 const FN = 'file-attr.kv'
14 if (existsSync(FN))
15 fileAttrDb.open(FN)
16 const FILE_ATTR_PREFIX = 'user.hfs.' // user. prefix to be linux compatible
16 -export function storeFileAttr(path: string, k: string, v: any) {
17 - return promisify(fsx.set)(path, FILE_ATTR_PREFIX + k, JSON.stringify(v))
18 - .catch(async () => { // fallback to our kv-storage
19 - if (!fileAttrDb.isOpen())
20 - await fileAttrDb.open(FN)
21 - return fileAttrDb.put(`${path}|${k}`, v) // pipe should be a safe separator
22 - }).then(() => true, (e: any) => {
23 - console.error("couldn't store metadata on", path, String(e.message || e))
24 - return false
25 - })
17 +export async function storeFileAttr(path: string, k: string, v: any) {
18 + if (await fsx.then(x => x?.set(path, FILE_ATTR_PREFIX + k, JSON.stringify(v)).then(() => 1, () => 0)))
19 + return true
20 + // fallback to our kv-storage
21 + if (!fileAttrDb.isOpen())
22 + await fileAttrDb.open(FN)
23 + // pipe should be a safe separator
24 + return await fileAttrDb.put(`${path}|${k}`, v)?.catch((e: any) => {
25 + console.error("couldn't store metadata on", path, String(e.message || e))
26 + return false
27 + }) ?? true // if put is undefined, the value was already there
28 }
29
30 export async function loadFileAttr(path: string, k: string) {
29 - return await promisify(fsx.get)(path, FILE_ATTR_PREFIX + k)
31 + return await fsx.then(x => x?.get(path, FILE_ATTR_PREFIX + k))
32 .then((x: any) => x && tryJson(String(x)), () => {})
33 .then((x: any) => x ?? (fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null))
34 ?? undefined // normalize, as we get null instead of undefined on windows