str-format 0.8.1

STR 结构化树资源格式(.str)的读写库、校验器与 CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! `str` CLI 入口。

use std::path::PathBuf;

use clap::{Parser, Subcommand};
use str_format::cmd;
use str_format::error::{Error, Result};

#[derive(Parser)]
#[command(
    name = "str",
    version,
    about = "STR 结构化树资源格式(.str)工具链",
    long_about = "STR 是目录 bundle 式的结构化树资源格式:深度 1 为独立节点,深度 ≥2 为关联分支,\n任意层级均可承载任意文件;每个分支的 `._meta`(TOML)记录元信息与内容清单。"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// 创建新的 .str bundle(生成 ROOT `._meta` 与 `._schema/`)
    Init {
        /// 目标目录(缺省为当前路径;未以 .str 结尾时自动追加 `.str`)
        dir: Option<PathBuf>,
        /// bundle 短名
        #[arg(long)]
        name: Option<String>,
        /// 标题
        #[arg(long)]
        title: Option<String>,
        /// 一句话摘要
        #[arg(long)]
        summary: Option<String>,
        /// `policies.id_version`:生成的 UUID 版本(4 或 7,缺省 7)
        #[arg(long, default_value_t = 7)]
        id_version: usize,
    },
    /// 全量校验(规范第 6 章全部错误码)
    Validate {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 把告警也视为失败(CI 用)
        #[arg(long)]
        strict: bool,
        /// 输出 JSON
        #[arg(long)]
        json: bool,
        /// 校验前先执行一次 sync 修正清单
        #[arg(long)]
        fix_manifest: bool,
    },
    /// 渲染分支树(含跨枝关联线)
    Tree {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 最大渲染深度
        #[arg(long)]
        depth: Option<usize>,
        /// 显示 `refs` 关联线
        #[arg(long)]
        show_refs: bool,
        /// 显示各分支的内容清单(`entries[]`,子分支行除外)
        #[arg(long)]
        show_entries: bool,
        /// 用纯 ASCII 制表符渲染(终端字体缺字时用)
        #[arg(long)]
        ascii: bool,
    },
    /// 列出某分支的内容清单
    Ls {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// `--uuid` 选项形式(等价于位置参数,保留兼容)
        #[arg(long = "uuid", conflicts_with = "uuid")]
        uuid_opt: Option<String>,
        /// 直接读磁盘而非读清单
        #[arg(long)]
        raw: bool,
    },
    /// 打印某分支的 `._meta`(归一化 JSON)
    Show {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 附带 payload 正文
        #[arg(long)]
        full: bool,
    },
    /// 独立节点操作(深度 1)
    Node {
        #[command(subcommand)]
        cmd: NodeCmd,
    },
    /// 关联分支操作(任意深度)
    Branch {
        #[command(subcommand)]
        cmd: BranchCmd,
    },
    /// 跨枝关联线操作
    Ref {
        #[command(subcommand)]
        cmd: RefCmd,
    },
    /// 软连接子分支操作(声明式挂载,磁盘不新建目录;规范 §4.6.1)
    Link {
        #[command(subcommand)]
        cmd: LinkCmd,
    },
    /// 分支自身元信息字段(`type` / `title` / `summary` / `name` / `tags`)
    Meta {
        #[command(subcommand)]
        cmd: MetaCmd,
    },
    /// `entries[]` 条目字段
    Entry {
        #[command(subcommand)]
        cmd: EntryCmd,
    },
    /// `[[authors]]` 协作记录
    Author {
        #[command(subcommand)]
        cmd: AuthorCmd,
    },
    /// 规范版本声明(bundle 级:`._meta.spec`)
    Spec {
        #[command(subcommand)]
        cmd: SpecCmd,
    },
    /// 忽略名单(ROOT `policies.ignore`,gitignore 语义)
    Ignore {
        #[command(subcommand)]
        cmd: IgnoreCmd,
    },
    /// 校验策略标量键(ROOT `[policies]`)
    Policies {
        #[command(subcommand)]
        cmd: PoliciesCmd,
    },
    /// 用磁盘实际状态修正 `entries` 与指纹
    Sync {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 只显示将要发生的变更
        #[arg(long)]
        dry_run: bool,
    },
    /// 按规范键序 / 表序重写 `._meta`(保注释)
    Fmt {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 只检查是否需要规范化
        #[arg(long)]
        check: bool,
        /// 丢弃整行注释(默认保留)
        #[arg(long)]
        strip_comments: bool,
    },
    /// 输出归一化 JSON(供外部 Schema 工具 / AI 使用)
    Norm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 输出目标:`-` 为 stdout(缺省),其余为文件路径
        #[arg(long)]
        out: Option<String>,
    },
    /// 生成供 AI 使用的上下文片段
    Context {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 下钻层数
        #[arg(long, default_value_t = 2)]
        depth: usize,
        /// 字符预算
        #[arg(long, default_value_t = 8000)]
        budget: usize,
    },
    /// 导出为单一文件(只读、派生)
    Export {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 输出格式:json / toml
        #[arg(long, default_value = "json")]
        format: String,
        /// 最大导出深度
        #[arg(long)]
        depth: Option<usize>,
        /// 输出目标:`-` 为 stdout(缺省),其余为文件路径(不得落在 bundle 内部)
        #[arg(long)]
        out: Option<String>,
    },
    /// 平台适配:macOS 设置 bundle 位并让 `._meta` 可见
    Reveal {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
    /// 元数据检索:按关键词 / 类型 / 标签定位分支(渐进式读取入口)
    Find {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 关键词(对 title / summary / type / tags 及条目字段做不区分大小写的包含匹配)
        query: Option<String>,
        /// 只看 `type` 精确等于该值的分支
        #[arg(long = "type")]
        type_: Option<String>,
        /// 标签过滤(分支须含全部所列标签;可重复 / 逗号分隔)
        #[arg(long, value_delimiter = ',')]
        tag: Vec<String>,
        /// 限定检索字段:all / title / summary / type / tags / note / path
        #[arg(long)]
        field: Option<String>,
        /// 检索范围:分支 id 或 bundle 相对路径(该分支及其全部后代);缺省为当前节点
        #[arg(long)]
        scope: Option<String>,
        /// 最大下钻深度
        #[arg(long)]
        depth: Option<usize>,
        /// 最多返回的命中数
        #[arg(long)]
        limit: Option<usize>,
        /// 文本输出使用绝对路径(JSON 恒含 `path_abs`)
        #[arg(long = "real-path")]
        real_path: bool,
        /// 输出 JSON
        #[arg(long)]
        json: bool,
    },
    /// 正文全文检索(命中行附所属分支上下文;覆盖未登记的内容文件夹子项)
    Grep {
        /// 检索文本(字面子串,非正则)
        pattern: String,
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 只检索路径匹配该通配模式的文件(如 `*.md`)
        #[arg(long)]
        glob: Option<String>,
        /// 忽略大小写
        #[arg(long = "ignore-case", short = 'i')]
        ignore_case: bool,
        /// 只检索清单已登记的条目(缺省遍历分支目录磁盘上的全部文本文件)
        #[arg(long = "manifest-only")]
        manifest_only: bool,
        /// 检索范围:分支 id 或 bundle 相对路径(该分支及其全部后代);缺省为当前节点
        #[arg(long)]
        scope: Option<String>,
        /// 最多返回的命中行数
        #[arg(long)]
        limit: Option<usize>,
        /// 文本输出使用绝对路径(JSON 恒含 `file` 绝对路径)
        #[arg(long = "real-path")]
        real_path: bool,
        /// 输出 JSON
        #[arg(long)]
        json: bool,
    },
    /// 汇总全 bundle 的标签词表(供导航)
    Tags {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 输出 JSON
        #[arg(long)]
        json: bool,
    },
    /// 定位某分支:打印从 ROOT 到目标的链条(面包屑)
    Where {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 输出 JSON
        #[arg(long)]
        json: bool,
    },
    /// 读取一个已登记条目的正文(单文件直出,不展开整树)
    Get {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 条目所在分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 条目路径(单段名,先 `str ls` 查看)
        #[arg(long = "path")]
        path: String,
        /// 只打印该条目的元信息(JSON),不输出正文
        #[arg(long)]
        info: bool,
    },
    /// 列出全部错误码
    Codes,
}

