@1-/scan 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,72 +5,98 @@
5
5
  <a id="en"></a>
6
6
  # @1-/scan : Incrementally scan directory files and track metadata in SQLite
7
7
 
8
- Incrementally scans directory files, tracks file sizes and modification times, and synchronizes status into a SQLite database.
8
+ Incrementally scans directory files, compares file sizes and modification times to detect changes, synchronizes metadata to an SQLite database, and returns updated relative paths.
9
9
 
10
10
  ## Features
11
11
 
12
- - Incremental Scanning: Detects and updates only new, modified, or deleted files, avoiding redundant file system operations.
13
- - Space-Efficient Storage: Employs Varint compression to serialize and compare file sizes and modification times.
14
- - Smart Path Key: Stores relative paths not exceeding 16 bytes as raw binary to preserve readability, while hashing longer paths to 16-byte MD5 digests to optimize index performance.
15
- - Database Synchronization: Synchronizes updates and deletions in a single atomic transaction.
16
- - Ignore Pattern Support: Integrates ignore rules dynamically during traversal.
12
+ - **Incremental Scanning**: Detects and processes only new, modified, or deleted files, avoiding redundant file system operations.
13
+ - **Key Optimization**: Stores relative paths within 16 bytes directly as raw bytes; hashes longer paths to 16-byte MD5 digests to optimize database index space and query performance.
14
+ - **Metadata Compression**: Compresses file sizes and modification times using Varint (variable-length byte) encoding.
15
+ - **Transactional Integrity**: Packages updates and deletions in a single database transaction to guarantee consistency.
16
+ - **Flexible Filtering**: Supports custom ignore callback functions to filter specific files and directories.
17
+ - **Native Database**: Integrates Bun's native `bun:sqlite` module, eliminating external database driver dependencies.
17
18
 
18
19
  ## Usage
19
20
 
21
+ ### Basic Incremental Scan
22
+
20
23
  ```javascript
21
24
  import scan from "@1-/scan";
22
25
 
23
- const dir = "./src";
24
- const dbPath = "./files.db";
26
+ const dir = "./data";
27
+ const dbPath = "./scan_record.db";
25
28
 
26
- // Scan directory and sync records into SQLite, returning an array of updated relative paths
29
+ // Scan directory and sync metadata to SQLite, returning modified relative paths
27
30
  const updatedPaths = await scan(dir, dbPath);
28
- console.log(updatedPaths);
31
+ console.log("Updated files:", updatedPaths);
32
+ ```
33
+
34
+ ### Scan with Ignore Filter
35
+
36
+ ```javascript
37
+ import { FILE } from "@1-/walk";
38
+ import scan from "@1-/scan";
39
+
40
+ const dir = "./data";
41
+ const dbPath = "./scan_record.db";
42
+
43
+ // Ignore temporary files and specific configurations
44
+ const ignore = (kind, relPath) => {
45
+ return relPath.startsWith("temp/") || relPath === "config.json";
46
+ };
47
+
48
+ const updatedPaths = await scan(dir, dbPath, ignore);
49
+ console.log("Synced. Updated files:", updatedPaths);
29
50
  ```
30
51
 
31
52
  ## Design Ideas
32
53
 
33
- Execution flow of modules:
54
+ The main entry orchestrates independent modules to execute the incremental scanning and synchronization flow.
34
55
 
35
56
  ```mermaid
36
57
  graph TD
37
- Entry["_.js (Main)"] -->|Open database| Sqlite[sqlite.js]
38
- Entry -->|Load existing records| FileAll[fileAll.js]
39
- Entry -->|Walk and compare| DirWalk[dirWalk.js]
40
- DirWalk -->|Traverse files| Walk["@1-/walk/walkRelIgnore"]
41
- DirWalk -->|Optimize keys| Hash[hash.js]
42
- Entry -->|Apply modifications| FileWrite[fileWrite.js]
43
- FileWrite -->|Wrap transaction| Trans[trans.js]
58
+ Entry["_.js (Entry Point)"] -->|1. Initialize Connection| Sqlite[sqlite.js]
59
+ Entry -->|2. Load Existing Records| Load[load.js]
60
+ Entry -->|3. Walk & Compare Files| DirWalk[dirWalk.js]
61
+ DirWalk -->|Invoke| Walk["@1-/walk/walkRelIgnore"]
62
+ DirWalk -->|Process Path Keys| Hash[hash.js]
63
+ Entry -->|4. Persist Changes| Save[save.js]
64
+ Save -->|Transaction Wrapper| Trans[trans.js]
44
65
  ```
