Files
SceneMarshal/scripts/explorer-media-rename.ps1
T
ali 0819f784eb fix(flow): 取消不再算失败——统一退出码 2 并在队列里显示「已取消」
- pipeline.run() 明确返回退出码:0 正常(含无需变更),2 用户取消;
  main.py 据此 sys.exit,媒体整理被取消时也能传到上层
- media-archive 的取消(选分类按 q、确认按 n)同样返回 2
- preview_and_confirm 遇到 EOF(没有 TTY/管道调用)按取消处理,
  不再抛 Traceback 崩掉
- 队列 worker 把退出码 2 显示为「⏭ 已取消(未改动任何文件)」,
  汇总区分 成功 / 取消 / 失败
2026-11-19 18:35:54 +08:00

274 lines
9.9 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#Requires -Version 7.0
<#
.SYNOPSIS
资源管理器右键菜单的入口,支持「多选排队、单窗口顺序处理」。
.DESCRIPTION
三种运行方式:
1) 入队(菜单用):-Enqueue -Action <动作> -Paths <路径>
把任务写进队列后立即退出,由 worker 统一处理。多次点击只会拉起一个窗口。
2) 队列 worker(内部使用):-Worker
串行消费队列;队列处理完即退出(不等新任务)。
同一时刻只允许一个 worker(靠 worker.lock 独占锁保证)。
3) 直接执行(调试/手动):-Action <动作> -Paths <路径>
不进队列,立即处理当前窗口里的这一项。
.PARAMETER Action
rename(默认)/ archive / extract-subs / check。
.PARAMETER DryRun
只打印将要执行的远端命令,不真正执行。
.PARAMETER Pause
执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。
.PARAMETER Paths
资源管理器传入的选中项。
#>
[CmdletBinding()]
param(
[ValidateSet('rename', 'archive', 'extract-subs', 'check')]
[string]$Action = 'rename',
[switch]$Pause,
[switch]$DryRun,
[switch]$Enqueue,
[switch]$Worker,
[Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @()
)
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { }
# ---------------------------------------------------------------- 公共定义
$QueueDir = Join-Path $env:LOCALAPPDATA 'SceneMarshal'
$QueueFile = Join-Path $QueueDir 'queue.jsonl'
$QueueLock = Join-Path $QueueDir 'queue.lock'
$WorkerLock = Join-Path $QueueDir 'worker.lock'
$SpawnLock = Join-Path $QueueDir 'spawn.lock'
$WorkerLog = Join-Path $QueueDir 'worker.log'
$PwshPath = (Get-Process -Id $PID).Path
$ActionPlan = @{
'archive' = @{ Runner = 'media-archive.ps1'; Extra = @() }
'extract-subs' = @{ Runner = 'media-rename.ps1'; Extra = @('extract-subs') }
'check' = @{ Runner = 'media-rename.ps1'; Extra = @('check') }
'rename' = @{ Runner = 'media-rename.ps1'; Extra = @() }
}
function Write-WorkerLog([string]$message) {
try {
$line = '{0} {1}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss'), $message
Add-Content -LiteralPath $WorkerLog -Value $line -Encoding utf8
}
catch { }
}
function Enter-FileLock([string]$path, [int]$timeoutMs = 3000) {
$deadline = (Get-Date).AddMilliseconds($timeoutMs)
while ((Get-Date) -lt $deadline) {
try { return [IO.File]::Open($path, 'OpenOrCreate', 'ReadWrite', 'None') }
catch { Start-Sleep -Milliseconds 50 }
}
return $null
}
function Add-QueueItem([string]$action, [string]$target) {
New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null
$lock = Enter-FileLock $QueueLock
if ($null -eq $lock) { throw '队列被占用,请稍后重试' }
try {
$item = [ordered]@{ action = $action; path = $target; ts = (Get-Date).ToString('o') }
Add-Content -LiteralPath $QueueFile -Value ($item | ConvertTo-Json -Compress) -Encoding utf8
}
finally { $lock.Close() }
}
function Take-QueueItem {
New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null
$lock = Enter-FileLock $QueueLock
if ($null -eq $lock) { return $null }
try {
if (-not (Test-Path -LiteralPath $QueueFile)) { return $null }
$lines = @(Get-Content -LiteralPath $QueueFile -Encoding utf8 | Where-Object { $_.Trim() })
if ($lines.Count -eq 0) {
Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue
return $null
}
$first = $lines[0]
$rest = @($lines | Select-Object -Skip 1)
if ($rest.Count -eq 0) {
Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue
}
else {
Set-Content -LiteralPath $QueueFile -Value $rest -Encoding utf8
}
return ($first | ConvertFrom-Json)
}
finally { $lock.Close() }
}
function Test-WorkerAlive {
$lock = Enter-FileLock $WorkerLock 200
if ($null -eq $lock) { return $true }
$lock.Close()
return $false
}
function Start-Worker {
Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-File', $PSCommandPath, '-Worker') `
-WindowStyle Normal | Out-Null
# 等它真正拿到锁再返回,避免同一批多选时重复拉起 worker
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Milliseconds 50
if (Test-WorkerAlive) { return }
}
}
function Resolve-Target([string[]]$rawPaths) {
$target = $rawPaths | Where-Object { $_ } | Select-Object -First 1
if (-not $target) { return $null }
if (Test-Path -LiteralPath $target -PathType Leaf) {
return (Split-Path -Parent $target)
}
return $target
}
function Invoke-Action([string]$itemAction, [string]$target) {
$plan = $ActionPlan[$itemAction]
if (-not $plan) {
Write-Host "❌ 未知动作: $itemAction" -ForegroundColor Red
return 1
}
$runnerPath = Join-Path $PSScriptRoot $plan.Runner
$tokens = @($target) + $plan.Extra
# 关键:用独立子进程「继承当前控制台」来跑,而不是在进程内 + 管道。
# 管道会让远端 ssh -t 的交互提示与本地输入回显错位(提示行会消失)。
$quotedTokens = ($tokens | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ','
$quotedRunner = "'" + ($runnerPath -replace "'", "''") + "'"
$extra = ''
if ($DryRun) { $extra = ' -DryRun' }
$command = "& $quotedRunner -Tokens @($quotedTokens)$extra"
$proc = Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-Command', ('"' + $command + '"')) `
-NoNewWindow -Wait -PassThru
if ($null -eq $proc) { return 1 }
return [int]$proc.ExitCode
}
# ---------------------------------------------------------------- worker 模式
function Invoke-Worker {
Write-WorkerLog 'worker 进程启动(抢锁中)'
$workerLock = Enter-FileLock $WorkerLock 200
if ($null -eq $workerLock) {
Write-WorkerLog '已有 worker 在运行,本次进程直接退出'
Write-Host '已有 worker 在运行,退出。' -ForegroundColor DarkGray
return 0
}
try { $Host.UI.RawUI.WindowTitle = 'SceneMarshal 队列' } catch { }
Write-WorkerLog ("worker 启动(stdin重定向={0} stdout重定向={1})" -f `
[Console]::IsInputRedirected, [Console]::IsOutputRedirected)
Write-Host '📋 SceneMarshal 队列已启动(处理完即退出)' -ForegroundColor Cyan
Write-Host ''
$done = 0
$failed = 0
$cancelled = 0
while ($true) {
$item = Take-QueueItem
if ($null -eq $item) { break } # 队列空就退出,不再等待新任务
$name = Split-Path -Leaf $item.path
Write-Host ('─── [{0}] {1}' -f $item.action, $name) -ForegroundColor Yellow
Write-WorkerLog ("开始处理 {0} :: {1}" -f $item.action, $item.path)
$started = Get-Date
try {
$code = Invoke-Action $item.action $item.path
}
catch {
Write-Host (" ❌ 异常: {0}" -f $_.Exception.Message) -ForegroundColor Red
$code = 1
}
$cost = [int]((Get-Date) - $started).TotalSeconds
if ($code -eq 0) {
$done++
Write-Host (" ✅ 完成,用时 {0}s" -f $cost) -ForegroundColor Green
Write-WorkerLog ("完成 {0}({1}s)" -f $item.path, $cost)
}
elseif ($code -eq 2) {
# 退出码 2 约定为「用户主动取消」,不算失败
$cancelled++
Write-Host (" ⏭ 已取消(未改动任何文件),用时 {0}s" -f $cost) -ForegroundColor DarkYellow
Write-WorkerLog ("已取消 {0}" -f $item.path)
}
else {
$failed++
Write-Host (" ⚠️ 失败(退出码 {0}),用时 {1}s" -f $code, $cost) -ForegroundColor Red
Write-WorkerLog ("失败 {0}(code={1}, {2}s)" -f $item.path, $code, $cost)
}
Write-Host ''
}
$total = $done + $cancelled + $failed
Write-Host ('📊 本次共处理 {0} 项:成功 {1},取消 {2},失败 {3}' -f $total, $done, $cancelled, $failed) -ForegroundColor Cyan
Write-Host ' 队列已空,窗口即将关闭(详细记录见 worker.log)' -ForegroundColor DarkGray
Write-WorkerLog ("worker 退出:成功 {0},取消 {1},失败 {2}" -f $done, $cancelled, $failed)
$workerLock.Close()
if ($total -gt 0) { Start-Sleep -Seconds 2 } # 留两秒给汇总留在屏幕上
return 0
}
# ---------------------------------------------------------------- 主流程
if ($Worker) {
exit (Invoke-Worker)
}
$target = Resolve-Target $Paths
if ($Enqueue) {
if (-not $target) { exit 0 } # 没拿到路径就静默退出,不弹窗
Add-QueueItem $Action $target
if (-not (Test-WorkerAlive)) {
# 多选时 Explorer 会同时发起 N 个入队调用,这里必须串行化,
# 否则每个调用都会在 worker 抢到锁之前各拉起一个窗口。
$spawnLock = Enter-FileLock $SpawnLock 8000
try {
if ($null -ne $spawnLock -and -not (Test-WorkerAlive)) { Start-Worker }
}
finally {
if ($null -ne $spawnLock) { $spawnLock.Close() }
}
}
exit 0
}
# 直接执行模式
if (-not $target) {
Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red
if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null }
exit 1
}
Write-Host "📁 目标: $target" -ForegroundColor DarkGray
Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray
$exitCode = Invoke-Action $Action $target
if ($Pause) {
Write-Host ''
Read-Host '按 Enter 关闭窗口' | Out-Null
}
exit $exitCode