#[derive(Subcommand)]
enum NodeCmd {
    /// 新增独立节点(深度 1)
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 实体类型,如 crm.customer
        #[arg(long = "type")]
        type_: Option<String>,
        /// 标题
        #[arg(long)]
        title: Option<String>,
        /// 摘要
        #[arg(long)]
        summary: Option<String>,
    },
}

#[derive(Subcommand)]
enum BranchCmd {
    /// 在指定分支下新增关联分支
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 锚点分支 id(缺省为当前节点;真 ROOT 的直接子分支应改用 `node add`)
        anchor: Option<String>,
        /// 类型
        #[arg(long = "type")]
        type_: Option<String>,
        /// 标题
        #[arg(long)]
        title: Option<String>,
        /// 摘要
        #[arg(long)]
        summary: Option<String>,
        /// 排序键
        #[arg(long)]
        order: Option<i64>,
    },
    /// 删除关联分支(含全部下级)
    Rm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为 ROOT;ROOT 不可删除)
        uuid: Option<String>,
        /// 确认删除
        #[arg(long)]
        force: bool,
        /// 递归删除下级(规范 §9 的写法;本命令**始终**递归,该旗标为兼容而接受)
        #[arg(long)]
        recursive: bool,
    },
}

#[derive(Subcommand)]
enum RefCmd {
    /// 新增跨枝关联线
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 源分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 目标分支 id
        #[arg(long)]
        target: String,
        /// 关联语义
        #[arg(long, default_value = "related")]
        rel: String,
        /// 标签
        #[arg(long)]
        title: Option<String>,
        /// 备注
        #[arg(long)]
        note: Option<String>,
    },
    /// 删除关联线
    Rm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 关联线 id(规范 §9 的位置参数形式)
        ref_id: Option<String>,
        /// 源分支 id(缺省:在整棵树上定位该关联线)
        #[arg(long)]
        uuid: Option<String>,
        /// 关联线 id 的选项形式(等价于位置参数,保留兼容)
        #[arg(long = "ref", conflicts_with = "ref_id")]
        ref_opt: Option<String>,
    },
}