45
66
 
67
+ 1. **Initialize Connection (`sqlite.js`)**: Opens the SQLite database connection and configures automatic connection disposal.
68
+ 2. **Load Records (`load.js`)**: Automatically creates the schema if missing, retrieves existing file hashes, sizes, and modification times, and reconstructs the reference set in memory.
69
+ 3. **Walk & Compare (`dirWalk.js`)**: Traverses the directory structure recursively. Paths are transformed into 16-byte keys via `hash.js`. File attributes are encoded using `@3-/vb` and compared against database records to identify additions and modifications.
70
+ 4. **Persist Changes (`save.js`)**: Executes bulk inserts and deletions in a single transaction via `trans.js` to update database state.
71
+
46
72
  ## Tech Stack
47
73
 
48
- - Bun: Runtime and test runner
49
- - SQLite: Local relational database engine
50
- - `@1-/walk`: Directory walker with ignore support
51
- - `@3-/vb`: Variable-length byte encoder
52
- - `@3-/binmap` / `@3-/binset`: Efficient binary collection structures
74
+ - **Bun**: Runtime environment and test framework.
75
+ - **Bun SQLite**: Native high-performance SQLite engine built into Bun.
76
+ - **@1-/walk**: Directory walker with ignore support.
77
+ - **@3-/vb**: Variable-length byte (Varint) encoder and decoder.
78
+ - **@3-/binmap / @3-/binset**: Memory-efficient collections designed for binary keys.
53
79
 
54
80
  ## Directory Structure
55
81
 
56
82
  ```
57
83
  .
58
84
  ├── src
59
- │ ├── _.js # Entry point orchestrating the scanning and sync process
60
- │ ├── dirWalk.js # Recursively scans files and filters modified ones
61
- │ ├── fileAll.js # Retrieves database records and initializes schema
62
- │ ├── fileWrite.js # Performs bulk database inserts and deletes
63
- │ ├── hash.js # Processes path keys into raw bytes or MD5 digests
64
- │ ├── sqlite.js # Manages SQLite database connection and disposal
65
- │ └── trans.js # Wraps operations inside an SQL transaction
85
+ │ ├── _.js # Entry point coordinating scanning and synchronization
86
+ │ ├── dirWalk.js # Directory traverser comparing file metadata
87
+ │ ├── hash.js # Hashing helper mapping paths to 16-byte keys
88
+ │ ├── load.js # Database loader initializing schema and loading records
89
+ │ ├── save.js # Writer executing bulk updates and deletions
90
+ │ ├── sqlite.js # Connection manager instantiating SQLite database
91
+ │ └── trans.js # Transaction wrapper providing rollback mechanism
66
92
  └── tests # Test suites
67
93
  ```
68
94
 
69
95
  ## History
70
96
 
71
- SQLite was designed in 2000 by D. Richard Hipp while working on a US Navy damage control system. The application originally relied on an Informix database, which required extensive database administration. Hipp designed SQLite to be a serverless, self-contained library requiring zero configuration, allowing the software to function reliably even when database services were unavailable.
97
+ SQLite was created by D. Richard Hipp in 2000 while designing board software for US Navy guided-missile destroyers. The system originally depended on a commercial database that required constant database administration; a connection loss could stall the entire damage control application. To resolve this vulnerability, Hipp designed a serverless, zero-configuration embedded database that directly reads and writes local files—marking the birth of SQLite.
72
98
 
73
- To optimize space inside the database file, SQLite internally uses variable-length integers (Varints) to compress metadata. This project adopts similar techniques—compressing file size and modification time into varints before storage—inheriting the SQLite philosophy of minimalism and space efficiency for local file synchronization.
99
+ To conserve disk space and reduce I/O overhead, SQLite utilizes Varint (variable-length integer) encoding for metadata storage. Under this scheme, small integers consume only 1 byte, while larger numbers scale dynamically. This library inherits that design philosophy, compressing file metadata into varints before storing it, ensuring minimal footprint and high sync performance.
74
100
  ../doc/en/about.md
