@kevlns/xlmerge 2.0.3 → 2.0.5

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.
@@ -1,141 +1,140 @@
1
- [CmdletBinding()]
2
- param([string]$ParametersPath, [string]$CleanupParametersPath)
3
-
4
- $ErrorActionPreference = 'Stop'
5
- $excel = $null
6
- $book = $null
7
- $excelPid = $null
8
- $ownedExcel = $false
9
- $excelStartFileTimeUtc = $null
10
- $statePath = $null
11
-
12
- if (![string]::IsNullOrWhiteSpace($CleanupParametersPath)) {
13
- try {
14
- $owned = Get-Content -LiteralPath $CleanupParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
15
- $p = Get-Process -Id ([int]$owned.pid) -ErrorAction SilentlyContinue
16
- if ($p -and $p.ProcessName -ieq 'EXCEL') {
17
- $ft = $p.StartTime.ToUniversalTime().ToFileTimeUtc()
18
- if ($ft -eq [int64]$owned.startFileTimeUtc) {
19
- Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
20
- }
21
- }
22
- exit 0
23
- } catch { exit 1 }
24
- }
25
- if ([string]::IsNullOrWhiteSpace($ParametersPath)) { throw 'ParametersPath is required' }
26
-
27
- if (-not ('XlmergeExcelWindow' -as [type])) {
28
- Add-Type @"
29
- using System;
30
- using System.Runtime.InteropServices;
31
- public static class XlmergeExcelWindow {
32
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
33
- }
34
- "@
35
- }
36
-
37
- function Write-State([string]$status, [string]$errorText = $null) {
38
- if ([string]::IsNullOrWhiteSpace($statePath)) { return }
39
- $state = [ordered]@{ status = $status }
40
- if ($null -ne $excelPid) {
41
- $state.pid = [int]$excelPid
42
- if ($null -ne $excelStartFileTimeUtc) { $state.startFileTimeUtc = [int64]$excelStartFileTimeUtc }
43
- }
44
- if ($null -ne $errorText) { $state.error = $errorText }
45
- $state | ConvertTo-Json -Compress | Set-Content -LiteralPath $statePath -Encoding UTF8
46
- }
47
-
48
- try {
49
- $parameters = Get-Content -LiteralPath $ParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
50
- $source = [IO.Path]::GetFullPath([string]$parameters.source)
51
- $result = [IO.Path]::GetFullPath([string]$parameters.result)
52
- $statePath = [IO.Path]::GetFullPath([string]$parameters.state)
53
- $timeoutSeconds = [int]$parameters.timeoutSeconds
54
- if ($timeoutSeconds -lt 1) { throw 'timeoutSeconds must be positive' }
55
- if (!(Test-Path -LiteralPath $source -PathType Leaf)) { throw "Source workbook does not exist: $source" }
56
- $parent = Split-Path -Parent $result
57
- if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
58
-
59
- # Excel constants are used as numbers so this script has no interop assembly
60
- # dependency. AutomationSecurity=3 is msoAutomationSecurityForceDisable.
61
- $existingExcelPids = @(Get-Process -Name EXCEL -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
62
- $excel = New-Object -ComObject Excel.Application
63
- $window = [IntPtr]$excel.Hwnd
64
- [uint32]$windowPid = 0
65
- [XlmergeExcelWindow]::GetWindowThreadProcessId($window, [ref]$windowPid) | Out-Null
66
- if ($windowPid -eq 0) { throw 'Unable to identify the Excel process created for this calculation' }
67
- $excelProcess = Get-Process -Id ([int]$windowPid) -ErrorAction Stop
68
- if ($excelProcess.ProcessName -ine 'EXCEL') { throw 'Excel window belongs to an unexpected process' }
69
- if ($existingExcelPids -contains $excelProcess.Id) { throw 'Excel COM attached to a pre-existing user Excel process' }
70
- $excelPid = $excelProcess.Id
71
- $excelStartFileTimeUtc = [int64]$excelProcess.StartTime.ToUniversalTime().ToFileTimeUtc()
72
- $ownedExcel = $true
73
- Write-State 'running'
74
-
75
- $excel.Visible = $false
76
- $excel.DisplayAlerts = $false
77
- $excel.EnableEvents = $false
78
- $excel.ScreenUpdating = $false
79
- $excel.AskToUpdateLinks = $false
80
- $excel.AutomationSecurity = 3
81
- $excel.UserControl = $false
82
- # Iterative calculation can make a circular workbook appear to have a
83
- # stable value. It is never safe for a conflict snapshot.
84
- if ($excel.Iteration) { throw 'Excel iterative calculation is enabled' }
85
-
86
- # UpdateLinks=0 and ReadOnly=true are positional arguments in the Excel COM
87
- # API. The temporary source is never saved in place.
88
- $book = $excel.Workbooks.Open($source, 0, $true)
89
- if ($excel.Iteration) { throw 'Workbook enables iterative calculation' }
90
- $excel.CalculateFullRebuild()
91
- $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
92
- while ($excel.CalculationState -ne 0) { # xlDone
93
- if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation did not reach xlDone before timeout' }
94
- Start-Sleep -Milliseconds 100
95
- }
96
- if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation exceeded timeout' }
97
- try {
98
- $circular = $excel.CircularReference
99
- if ($null -ne $circular) { throw 'Workbook contains a circular reference' }
100
- } catch {
101
- if ($_.Exception.Message -like '*circular reference*') { throw }
102
- throw "Unable to verify circular references: $($_.Exception.Message)"
103
- }
104
- # Save the completed calculation once. Python verifies every original
105
- # formula's serialized cache and cell type, including errors and missing
106
- # results. Traversing UsedRange through COM duplicates that validation and
107
- # also visits potentially millions of formatted, non-formula cells.
108
- $book.SaveCopyAs($result)
109
- if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
110
- Write-State 'completed'
111
- exit 0
112
- }
113
- catch {
114
- Write-State 'failed' $_.Exception.Message
115
- exit 1
116
- }
117
- finally {
118
- if ($null -ne $book) {
119
- try { $book.Close($false) } catch { }
120
- try { [Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null } catch { }
121
- }
122
- if ($null -ne $excel -and $ownedExcel) {
123
- try { $excel.Quit() } catch { }
124
- }
125
- if ($null -ne $excel) {
126
- try { [Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null } catch { }
127
- }
128
- [GC]::Collect()
129
- [GC]::WaitForPendingFinalizers()
130
- # Quit can leave an orphaned hidden Excel process while COM child ranges
131
- # are being finalized. Ownership is exact: PID + creation timestamp.
132
- if ($null -ne $excelProcess -and $null -ne $excelPid) {
133
- try {
134
- $left = Get-Process -Id ([int]$excelPid) -ErrorAction SilentlyContinue
135
- if ($left -and $left.ProcessName -ieq 'EXCEL' -and
136
- $left.StartTime.ToUniversalTime().ToFileTimeUtc() -eq $excelStartFileTimeUtc) {
137
- Stop-Process -Id ([int]$excelPid) -Force -ErrorAction SilentlyContinue
138
- }
139
- } catch { }
140
- }
141
- }
1
+ [CmdletBinding()]
2
+ param([string]$ParametersPath, [string]$CleanupParametersPath)
3
+
4
+ $ErrorActionPreference = 'Stop'
5
+ $excel = $null
6
+ $book = $null
7
+ $excelPid = $null
8
+ $ownedExcel = $false
9
+ $excelStartFileTimeUtc = $null
10
+ $statePath = $null
11
+
12
+ if (![string]::IsNullOrWhiteSpace($CleanupParametersPath)) {
13
+ try {
14
+ $owned = Get-Content -LiteralPath $CleanupParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
15
+ $p = Get-Process -Id ([int]$owned.pid) -ErrorAction SilentlyContinue
16
+ if ($p -and $p.ProcessName -ieq 'EXCEL') {
17
+ $ft = $p.StartTime.ToUniversalTime().ToFileTimeUtc()
18
+ if ($ft -eq [int64]$owned.startFileTimeUtc) {
19
+ Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
20
+ }
21
+ }
22
+ exit 0
23
+ } catch { exit 1 }
24
+ }
25
+ if ([string]::IsNullOrWhiteSpace($ParametersPath)) { throw 'ParametersPath is required' }
26
+
27
+ if (-not ('XlmergeExcelWindow' -as [type])) {
28
+ Add-Type @"
29
+ using System;
30
+ using System.Runtime.InteropServices;
31
+ public static class XlmergeExcelWindow {
32
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
33
+ }
34
+ "@
35
+ }
36
+
37
+ function Write-State([string]$status, [string]$errorText = $null) {
38
+ if ([string]::IsNullOrWhiteSpace($statePath)) { return }
39
+ $state = [ordered]@{ status = $status }
40
+ if ($null -ne $excelPid) {
41
+ $state.pid = [int]$excelPid
42
+ if ($null -ne $excelStartFileTimeUtc) { $state.startFileTimeUtc = [int64]$excelStartFileTimeUtc }
43
+ }
44
+ if ($null -ne $errorText) { $state.error = $errorText }
45
+ $state | ConvertTo-Json -Compress | Set-Content -LiteralPath $statePath -Encoding UTF8
46
+ }
47
+
48
+ try {
49
+ $parameters = Get-Content -LiteralPath $ParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
50
+ $source = [IO.Path]::GetFullPath([string]$parameters.source)
51
+ $result = [IO.Path]::GetFullPath([string]$parameters.result)
52
+ $statePath = [IO.Path]::GetFullPath([string]$parameters.state)
53
+ $timeoutSeconds = [int]$parameters.timeoutSeconds
54
+ if ($timeoutSeconds -lt 1) { throw 'timeoutSeconds must be positive' }
55
+ if (!(Test-Path -LiteralPath $source -PathType Leaf)) { throw "Source workbook does not exist: $source" }
56
+ $parent = Split-Path -Parent $result
57
+ if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
58
+
59
+ # Excel constants are used as numbers so this script has no interop assembly
60
+ # dependency. AutomationSecurity=3 is msoAutomationSecurityForceDisable.
61
+ $existingExcelPids = @(Get-Process -Name EXCEL -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
62
+ $excel = New-Object -ComObject Excel.Application
63
+ $window = [IntPtr]$excel.Hwnd
64
+ [uint32]$windowPid = 0
65
+ [XlmergeExcelWindow]::GetWindowThreadProcessId($window, [ref]$windowPid) | Out-Null
66
+ if ($windowPid -eq 0) { throw 'Unable to identify the Excel process created for this calculation' }
67
+ $excelProcess = Get-Process -Id ([int]$windowPid) -ErrorAction Stop
68
+ if ($excelProcess.ProcessName -ine 'EXCEL') { throw 'Excel window belongs to an unexpected process' }
69
+ if ($existingExcelPids -contains $excelProcess.Id) { throw 'Excel COM attached to a pre-existing user Excel process' }
70
+ $excelPid = $excelProcess.Id
71
+ $excelStartFileTimeUtc = [int64]$excelProcess.StartTime.ToUniversalTime().ToFileTimeUtc()
72
+ $ownedExcel = $true
73
+ Write-State 'running'
74
+
75
+ $excel.Visible = $false
76
+ $excel.DisplayAlerts = $false
77
+ $excel.EnableEvents = $false
78
+ $excel.ScreenUpdating = $false
79
+ $excel.AskToUpdateLinks = $false
80
+ $excel.AutomationSecurity = 3
81
+ $excel.UserControl = $false
82
+ # UpdateLinks=0 and ReadOnly=true are positional arguments in the Excel COM
83
+ # API. The temporary source is never saved in place.
84
+ $book = $excel.Workbooks.Open($source, 0, $true)
85
+ # Iterative calculation can make a circular workbook appear to have a
86
+ # stable value. Check after opening the workbook: with no open workbooks,
87
+ # some Excel versions report Application.Iteration as true unconditionally.
88
+ if ($excel.Iteration) { throw 'Workbook enables iterative calculation' }
89
+ $excel.CalculateFullRebuild()
90
+ $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
91
+ while ($excel.CalculationState -ne 0) { # xlDone
92
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation did not reach xlDone before timeout' }
93
+ Start-Sleep -Milliseconds 100
94
+ }
95
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation exceeded timeout' }
96
+ try {
97
+ $circular = $excel.CircularReference
98
+ if ($null -ne $circular) { throw 'Workbook contains a circular reference' }
99
+ } catch {
100
+ if ($_.Exception.Message -like '*circular reference*') { throw }
101
+ throw "Unable to verify circular references: $($_.Exception.Message)"
102
+ }
103
+ # Save the completed calculation once. Python verifies every original
104
+ # formula's serialized cache and cell type, including errors and missing
105
+ # results. Traversing UsedRange through COM duplicates that validation and
106
+ # also visits potentially millions of formatted, non-formula cells.
107
+ $book.SaveCopyAs($result)
108
+ if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
109
+ Write-State 'completed'
110
+ exit 0
111
+ }
112
+ catch {
113
+ Write-State 'failed' $_.Exception.Message
114
+ exit 1
115
+ }
116
+ finally {
117
+ if ($null -ne $book) {
118
+ try { $book.Close($false) } catch { }
119
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null } catch { }
120
+ }
121
+ if ($null -ne $excel -and $ownedExcel) {
122
+ try { $excel.Quit() } catch { }
123
+ }
124
+ if ($null -ne $excel) {
125
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null } catch { }
126
+ }
127
+ [GC]::Collect()
128
+ [GC]::WaitForPendingFinalizers()
129
+ # Quit can leave an orphaned hidden Excel process while COM child ranges
130
+ # are being finalized. Ownership is exact: PID + creation timestamp.
131
+ if ($null -ne $excelProcess -and $null -ne $excelPid) {
132
+ try {
133
+ $left = Get-Process -Id ([int]$excelPid) -ErrorAction SilentlyContinue
134
+ if ($left -and $left.ProcessName -ieq 'EXCEL' -and
135
+ $left.StartTime.ToUniversalTime().ToFileTimeUtc() -eq $excelStartFileTimeUtc) {
136
+ Stop-Process -Id ([int]$excelPid) -Force -ErrorAction SilentlyContinue
137
+ }
138
+ } catch { }
139
+ }
140
+ }
@@ -151,6 +151,10 @@ def build_parser() -> argparse.ArgumentParser:
151
151
  serve_parser.add_argument('--prepare', action='store_true', help=argparse.SUPPRESS)
152
152
  serve_parser.add_argument('--path', help=argparse.SUPPRESS)
153
153
 
154
+ for action in ("status", "cancel"):
155
+ control = subparsers.add_parser(action, help="查询或停止原审阅服务。")
156
+ control.add_argument("--manifest", required=True)
157
+
154
158
  apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
155
159
  apply_parser.add_argument("--manifest", required=True)
156
160
  apply_parser.add_argument("--decisions", required=True)
@@ -164,6 +168,11 @@ def main(argv: list[str] | None = None) -> int:
164
168
  _configure_stdio()
165
169
  args = build_parser().parse_args(argv)
166
170
  try:
171
+ if args.command in ("status", "cancel"):
172
+ from session import inspect_session
173
+ result = inspect_session(args.manifest, cancel=args.command == "cancel")
174
+ _print(result)
175
+ return 0 if result["ok"] else 1
167
176
  # serve/apply 仅依赖 manifest(其 repoRoot 在 apply_manifest 内部解析),
168
177
  # 可在非 git 目录下运行;其余公开命令需要前置解析仓库。
169
178
  if args.command in ("detect", "filter", "prepare", "resolve", "launch"):
@@ -0,0 +1,49 @@
1
+ """审阅服务的持久化身份与完成回执。"""
2
+ import json
3
+ import os
4
+ import uuid
5
+ import time
6
+ from pathlib import Path
7
+ from urllib.request import Request, urlopen
8
+ from urllib.parse import urlparse
9
+
10
+
11
+ def save_session(file, data):
12
+ file = Path(file)
13
+ file.parent.mkdir(parents=True, exist_ok=True)
14
+ temp = file.with_name(file.name + '.' + uuid.uuid4().hex + '.tmp')
15
+ temp.write_text(json.dumps(data, ensure_ascii=False), encoding='utf-8')
16
+ os.replace(temp, file)
17
+
18
+
19
+ def inspect_session(manifest, cancel=False):
20
+ file = Path(manifest).resolve().parent / 'session.json'
21
+ original = json.loads(file.read_text(encoding='utf-8'))
22
+ if str(Path(original['manifest']).resolve()) != str(Path(manifest).resolve()):
23
+ raise ValueError('审阅身份与清单不一致')
24
+ if original['state'] in ('completed', 'cancelled', 'failed'):
25
+ return {**original, 'ok': True, 'stopConfirmed': True}
26
+ url = urlparse(original['url'])
27
+ if url.scheme != 'http' or url.hostname != '127.0.0.1' or not url.port or url.path:
28
+ raise ValueError('审阅服务地址无效')
29
+ try:
30
+ live = json.load(urlopen(original['url'] + '/api/session', timeout=3))
31
+ if live.get('sessionId') != original['sessionId'] or live.get('pid') != original['pid']:
32
+ raise ValueError('审阅服务身份变化,拒绝操作')
33
+ if not cancel:
34
+ return {**live, 'ok': True, 'stopConfirmed': False}
35
+ req = Request(original['url'] + '/api/shutdown', data=b'{}', headers={'X-Xlmerge-Session': original['sessionId']}, method='POST')
36
+ with urlopen(req, timeout=3):
37
+ pass
38
+ deadline = time.monotonic() + 5
39
+ while time.monotonic() < deadline:
40
+ settled = json.loads(file.read_text(encoding='utf-8'))
41
+ if settled['state'] in ('completed', 'cancelled', 'failed'):
42
+ return {**settled, 'ok': True, 'stopConfirmed': True}
43
+ time.sleep(.1)
44
+ return {**live, 'ok': True, 'state': 'cancelling', 'stopConfirmed': False}
45
+ except OSError as exc:
46
+ settled = json.loads(file.read_text(encoding='utf-8'))
47
+ if settled['state'] in ('completed', 'cancelled', 'failed'):
48
+ return {**settled, 'ok': True, 'stopConfirmed': True}
49
+ return {**original, 'ok': False, 'state': 'unknown', 'stopConfirmed': False, 'error': str(exc)}