#[derive(Subcommand)]
enum LinkCmd {
    /// 在本分支下挂载一个软连接子分支
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 挂载位置(父分支 id,缺省为当前节点)
        uuid: Option<String>,
        /// 目标分支 id(`node` / `branch`,不得是 ROOT)
        #[arg(long)]
        target: String,
        /// 链接形态:soft = 目标完整视图(缺省);hard = 仅内容关联(只读)
        #[arg(long, default_value = "soft")]
        mode: String,
        /// 挂载点别名(覆盖目标标题显示)
        #[arg(long)]
        title: Option<String>,
        /// 排序键
        #[arg(long)]
        order: Option<i64>,
        /// 备注
        #[arg(long)]
        note: Option<String>,
    },
    /// 摘除一条软连接(只摘引用,目标分支与数据不动)
    Rm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 父分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 目标分支 id
        #[arg(long)]
        target: String,
    },
}

#[derive(Subcommand)]
enum MetaCmd {
    /// 设置分支自身的元信息字段(空串表示移除该字段)
    Set {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 实体类型,如 crm.customer(空串移除)
        #[arg(long = "type")]
        type_: Option<String>,
        /// 标题(空串移除)
        #[arg(long)]
        title: Option<String>,
        /// 摘要(空串移除)
        #[arg(long)]
        summary: Option<String>,
        /// bundle 短名(仅 root 有效,空串移除)
        #[arg(long)]
        name: Option<String>,
        /// 标签(逗号分隔,可重复;空串清空)
        #[arg(long, value_delimiter = ',')]
        tags: Option<Vec<String>>,
    },
}