75
101
 
76
102
  ---
@@ -78,70 +104,96 @@ To optimize space inside the database file, SQLite internally uses variable-leng
78
104
  <a id="zh"></a>
79
105
  # @1-/scan : 增量扫描目录文件并使用 SQLite 记录元数据
80
106
 
81
- 增量扫描目录,比对并同步文件大小与修改时间,记录存入 SQLite 数据库。
107
+ 增量扫描目录文件,通过比对文件大小和修改时间检测变更,并同步至 SQLite 数据库中,最终返回有更新的相对路径列表。
82
108
 
83
109
  ## 功能介绍
84
110
 
85
- - 增量扫描:仅处理新增、修改或删除的文件,避免冗余文件操作。
86
- - 紧凑存储:使用可变字节码(Varint)压缩技术比对并保存文件大小和修改时间。
87
- - 路径映射:相对路径长度不大于 16 字节时保留原始字节,大于 16 字节时计算为 16 字节 MD5,优化数据库索引。
88
- - 事务同步:更新与删除操作合并至单次数据库事务,确保一致性。
89
- - 规则过滤:基于 `@1-/walk` 的忽略规则过滤特定文件与目录。
111
+ - **增量扫描**:仅处理新增、修改或删除的文件,避免冗余的文件系统读写,提升同步速度。
112
+ - **路径压缩**:当相对路径长度小于等于 16 字节时保留原始字节;超出 16 字节则转换为 16 字节 MD5 值作为数据库主键,优化索引空间与查询性能。
113
+ - **元数据压缩**:使用 Varint(可变字节整型)编码方式压缩存储文件大小和修改时间。
114
+ - **事务安全**:将更新与删除操作合并在单个数据库事务中执行,确保数据一致性。
115
+ - **灵活过滤**:支持通过自定义回调函数过滤指定类型的文件与目录。
116
+ - **原生依赖**:基于 Bun 内置 `bun:sqlite` 模块,无需额外安装或编译数据库驱动。
90
117
 
91
118
  ## 使用演示
92
119
 
120
+ ### 基础增量扫描
121
+
93
122
  ```javascript
94
123
  import scan from "@1-/scan";
95
124
 
96
- const dir = "./src";
97
- const dbPath = "./files.db";
125
+ const dir = "./data";
126
+ const dbPath = "./scan_record.db";
98
127
 
99
- // 扫描目录并同步至 SQLite 数据库,返回有变更的相对路径数组
128
+ // 扫描目录并同步至 SQLite,返回发生变更的相对路径列表
100
129
  const updatedPaths = await scan(dir, dbPath);
101
- console.log(updatedPaths);
130
+ console.log("更新文件列表:", updatedPaths);
131
+ ```
132
+
133
+ ### 带有忽略规则的扫描
134
+
135
+ ```javascript
136
+ import { FILE } from "@1-/walk";
137
+ import scan from "@1-/scan";
138
+
139
+ const dir = "./data";
140
+ const dbPath = "./scan_record.db";
141
+
142
+ // 忽略特定文件或目录
143
+ const ignore = (kind, relPath) => {
144
+ return relPath.startsWith("temp/") || relPath === "config.json";
145
+ };
146
+
147
+ const updatedPaths = await scan(dir, dbPath, ignore);
148
+ console.log("已同步,更新列表:", updatedPaths);
102
149
  ```
103
150
 
104
151
  ## 设计思路
105
152
 
106
- 模块调用流程:
153
+ 系统主入口调用各个独立模块完成增量扫描与数据同步流程。
107
154
 
