# 文件与文件夹

存取文件有三种方式:

1. **标准的文件选择器**: `showOpenFilePicker`、`showSaveFilePicker`、`showDirectoryPicker`、`<input type="file">`. 不需要申请能力, 用户选什么给什么.
2. **`acde:fs`**: 按「根」访问文件: 应用自己的私有文件夹、它点名的共享文件夹 (下载、文档 ……)、用户选的文件夹. 适合文件管理器、编辑器这类应用. 要申请 `fs`.
3. **私有存储**: `navigator.storage.getDirectory()` (OPFS)、IndexedDB、`localStorage`, 应用自己的数据.

应用用的是句柄和根的 id, 不是绝对路径; 只有桌面和它自带的系统应用看得到路径.

## 文件选择器

和浏览器里一样:

```js
const [handle] = await window.showOpenFilePicker({
  types: [{ description: 'Markdown', accept: { 'text/markdown': ['.md'] } }],
})
const text = await (await handle.getFile()).text()
```

- 弹出的是系统的对话框 (macOS 的打开 / 保存面板、Windows 的文件对话框、Linux 的 portal).
- 选中的文件只给这个页面读写.
- `showDirectoryPicker()` 选中的文件夹还会**授权给应用**: 它在 `acde:fs` 里作为一个根出现 (`source: 'granted'`), 下次启动还在. 默认选的是只读的 (根带 `mode: 'read_only'`); `showDirectoryPicker({ mode: 'readwrite' })` 给的是可写的. 用 `fs.revoke(id)` 交还.
- 用户取消时 reject `AbortError`. headless 会话里没有对话框: 选择器在那里也 reject `AbortError`, 除非测试事先回答了它 (`chooseFiles`、`chooseFolder`、`chooseSaveFile`, 见 [端到端测试](https://docs.dopame.ai/zh/guide/testing.md)).

## acde:fs

```jsonc
{ "capabilities": { "fs": true } }
```

```js
import { fs } from 'acde:fs'

const roots = await fs.roots()
// [{ id: 'private', label: '…', source: 'private', mode: 'writable', reason: null, exists: true }]

await fs.writeFile('private', 'notes/todo.md', '- 买牛奶\n', { mkdirs: true })

const { entries } = await fs.list('private', 'notes')
const { text, modifiedMs } = await fs.readText('private', 'notes/todo.md')
await fs.writeFile('private', 'notes/todo.md', text + '- 新的一条\n', { ifModifiedMs: modifiedMs })
```

### 根

每个调用的第一个参数是某个根的 **`id`**, 第二个是这个根下的路径. 根的 `id` 是一个不透明的名字, 不是路径: `fs.list('/home/me/Downloads')` 会被拒绝.

根有三种:

| `source` | `id` | 是什么 | 应用怎么得到 |
| --- | --- | --- | --- |
| `private` | `private` | 应用自己的数据文件夹, 第一次用到时创建 | `"fs": true` (或 `fs` 的任何取值) |
| `place` | 位置的名字, 如 `downloads` | 用户的一个共享文件夹 | 写进 `fs.roots` (见 [共享位置](#共享位置)) |
| `granted` | `folder-` 加 16 位十六进制数字 | 用户选的文件夹 | `showDirectoryPicker()` |

`roots()` 给应用现在能用的每个根返回一项: `{id, label, source, mode, reason, exists}`, 共享位置还带 `place` (位置的名字). `label` 是给用户看的名字 (选的文件夹就是文件夹名). `mode` 是 `writable`、`read_only` (选的时候没带 `mode: 'readwrite'` 的文件夹) 或 `unavailable`; 是 `unavailable` 时, `reason` 说明原因 (`the folder does not exist`), `exists` 是 `false`.

按句柄的名字找到所选文件夹的根:

```js
const handle = await window.showDirectoryPicker({ mode: 'readwrite' })
const picked = (await fs.roots()).find((root) => root.source === 'granted' && root.label === handle.name)
await fs.writeFile(picked.id, 'export.txt', 'hello')
```

**工作数据放在 `private` 里.** 除了 `fs` 它不用再声明什么, 也不用选择器, 总是可写, 也不是别的任何应用的根. 只有该让用户在应用外面找得到的文件, 才用共享位置或选的文件夹. 私有文件夹在磁盘上是 `$XDG_DATA_HOME/acde/files/<应用 id>/`, 调试时用得上; 应用自己只知道它叫 `private`.

### 共享位置

```jsonc
{ "capabilities": { "fs": { "roots": ["downloads", "documents"] } } }
```

`fs.roots` 按名字列出共享位置: `desktop`、`documents`、`downloads`、`music`、`pictures`、`videos`. 别的名字过不了 `acdev check`: `fs.roots "work" is not a shared place (desktop, documents, downloads, music, pictures, videos); any other folder is one the user picks (showDirectoryPicker() with "fs": true)`, 写的是路径时则是 `fs.roots "~/Documents" is not a shared place: write "documents", the runtime finds that folder through the system (also when it was moved)`. `private` 和选的文件夹不管 `fs` 取什么值都有, 不用列.

声明了一个位置, 应用就能访问它; 不会问用户. 声明的每个位置都在 `roots()` 里, 是 `{ id: 'downloads', source: 'place', place: 'downloads', … }`, 它的 `id` 可以当第一个参数: `fs.list('downloads')`. 这台机器上没有这个文件夹时, 根带 `mode: 'unavailable'`, 对它的调用 reject `ENOENT`.

### 路径

第二个参数是根下的**相对路径**, 用 `/` 分隔; `''` (或在 `list` 里不写) 就是根本身. 绝对路径、用 `..` 或符号链接跑出根, 都会被拒绝.

### 常用调用

| 调用 | 返回 |
| --- | --- |
| `roots()` | 应用现在能用的根 |
| `list(root, path?, hidden?)` | `{root, path, entries, truncated, skipped?}`: 文件夹在前, 最多 5000 项 (`truncated`); 隐藏的项 (名字以点开头, Windows 上还有带隐藏或系统属性的) 只在 `hidden` 是 `true` 时才有; `skipped` 数的是名字不是合法 Unicode 的项 |
| `stat(root, path)` | `{name, kind, size, modifiedMs, version, path}` (不跟随符号链接) |
| `readText(root, path)` | `{text, modifiedMs, size, version}`, 最多 64 MiB, 不是 UTF-8 时 `EILSEQ` |
| `readBytes(root, path)` | `{data: Uint8Array, modifiedMs, size, version}`, 最多 64 MiB |
| `writeFile(root, path, data, options?)` | 写文本或字节, 最多 64 MiB; 返回这一项, 带它新的 `version` |
| `readRange(root, path, offset, length, {ifVersion}?)` | `{data, offset, size, modifiedMs, version}`: 文件的一段, 一次最多 16 MiB; `size` 是整个文件的 |
| `mkdir(root, path, {recursive?})` | 建文件夹 |
| `rename(root, from, to)` | 改名 / 移动, 在同一个根里 |
| `delete(root, path)` | 删除一个文件或空文件夹: `{status: 'deleted', path}` |
| `copy(fromRoot, fromPath, toRoot, toDir)` | 把一个文件或文件夹复制进另一个根 (或同一个根) 的文件夹 `toDir`; 返回新的项和它的 `path`. 名字被占用时加一个数字 (`todo 2.md`) |
| `revoke(id)` | 交还用户选的一个文件夹 |

要把共享位置或选的文件夹里的文件拿进应用自己的数据, 就复制它: `await fs.copy('downloads', 'report.txt', 'private', '')`.

### 安全地写

`writeFile` 的选项:

- `create`: `'always'` (默认, 没有就建)、`'new'` (已存在则 `EEXIST`)、`'never'` (不存在则 `ENOENT`).
- `ifVersion`: 文件已经不是你读到的那一版时不写, 报 `ECONFLICT`. 每次读都返回一个 `version` (一个不透明的字符串, 能区分文件的两个状态, 哪怕是同一毫秒里的两次写入); 写的时候带上它, 就不会覆盖别人的修改. `ifModifiedMs` 用修改时间做同样的事; 两者里 `ifVersion` 更可靠. 两者都不能和 `create: 'new'` 一起用.
- `mkdirs`: 先建好上层文件夹. 不带它时, 往不存在的文件夹里写会失败, 报 `EINVAL`.

替换一个文件的写入先写到同一个文件夹里的临时文件, fsync, 再原子地替换原文件 (保留它的权限; Windows 上还有它的属性和 ACL), 所以崩溃后留下的要么是旧内容, 要么是新内容. 文件夹不让应用建文件时, 它改为写在原文件上, 返回的这一项带 `inPlace: true`: 这样的写入在崩溃时不安全.

### 大文件

整个文件的调用到 64 MiB 为止. 更大的文件用标准的句柄: `getFile()` 给出一个按需读的 `File` (`slice()`、`stream()`), `createWritable()` 在任意位置写进一个临时文件, `close()` 再把它原子地放到位. `acde:fs` 有对应的调用: 上面的 `readRange()`, 以及 `openWrite(root, path, {keepExistingData, create, ifVersion, mkdirs}?)` → `{id, size}`, 然后 `writeChunk(id, offset, data)` (每次最多 16 MiB)、`truncateWrite(id, size)`, 最后 `commitWrite(id)` (返回这一项和它的 `version`) 或 `abortWrite(id)`. 带 `ifVersion` 时, 在打开和提交之间被别人改了就是 `ECONFLICT`, 文件保持原样. 放着 10 分钟没动的写入会被放弃.

### 错误

失败时 reject 一个 `Error`, 带 `code` 和 `status`:

| `code` | `status` | 什么时候 |
| --- | --- | --- |
| `EINVAL` | 400 | 参数不对、绝对路径或跑出根的路径、上层文件夹不存在、类型不对、符号链接 |
| `EACCES` | 403 | 第一个参数不是应用的根、根是只读的、系统不允许 |
| `ENOENT` | 404 | 不存在 |
| `EEXIST` | 409 | 已存在 |
| `ECONFLICT` | 409 | 读了之后被别人改了或删了 (`ifVersion`、`ifModifiedMs`) |
| `ENOTEMPTY` | 409 | 删除非空文件夹 |
| `EFBIG` | 413 | 超过大小上限 |
| `EILSEQ` | 400 | `readText` 读到的不是 UTF-8 |
| `ENOSPC` | 507 | 磁盘满 |
| `EIO` | 500 | 其它 |

```js
try {
  await fs.writeFile(root, path, text, { ifModifiedMs })
} catch (e) {
  if (e.code === 'ECONFLICT') askToReload()
  else throw e
}
```

常见的错误用法是这样的:

| 错误用法 | 拒绝 |
| --- | --- |
| 把路径当根: `fs.list('/tmp')` | `EACCES`: `this app may not use the files of /tmp (not one of its roots)` |
| 不在 `fs.roots` 里的位置: 配置是 `"fs": true` 时调 `fs.list('downloads')` | `EACCES`: `this app may not use the files of downloads (not one of its roots)` |
| 第二个参数是绝对路径: `fs.readText('private', '/etc/hosts')` | `EINVAL`: `path must be relative to the workspace` |
| 用 `..` 跑出根: `fs.readText('private', '../x')` | `EINVAL`: `path escapes the workspace` |
| 往不存在的文件夹里写, 没带 `mkdirs` | `EINVAL`: `parent directory is missing or outside the workspace` |
| 往选的时候没带 `mode: 'readwrite'` 的文件夹里写 | `EACCES`: `<folder> was picked read-only` |
| `fs.locate(path)` 或 `fs.openPath(root, path)` (它们在路径和根之间互相转换) | `EACCES`: `fs.locate() works only in system apps that declare shared places` |

## 拖进来的文件

把文件或文件夹从宿主系统拖进窗口, 页面收到标准的拖拽事件, 最后是 `drop`, `dataTransfer` 按标准的方式带着这些文件. 页面拿不到路径.

- 拖进来的每个文件或文件夹是 `dataTransfer.items` 里 `kind: 'file'` 的一项; `item.getAsFileSystemHandle()` resolve 成**只读**的 `FileSystemFileHandle` 或 `FileSystemDirectoryHandle` (`createWritable()` reject `NotAllowedError`).
- 不超过 64 MiB 的文件也在 `dataTransfer.files` 里. 文件夹和更大的文件不在, 用它们的句柄.
- `dataTransfer.types` 是 `['Files']`; 没有带路径的 `text/uri-list` 或 `text/plain`.

要留下拖进来的文件, 把它的内容复制进 `private`:

```js
import { fs } from 'acde:fs'

addEventListener('dragover', (event) => event.preventDefault())
addEventListener('drop', async (event) => {
  event.preventDefault()
  const items = [...event.dataTransfer.items].filter((item) => item.kind === 'file')
  const handles = await Promise.all(items.map((item) => item.getAsFileSystemHandle()))
  for (const handle of handles) {
    if (handle.kind !== 'file') continue
    const file = await handle.getFile()
    await fs.writeFile('private', `inbox/${file.name}`, new Uint8Array(await file.arrayBuffer()), { mkdirs: true })
  }
})
```

句柄 (来自拖放、选择器或打开请求) 也可以交给别的应用, 见 [打开应用](https://docs.dopame.ai/zh/guide/open.md#文件和链接).