#[derive(Subcommand)]
enum EntryCmd {
    /// 登记一个实体条目到目标分支 `entries[]`(自动补 size/sha256/count/role 推断)
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 条目所在分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 条目路径(单段名,与子项目录名/文件名一致)
        #[arg(long = "path")]
        path: String,
        /// role(缺省按磁盘对象推断;`other` 须配 `--note`)
        #[arg(long)]
        role: Option<String>,
        /// 子分支类型
        #[arg(long = "type")]
        type_: Option<String>,
        /// 展示名
        #[arg(long)]
        title: Option<String>,
        /// 摘要
        #[arg(long)]
        summary: Option<String>,
        /// 备注
        #[arg(long)]
        note: Option<String>,
        /// 同层排序键
        #[arg(long)]
        order: Option<i64>,
        /// 媒体类型(仅文件;缺省按扩展名推断)
        #[arg(long = "media-type")]
        media_type: Option<String>,
        /// 磁盘不存在时先登记占位(`optional = true`)
        #[arg(long)]
        optional: bool,
    },
    /// 移除一条登记(只移除登记,不删除磁盘文件)
    Rm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 条目所在分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 条目路径(单段名)
        #[arg(long = "path")]
        path: String,
    },
    /// 设置某分支 `entries[]` 中一条目的字段(空串表示移除该字段)
    Set {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 条目所在分支 id(缺省为当前节点)
        uuid: Option<String>,
        /// 条目路径(单段名,与子项目录名/文件名一致)
        #[arg(long = "path")]
        path: String,
        /// 子分支类型(空串移除)
        #[arg(long = "type")]
        type_: Option<String>,
        /// 展示名(空串移除)
        #[arg(long)]
        title: Option<String>,
        /// 子分支摘要(空串移除)
        #[arg(long)]
        summary: Option<String>,
        /// 备注(空串移除)
        #[arg(long)]
        note: Option<String>,
        /// 同层排序键(规范 §4.6)
        #[arg(long)]
        order: Option<i64>,
    },
}

#[derive(Subcommand)]
enum AuthorCmd {
    /// 新增 / 覆盖一条 `[[authors]]`(按 id 去重)
    Add {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 稳定标识符(SSO sub / 邮箱 hash;禁止用显示名)
        #[arg(long)]
        id: String,
        /// 展示名
        #[arg(long)]
        name: Option<String>,
        /// 角色:owner / editor / viewer / agent
        #[arg(long)]
        role: String,
        /// 参与时间(offset date-time,缺省为当前时间)
        #[arg(long)]
        at: Option<String>,
    },
    /// 按 id 删除一条 `[[authors]]`
    Rm {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 分支 id(缺省为当前节点:`[dir]` 即 bundle 根时为 ROOT,指向分支目录时为该分支)
        uuid: Option<String>,
        /// 稳定标识符
        #[arg(long)]
        id: String,
    },
}