108
155
  ```mermaid
109
156
  graph TD
110
- Entry["_.js (主入口)"] -->|打开数据库| Sqlite[sqlite.js]
111
- Entry -->|载入已有记录| FileAll[fileAll.js]
112
- Entry -->|遍历并比对| DirWalk[dirWalk.js]
113
- DirWalk -->|扫描文件系统| Walk["@1-/walk/walkRelIgnore"]
114
- DirWalk -->|计算路径哈希| Hash[hash.js]
115
- Entry -->|写入变更数据| FileWrite[fileWrite.js]
116
- FileWrite -->|执行事务控制| Trans[trans.js]
157
+ Entry["_.js (主入口)"] -->|1. 初始化连接| Sqlite[sqlite.js]
158
+ Entry -->|2. 加载已有记录| Load[load.js]
159
+ Entry -->|3. 扫描文件系统并对比| DirWalk[dirWalk.js]
160
+ DirWalk -->|调用| Walk["@1-/walk/walkRelIgnore"]
161
+ DirWalk -->|处理路径键| Hash[hash.js]
162
+ Entry -->|4. 持久化数据变更| Save[save.js]
163
+ Save -->|事务保障| Trans[trans.js]
117
164
  ```
118
165
 
166
+ 1. **初始化连接 (`sqlite.js`)**:打开 SQLite 数据库,并配置自动释放连接机制。
167
+ 2. **加载记录 (`load.js`)**:若表不存在则自动创建,读取已记录的文件哈希、大小及修改时间,在内存中还原比对集合。
168
+ 3. **文件系统扫描 (`dirWalk.js`)**:递归遍历目录,利用 `hash.js` 将路径映射为 16 字节键。对比当前文件与数据库元数据(利用 `@3-/vb` 进行压缩状态对比),筛选出新增和修改的文件。
169
+ 4. **数据存储 (`save.js`)**:使用 `trans.js` 开启事务,将需要删除的无效记录及需要更新的元数据批量写入 SQLite 数据库。
170
+
119
171
  ## 技术栈
120
172
 
121
- - Bun:运行环境与测试工具
122
- - SQLite:本地关系型数据库
123
- - `@1-/walk`:支持忽略规则的目录遍历工具
124
- - `@3-/vb`:可变长度整型编码器
125
- - `@3-/binmap` / `@3-/binset`:二进制哈希键容器
173
+ - **Bun**:JavaScript 运行时及测试框架。
174
+ - **Bun SQLite**:内置的轻量级、高性能 SQLite 实现。
175
+ - **@1-/walk**:支持过滤规则的目录递归遍历工具。
176
+ - **@3-/vb**:Varint(可变字节)编码与解码器。
177
+ - **@3-/binmap / @3-/binset**:针对二进制键优化的 Map 和 Set 容器。
126
178
 
127
179
  ## 目录结构
128
180
 
129
181
  ```
130
182
  .
131
183
  ├── src
132
- │ ├── _.js # 主入口,统筹扫描与同步逻辑
133
- │ ├── dirWalk.js # 递归遍历目录,比对筛选出变更文件
134
- │ ├── fileAll.js # 读取数据库中全部记录,初始化数据表
135
- │ ├── fileWrite.js # 事务内执行批量插入与删除
136
- │ ├── hash.js # 计算相对路径哈希值或保留原始字节
137
- │ ├── sqlite.js # 管理 SQLite 数据库连接及资源释放
138
- │ └── trans.js # 封装数据库事务控制
139
- └── tests # 测试目录
184
+ │ ├── _.js # 核心流程控制器,调度各模块完成增量同步
185
+ │ ├── dirWalk.js # 遍历目录并比对元数据,输出变更队列
186
+ │ ├── hash.js # 将文件相对路径编码或计算为固定 16 字节键
187
+ │ ├── load.js # 查询数据库现有记录,若数据表缺失则执行初始化
188
+ │ ├── save.js # 执行批量写入与删除操作
189
+ │ ├── sqlite.js # 创建并配置 SQLite 数据库实例
190
+ │ └── trans.js # 封装 SQLite 事务,提供异常回滚机制
191
+ └── tests # 单元测试模块
140
192
  ```
141
193
 
142
194
  ## 历史故事
143
195
 
144
- SQLite D. Richard Hipp 于 2000 年为驱逐舰控制系统编写。当时系统采用的商业数据库需要繁琐的管理,且一旦故障系统便无法运行。Hipp 设计出无服务器、零配置且直接读写单文件的 SQLite。
196
+ SQLite 的诞生与军事应用密切相关。2000 年,D. Richard Hipp 在为美国海军陆战队设计导弹驱逐舰板载损害控制系统软件时,遇到商业数据库由于配置复杂、日常需要专业维护且一旦连接丢失便会导致整个软件瘫痪的问题。Hipp 随即着手设计了一套无需任何独立服务器、零配置且直接对本地文件进行读写的嵌入式数据库,这便是 SQLite。
145
197
 
