dsh-profile-config-sync 0.4.0 → 0.5.0
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/client.js +190 -24
- package/index.js +392 -76
- package/package.json +1 -1
- package/runtime/post-exit.ps1 +22 -4
- package/runtime/sync-engine.mjs +50 -2
- package/runtime/sync.ps1 +190 -35
- package/runtime/webdav.mjs +115 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-profile-config-sync",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。支持 Windows(PowerShell)/ macOS / Linux(Node 引擎),并可选 WebDAV 作为传输层。面板与文案跟随客户端语言(中文/English)。",
|
|
6
6
|
"main": "./index.js",
|
package/runtime/post-exit.ps1
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
<#
|
|
2
2
|
退出后执行同步:等 DSH 完全退出,再跑 pull 或 push(插件在 DSH 进程里,自己等不了自己退出)
|
|
3
3
|
|
|
4
4
|
由插件在 DSH 运行期用 detached 方式拉起:
|
|
@@ -28,6 +28,8 @@ param(
|
|
|
28
28
|
[switch]$Restart,
|
|
29
29
|
[int]$MaxWaitMinutes = 30,
|
|
30
30
|
[string]$LogFile,
|
|
31
|
+
# 仅 Phase=wait 用:由外部启动器(如 ShellExecute 脱离 Job Object)回读本进程真实 PID
|
|
32
|
+
[string]$PidFile = '',
|
|
31
33
|
# ---- 仅 -Mode restore 用:还原到哪份快照 ----
|
|
32
34
|
[string]$BackupDir = '',
|
|
33
35
|
# 备份类型:profile(配置快照,默认)/ plugin(插件本体备份)/ session(会话目录备份)
|
|
@@ -46,6 +48,13 @@ param(
|
|
|
46
48
|
# 为什么要分两段:窗口必须**在 DSH 退出之后**才出现。排队阶段就弹窗的话,
|
|
47
49
|
# 用户从开机到关窗口这段时间会一直挂着一个"等 DSH 退出"的黑窗,什么也干不了还挡着视线。
|
|
48
50
|
if ($Phase -eq 'wait') {
|
|
51
|
+
if ($PidFile) {
|
|
52
|
+
try {
|
|
53
|
+
$pdir = Split-Path -Parent $PidFile
|
|
54
|
+
if ($pdir -and -not (Test-Path -LiteralPath $pdir)) { New-Item -ItemType Directory -Path $pdir -Force | Out-Null }
|
|
55
|
+
[IO.File]::WriteAllText($PidFile, [string]$PID, (New-Object Text.UTF8Encoding $false))
|
|
56
|
+
} catch { }
|
|
57
|
+
}
|
|
49
58
|
$deadline = (Get-Date).AddMinutes($MaxWaitMinutes)
|
|
50
59
|
$noWindowTicks = 0
|
|
51
60
|
$waitLog = Join-Path $DshHome 'logs\auto-sync-wait.log'
|
|
@@ -97,7 +106,15 @@ if ($Phase -eq 'wait') {
|
|
|
97
106
|
if ($UpdateTgz) { $relay += @('-UpdateTgz', $UpdateTgz) }
|
|
98
107
|
if ($UpdateSha256) { $relay += @('-UpdateSha256', $UpdateSha256) }
|
|
99
108
|
if ($UpdateToken) { $relay += @('-UpdateToken', $UpdateToken) }
|
|
100
|
-
|
|
109
|
+
# PowerShell 5.1 的 Start-Process -ArgumentList 会直接用空格拼接数组元素,不会自动给含空格的路径加引号;
|
|
110
|
+
# AppRoot(例如 ...\DeepSeek Harness)带空格时直接参数绑定失败退出。这里显式按 Windows argv 规则加引号。
|
|
111
|
+
function Quote-WinArg([string]$s) {
|
|
112
|
+
if ($null -eq $s -or $s -eq '') { return '""' }
|
|
113
|
+
if ($s -notmatch '[\s"]') { return $s }
|
|
114
|
+
return '"' + ($s -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"'
|
|
115
|
+
}
|
|
116
|
+
$quotedRelay = @($relay | ForEach-Object { Quote-WinArg ([string]$_) })
|
|
117
|
+
try { Start-Process -FilePath $pwshExe -ArgumentList $quotedRelay -WindowStyle Normal | Out-Null } catch { }
|
|
101
118
|
exit 0
|
|
102
119
|
}
|
|
103
120
|
|
|
@@ -720,13 +737,14 @@ if ($AppRoot) { $syncArgs['AppRoot'] = $AppRoot }
|
|
|
720
737
|
# ---------- pull 前留一张底:HEAD + 备份快照清单 ----------
|
|
721
738
|
$git = Get-GitExe
|
|
722
739
|
$headBefore = ''
|
|
740
|
+
$hasGitRepo = $RepoRoot -and (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))
|
|
723
741
|
$backupRoot = Join-Path $DshHome 'backups'
|
|
724
742
|
$backupsBefore = @()
|
|
725
743
|
if ($Mode -eq 'pull') {
|
|
726
|
-
if ($git) {
|
|
744
|
+
if ($git -and $hasGitRepo) {
|
|
727
745
|
$headBefore = (& $git -C $RepoRoot rev-parse HEAD 2>$null | Out-String).Trim()
|
|
728
746
|
Log ("拉取前 HEAD:{0}" -f $headBefore)
|
|
729
|
-
}
|
|
747
|
+
} elseif (-not $git) {
|
|
730
748
|
Log '找不到 git.exe,失败时将无法回滚仓库(只能回滚配置)'
|
|
731
749
|
}
|
|
732
750
|
if (Test-Path -LiteralPath $backupRoot) {
|
package/runtime/sync-engine.mjs
CHANGED
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
} from './platform.mjs'
|
|
30
30
|
import { buildContract, contractPath, contractText, readContract } from './contract.mjs'
|
|
31
31
|
import { listMachines, localMachineInfo, writeMachineInfo } from './machines.mjs'
|
|
32
|
+
import { downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive } from './webdav.mjs'
|
|
32
33
|
|
|
33
34
|
/** 占位符:仓库里存这些,落地时展开成本机路径。 */
|
|
34
35
|
export const TOKENS = {
|
|
@@ -696,6 +697,16 @@ function parseArgs(argv) {
|
|
|
696
697
|
return out
|
|
697
698
|
}
|
|
698
699
|
|
|
700
|
+
function readSyncSettings(dshHome) {
|
|
701
|
+
try {
|
|
702
|
+
const p = join(dshHome, 'dsh-config-sync.json')
|
|
703
|
+
if (!existsSync(p)) return {}
|
|
704
|
+
return JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
|
|
705
|
+
} catch {
|
|
706
|
+
return {}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
699
710
|
/** 命令行主流程。返回进程退出码。 */
|
|
700
711
|
export async function runCli(argv) {
|
|
701
712
|
const [cmd, ...rest] = argv
|
|
@@ -705,6 +716,9 @@ export async function runCli(argv) {
|
|
|
705
716
|
const appRoot = a.AppRoot || a.appRoot || ''
|
|
706
717
|
const workspaceHome = a.WorkspaceHome || a.workspaceHome || ''
|
|
707
718
|
const profileName = a.ProfileName || a.profileName || 'desktop'
|
|
719
|
+
const syncSettings = readSyncSettings(dshHome)
|
|
720
|
+
const useWebdav = webdavActive(syncSettings)
|
|
721
|
+
const w = normalizeWebdav(syncSettings)
|
|
708
722
|
|
|
709
723
|
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
710
724
|
console.log([
|
|
@@ -735,15 +749,49 @@ export async function runCli(argv) {
|
|
|
735
749
|
return 0
|
|
736
750
|
}
|
|
737
751
|
if (cmd === 'push') {
|
|
752
|
+
if (useWebdav) {
|
|
753
|
+
if (!isSecureUrl(w.url)) {
|
|
754
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
755
|
+
return 1
|
|
756
|
+
}
|
|
757
|
+
const repoReady = existsSync(join(repoRoot, 'profile', 'package.json'))
|
|
758
|
+
if (!repoReady) {
|
|
759
|
+
const probe = await testConnection(w)
|
|
760
|
+
if (!probe.ok) { console.error(`WebDAV 探测失败:${probe.error}`); return 1 }
|
|
761
|
+
if (probe.files > 0) { console.error('云端 WebDAV 已有内容,本机还是空的,请先执行拉取'); return 1 }
|
|
762
|
+
mkdirSync(repoRoot, { recursive: true })
|
|
763
|
+
}
|
|
764
|
+
}
|
|
738
765
|
const r = capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName })
|
|
739
766
|
for (const c of r.changed) console.log(` + ${c}`)
|
|
740
767
|
for (const e of r.errors) console.error(` [!] ${e}`)
|
|
741
768
|
console.log(`capture 完成:${r.files} 个文件 / ${r.bytes} 字节,变更 ${r.changed.length} 项`)
|
|
742
|
-
|
|
769
|
+
if (!r.ok) return 1
|
|
770
|
+
if (useWebdav) {
|
|
771
|
+
const up = await uploadRepo(w, repoRoot)
|
|
772
|
+
for (const e of up.errors) console.error(` [!] ${e}`)
|
|
773
|
+
console.log(`WebDAV 上传:上传 ${up.uploaded.length} · 跳过 ${up.skipped.length} · 错误 ${up.errors.length}`)
|
|
774
|
+
return up.ok ? 0 : 1
|
|
775
|
+
}
|
|
776
|
+
return 0
|
|
743
777
|
}
|
|
744
778
|
if (cmd === 'pull') {
|
|
779
|
+
if (useWebdav) {
|
|
780
|
+
if (!isSecureUrl(w.url)) {
|
|
781
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
782
|
+
return 1
|
|
783
|
+
}
|
|
784
|
+
const probe = await testConnection(w)
|
|
785
|
+
if (!probe.ok) { console.error(`WebDAV 探测失败:${probe.error}`); return 1 }
|
|
786
|
+
if (!probe.exists || probe.files <= 0) { console.error('云端 WebDAV 目录里还没有内容,请先在一台机器推送'); return 1 }
|
|
787
|
+
mkdirSync(repoRoot, { recursive: true })
|
|
788
|
+
const dn = await downloadRepo(w, repoRoot)
|
|
789
|
+
for (const e of dn.errors) console.error(` [!] ${e}`)
|
|
790
|
+
console.log(`WebDAV 下载:下载 ${dn.downloaded.length} · 跳过 ${dn.skipped.length} · 冲突 ${dn.conflicts.length} · 错误 ${dn.errors.length}`)
|
|
791
|
+
if (!dn.ok) return 1
|
|
792
|
+
}
|
|
745
793
|
const r = apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName })
|
|
746
|
-
for (const
|
|
794
|
+
for (const wItem of r.written) console.log(` > ${wItem}`)
|
|
747
795
|
for (const s of r.skipped) console.log(` - 跳过 ${s}`)
|
|
748
796
|
for (const e of r.errors) console.error(` [!] ${e}`)
|
|
749
797
|
if (r.backupDir) console.log(` 被覆盖的本机文件已留底:${r.backupDir}`)
|
package/runtime/sync.ps1
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
<#
|
|
2
2
|
DSH 配置同步 —— 一条命令入口(把原来的「capture + git add + commit + push」和「git pull + apply」各收成一次调用)
|
|
3
3
|
|
|
4
4
|
用法
|
|
@@ -47,9 +47,25 @@ if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
|
|
|
47
47
|
# 本动作的未同步清单从这里起算(pull 也要清:上一轮 push 的清单不能挂到这次拉取头上)
|
|
48
48
|
Reset-SyncNotices $DshHome $Action
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
function Get-SyncSettings {
|
|
51
|
+
$p = Join-Path $DshHome 'dsh-config-sync.json'
|
|
52
|
+
if (-not (Test-Path -LiteralPath $p)) { return $null }
|
|
53
|
+
try { return (Get-Content -LiteralPath $p -Raw -Encoding utf8 | ConvertFrom-Json) } catch { return $null }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function Test-WebdavActive($s) {
|
|
57
|
+
if (-not $s) { return $false }
|
|
58
|
+
$mode = [string]$s.syncMode
|
|
59
|
+
$url = ([string]$s.webdavUrl).Trim()
|
|
60
|
+
return (($mode -eq 'webdav' -or $mode -eq 'auto') -and [bool]$url)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
$SyncSettings = Get-SyncSettings
|
|
64
|
+
$UseWebdav = Test-WebdavActive $SyncSettings
|
|
65
|
+
|
|
66
|
+
# git 位置探测统一在 dsh-sync-common.ps1 里(Get-GitExe);WebDAV 模式不依赖 git
|
|
51
67
|
$git = Get-GitExe
|
|
52
|
-
if (-not $git) { Die "找不到 git.exe。请先安装 Git 并加入 PATH。" }
|
|
68
|
+
if (-not $git -and -not $UseWebdav) { Die "找不到 git.exe。请先安装 Git 并加入 PATH。" }
|
|
53
69
|
|
|
54
70
|
# 客户端装哪个盘不是固定的(会被卸载重装到别处),所以 -AppRoot 传进来的值先校验,
|
|
55
71
|
# 对不上就按注册表/常见位置重新定位 —— 老脚本里写死的旧路径因此不会把整条链路带偏。
|
|
@@ -104,7 +120,9 @@ function Write-SyncState([string]$Mode) {
|
|
|
104
120
|
try {
|
|
105
121
|
if (-not (Test-Path -LiteralPath $DshHome)) { New-Item -ItemType Directory -Path $DshHome -Force | Out-Null }
|
|
106
122
|
$head = ''
|
|
107
|
-
|
|
123
|
+
if ($git -and (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))) {
|
|
124
|
+
try { $head = ((& $git -C $RepoRoot log -1 --format='%h' 2>$null) | Out-String).Trim() } catch {}
|
|
125
|
+
}
|
|
108
126
|
$state = [ordered]@{
|
|
109
127
|
lastSyncAt = (Get-Date).ToString('o')
|
|
110
128
|
mode = $Mode
|
|
@@ -409,10 +427,20 @@ function Restore-LocalKept($Report) {
|
|
|
409
427
|
|
|
410
428
|
# ---------- status ----------
|
|
411
429
|
if ($Action -eq 'status') {
|
|
412
|
-
$
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
430
|
+
if ($UseWebdav) {
|
|
431
|
+
Say ("传输方式:WebDAV({0} / {1})" -f $SyncSettings.webdavUrl, $(if ($SyncSettings.webdavDir) { $SyncSettings.webdavDir } else { 'dsh-config-sync' }))
|
|
432
|
+
$wp = Invoke-WebdavAction 'probe'
|
|
433
|
+
if ($wp.ok) { Ok ("WebDAV 已连通(云端 {0} 项)" -f [int]$wp.files) }
|
|
434
|
+
else { Warn ("WebDAV 探测失败:{0}" -f $wp.error) }
|
|
435
|
+
}
|
|
436
|
+
if ($git -and (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))) {
|
|
437
|
+
$st = Get-RepoState
|
|
438
|
+
Say "分支:$($st.Branch)"
|
|
439
|
+
Say "HEAD:$($st.Head)"
|
|
440
|
+
if ($st.Dirty -eq 0) { Ok "工作区干净" } else { Warn "工作区有 $($st.Dirty) 项未提交" }
|
|
441
|
+
} elseif (-not $UseWebdav) {
|
|
442
|
+
Warn "目录还没有 .git:$RepoRoot"
|
|
443
|
+
}
|
|
416
444
|
$app = Get-HostAppVersion $AppRoot
|
|
417
445
|
$contract = $null
|
|
418
446
|
$cp = Join-Path $RepoRoot 'profile\host-contract.json'
|
|
@@ -520,41 +548,17 @@ function Get-RemoteFileCount([string]$RemoteUrl, [int]$Heads = -2) {
|
|
|
520
548
|
少拷了它们,远端就变成「只有 settings 没有执行体」的半截仓库,另一台 pull 下来跑不起来。
|
|
521
549
|
profile\host-contract.json 用本机客户端版本生成(apply 靠它校验两端版本,缺了只会跳过校验)。
|
|
522
550
|
#>
|
|
523
|
-
function Initialize-
|
|
524
|
-
if (-not $RemoteUrl) {
|
|
525
|
-
Die ("本机仓库还是空的($RepoRoot),也没读到云端仓库地址:" +
|
|
526
|
-
"请先在面板「云端仓库」里填好地址并保存,再重跑本脚本。")
|
|
527
|
-
}
|
|
551
|
+
function Initialize-RepoSkeleton {
|
|
528
552
|
if (-not (Test-Path -LiteralPath $RepoRoot)) { New-Item -ItemType Directory -Path $RepoRoot -Force | Out-Null }
|
|
529
|
-
Say ""
|
|
530
|
-
Say "== 初始化仓库(首次推送) =="
|
|
531
|
-
Say " 目录:$RepoRoot"
|
|
532
|
-
Say " 云端:$RemoteUrl(空仓库)"
|
|
533
|
-
if (-not (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))) {
|
|
534
|
-
$initLine = '"' + $git + '" -C "' + $RepoRoot + '" init --initial-branch=main 2>&1'
|
|
535
|
-
& "$env:ComSpec" /c $initLine | Out-Null
|
|
536
|
-
if ($LASTEXITCODE -ne 0) {
|
|
537
|
-
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" init 2>&1') | Out-Null
|
|
538
|
-
if ($LASTEXITCODE -ne 0) { Die "git init 失败:$RepoRoot" }
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
$originUrl = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote get-url origin 2>nul')) -join '').Trim()
|
|
542
|
-
if ($originUrl) {
|
|
543
|
-
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote set-url origin "' + $RemoteUrl + '" 2>&1') | Out-Null
|
|
544
|
-
} else {
|
|
545
|
-
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote add origin "' + $RemoteUrl + '" 2>&1') | Out-Null
|
|
546
|
-
}
|
|
547
|
-
if ($LASTEXITCODE -ne 0) { Die "给仓库加 origin 失败:$RemoteUrl" }
|
|
548
|
-
|
|
549
553
|
$copied = 0
|
|
550
|
-
foreach ($n in @('apply.ps1', 'capture.ps1', 'sync.ps1', 'restore.ps1', 'post-exit.ps1', 'dsh-sync-common.ps1')) {
|
|
554
|
+
foreach ($n in @('apply.ps1', 'capture.ps1', 'sync.ps1', 'restore.ps1', 'post-exit.ps1', 'dsh-sync-common.ps1', 'webdav.mjs')) {
|
|
551
555
|
$src = Join-Path $PSScriptRoot $n
|
|
552
556
|
if (Test-Path -LiteralPath $src) {
|
|
553
557
|
Copy-Item -LiteralPath $src -Destination (Join-Path $RepoRoot $n) -Force
|
|
554
558
|
$copied++
|
|
555
559
|
}
|
|
556
560
|
}
|
|
557
|
-
if ($copied -gt 0) { Ok "已写入仓库骨架:$copied 个执行体(apply / capture / sync / restore / post-exit / common)" }
|
|
561
|
+
if ($copied -gt 0) { Ok "已写入仓库骨架:$copied 个执行体(apply / capture / sync / restore / post-exit / common / webdav)" }
|
|
558
562
|
# tools\fix-session-cwd.mjs 也随仓库同步(apply 在没有插件副本时会用它修会话工作目录),
|
|
559
563
|
# 初始化骨架漏掉它,配置仓库就永远缺这一份,自检的逐字节一致性断言也会一直红。
|
|
560
564
|
$toolSrc = Join-Path (Join-Path $PSScriptRoot 'tools') 'fix-session-cwd.mjs'
|
|
@@ -590,6 +594,79 @@ function Initialize-EmptyRepo([string]$RemoteUrl) {
|
|
|
590
594
|
Warn "读不到本机客户端版本,跳过 profile\host-contract.json(另一台 pull 时会跳过版本校验)"
|
|
591
595
|
}
|
|
592
596
|
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function Get-NodeExeForWebdav {
|
|
600
|
+
foreach ($c in @(
|
|
601
|
+
(Join-Path $AppRoot 'resources\runtime\primary-runtime\dependencies\node\bin\node.exe'),
|
|
602
|
+
(Join-Path $AppRoot 'resources\runtime\bin\node.exe'),
|
|
603
|
+
(Join-Path $AppRoot 'resources\runtime\node.exe')
|
|
604
|
+
)) {
|
|
605
|
+
if ($c -and (Test-Path -LiteralPath $c)) { return $c }
|
|
606
|
+
}
|
|
607
|
+
$cmd = Get-Command node.exe -ErrorAction SilentlyContinue
|
|
608
|
+
if ($cmd) { return $cmd.Source }
|
|
609
|
+
return $null
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function Find-WebdavScript {
|
|
613
|
+
foreach ($c in @(
|
|
614
|
+
(Join-Path $PSScriptRoot 'webdav.mjs'),
|
|
615
|
+
(Join-Path $RepoRoot 'webdav.mjs')
|
|
616
|
+
)) {
|
|
617
|
+
if ($c -and (Test-Path -LiteralPath $c)) { return $c }
|
|
618
|
+
}
|
|
619
|
+
return $null
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function Invoke-WebdavAction([string]$SubCmd) {
|
|
623
|
+
$nodeExe = Get-NodeExeForWebdav
|
|
624
|
+
if (-not $nodeExe) { Die "找不到 node.exe,无法执行 WebDAV 同步(请确认客户端完整或已安装 Node.js)。" }
|
|
625
|
+
$script = Find-WebdavScript
|
|
626
|
+
if (-not $script) { Die "找不到 webdav.mjs,无法执行 WebDAV 同步。" }
|
|
627
|
+
$eap = $ErrorActionPreference
|
|
628
|
+
$ErrorActionPreference = 'Continue'
|
|
629
|
+
$out = (& $nodeExe $script $SubCmd -DshHome $DshHome -RepoRoot $RepoRoot 2>&1 | Out-String)
|
|
630
|
+
$code = $LASTEXITCODE
|
|
631
|
+
$ErrorActionPreference = $eap
|
|
632
|
+
if ($SubCmd -eq 'probe') {
|
|
633
|
+
$line = ($out -split "`r?`n" | Where-Object { $_.Trim().StartsWith('{') } | Select-Object -Last 1)
|
|
634
|
+
if (-not $line) { return [pscustomobject]@{ ok = $false; error = ($out.Trim()) } }
|
|
635
|
+
try { return ($line | ConvertFrom-Json) } catch { return [pscustomobject]@{ ok = $false; error = ($out.Trim()) } }
|
|
636
|
+
}
|
|
637
|
+
foreach ($l in ($out -split "`r?`n")) {
|
|
638
|
+
if ($l -and $l.Trim()) { Say (' ' + $l.TrimEnd()) }
|
|
639
|
+
}
|
|
640
|
+
if ($code -ne 0) { Die ("WebDAV $SubCmd 失败(退出码 $code)。") }
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function Initialize-EmptyRepo([string]$RemoteUrl) {
|
|
644
|
+
if (-not $RemoteUrl) {
|
|
645
|
+
Die ("本机仓库还是空的($RepoRoot),也没读到云端仓库地址:" +
|
|
646
|
+
"请先在面板「云端仓库」里填好地址并保存,再重跑本脚本。")
|
|
647
|
+
}
|
|
648
|
+
if (-not (Test-Path -LiteralPath $RepoRoot)) { New-Item -ItemType Directory -Path $RepoRoot -Force | Out-Null }
|
|
649
|
+
Say ""
|
|
650
|
+
Say "== 初始化仓库(首次推送) =="
|
|
651
|
+
Say " 目录:$RepoRoot"
|
|
652
|
+
Say " 云端:$RemoteUrl(空仓库)"
|
|
653
|
+
if (-not (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))) {
|
|
654
|
+
$initLine = '"' + $git + '" -C "' + $RepoRoot + '" init --initial-branch=main 2>&1'
|
|
655
|
+
& "$env:ComSpec" /c $initLine | Out-Null
|
|
656
|
+
if ($LASTEXITCODE -ne 0) {
|
|
657
|
+
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" init 2>&1') | Out-Null
|
|
658
|
+
if ($LASTEXITCODE -ne 0) { Die "git init 失败:$RepoRoot" }
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
$originUrl = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote get-url origin 2>nul')) -join '').Trim()
|
|
662
|
+
if ($originUrl) {
|
|
663
|
+
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote set-url origin "' + $RemoteUrl + '" 2>&1') | Out-Null
|
|
664
|
+
} else {
|
|
665
|
+
& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote add origin "' + $RemoteUrl + '" 2>&1') | Out-Null
|
|
666
|
+
}
|
|
667
|
+
if ($LASTEXITCODE -ne 0) { Die "给仓库加 origin 失败:$RemoteUrl" }
|
|
668
|
+
|
|
669
|
+
Initialize-RepoSkeleton
|
|
593
670
|
Ok "已初始化空仓库并指向 origin"
|
|
594
671
|
}
|
|
595
672
|
|
|
@@ -639,6 +716,57 @@ function Initialize-RepoIfNeeded {
|
|
|
639
716
|
|
|
640
717
|
# ---------- push ----------
|
|
641
718
|
if ($Action -eq 'push') {
|
|
719
|
+
if ($UseWebdav) {
|
|
720
|
+
$repoReady = (Test-Path -LiteralPath (Join-Path $RepoRoot 'apply.ps1')) -and (Test-Path -LiteralPath (Join-Path $RepoRoot 'profile\package.json'))
|
|
721
|
+
if (-not $repoReady) {
|
|
722
|
+
if (Test-Path -LiteralPath $RepoRoot) {
|
|
723
|
+
$stray = @(Get-ChildItem -LiteralPath $RepoRoot -Force |
|
|
724
|
+
Where-Object { -not $_.Name.StartsWith('.') -and $_.Name -notmatch '^同步-[\s\S]*\.(cmd|sh)$' })
|
|
725
|
+
if ($stray.Count -gt 0) {
|
|
726
|
+
$isSyncRepo = (Test-Path -LiteralPath (Join-Path $RepoRoot 'dsh-sync-common.ps1')) -or
|
|
727
|
+
(Test-Path -LiteralPath (Join-Path $RepoRoot 'sync.ps1')) -or
|
|
728
|
+
(Test-Path -LiteralPath (Join-Path $RepoRoot 'capture.ps1'))
|
|
729
|
+
if (-not $isSyncRepo) {
|
|
730
|
+
Warn ("这个目录不是空的({0} 项:{1}),也不像 dsh-config 仓库:{2}" -f `
|
|
731
|
+
$stray.Count, (($stray | Select-Object -First 3 | ForEach-Object { $_.Name }) -join '、'), $RepoRoot)
|
|
732
|
+
Die "已停止(未抓取、未上传)。请在面板「本机仓库」里重新设路径。"
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
$wp = Invoke-WebdavAction 'probe'
|
|
737
|
+
if (-not $wp.ok) {
|
|
738
|
+
Warn ("连不上 WebDAV({0}):{1}" -f $SyncSettings.webdavUrl, $wp.error)
|
|
739
|
+
Die "已停止(未抓取、未上传)。请先在 WebDAV 卡里确认地址/凭据能连通,再重跑。"
|
|
740
|
+
}
|
|
741
|
+
if ([int]$wp.files -gt 0) {
|
|
742
|
+
Warn ("云端 WebDAV 已经有内容({0} 项):本机还是空的,应该先拉取,而不是推送" -f [int]$wp.files)
|
|
743
|
+
Die "已停止(未抓取、未上传)。请先执行「立即拉取」。"
|
|
744
|
+
}
|
|
745
|
+
Say ""
|
|
746
|
+
Say "== 初始化仓库(WebDAV 首次推送) =="
|
|
747
|
+
Say " 目录:$RepoRoot"
|
|
748
|
+
Say (" 云端:{0} / {1}" -f $SyncSettings.webdavUrl, $(if ($SyncSettings.webdavDir) { $SyncSettings.webdavDir } else { 'dsh-config-sync' }))
|
|
749
|
+
Initialize-RepoSkeleton
|
|
750
|
+
}
|
|
751
|
+
if ((Test-DshRunning) -and (-not $Force)) {
|
|
752
|
+
Warn "检测到 DeepSeek Harness 在运行:capture 可能抓到写了一半的配置"
|
|
753
|
+
Warn "建议完全退出(含托盘)后重跑;确认要继续可加 -Force"
|
|
754
|
+
Die "已停止(未抓取、未上传)。"
|
|
755
|
+
}
|
|
756
|
+
$captureArgs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; ProfileName = $ProfileName; AppRoot = $AppRoot; WorkspaceHome = $WorkspaceHome; NoResetNotices = $true }
|
|
757
|
+
if ($WorkspaceOnly) { $captureArgs['WorkspaceOnly'] = $true }
|
|
758
|
+
if ($SkipWorkspace) { $captureArgs['SkipWorkspace'] = $true }
|
|
759
|
+
if ($DeepVerify) { $captureArgs['DeepVerify'] = $true }
|
|
760
|
+
& (Join-Path $PSScriptRoot 'capture.ps1') @captureArgs
|
|
761
|
+
if ($LASTEXITCODE -ne 0) { Die "capture.ps1 未正常结束,已停止(未上传)。" }
|
|
762
|
+
Say ""
|
|
763
|
+
Say "== 上传到 WebDAV =="
|
|
764
|
+
Invoke-WebdavAction 'upload'
|
|
765
|
+
Ok "已通过 WebDAV 推送到云端"
|
|
766
|
+
Write-SyncState 'push'
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
|
|
642
770
|
# 推送的三种起点,判据统一成「本机有没有历史 + 云端有没有内容」:
|
|
643
771
|
# 有仓库有历史 → 正常推送(老逻辑照旧)
|
|
644
772
|
# 本机没内容、云端有内容 → 只能先拉取(硬推会把本机状态写进一份已经在用的历史)
|
|
@@ -924,6 +1052,33 @@ if ($Action -eq 'push') {
|
|
|
924
1052
|
}
|
|
925
1053
|
|
|
926
1054
|
# ---------- pull ----------
|
|
1055
|
+
if ($UseWebdav) {
|
|
1056
|
+
if ((Test-DshRunning) -and (-not $Force)) {
|
|
1057
|
+
Die "DeepSeek Harness 仍在运行。请完全退出(含托盘)后重跑,或加 -Force 强制继续。"
|
|
1058
|
+
}
|
|
1059
|
+
if (-not (Test-Path -LiteralPath $RepoRoot)) { New-Item -ItemType Directory -Path $RepoRoot -Force | Out-Null }
|
|
1060
|
+
Say ""
|
|
1061
|
+
Say "== 从 WebDAV 拉取 =="
|
|
1062
|
+
$wp = Invoke-WebdavAction 'probe'
|
|
1063
|
+
if (-not $wp.ok) {
|
|
1064
|
+
Die ("连不上 WebDAV({0}):{1}" -f $SyncSettings.webdavUrl, $wp.error)
|
|
1065
|
+
}
|
|
1066
|
+
if (-not $wp.exists -or [int]$wp.files -le 0) {
|
|
1067
|
+
Die "云端 WebDAV 目录里还没有内容,请先在一台机器执行「推送」。"
|
|
1068
|
+
}
|
|
1069
|
+
Invoke-WebdavAction 'download'
|
|
1070
|
+
Say ""
|
|
1071
|
+
$applyArgs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; ProfileName = $ProfileName; AppRoot = $AppRoot; WorkspaceHome = $WorkspaceHome; NoResetNotices = $true }
|
|
1072
|
+
if ($WorkspaceOnly) { $applyArgs['WorkspaceOnly'] = $true }
|
|
1073
|
+
if ($SkipWorkspace) { $applyArgs['SkipWorkspace'] = $true }
|
|
1074
|
+
if ($SkipInstall) { $applyArgs['SkipInstall'] = $true }
|
|
1075
|
+
if ($AllowVersionDrift) { $applyArgs['AllowVersionDrift'] = $true }
|
|
1076
|
+
if ($Force) { $applyArgs['Force'] = $true }
|
|
1077
|
+
& (Join-Path $PSScriptRoot 'apply.ps1') @applyArgs
|
|
1078
|
+
if ($LASTEXITCODE -eq 0) { Write-SyncState 'pull' }
|
|
1079
|
+
exit $LASTEXITCODE
|
|
1080
|
+
}
|
|
1081
|
+
|
|
927
1082
|
Initialize-RepoIfNeeded
|
|
928
1083
|
if ((Test-DshRunning) -and (-not $Force)) {
|
|
929
1084
|
Die "DeepSeek Harness 仍在运行。请完全退出(含托盘)后重跑,或加 -Force 强制继续。"
|
package/runtime/webdav.mjs
CHANGED
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
|
|
24
24
|
import { createHash } from 'node:crypto'
|
|
25
25
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
26
|
-
import {
|
|
26
|
+
import { homedir } from 'node:os'
|
|
27
|
+
import { dirname, join, resolve, sep as SEP } from 'node:path'
|
|
28
|
+
import { fileURLToPath } from 'node:url'
|
|
27
29
|
|
|
28
30
|
/** WebDAV 方法体里常用的 XML 命名空间。 */
|
|
29
31
|
const NS_DAV = 'DAV:'
|
|
@@ -120,17 +122,39 @@ async function textOf(res) {
|
|
|
120
122
|
|
|
121
123
|
/**
|
|
122
124
|
* 确保远端目录存在(MKCOL,已存在则忽略 405/301)。
|
|
125
|
+
* nginx ngx_http_dav_module 要求 MKCOL URL 带尾斜杠,否则直接报 409;
|
|
126
|
+
* 若遇到 400/501 再退回不带尾斜杠。根路径含多段(如 a/b)时逐级创建。
|
|
123
127
|
* 返回 { ok, error }。
|
|
124
128
|
*/
|
|
129
|
+
async function mkcolOne(url, w) {
|
|
130
|
+
const withSlash = url.endsWith('/') ? url : `${url}/`
|
|
131
|
+
let res = await request(withSlash, w, { method: 'MKCOL' })
|
|
132
|
+
if (res.status === 400 || res.status === 501) {
|
|
133
|
+
res = await request(url.replace(/\/+$/, ''), w, { method: 'MKCOL' })
|
|
134
|
+
}
|
|
135
|
+
if (res.ok || res.status === 405 || res.status === 301) {
|
|
136
|
+
return { ok: true, status: res.status, error: '' }
|
|
137
|
+
}
|
|
138
|
+
if (res.status === 409) {
|
|
139
|
+
return { ok: false, status: 409, error: 'parent-missing' }
|
|
140
|
+
}
|
|
141
|
+
return { ok: false, status: res.status, error: `MKCOL ${res.status} ${await textOf(res)}` }
|
|
142
|
+
}
|
|
143
|
+
|
|
125
144
|
export async function ensureRemoteDir(w, relDir = '') {
|
|
126
145
|
const url = remoteUrlFor(w, relDir)
|
|
127
146
|
try {
|
|
128
|
-
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
|
|
147
|
+
let r = await mkcolOne(url, w)
|
|
148
|
+
if (r.status === 409 && !relDir && w.dir && w.dir.includes('/')) {
|
|
149
|
+
const segs = String(w.dir).split('/').filter(Boolean)
|
|
150
|
+
const base = String(w.url || '').replace(/\/+$/, '')
|
|
151
|
+
for (let i = 1; i <= segs.length; i++) {
|
|
152
|
+
const prefix = segs.slice(0, i).map((s) => encodeURIComponent(s)).join('/')
|
|
153
|
+
r = await mkcolOne(`${base}/${prefix}`, w)
|
|
154
|
+
if (!r.ok) return r
|
|
155
|
+
}
|
|
132
156
|
}
|
|
133
|
-
return
|
|
157
|
+
return r
|
|
134
158
|
} catch (e) {
|
|
135
159
|
return { ok: false, error: e && e.message ? e.message : String(e) }
|
|
136
160
|
}
|
|
@@ -473,7 +497,7 @@ function fromRepoRel(rel) {
|
|
|
473
497
|
return String(rel).split('/').join(SEP)
|
|
474
498
|
}
|
|
475
499
|
|
|
476
|
-
/**
|
|
500
|
+
/** 连通性测试(面板「测试连接」与探云端是否为空共用)。 */
|
|
477
501
|
export async function testConnection(w) {
|
|
478
502
|
if (!w.enabled) return { ok: false, error: '未配置 WebDAV 地址' }
|
|
479
503
|
if (!isSecureUrl(w.url)) {
|
|
@@ -481,5 +505,88 @@ export async function testConnection(w) {
|
|
|
481
505
|
}
|
|
482
506
|
const res = await listRemote(w, '')
|
|
483
507
|
if (!res) return { ok: false, error: '连不上或认证失败(PROPFIND 无响应)' }
|
|
484
|
-
|
|
508
|
+
const dirs = res.exists ? await listRemoteDirs(w, '') : []
|
|
509
|
+
return {
|
|
510
|
+
ok: true,
|
|
511
|
+
exists: res.exists,
|
|
512
|
+
files: res.entries.size + dirs.length,
|
|
513
|
+
rootFiles: res.entries.size,
|
|
514
|
+
rootDirs: dirs.length,
|
|
515
|
+
url: w.url,
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function parseCliArgs(argv) {
|
|
520
|
+
const out = {}
|
|
521
|
+
for (let i = 0; i < argv.length; i++) {
|
|
522
|
+
const tok = String(argv[i])
|
|
523
|
+
if (!tok.startsWith('-')) continue
|
|
524
|
+
const clean = tok.replace(/^-+/, '')
|
|
525
|
+
const eq = clean.indexOf('=')
|
|
526
|
+
if (eq > 0) { out[clean.slice(0, eq)] = clean.slice(eq + 1); continue }
|
|
527
|
+
const next = argv[i + 1]
|
|
528
|
+
if (next !== undefined && !String(next).startsWith('-')) { out[clean] = String(next); i++ }
|
|
529
|
+
else out[clean] = true
|
|
530
|
+
}
|
|
531
|
+
return out
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function readLocalSettings(dshHome) {
|
|
535
|
+
const p = join(dshHome, 'dsh-config-sync.json')
|
|
536
|
+
if (!existsSync(p)) return {}
|
|
537
|
+
return JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export async function runWebdavCli(argv) {
|
|
541
|
+
const [cmd, ...rest] = argv
|
|
542
|
+
const a = parseCliArgs(rest)
|
|
543
|
+
const dshHome = a.DshHome || a.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
544
|
+
const repoRoot = a.RepoRoot || a.repoRoot || process.cwd()
|
|
545
|
+
if (!cmd || !['probe', 'upload', 'download'].includes(cmd)) {
|
|
546
|
+
console.error('用法:node webdav.mjs <probe|upload|download> -DshHome <dir> -RepoRoot <dir>')
|
|
547
|
+
return 2
|
|
548
|
+
}
|
|
549
|
+
const settings = readLocalSettings(dshHome)
|
|
550
|
+
const w = normalizeWebdav(settings)
|
|
551
|
+
if (!w.enabled) {
|
|
552
|
+
console.error('WebDAV 未配置地址')
|
|
553
|
+
return 1
|
|
554
|
+
}
|
|
555
|
+
if (cmd === 'probe') {
|
|
556
|
+
const r = await testConnection(w)
|
|
557
|
+
console.log(JSON.stringify(r))
|
|
558
|
+
return r.ok ? 0 : 1
|
|
559
|
+
}
|
|
560
|
+
if (cmd === 'upload') {
|
|
561
|
+
if (!isSecureUrl(w.url)) {
|
|
562
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
563
|
+
return 1
|
|
564
|
+
}
|
|
565
|
+
const r = await uploadRepo(w, repoRoot)
|
|
566
|
+
console.log(`WebDAV 上传:上传 ${r.uploaded.length} · 跳过 ${r.skipped.length} · 错误 ${r.errors.length}`)
|
|
567
|
+
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
568
|
+
return r.ok ? 0 : 1
|
|
569
|
+
}
|
|
570
|
+
if (cmd === 'download') {
|
|
571
|
+
if (!isSecureUrl(w.url)) {
|
|
572
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
573
|
+
return 1
|
|
574
|
+
}
|
|
575
|
+
const r = await downloadRepo(w, repoRoot)
|
|
576
|
+
console.log(`WebDAV 下载:下载 ${r.downloaded.length} · 跳过 ${r.skipped.length} · 冲突 ${r.conflicts.length} · 错误 ${r.errors.length}`)
|
|
577
|
+
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
578
|
+
return r.ok ? 0 : 1
|
|
579
|
+
}
|
|
580
|
+
return 2
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
const invokedDirectly = (() => {
|
|
584
|
+
try { return resolve(process.argv[1] || '') === resolve(fileURLToPath(import.meta.url)) } catch { return false }
|
|
585
|
+
})()
|
|
586
|
+
|
|
587
|
+
if (invokedDirectly) {
|
|
588
|
+
runWebdavCli(process.argv.slice(2)).then((code) => process.exit(code)).catch((e) => {
|
|
589
|
+
console.error(e && e.stack ? e.stack : e)
|
|
590
|
+
process.exit(1)
|
|
591
|
+
})
|
|
485
592
|
}
|