#[derive(Subcommand)]
enum SpecCmd {
    /// 把整份 bundle 的 `spec` 统一改写为目标版本(幂等;从此改 `spec` 不再需要手改 `._meta`)
    Set {
        /// 目标规范版本,如 1.10.0(`str` 主版本固定为 1;可用 `v` 前缀)
        version: String,
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
        /// 只显示将要发生的变更
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum IgnoreCmd {
    /// 追加一条忽略模式(幂等;写入 ROOT `policies.ignore`)
    Add {
        /// 忽略模式(gitignore 语义,匹配 bundle 内相对路径)
        pattern: String,
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
    /// 移除一条忽略模式
    Rm {
        /// 忽略模式(须与既有条目完全一致)
        pattern: String,
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
    /// 查看 `policies.ignore` 与检测到的 `.gitignore` 来源
    List {
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
}

#[derive(Subcommand)]
enum PoliciesCmd {
    /// 写入 ROOT `[policies]` 的标量键(`ignore` 数组键请用 `str ignore add|rm`)
    Set {
        /// 策略键:id_version / max_depth / manifest / sha256 / gitignore / large_asset_bytes / deep_tree_warn
        key: String,
        /// 目标值
        value: String,
        /// bundle 目录(缺省为当前目录)
        #[arg(default_value = ".")]
        dir: PathBuf,
    },
}

fn dispatch(cmd: Cmd) -> Result<i32> {
    match cmd {
        Cmd::Init {
            dir,
            name,
            title,
            summary,
            id_version,
        } => {
            // `[dir]` 缺省为当前路径:仍按「未以 `.str` 结尾则追加」定名,
            // 故在 `foo/` 里执行 `str init` 创建的是 `foo.str`(而非在 `.` 里生成 `..str`)。
            let dir =
                dir.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
            cmd::init(&dir, name, title, summary, id_version)?;
            Ok(0)
        }
        Cmd::Validate {
            dir,
            strict,
            json,
            fix_manifest,
        } => cmd::validate(&dir, strict, json, fix_manifest),
        Cmd::Tree {
            dir,
            depth,
            show_refs,
            show_entries,
            ascii,
        } => {
            cmd::tree(&dir, depth, show_refs, show_entries, ascii)?;
            Ok(0)
        }
        Cmd::Ls {
            dir,
            uuid,
            uuid_opt,
            raw,
        } => {
            cmd::ls(&dir, uuid.or(uuid_opt), raw)?;
            Ok(0)
        }
        Cmd::Show { dir, uuid, full } => {
            cmd::show(&dir, uuid, full)?;
            Ok(0)
        }
        Cmd::Node { cmd } => match cmd {
            NodeCmd::Add {
                dir,
                type_,
                title,
                summary,
            } => {
                cmd::node_add(&dir, type_, title, summary)?;
                Ok(0)
            }
        },
        Cmd::Branch { cmd } => match cmd {
            BranchCmd::Add {
                dir,
                anchor,
                type_,
                title,
                summary,
                order,
            } => {
                cmd::branch_add(&dir, anchor, type_, title, summary, order)?;
                Ok(0)
            }
            BranchCmd::Rm {
                dir,
                uuid,
                force,
                // 删除**总是**递归(`remove_dir_all`),该旗标仅为兼容规范 §9 的写法而接受
                recursive: _,
            } => {
                cmd::branch_rm(&dir, uuid, force)?;
                Ok(0)
            }
        },
        Cmd::Ref { cmd } => match cmd {
            RefCmd::Add {
                dir,
                uuid,
                target,
                rel,
                title,
                note,
            } => {
                cmd::ref_add(&dir, uuid, &target, rel, title, note)?;
                Ok(0)
            }
            RefCmd::Rm {
                dir,
                ref_id,
                uuid,
                ref_opt,
            } => {
                let ref_id = ref_id.or(ref_opt).ok_or_else(|| {
                    Error::BadArg("缺少关联线 id(位置参数 `<REF_ID>` 或 `--ref <REF_ID>`)".into())
                })?;
                cmd::ref_rm(&dir, uuid, &ref_id)?;
                Ok(0)
            }
        },
        Cmd::Link { cmd } => match cmd {
            LinkCmd::Add {
                dir,
                uuid,
                target,
                mode,
                title,
                order,
                note,
            } => {
                cmd::link_add(&dir, uuid, &target, &mode, title, order, note)?;
                Ok(0)
            }
            LinkCmd::Rm { dir, uuid, target } => {
                cmd::link_rm(&dir, uuid, &target)?;
                Ok(0)
            }
        },
        Cmd::Meta { cmd } => match cmd {
            MetaCmd::Set {
                dir,
                uuid,
                type_,
                title,
                summary,
                name,
                tags,
            } => {
                cmd::meta_set(&dir, uuid, type_, title, summary, name, tags)?;
                Ok(0)
            }
        },
        Cmd::Entry { cmd } => match cmd {
            EntryCmd::Add {
                dir,
                uuid,
                path,
                role,
                type_,
                title,
                summary,
                note,
                order,
                media_type,
                optional,
            } => {
                cmd::entry_add(
                    &dir,
                    uuid,
                    &path,
                    &cmd::EntryNew {
                        role,
                        type_,
                        title,
                        summary,
                        note,
                        order,
                        media_type,
                        optional,
                    },
                )?;
                Ok(0)
            }
            EntryCmd::Rm { dir, uuid, path } => {
                cmd::entry_rm(&dir, uuid, &path)?;
                Ok(0)
            }
            EntryCmd::Set {
                dir,
                uuid,
                path,
                type_,
                title,
                summary,
                note,
                order,
            } => {
                cmd::entry_set(
                    &dir,
                    uuid,
                    &path,
                    &cmd::EntryPatch {
                        type_,
                        title,
                        summary,
                        note,
                        order,
                    },
                )?;
                Ok(0)
            }
        },
        Cmd::Author { cmd } => match cmd {
            AuthorCmd::Add {
                dir,
                uuid,
                id,
                name,
                role,
                at,
            } => {
                cmd::author_add(&dir, uuid, id, name, role, at)?;
                Ok(0)
            }
            AuthorCmd::Rm { dir, uuid, id } => {
                cmd::author_rm(&dir, uuid, &id)?;
                Ok(0)
            }
        },
        Cmd::Spec { cmd } => match cmd {
            SpecCmd::Set {
                dir,
                version,
                dry_run,
            } => {
                cmd::spec_set(&dir, &version, dry_run)?;
                Ok(0)
            }
        },
        Cmd::Ignore { cmd } => match cmd {
            IgnoreCmd::Add { dir, pattern } => {
                cmd::ignore_add(&dir, &pattern)?;
                Ok(0)
            }
            IgnoreCmd::Rm { dir, pattern } => {
                cmd::ignore_rm(&dir, &pattern)?;
                Ok(0)
            }
            IgnoreCmd::List { dir } => {
                cmd::ignore_list(&dir)?;
                Ok(0)
            }
        },
        Cmd::Policies { cmd } => match cmd {
            PoliciesCmd::Set { dir, key, value } => {
                cmd::policies_set(&dir, &key, &value)?;
                Ok(0)
            }
        },
        Cmd::Sync { dir, dry_run } => {
            cmd::sync(&dir, dry_run)?;
            Ok(0)
        }
        Cmd::Fmt {
            dir,
            check,
            strip_comments,
        } => cmd::fmt(&dir, check, strip_comments),
        Cmd::Norm { dir, uuid, out } => {
            cmd::norm(&dir, uuid, out)?;
            Ok(0)
        }
        Cmd::Context {
            dir,
            uuid,
            depth,
            budget,
        } => {
            cmd::context(&dir, uuid, depth, budget)?;
            Ok(0)
        }
        Cmd::Export {
            dir,
            format,
            depth,
            out,
        } => {
            cmd::export(&dir, format, depth, out)?;
            Ok(0)
        }
        Cmd::Reveal { dir } => {
            cmd::reveal(&dir)?;
            Ok(0)
        }
        Cmd::Find {
            dir,
            query,
            type_,
            tag,
            field,
            scope,
            depth,
            limit,
            real_path,
            json,
        } => {
            cmd::find(
                &dir,
                query,
                type_.as_deref(),
                &tag,
                field.as_deref(),
                scope.as_deref(),
                depth,
                limit,
                real_path,
                json,
            )?;
            Ok(0)
        }
        Cmd::Grep {
            dir,
            pattern,
            glob,
            ignore_case,
            manifest_only,
            scope,
            real_path,
            limit,
            json,
        } => {
            cmd::grep(
                &dir,
                &pattern,
                glob.as_deref(),
                ignore_case,
                manifest_only,
                scope.as_deref(),
                real_path,
                limit,
                json,
            )?;
            Ok(0)
        }
        Cmd::Tags { dir, json } => {
            cmd::tags(&dir, json)?;
            Ok(0)
        }
        Cmd::Where { dir, uuid, json } => {
            cmd::where_(&dir, uuid, json)?;
            Ok(0)
        }
        Cmd::Get {
            dir,
            uuid,
            path,
            info,
        } => {
            cmd::get(&dir, uuid, &path, info)?;
            Ok(0)
        }
        Cmd::Codes => {
            cmd::list_codes();
            Ok(0)
        }
    }
}

fn main() -> std::process::ExitCode {
    let cli = Cli::parse();
    match dispatch(cli.cmd) {
        Ok(code) => std::process::ExitCode::from(code as u8),
        Err(e) => {
            eprintln!("str: {e}");
            let code = match e {
                Error::NotFound(_) | Error::BadArg(_) => 2,
                Error::Io { .. } => 3,
                Error::Validation(_) | Error::Other(_) => 1,
            };
            std::process::ExitCode::from(code)
        }
    }
}