146
- 为节约存储空间,SQLite 内部采用可变长度整数(Varint)编码。本项目同样引入 Varint 压缩算法,对文件大小与修改时间做编码后再比对存储,延续了 SQLite 追求性能与紧凑空间的优良传统。
198
+ 为极限节约磁盘空间和降低读写延迟,SQLite 广泛应用了 Varint(可变字节整型)编码。在这种编码下,数值较小的整数(如常见的文件大小、序列号)仅占用 1 个字节,只有大数值才会占用更多字节。本项目中对文件大小和修改时间采用同样的压缩设计,从而秉承了 SQLite 极致节约空间与高效率的系统设计哲学。
147
199
  ../doc/zh/about.md
package/_.js CHANGED
@@ -1,20 +1,20 @@
1
1
  import { BinMap } from "@3-/binmap";
2
2
  import vbE from "@3-/vb/vbE.js";
3
3
  import sqlite from "./sqlite.js";
4
- import fileAll from "./fileAll.js";
4
+ import load from "./load.js";
5
5
  import dirWalk from "./dirWalk.js";
6
- import fileWrite from "./fileWrite.js";
6
+ import save from "./save.js";
7
7
 
8
- export default async (dir, db_path) => {
8
+ export default async (dir, db_path, ignore) => {
9
9
  using db = sqlite(db_path);
10
10
  const existing = new BinMap(),
11
- db_rows = fileAll(db);
11
+ db_rows = load(db);
12
12
 
13
13
  for (const row of db_rows) {
14
14
  existing.set(row.hash, vbE([row.size, row.mtime]));
15
15
  }
16
16
 
17
- const [scanned, to_update] = await dirWalk(dir, existing),
17
+ const [scanned, to_update] = await dirWalk(dir, existing, ignore),
18
18
  to_delete = [];
19
19
  for (const row of db_rows) {
20
20
  if (!scanned.has(row.hash)) {
@@ -22,6 +22,6 @@ export default async (dir, db_path) => {
22
22
  }
23
23
  }
24
24
 
25
- fileWrite(db, to_update, to_delete);
25
+ save(db, to_update, to_delete);
26
26
  return to_update.map(([rel_path]) => rel_path);
27
27
  };
package/dirWalk.js CHANGED
@@ -8,11 +8,14 @@ import vbE from "@3-/vb/vbE.js";
8
8
  import int from "@3-/int";
9
9
  import hash from "./hash.js";
10
10
 
11
- export default async (dir, existing) => {
11
+ export default async (dir, existing, ignore) => {
12
12
  const scanned = new BinSet(),
13
13
  to_update = [];
14
14
 
15
15
  await walkRelIgnore(dir, async (kind, rel_path) => {
16
+ if (ignore && ignore(kind, rel_path)) {
17
+ return false;
18
+ }
16
19
  if (kind === FILE) {
17
20
  const { size, mtimeMs } = await stat(join(dir, rel_path)),
18
21
  mtime = int(mtimeMs),
@@ -4,7 +4,7 @@ export default (db) => {
4
4
  try {
5
5
  return db.prepare("SELECT hash,size,mtime FROM file").all();
6
6
  } catch (err) {
7
- if (err.errcode === SQLITE_ERROR) {
7
+ if (err.errno === SQLITE_ERROR) {
8
8
  db.exec("CREATE TABLE file(hash PRIMARY KEY,size INT UNSIGNED,mtime INT UNSIGNED)");
9
9
  return [];
10
10
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1-/scan",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Incrementally scan directory files and track metadata in SQLite / 增量扫描目录文件并使用 SQLite 记录元数据",
5
5
  "keywords": [
6
6
  "scan",
package/sqlite.js CHANGED
@@ -1,7 +1,7 @@
1
- const { DatabaseSync } = await import("node:sqlite");
1
+ import { Database } from "bun:sqlite";
2
2
 
3
3
  export default (db_path) => {
4
- const db = new DatabaseSync(db_path);
4
+ const db = new Database(db_path);
5
5
  db[Symbol.dispose] = () => db.close();
6
6
  return db;
7
7
  };
File without changes