-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.js
More file actions
1248 lines (1082 loc) · 37.4 KB
/
sync.js
File metadata and controls
1248 lines (1082 loc) · 37.4 KB
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
import { Buffer } from 'node:buffer';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
/**
* 这个文件是“正式同步脚本”的主入口。
*
* 它负责做 4 件核心事情:
* 1. 从指定的 Git 仓库 / 分支里拉取某个目录或单个文件。
* 2. 把远端内容映射到当前仓库里的另一个目录或文件路径。
* 3. 对文本文件执行三方合并,必要时写入 Git 风格冲突标记。
* 4. 对二进制冲突生成副本,并输出一份结构化报告方便回看。
*
* 阅读这个文件时,建议重点关注下面几类对象:
* - `DEFAULT_CONFIG`:脚本默认配置对象,决定默认同步行为。
* - `SourceInfo`:描述“源路径本身是什么”的对象,是文件还是目录。
* - `SourceEntry`:描述“每一个待同步文件”的对象,是后续真正参与合并的单位。
* - `MergeSummary`:记录本次同步结果统计的对象,控制台输出和报告文件都基于它。
* - `SyncReport`:最终写到 `sync-report.json` 的对象,便于后续排查和审计。
*/
/**
* @typedef {'file' | 'directory'} SourceKind
* 说明源路径的类型:
* - `file` 表示这次同步的是单个文件
* - `directory` 表示这次同步的是整个目录
*/
/**
* @typedef {object} SyncConfig
* 正式脚本的默认配置对象。
*
* 这个对象主要解决“我不想每次都在命令行里手敲一长串参数”的问题。
* 命令行传参时,命令行参数优先;没有传的字段才会回落到这里。
*
* @property {string} repo 远端 Git 地址,或者当前仓库里已有的 remote 名称。
* @property {string} branch 远端分支名。
* @property {string} sourceDir 远端仓库里的源路径,支持目录或单文件。
* @property {string} targetDir 当前仓库里的目标路径,支持目录或单文件。
* @property {string} reportFile 本次同步报告输出到仓库内哪个路径。
* @property {boolean} failOnDirty 当前工作区有未提交改动时是否直接中止。
* @property {boolean} resetTaskStateBeforeSync 正式同步前是否自动清理当前任务的历史基线快照。
*/
/**
* @typedef {object} SourceInfo
* 描述“源路径本身”是什么。
*
* 这个对象只关心源路径的抽象属性,不关心目录下具体有哪些文件。
* 后续是否要枚举多个文件,要看它的 `kind` 是 `file` 还是 `directory`。
*
* @property {SourceKind} kind 源路径类型:单文件或目录。
* @property {string} path 源路径在远端仓库里的相对路径。
*/
/**
* @typedef {object} SourceEntry
* 描述“一个真正要参与同步的文件”。
*
* 无论用户最初传入的是目录还是单文件,真正进入合并流程时,都会被拆成一个或多个
* `SourceEntry`。可以把它理解为“同步循环里的一条任务记录”。
*
* @property {string} defaultTargetName 如果目标被当成目录时,这个文件默认要落下来的文件名。
* @property {string} relativePath 该文件相对于源目录根的相对路径;单文件模式下通常就是文件名。
* @property {string} sourceFile 该文件在远端仓库里的真实路径,用于 `git show` 取内容。
* @property {string} sourceLabelPath 该文件对外展示用的源路径,主要用于日志和报告。
* @property {string} stateKey 写入 `.git/sync-state` 时使用的唯一键,用于关联基线快照。
* @property {string} [tempFilePath] 导出到本地临时目录后的文件路径,后续真正合并时会读取它。
*/
/**
* @typedef {object} MergeLabels
* 传给 `git merge-file -L` 的 3 个标签对象。
*
* 这 3 个字段最终会出现在冲突标记里,帮助使用者判断:
* - 哪一段是当前本地版本
* - 哪一段是历史基线版本
* - 哪一段是新拉到的远端版本
*
* @property {string} local 本地目标文件标签。
* @property {string} base 基线文件标签。
* @property {string} remote 远端源文件标签。
*/
/**
* @typedef {object} ConflictRecord
* 文本冲突记录对象。
*
* 当三方合并后 `git merge-file` 返回冲突状态时,不会丢失任何内容,而是把冲突标记写回目标文件,
* 同时把本条记录收集到 `MergeSummary.conflicts` 里。
*
* @property {string} sourcePath 远端源文件路径。
* @property {string} targetPath 当前仓库里的目标文件路径。
* @property {string} reason 冲突原因说明,主要给控制台和报告使用。
*/
/**
* @typedef {object} BinaryCopyRecord
* 二进制冲突副本记录对象。
*
* 二进制文件没法像文本那样插入 `<<<<<<<` 标记,所以脚本会额外生成一份副本,
* 并把副本位置写到这个对象里,方便后续人工比对。
*
* @property {string} sourcePath 远端源文件路径。
* @property {string} targetPath 当前仓库里的目标文件路径。
* @property {string} copyPath 为这次二进制冲突生成的远端副本路径。
* @property {string} reason 说明为什么采用副本策略。
*/
/**
* @typedef {object} ManualRecord
* 无法自动处理时的手工处理记录对象。
*
* 典型场景包括:
* - 目标位置的父级路径被文件占用
* - 目标本身不是普通文件
* - `git merge-file` 执行失败
*
* @property {string} sourcePath 远端源文件路径。
* @property {string} targetPath 当前仓库里的目标文件路径。
* @property {string} reason 需要人工介入的原因。
*/
/**
* @typedef {object} MergeSummary
* 本次同步的汇总统计对象。
*
* 这是整个脚本里最关键的“结果容器”之一:
* - 控制台最终汇总输出依赖它
* - `sync-report.json` 依赖它
* - 调试时看这个对象,基本就能知道本次同步发生了什么
*
* @property {string[]} created 本地原来没有、这次新创建的目标文件路径列表。
* @property {string[]} identical 本地与远端完全相同,因此被直接跳过的目标文件路径列表。
* @property {string[]} merged 自动三方合并成功的目标文件路径列表。
* @property {ConflictRecord[]} conflicts 已写入文本冲突标记的文件列表。
* @property {BinaryCopyRecord[]} binaryCopies 已生成二进制副本的文件列表。
* @property {ManualRecord[]} manual 无法自动处理、需要人工处理的文件列表。
*/
/**
* @typedef {object} SyncReport
* 最终写入 `sync-report.json` 的报告对象。
*
* 它本质上是在 `MergeSummary` 的基础上再补齐“这次任务是谁、从哪来、往哪去”的元数据,
* 目的是方便未来回看、排障和审计。
*
* @property {string} generatedAt 报告生成时间。
* @property {string} repo 本次同步使用的仓库地址或 remote 名称。
* @property {string} branch 本次同步的分支名。
* @property {string} sourceDir 远端源路径。
* @property {SourceKind} sourceKind 远端源路径类型。
* @property {string} targetDir 本地目标路径。
* @property {number} createdCount 新增文件数量。
* @property {number} identicalCount 相同跳过数量。
* @property {number} mergedCount 自动合并数量。
* @property {number} conflictCount 文本冲突数量。
* @property {number} binaryCopyCount 二进制副本数量。
* @property {number} manualCount 需人工处理数量。
* @property {string[]} created 新增文件列表。
* @property {string[]} identical 相同跳过列表。
* @property {string[]} merged 自动合并列表。
* @property {ConflictRecord[]} conflicts 文本冲突列表。
* @property {BinaryCopyRecord[]} binaryCopies 二进制副本列表。
* @property {ManualRecord[]} manual 需人工处理列表。
*/
/** @type {SyncConfig} */
const DEFAULT_CONFIG = {
// 远端 Git 地址,既可以写完整仓库地址,也可以写当前仓库已经配置好的 remote 名称。
repo: 'git@example.com:demo/blueprint-kit.git',
// 默认同步哪个分支。没有传 --branch 时,就会回落到这里。
branch: 'dev',
// 远端源路径,可以是目录,也可以是单文件。
sourceDir: 'packages/widgets/src/elements',
// 当前仓库里的目标路径,可以是目录,也可以是单文件。
targetDir: 'projects/sandbox/src/ui/elements',
// 同步完成后把报告写到哪里,路径必须位于当前仓库内。
reportFile: 'sync-report.json',
// 是否要求工作区必须干净。true 更安全,false 更灵活。
failOnDirty: true,
// 是否在每次“正式同步”前自动清理这条任务对应的历史基线。
// 这样做的目的,是避免上一次运行遗留的 base 快照影响本次结果,
// 让脚本默认更接近“重新按当前本地代码 + 当前远端代码重新判断”的行为。
// 如果你明确想复用旧基线,可以通过命令行 `--keep-state` 关闭这个行为。
resetTaskStateBeforeSync: true,
};
// 二进制冲突时,优先在目标文件旁边生成的远端副本后缀。
const BINARY_CONFLICT_SUFFIX = '.sync-binary-incoming';
// 如果目标文件旁边没法安全落副本,就退回到仓库内这个目录下。
const BINARY_CONFLICT_FALLBACK_DIR = '.sync-conflicts';
// 当前脚本所在目录,用来定位仓库根路径。
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
function printHelp() {
console.log(`
用法:
node sync.js --repo <git地址或remote名> --source <远端路径> --target <本地路径> [options]
示例:
node sync.js --repo git@example.com:demo/blueprint-kit.git --branch main --source packages/widgets/src/elements --target projects/sandbox/src/ui/elements
node sync.js --repo template-remote --branch release --source packages/config/src/theme.ts --target projects/sandbox/src/ui/theme/app-theme.ts
node sync.js --repo template-remote --branch release --source packages/config/src/theme.ts --target projects/sandbox/src/ui/theme/ --dry-run
参数:
--repo Git 地址,或者当前仓库已配置好的 remote 名称
--branch 远端分支名,默认 main
--source 远端仓库里要同步的路径,支持目录或单个文件
--target 当前仓库里要合并到的路径,支持目录或单个文件
--report 运行报告输出路径,默认 sync-report.json
--allow-dirty 当前仓库有未提交改动时也继续执行
--keep-state 保留当前任务已有的基线快照,不在同步开始前自动清理
--dry-run 只预览,不真正写文件
--help 打印帮助
单文件目标规则:
- 如果 --source 是单文件,且 --target 是已存在目录,或者以 / 结尾,则保留原文件名同步进目录
- 否则 --target 会被当成最终文件路径,所以可以直接改成不同文件名
冲突策略:
- 文本冲突:直接写入 Git 风格冲突标记(<<<<<<< / ======= / >>>>>>>)
- 二进制冲突:生成 .sync-binary-incoming 副本,并在控制台和报告里提示你处理
- 结构冲突:不改文件,只在控制台和报告里提示你手动处理
也可以直接编辑 sync.js 顶部的 DEFAULT_CONFIG,然后运行:
node sync.js
`);
}
function parseArgs(argv) {
const cliConfig = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
switch (arg) {
case '--allow-dirty': {
cliConfig.failOnDirty = false;
break;
}
case '--branch': {
cliConfig.branch = readValue(argv, index, arg);
index += 1;
break;
}
case '--dry-run': {
cliConfig.dryRun = true;
break;
}
case '--help': {
cliConfig.help = true;
break;
}
case '--keep-state': {
cliConfig.resetTaskStateBeforeSync = false;
break;
}
case '--repo': {
cliConfig.repo = readValue(argv, index, arg);
index += 1;
break;
}
case '--report': {
cliConfig.reportFile = readValue(argv, index, arg);
index += 1;
break;
}
case '--source': {
cliConfig.sourceDir = readValue(argv, index, arg);
index += 1;
break;
}
case '--target': {
cliConfig.targetDir = readValue(argv, index, arg);
index += 1;
break;
}
default: {
throw new Error(`未知参数:${arg}`);
}
}
}
return cliConfig;
}
function readValue(argv, currentIndex, argName) {
const value = argv[currentIndex + 1];
if (!value || value.startsWith('--')) {
throw new Error(`${argName} 缺少值`);
}
return value;
}
function normalizeGitPath(input) {
return path.posix
.normalize(input.replaceAll('\\', '/'))
.replace(/^\.\//u, '')
.replace(/\/+$/u, '');
}
function normalizeRepoRelativePath(input) {
return input.replaceAll('\\', '/').replace(/^\.\//u, '').replace(/\/+$/u, '');
}
/**
* 把命令行参数和 DEFAULT_CONFIG 合并成真正执行时使用的配置对象。
*
* 这个阶段除了“合并值”以外,还会顺手做两类规范化:
* - 把路径分隔符统一成 /,避免不同平台路径格式影响判断
* - 额外算出 `targetTreatAsDirectory`,用来判断单文件模式下目标应按目录还是文件处理
*/
function resolveConfig(cliConfig) {
const rawTarget = cliConfig.targetDir ?? DEFAULT_CONFIG.targetDir;
return {
...DEFAULT_CONFIG,
...cliConfig,
sourceDir: normalizeGitPath(
cliConfig.sourceDir ?? DEFAULT_CONFIG.sourceDir,
),
targetDir: normalizeRepoRelativePath(rawTarget),
reportFile: normalizeRepoRelativePath(
cliConfig.reportFile ?? DEFAULT_CONFIG.reportFile,
),
targetTreatAsDirectory: /[\\/]$/u.test(rawTarget),
};
}
function gitText(cwd, args) {
return execFileSync('git', args, {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
}).trim();
}
function gitBuffer(cwd, args) {
return execFileSync('git', args, {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
});
}
function gitInherit(cwd, args) {
execFileSync('git', args, {
cwd,
stdio: 'inherit',
});
}
function getRepoRoot() {
return gitText(scriptDir, ['rev-parse', '--show-toplevel']);
}
function getGitDir(repoRoot) {
return path.resolve(repoRoot, gitText(repoRoot, ['rev-parse', '--git-dir']));
}
function assertRequiredConfig(config) {
const missingFields = [];
if (!config.repo) {
missingFields.push('--repo');
}
if (!config.sourceDir) {
missingFields.push('--source');
}
if (!config.targetDir) {
missingFields.push('--target');
}
if (missingFields.length > 0) {
throw new Error(`缺少必要参数:${missingFields.join(', ')}`);
}
}
function assertSafeGitPath(input, fieldName) {
if (!input || input === '.' || path.posix.isAbsolute(input)) {
throw new Error(`${fieldName} 必须是相对路径,不能是空值、. 或绝对路径`);
}
if (input === '..' || input.startsWith('../') || input.includes('/../')) {
throw new Error(`${fieldName} 不能包含 ..`);
}
}
function assertSafeRepoRelativePath(input, fieldName) {
if (!input || input === '.' || path.isAbsolute(input)) {
throw new Error(
`${fieldName} 必须是仓库内的相对路径,不能是空值、. 或绝对路径`,
);
}
const normalized = input.replaceAll('\\', '/');
if (
normalized === '..' ||
normalized.startsWith('../') ||
normalized.includes('/../')
) {
throw new Error(`${fieldName} 不能包含 ..`);
}
}
function validateConfig(config) {
assertRequiredConfig(config);
assertSafeGitPath(config.sourceDir, '--source');
assertSafeRepoRelativePath(config.targetDir, '--target');
assertSafeRepoRelativePath(config.reportFile, '--report');
}
function resolvePathInsideRepo(repoRoot, repoRelativePath, fieldName) {
const resolvedPath = path.resolve(repoRoot, repoRelativePath);
const relativePath = path.relative(repoRoot, resolvedPath);
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
throw new Error(`${fieldName} 必须位于当前仓库内:${repoRelativePath}`);
}
return resolvedPath;
}
function ensureWorkingTreeClean(repoRoot) {
const status = gitText(repoRoot, ['status', '--porcelain']);
if (status) {
throw new Error(
'当前仓库存在未提交改动,请先提交或暂存;如确认继续,请追加 --allow-dirty',
);
}
}
function fetchSource(repoRoot, config, tempRef) {
console.log(`\n[1/4] 拉取远端:${config.repo} (${config.branch})`);
gitInherit(repoRoot, [
'fetch',
'--no-tags',
'--depth',
'1',
config.repo,
`${config.branch}:${tempRef}`,
]);
}
/**
* 检查远端源路径到底是“文件”还是“目录”。
*
* 返回的是 `SourceInfo` 对象,它只描述源路径的类型与路径本身,
* 还没有展开到每一个具体待同步文件。
*
* @returns {SourceInfo} 返回源路径的类型与标准化后的远端相对路径。
*/
function inspectSourcePath(repoRoot, tempRef, sourcePath) {
try {
const type = gitText(repoRoot, [
'cat-file',
'-t',
`${tempRef}:${sourcePath}`,
]);
if (type === 'blob') {
return {
kind: 'file',
path: sourcePath,
};
}
if (type === 'tree') {
return {
kind: 'directory',
path: sourcePath,
};
}
} catch {}
throw new Error(`远端分支中没有找到路径:${sourcePath}`);
}
/**
* 把源路径展开成一个或多个 `SourceEntry`。
*
* - 如果源路径本来就是单文件,那么只会生成 1 条记录。
* - 如果源路径是目录,那么会把目录下所有文件全部展开。
*
* 后续真正的同步循环,是围绕这些 `SourceEntry` 在跑,而不是围绕原始 `SourceInfo`。
*
* @returns {SourceEntry[]} 返回展开后的待同步文件列表。
*/
function buildSourceEntries(repoRoot, tempRef, sourceInfo) {
if (sourceInfo.kind === 'file') {
return [
{
defaultTargetName: path.posix.basename(sourceInfo.path),
relativePath: path.posix.basename(sourceInfo.path),
sourceFile: sourceInfo.path,
sourceLabelPath: sourceInfo.path,
stateKey: path.posix.basename(sourceInfo.path),
},
];
}
const output = gitText(repoRoot, [
'ls-tree',
'-r',
'--name-only',
tempRef,
'--',
sourceInfo.path,
]);
if (!output) {
throw new Error(`远端目录下没有可同步文件:${sourceInfo.path}`);
}
return output
.split('\n')
.filter(Boolean)
.map((sourceFile) => {
const relativePath = path.posix.relative(sourceInfo.path, sourceFile);
return {
defaultTargetName: path.posix.basename(sourceFile),
relativePath,
sourceFile,
sourceLabelPath: sourceFile,
stateKey: relativePath,
};
});
}
/**
* 把远端文件内容导出到本地临时目录,并补齐 `tempFilePath` 字段。
*
* 导出之后,每一个 `SourceEntry` 都会变成一个“可直接拿来 merge 的本地临时文件”,
* 这样后续统一交给 `git merge-file` 处理即可。
*
* @returns {SourceEntry[]} 返回已经补齐 tempFilePath 的待同步文件列表。
*/
function exportSourceFiles(
repoRoot,
tempRef,
tempSourceDir,
sourceInfo,
sourceEntries,
) {
console.log(
`[2/4] 提取${sourceInfo.kind === 'file' ? '文件' : '目录'}:${sourceInfo.path}`,
);
return sourceEntries.map((entry) => {
const tempFilePath = path.join(tempSourceDir, entry.stateKey);
const content = gitBuffer(repoRoot, [
'show',
`${tempRef}:${entry.sourceFile}`,
]);
fs.mkdirSync(path.dirname(tempFilePath), { recursive: true });
fs.writeFileSync(tempFilePath, content);
return {
...entry,
tempFilePath,
};
});
}
function findBlockingAncestor(filePath) {
let current = path.dirname(filePath);
while (true) {
if (fs.existsSync(current)) {
return fs.statSync(current).isDirectory() ? '' : current;
}
const parent = path.dirname(current);
if (parent === current) {
return '';
}
current = parent;
}
}
function tryWriteFile(filePath, content) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
}
function canUseFilePath(filePath) {
const blockingAncestor = findBlockingAncestor(filePath);
if (blockingAncestor) {
return false;
}
if (!fs.existsSync(filePath)) {
return true;
}
return fs.statSync(filePath).isFile();
}
function toRepoRelative(repoRoot, absolutePath) {
return path.relative(repoRoot, absolutePath).replaceAll(path.sep, '/') || '.';
}
function createTaskKey(config) {
return createHash('sha1')
.update(
JSON.stringify({
repo: config.repo,
branch: config.branch,
sourceDir: config.sourceDir,
targetDir: config.targetDir,
}),
)
.digest('hex')
.slice(0, 12);
}
function makeTargetLabel(targetDir) {
return (
targetDir.replaceAll('/', '__').replace(/^_+/u, '').replace(/_+$/u, '') ||
'target'
);
}
function getStateRoot(gitDir, config) {
return path.join(
gitDir,
'sync-state',
`${makeTargetLabel(config.targetDir)}-${createTaskKey(config)}`,
);
}
/**
* 在正式同步前,按“当前任务维度”清理旧的基线快照目录。
*
* 这里删掉的不是远端内容,也不是当前仓库的提交历史,而只是脚本自己放在 `.git/sync-state`
* 下面的本地缓存。任务维度由 `repo + branch + sourceDir + targetDir` 共同决定,
* 所以只会影响这一次正在执行的同步配置,不会误删别的同步记录。
*
* 额外约束:
* - `--dry-run` 时不做任何清理,避免“只是预览一下”却把本地状态改掉
* - `--keep-state` 时保留旧基线,允许显式回到原来的三方合并策略
*
* @returns {string} 返回被清理掉的任务基线路径;如果本次没有清理,则返回空字符串。
*/
function clearTaskStateBeforeSync(gitDir, config) {
if (config.dryRun || !config.resetTaskStateBeforeSync) {
return '';
}
const stateRoot = getStateRoot(gitDir, config);
if (!fs.existsSync(stateRoot)) {
return '';
}
fs.rmSync(stateRoot, { recursive: true, force: true });
return stateRoot;
}
function getBaseFilePath(stateRoot, stateKey) {
return path.join(stateRoot, 'base', stateKey);
}
function saveBaseSnapshot(stateRoot, stateKey, content) {
tryWriteFile(getBaseFilePath(stateRoot, stateKey), content);
}
function isProbablyBinary(buffer) {
return buffer.includes(0);
}
function runMergeFile(localFilePath, baseFilePath, remoteFilePath, labels) {
const args = [
'merge-file',
'-p',
'-L',
labels.local,
'-L',
labels.base,
'-L',
labels.remote,
localFilePath,
baseFilePath,
remoteFilePath,
];
try {
const output = execFileSync('git', args, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
maxBuffer: 20 * 1024 * 1024,
});
return {
exitCode: 0,
output,
stderr: '',
};
} catch (error) {
if (typeof error?.status === 'number') {
return {
exitCode: error.status,
output: Buffer.isBuffer(error.stdout)
? error.stdout.toString('utf8')
: String(error.stdout ?? ''),
stderr: Buffer.isBuffer(error.stderr)
? error.stderr.toString('utf8')
: String(error.stderr ?? ''),
};
}
throw error;
}
}
/**
* 判断 `git merge-file` 这次返回的是“冲突结果”还是“真正执行失败”。
*
* 这里容易踩坑的点在于:`git merge-file` 的退出码不是只有 0 和 1 两种。
* 按官方文档,它在成功执行时会返回“冲突块数量”:
* - `0` 表示无冲突、合并干净
* - `1 ~ 127` 表示有这么多个冲突块,输出内容里已经带了 `<<<<<<<` 标记
*
* 真正的执行失败通常会表现成:
* - Git 自己报 usage / 参数错误,常见退出码是 `128+`
* - 或者底层异常导致根本没有得到可用的合并输出
*
* 所以这里不能把 `> 1` 直接当失败;否则像“4 个冲突块”这种完全正常的结果,
* 就会被误判成失败,最终既不写回文件,也看不到冲突标记。
*/
function isMergeFileExecutionError(mergeResult) {
if (mergeResult.exitCode >= 0 && mergeResult.exitCode < 128) {
return false;
}
return true;
}
function getChangeKind(repoRoot, targetFilePath, blockingAncestor) {
if (blockingAncestor) {
return `目标目录的父级路径被文件占用:${toRepoRelative(repoRoot, blockingAncestor)}`;
}
if (fs.existsSync(targetFilePath) && !fs.statSync(targetFilePath).isFile()) {
return '目标路径已存在,但它不是普通文件';
}
return '目标文件已存在,且内容与远端不同';
}
/**
* 生成传给 `git merge-file` 的 3 个标签对象。
*
* 这些标签最终会直接显示在冲突标记里,因此命名一定要可读,
* 否则用户后面看到 `<<<<<<<` 时根本分不清哪一段是哪一边。
*
* @returns {MergeLabels} 返回会写进 Git 冲突标记中的三方标签对象。
*/
function buildMergeLabels(targetPath, sourcePath) {
return {
local: `LOCAL:${targetPath}`,
base: 'BASE:last-synced-remote',
remote: `REMOTE:${sourcePath}`,
};
}
function getBinaryConflictCopyPath(repoRoot, targetFilePath, targetPathLabel) {
const preferredPath = `${targetFilePath}${BINARY_CONFLICT_SUFFIX}`;
if (canUseFilePath(preferredPath)) {
return preferredPath;
}
return path.join(
repoRoot,
BINARY_CONFLICT_FALLBACK_DIR,
`${targetPathLabel}${BINARY_CONFLICT_SUFFIX}`,
);
}
function writeBinaryConflictCopy(
repoRoot,
targetFilePath,
targetPathLabel,
content,
) {
const copyPath = getBinaryConflictCopyPath(
repoRoot,
targetFilePath,
targetPathLabel,
);
tryWriteFile(copyPath, content);
return copyPath;
}
function resolveTargetStrategy(repoRoot, config, sourceInfo) {
const targetPath = resolvePathInsideRepo(
repoRoot,
config.targetDir,
'--target',
);
const targetExists = fs.existsSync(targetPath);
if (sourceInfo.kind === 'directory') {
if (targetExists && !fs.statSync(targetPath).isDirectory()) {
throw new Error(
'--source 是目录时,--target 必须是目录路径,不能指向已有文件',
);
}
return {
kind: 'directory',
targetRoot: targetPath,
};
}
if (targetExists) {
if (fs.statSync(targetPath).isDirectory()) {
return {
kind: 'directory',
targetRoot: targetPath,
};
}
return {
kind: 'file',
targetFilePath: targetPath,
};
}
if (config.targetTreatAsDirectory) {
return {
kind: 'directory',
targetRoot: targetPath,
};
}
return {
kind: 'file',
targetFilePath: targetPath,
};
}
function getTargetFilePath(targetStrategy, entry) {
if (targetStrategy.kind === 'file') {
return targetStrategy.targetFilePath;
}
return path.join(
targetStrategy.targetRoot,
entry.relativePath || entry.defaultTargetName,
);
}
function syncFiles(
repoRoot,
gitDir,
config,
sourceInfo,
sourceEntries,
tempDir,
) {
console.log(`[3/4] 开始合并到:${config.targetDir}`);
const stateRoot = getStateRoot(gitDir, config);
const targetStrategy = resolveTargetStrategy(repoRoot, config, sourceInfo);
const emptyBasePath = path.join(tempDir, 'empty-base.txt');
/**
* 本次同步的汇总统计对象。
*
* 这里每个数组都代表一种处理结果分组:
* - `created`:这次新增到了目标目录的文件
* - `identical`:本地与远端完全一致,因此跳过的文件
* - `merged`:三方合并成功、无需人工处理的文件
* - `conflicts`:已经把 `<<<<<<<` 标记写进目标文件的文本冲突
* - `binaryCopies`:因为是二进制冲突,所以额外生成了副本的文件
* - `manual`:结构冲突或其他脚本无法自动完成的情况
*
* @type {MergeSummary}
*/
const summary = {
created: [],
identical: [],
merged: [],
conflicts: [],
binaryCopies: [],
manual: [],
};
fs.writeFileSync(emptyBasePath, '');
for (const entry of sourceEntries) {
const targetFilePath = getTargetFilePath(targetStrategy, entry);
const targetPathLabel = toRepoRelative(repoRoot, targetFilePath);
const sourceContent = fs.readFileSync(entry.tempFilePath);
const targetExists = fs.existsSync(targetFilePath);
const blockingAncestor = findBlockingAncestor(targetFilePath);
if (!targetExists && !blockingAncestor) {
summary.created.push(targetPathLabel);
if (!config.dryRun) {
tryWriteFile(targetFilePath, sourceContent);
saveBaseSnapshot(stateRoot, entry.stateKey, sourceContent);
}
continue;
}
if (!targetExists || !fs.statSync(targetFilePath).isFile()) {
summary.manual.push({
sourcePath: entry.sourceLabelPath,
targetPath: targetPathLabel,
reason: getChangeKind(repoRoot, targetFilePath, blockingAncestor),
});
continue;
}
const targetContent = fs.readFileSync(targetFilePath);
if (sourceContent.equals(targetContent)) {
summary.identical.push(targetPathLabel);
if (!config.dryRun) {
saveBaseSnapshot(stateRoot, entry.stateKey, sourceContent);
}
continue;
}
const baseFilePath = getBaseFilePath(stateRoot, entry.stateKey);
const hasBaseSnapshot = fs.existsSync(baseFilePath);
const baseContent = hasBaseSnapshot
? fs.readFileSync(baseFilePath)
: Buffer.from('');
if (
isProbablyBinary(sourceContent) ||
isProbablyBinary(targetContent) ||
isProbablyBinary(baseContent)
) {
const copyPath = config.dryRun
? getBinaryConflictCopyPath(repoRoot, targetFilePath, targetPathLabel)
: writeBinaryConflictCopy(
repoRoot,
targetFilePath,
targetPathLabel,
sourceContent,
);
if (!config.dryRun) {
saveBaseSnapshot(stateRoot, entry.stateKey, sourceContent);
}
summary.binaryCopies.push({
sourcePath: entry.sourceLabelPath,
targetPath: targetPathLabel,
copyPath: toRepoRelative(repoRoot, copyPath),
reason: '检测到二进制文件冲突,已生成远端副本,请手动比对合并',
});
continue;
}
const mergeResult = runMergeFile(
targetFilePath,
hasBaseSnapshot ? baseFilePath : emptyBasePath,
entry.tempFilePath,
buildMergeLabels(targetPathLabel, entry.sourceLabelPath),
);
if (isMergeFileExecutionError(mergeResult)) {
const detail = mergeResult.stderr.trim() || 'git merge-file 执行失败';
summary.manual.push({
sourcePath: entry.sourceLabelPath,
targetPath: targetPathLabel,
reason: detail,
});
continue;
}