Initial import of DxDesigner part replacement tool (r21)
This commit is contained in:
commit
ffe066cb1e
151 files changed
+58745
No files matched your search
@@ -0,0 +1,225 @@
|
||||
' Shared DxDesigner 7.9.5 bridge helpers. Keep this file ASCII-only.
|
||||
|
||||
Function DxReadUtf8(ByVal FilePath)
|
||||
Dim Stream
|
||||
Dim ErrorNumber
|
||||
Dim ErrorDescription
|
||||
Dim ErrorSource
|
||||
|
||||
Set Stream = CreateObject("ADODB.Stream")
|
||||
Stream.Type = 2
|
||||
Stream.Charset = "utf-8"
|
||||
Stream.Open
|
||||
|
||||
On Error Resume Next
|
||||
Stream.LoadFromFile CStr(FilePath)
|
||||
ErrorNumber = Err.Number
|
||||
ErrorDescription = Err.Description
|
||||
ErrorSource = Err.Source
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If ErrorNumber <> 0 Then
|
||||
Stream.Close
|
||||
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
|
||||
End If
|
||||
|
||||
DxReadUtf8 = Stream.ReadText
|
||||
Stream.Close
|
||||
End Function
|
||||
|
||||
Sub DxWriteUtf8Atomic(ByVal FilePath, ByVal Text)
|
||||
Dim Fso
|
||||
Dim Stream
|
||||
Dim Shell
|
||||
Dim ParentPath
|
||||
Dim TemporaryPath
|
||||
Dim CommandLine
|
||||
Dim ExitCode
|
||||
Dim ErrorNumber
|
||||
Dim ErrorDescription
|
||||
Dim ErrorSource
|
||||
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
ParentPath = Fso.GetParentFolderName(Fso.GetAbsolutePathName(CStr(FilePath)))
|
||||
If Not Fso.FolderExists(ParentPath) Then
|
||||
Err.Raise vbObjectError + 795, "DxWriteUtf8Atomic", _
|
||||
"Destination directory does not exist"
|
||||
End If
|
||||
TemporaryPath = Fso.BuildPath(ParentPath, Fso.GetTempName)
|
||||
|
||||
Set Stream = CreateObject("ADODB.Stream")
|
||||
Stream.Type = 2
|
||||
Stream.Charset = "utf-8"
|
||||
Stream.Open
|
||||
Stream.WriteText CStr(Text)
|
||||
|
||||
On Error Resume Next
|
||||
Stream.SaveToFile TemporaryPath, 2
|
||||
ErrorNumber = Err.Number
|
||||
ErrorDescription = Err.Description
|
||||
ErrorSource = Err.Source
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
Stream.Close
|
||||
If ErrorNumber <> 0 Then
|
||||
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
|
||||
End If
|
||||
|
||||
Set Shell = CreateObject("WScript.Shell")
|
||||
CommandLine = DxCommandQuote( _
|
||||
Shell.ExpandEnvironmentStrings("%ComSpec%")) & _
|
||||
" /d /s /c " & Chr(34) & "move /y " & _
|
||||
DxCommandQuote(TemporaryPath) & " " & _
|
||||
DxCommandQuote(Fso.GetAbsolutePathName(CStr(FilePath))) & _
|
||||
" >nul" & Chr(34)
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
If ExitCode <> 0 Then
|
||||
If Fso.FileExists(TemporaryPath) Then
|
||||
Fso.DeleteFile TemporaryPath, True
|
||||
End If
|
||||
Err.Raise vbObjectError + 796, "DxWriteUtf8Atomic", _
|
||||
"Cannot atomically replace destination file"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Function DxJsonEscape(ByVal Value)
|
||||
Dim Text
|
||||
Dim Result
|
||||
Dim Index
|
||||
Dim Character
|
||||
Dim CodePoint
|
||||
|
||||
Text = CStr(Value)
|
||||
Result = ""
|
||||
For Index = 1 To Len(Text)
|
||||
Character = Mid(Text, Index, 1)
|
||||
CodePoint = AscW(Character)
|
||||
If CodePoint < 0 Then CodePoint = CodePoint + 65536
|
||||
Select Case CodePoint
|
||||
Case 8
|
||||
Result = Result & Chr(92) & "b"
|
||||
Case 9
|
||||
Result = Result & Chr(92) & "t"
|
||||
Case 10
|
||||
Result = Result & Chr(92) & "n"
|
||||
Case 12
|
||||
Result = Result & Chr(92) & "f"
|
||||
Case 13
|
||||
Result = Result & Chr(92) & "r"
|
||||
Case 34
|
||||
Result = Result & Chr(92) & Chr(34)
|
||||
Case 92
|
||||
Result = Result & Chr(92) & Chr(92)
|
||||
Case Else
|
||||
If CodePoint < 32 Then
|
||||
Result = Result & Chr(92) & "u00" & _
|
||||
Right("0" & Hex(CodePoint), 2)
|
||||
Else
|
||||
Result = Result & Character
|
||||
End If
|
||||
End Select
|
||||
Next
|
||||
DxJsonEscape = Result
|
||||
End Function
|
||||
|
||||
Function DxInvariantNumber(ByVal Value)
|
||||
Dim Text
|
||||
Dim DecimalSample
|
||||
Dim DecimalSeparator
|
||||
|
||||
If IsNull(Value) Or IsEmpty(Value) Or Not IsNumeric(Value) Then
|
||||
Err.Raise vbObjectError + 797, "DxInvariantNumber", _
|
||||
"Value is not numeric"
|
||||
End If
|
||||
Text = Trim(CStr(Value))
|
||||
DecimalSample = Trim(CStr(1.5))
|
||||
DecimalSeparator = Mid(DecimalSample, 2, Len(DecimalSample) - 2)
|
||||
If Len(DecimalSeparator) > 0 And DecimalSeparator <> "." Then
|
||||
Text = Replace(Text, DecimalSeparator, ".")
|
||||
End If
|
||||
DxInvariantNumber = Text
|
||||
End Function
|
||||
|
||||
Function DxResolveRunPath(ByVal RootPath, ByVal RunRelativePath)
|
||||
Dim Fso
|
||||
Dim RootAbsolute
|
||||
Dim Candidate
|
||||
Dim RelativeText
|
||||
Dim Prefix
|
||||
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
RootAbsolute = Fso.GetAbsolutePathName(CStr(RootPath))
|
||||
Do While Len(RootAbsolute) > 3 And Right(RootAbsolute, 1) = "\"
|
||||
RootAbsolute = Left(RootAbsolute, Len(RootAbsolute) - 1)
|
||||
Loop
|
||||
If Not Fso.FolderExists(RootAbsolute) Then
|
||||
Err.Raise vbObjectError + 798, "DxResolveRunPath", _
|
||||
"Run root does not exist"
|
||||
End If
|
||||
DxValidateNoReparse Fso, RootAbsolute
|
||||
|
||||
RelativeText = CStr(RunRelativePath)
|
||||
If Len(RelativeText) = 0 Or Left(RelativeText, 1) = "\" Or _
|
||||
InStr(RelativeText, ":") > 0 Or _
|
||||
InStr(RelativeText, "*") > 0 Or _
|
||||
InStr(RelativeText, "?") > 0 Then
|
||||
Err.Raise vbObjectError + 799, "DxResolveRunPath", _
|
||||
"Run path must be a non-empty relative path"
|
||||
End If
|
||||
|
||||
Candidate = Fso.GetAbsolutePathName( _
|
||||
Fso.BuildPath(RootAbsolute, RelativeText))
|
||||
Prefix = RootAbsolute
|
||||
If Right(Prefix, 1) <> "\" Then Prefix = Prefix & "\"
|
||||
If Len(Candidate) <= Len(Prefix) Or _
|
||||
StrComp(Left(Candidate, Len(Prefix)), Prefix, _
|
||||
vbTextCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 800, "DxResolveRunPath", _
|
||||
"Run path escapes the supplied root"
|
||||
End If
|
||||
DxValidateNoReparse Fso, Candidate
|
||||
DxResolveRunPath = Candidate
|
||||
End Function
|
||||
|
||||
Sub DxValidateNoReparse(ByRef Fso, ByVal FilePath)
|
||||
Dim AbsolutePath
|
||||
Dim DriveName
|
||||
Dim CurrentPath
|
||||
Dim Remaining
|
||||
Dim Parts
|
||||
Dim Part
|
||||
Dim Attributes
|
||||
|
||||
AbsolutePath = Fso.GetAbsolutePathName(CStr(FilePath))
|
||||
DriveName = Fso.GetDriveName(AbsolutePath)
|
||||
If Len(DriveName) = 0 Then
|
||||
Err.Raise vbObjectError + 801, "DxResolveRunPath", _
|
||||
"Run paths must use a local drive"
|
||||
End If
|
||||
CurrentPath = DriveName & "\"
|
||||
Remaining = Mid(AbsolutePath, Len(CurrentPath) + 1)
|
||||
If Len(Remaining) = 0 Then Exit Sub
|
||||
|
||||
Parts = Split(Remaining, "\")
|
||||
For Each Part In Parts
|
||||
If Len(CStr(Part)) > 0 Then
|
||||
CurrentPath = Fso.BuildPath(CurrentPath, CStr(Part))
|
||||
If Fso.FolderExists(CurrentPath) Then
|
||||
Attributes = Fso.GetFolder(CurrentPath).Attributes
|
||||
ElseIf Fso.FileExists(CurrentPath) Then
|
||||
Attributes = Fso.GetFile(CurrentPath).Attributes
|
||||
Else
|
||||
Exit For
|
||||
End If
|
||||
If (Attributes And 1024) <> 0 Then
|
||||
Err.Raise vbObjectError + 802, "DxResolveRunPath", _
|
||||
"Run path contains a reparse point"
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Function DxCommandQuote(ByVal Value)
|
||||
DxCommandQuote = Chr(34) & Replace(CStr(Value), Chr(34), _
|
||||
Chr(92) & Chr(34)) & Chr(34)
|
||||
End Function
|
||||
@@ -0,0 +1,183 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$InstallRoot,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$PythonExecutable,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$CompatibilityProfile,
|
||||
[string]$SettingsRoot,
|
||||
[switch]$TestMode,
|
||||
[switch]$WhatIf
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
. (Join-Path $PSScriptRoot "PathSafety.ps1")
|
||||
|
||||
function Resolve-FullPath {
|
||||
param([string]$Value)
|
||||
return [IO.Path]::GetFullPath($Value)
|
||||
}
|
||||
|
||||
function Resolve-ExistingFile {
|
||||
param([string]$Value, [string]$Name)
|
||||
$resolved = Resolve-FullPath $Value
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
if (-not (Test-Path -LiteralPath $resolved -PathType Leaf)) {
|
||||
throw "$Name does not exist: $resolved"
|
||||
}
|
||||
return $resolved
|
||||
}
|
||||
|
||||
$toolHome = Resolve-FullPath $InstallRoot
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
if (-not (Test-Path -LiteralPath $toolHome -PathType Container)) {
|
||||
throw "installation root does not exist: $toolHome"
|
||||
}
|
||||
|
||||
$runtimeDirectory = Join-Path $toolHome "integration\dxdesigner795"
|
||||
Assert-DxNoReparsePath $runtimeDirectory "runtime directory"
|
||||
$requiredRuntimeFiles = @(
|
||||
"PathSafety.ps1",
|
||||
"PartReplacementContract.ps1",
|
||||
"MenuAdd.vbs",
|
||||
"MenuRuntime.vbs",
|
||||
"PartReplaceMenuRuntime.vbs",
|
||||
"BridgeCommon.vbs",
|
||||
"PartReplaceProbe.vbs",
|
||||
"PartReplaceBridge.vbs"
|
||||
)
|
||||
$missingRuntimeFiles = @()
|
||||
$requiredRuntimePaths = @()
|
||||
foreach ($runtimeName in $requiredRuntimeFiles) {
|
||||
$runtimePath = Join-Path $runtimeDirectory $runtimeName
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
$requiredRuntimePaths += $runtimePath
|
||||
if (-not (Test-Path -LiteralPath $runtimePath -PathType Leaf)) {
|
||||
$missingRuntimeFiles += $runtimePath
|
||||
}
|
||||
}
|
||||
if ($missingRuntimeFiles.Count -ne 0) {
|
||||
throw "required runtime files are missing (including MenuRuntime.vbs): $($missingRuntimeFiles -join ', ')"
|
||||
}
|
||||
|
||||
$python = Resolve-ExistingFile $PythonExecutable "Python executable"
|
||||
$profileSource = Resolve-ExistingFile $CompatibilityProfile `
|
||||
"compatibility profile"
|
||||
|
||||
if ($TestMode) {
|
||||
if ($env:DX_PRODUCTIVITY_TEST_MODE -cne "1") {
|
||||
throw "TestMode requires DX_PRODUCTIVITY_TEST_MODE=1"
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
throw "TestMode requires an explicit SettingsRoot"
|
||||
}
|
||||
$settingsBase = Resolve-FullPath $SettingsRoot
|
||||
Assert-DxNoReparsePath $settingsBase "TestMode settings root"
|
||||
$systemTemp = (Resolve-FullPath ([IO.Path]::GetTempPath())).TrimEnd('\')
|
||||
$tempPrefix = $systemTemp + "\"
|
||||
if (-not $toolHome.StartsWith(
|
||||
$tempPrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "TestMode InstallRoot must be under the system temp directory"
|
||||
}
|
||||
if (-not $settingsBase.StartsWith(
|
||||
$tempPrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "TestMode SettingsRoot must be under the system temp directory"
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (-not [string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
throw "SettingsRoot is allowed only with TestMode"
|
||||
}
|
||||
$settingsBase = [Environment]::GetFolderPath(
|
||||
[Environment+SpecialFolder]::LocalApplicationData
|
||||
)
|
||||
$settingsBase = Resolve-FullPath $settingsBase
|
||||
Assert-DxNoReparsePath $settingsBase "settings root"
|
||||
}
|
||||
|
||||
$settingsDirectory = Join-Path $settingsBase "DxProductivity"
|
||||
$settingsPath = Join-Path $settingsDirectory "settings.json"
|
||||
$runRoot = Join-Path $toolHome "runs"
|
||||
$deployedProfile = Join-Path $runRoot "compatibility-profile.json"
|
||||
Assert-DxNoReparsePath $settingsDirectory "settings directory"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
Assert-DxNoReparsePath $runRoot "run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
|
||||
Write-Output "InstallRoot=$toolHome"
|
||||
Write-Output "PythonExecutable=$python"
|
||||
Write-Output "ProfileSource=$profileSource"
|
||||
Write-Output "CompatibilityProfile=$deployedProfile"
|
||||
Write-Output "SettingsPath=$settingsPath"
|
||||
Write-Output "RunRoot=$runRoot"
|
||||
Write-Output "DXTOOLS_HOME=$toolHome"
|
||||
if ($TestMode) {
|
||||
Write-Output "TEST MODE: user-scope DXTOOLS_HOME is not written"
|
||||
}
|
||||
if ($WhatIf) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
foreach ($runtimePath in $requiredRuntimePaths) {
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
}
|
||||
Assert-DxNoReparsePath $python "Python executable"
|
||||
Assert-DxNoReparsePath $profileSource "compatibility profile"
|
||||
Assert-DxNoReparsePath $runRoot "run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
|
||||
$pythonCheck = @(
|
||||
"-c",
|
||||
"import sys, dx_productivity; raise SystemExit(0 if sys.version_info[:2] == (3, 12) else 1)"
|
||||
)
|
||||
& $python @pythonCheck
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Python must import dx_productivity and be exactly 3.12: $python"
|
||||
}
|
||||
|
||||
$profileDeploy = @(
|
||||
"-m",
|
||||
"dx_productivity",
|
||||
"deploy-profile",
|
||||
$profileSource,
|
||||
$deployedProfile
|
||||
)
|
||||
& $python @profileDeploy
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "compatibility profile deployment failed: $profileSource"
|
||||
}
|
||||
|
||||
$utf8 = New-Object Text.UTF8Encoding($false)
|
||||
$settingsData = [ordered]@{
|
||||
compatibility_profile = $deployedProfile
|
||||
dxtools_home = $toolHome
|
||||
python_executable = $python
|
||||
run_root = $runRoot
|
||||
}
|
||||
$settingsText = ($settingsData | ConvertTo-Json -Compress) + "`n"
|
||||
|
||||
Assert-DxNoReparsePath $settingsDirectory "settings directory"
|
||||
New-Item -ItemType Directory -Force -Path $settingsDirectory | Out-Null
|
||||
Assert-DxNoReparsePath $toolHome "installation root"
|
||||
foreach ($runtimePath in $requiredRuntimePaths) {
|
||||
Assert-DxNoReparsePath $runtimePath "runtime file"
|
||||
}
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
Write-DxBytesAtomic $settingsPath $utf8.GetBytes($settingsText)
|
||||
|
||||
if (-not $TestMode) {
|
||||
[Environment]::SetEnvironmentVariable(
|
||||
"DXTOOLS_HOME",
|
||||
$toolHome,
|
||||
[EnvironmentVariableTarget]::User
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
On Error Resume Next
|
||||
Set DxPartReplaceLoaderEntryPoint = GetRef("DxInstallPartReplacementMenu")
|
||||
DxPartReplaceLoaderNeedsRuntime = (Err.Number <> 0)
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
|
||||
If DxPartReplaceLoaderNeedsRuntime Then
|
||||
DxPartReplaceLoaderHome = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
|
||||
If Len(DxPartReplaceLoaderHome) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "MenuAdd.vbs", _
|
||||
"DXTOOLS_HOME is not configured"
|
||||
End If
|
||||
DxPartReplaceLoaderSource = CreateObject( _
|
||||
"Scripting.FileSystemObject").OpenTextFile( _
|
||||
DxPartReplaceLoaderHome & _
|
||||
"\integration\dxdesigner795\MenuRuntime.vbs", _
|
||||
1, False, 0).ReadAll
|
||||
ExecuteGlobal DxPartReplaceLoaderSource
|
||||
End If
|
||||
|
||||
Set DxPartReplaceLoaderEntryPoint = GetRef("DxInstallPartReplacementMenu")
|
||||
Call DxPartReplaceLoaderEntryPoint()
|
||||
@@ -0,0 +1,86 @@
|
||||
Option Explicit
|
||||
|
||||
Const DX_PART_REPLACE_TAG = "DX_PRODUCTIVITY_PART_REPLACE"
|
||||
Dim DxMenuModulesLoaded
|
||||
|
||||
Sub DxInstallPartReplacementMenu()
|
||||
Dim Bar
|
||||
Dim Controls
|
||||
Dim Index
|
||||
Dim Existing
|
||||
Dim Control
|
||||
Set Bar = CommandBars("Sheet Menu Bar")
|
||||
Set Controls = Bar.Controls
|
||||
For Index = Controls.Count To 1 Step -1
|
||||
Set Existing = Controls.Item(Index)
|
||||
If Existing.Tag = DX_PART_REPLACE_TAG Then Existing.Delete
|
||||
Next
|
||||
Set Control = Controls.Add(10, , , , True)
|
||||
Control.Tag = DX_PART_REPLACE_TAG
|
||||
Control.Caption = "Dx Productivity"
|
||||
DxAddAction Control.Controls, "Part replacement probe", _
|
||||
"DxPartReplacementMenuProbe"
|
||||
DxAddAction Control.Controls, "Inventory current project", _
|
||||
"DxPartReplacementMenuInventory"
|
||||
DxAddAction Control.Controls, "Continue part replacement", _
|
||||
"DxPartReplacementMenuContinue"
|
||||
End Sub
|
||||
|
||||
Sub DxAddAction(ByVal Controls, ByVal Caption, ByVal MacroName)
|
||||
Dim Control
|
||||
Set Control = Controls.Add(1, , , , True)
|
||||
Control.Caption = Caption
|
||||
Control.OnAction = MacroName
|
||||
End Sub
|
||||
|
||||
Function DxMenuHome()
|
||||
DxMenuHome = CStr(Scripting.GetEnvVariable("DXTOOLS_HOME"))
|
||||
If Len(DxMenuHome) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuHome", _
|
||||
"DXTOOLS_HOME is not configured"
|
||||
End If
|
||||
End Function
|
||||
|
||||
Sub DxMenuLoad(ByVal FileName)
|
||||
Dim Fso
|
||||
Dim Home
|
||||
Dim Text
|
||||
Home = DxMenuHome()
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
Text = Fso.OpenTextFile(Home & "\integration\dxdesigner795\" & _
|
||||
FileName, 1, False, 0).ReadAll
|
||||
ExecuteGlobal Text
|
||||
End Sub
|
||||
|
||||
Sub DxMenuLoadModules()
|
||||
If DxMenuModulesLoaded Then Exit Sub
|
||||
DxMenuLoad "BridgeCommon.vbs"
|
||||
DxMenuLoad "PartReplaceProbe.vbs"
|
||||
DxMenuLoad "PartReplaceBridge.vbs"
|
||||
DxMenuLoad "PartReplaceMenuRuntime.vbs"
|
||||
DxMenuModulesLoaded = True
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuProbe()
|
||||
Dim Request
|
||||
DxMenuLoadModules
|
||||
Request = "{""disposable_project_marker"":false," & _
|
||||
"""format_version"":1,""operator_confirmation"":false}" & vbLf
|
||||
DxWriteUtf8Atomic DxMenuHome() & _
|
||||
"\runs\menu-probe-request.json", Request
|
||||
DxRunPartReplaceProbe "runs\menu-probe-request.json", _
|
||||
"runs\menu-compatibility-profile.json"
|
||||
End Sub
|
||||
|
||||
Sub DxMenuBridge(ByVal MenuAction)
|
||||
DxMenuLoadModules
|
||||
DxPartReplaceMenuDispatch MenuAction
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuInventory()
|
||||
DxMenuBridge "inventory"
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplacementMenuContinue()
|
||||
DxMenuBridge "continue"
|
||||
End Sub
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,332 @@
|
||||
' DxDesigner 7.9.5 part replacement menu runtime. ASCII-only source.
|
||||
|
||||
Sub DxMenuRequireFields(ByRef Record, ByVal FieldNames, _
|
||||
ByVal ExpectedCount, ByVal Context)
|
||||
Dim Name
|
||||
If Not DxBridgeIsDictionary(Record) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " must be an object"
|
||||
End If
|
||||
If Record.Count <> ExpectedCount Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " fields are invalid"
|
||||
End If
|
||||
For Each Name In Split(CStr(FieldNames), ",")
|
||||
If Not Record.Exists(CStr(Name)) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireFields", _
|
||||
Context & " is missing " & CStr(Name)
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Sub DxMenuRequireString(ByRef Record, ByVal Name, ByVal Context)
|
||||
If VarType(Record(CStr(Name))) <> vbString Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireString", _
|
||||
Context & "." & CStr(Name) & " must be a string"
|
||||
End If
|
||||
If Len(CStr(Record(CStr(Name)))) = 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireString", _
|
||||
Context & "." & CStr(Name) & " must not be empty"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Function DxMenuCanonicalProjectPath(ByRef Fso, ByVal Value)
|
||||
DxMenuCanonicalProjectPath = LCase(Replace( _
|
||||
Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
|
||||
End Function
|
||||
|
||||
Sub DxMenuValidateManifestRecord(ByRef Record, ByVal Home)
|
||||
Dim Name
|
||||
DxMenuRequireFields Record, _
|
||||
"command,profile,project_id,project_path,snapshot,status", 6, _
|
||||
"runtime manifest project"
|
||||
For Each Name In Array("command", "profile", "project_id", _
|
||||
"project_path", "snapshot", "status")
|
||||
DxMenuRequireString Record, CStr(Name), "runtime manifest project"
|
||||
Next
|
||||
If StrComp(CStr(Record("profile")), _
|
||||
"runs/compatibility-profile.json", vbBinaryCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuValidateManifestRecord", _
|
||||
"runtime manifest profile is not the deployed profile"
|
||||
End If
|
||||
For Each Name In Array("profile", "command", "status", "snapshot")
|
||||
Call DxResolveRunPath(Home, CStr(Record(CStr(Name))))
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Function DxMenuReadManifest(ByVal Home)
|
||||
Dim ManifestPath
|
||||
Dim Manifest
|
||||
ManifestPath = DxResolveRunPath(Home, _
|
||||
"runs/current-part-replacement.json")
|
||||
Set Manifest = DxBridgeParseJson(DxReadUtf8(ManifestPath))
|
||||
DxMenuRequireFields Manifest, _
|
||||
"complete,current_action,current_command_id,current_project_id," & _
|
||||
"format_version,projects", 6, _
|
||||
"runtime manifest"
|
||||
If VarType(Manifest("complete")) <> vbBoolean Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest complete must be Boolean"
|
||||
End If
|
||||
If Not DxBridgeIsProtocolInteger(Manifest("format_version")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest format_version must be integer 2"
|
||||
End If
|
||||
If CLng(Manifest("format_version")) <> 2 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest format_version must be 2"
|
||||
End If
|
||||
If Not DxBridgeIsJsonArray(Manifest("projects")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest projects must be an array"
|
||||
End If
|
||||
If CBool(Manifest("complete")) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"part replacement job is complete"
|
||||
End If
|
||||
DxMenuRequireString Manifest, "current_action", "runtime manifest"
|
||||
DxMenuRequireString Manifest, "current_command_id", "runtime manifest"
|
||||
DxMenuRequireString Manifest, "current_project_id", "runtime manifest"
|
||||
If Not DxMenuIsBaseAction(CStr(Manifest("current_action"))) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifest", _
|
||||
"runtime manifest current_action is invalid"
|
||||
End If
|
||||
Set DxMenuReadManifest = Manifest
|
||||
End Function
|
||||
|
||||
Function DxMenuReadManifestRecord(ByRef Manifest, ByVal Home)
|
||||
Dim Entries
|
||||
Dim Record
|
||||
Dim MatchRecord
|
||||
Dim Index
|
||||
Dim Matches
|
||||
Set Entries = Manifest("projects")
|
||||
Matches = 0
|
||||
For Index = 0 To Entries.Count - 1
|
||||
If Not IsObject(Entries.Item(Index)) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifestRecord", _
|
||||
"runtime manifest project must be an object"
|
||||
End If
|
||||
Set Record = Entries.Item(Index)
|
||||
DxMenuValidateManifestRecord Record, Home
|
||||
If StrComp(CStr(Record("project_id")), _
|
||||
CStr(Manifest("current_project_id")), _
|
||||
vbBinaryCompare) = 0 Then
|
||||
Matches = Matches + 1
|
||||
Set MatchRecord = Record
|
||||
End If
|
||||
Next
|
||||
If Matches <> 1 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadManifestRecord", _
|
||||
"current project has zero or multiple runtime manifest matches"
|
||||
End If
|
||||
Set DxMenuReadManifestRecord = MatchRecord
|
||||
End Function
|
||||
|
||||
Function DxMenuIsBaseAction(ByVal ActionName)
|
||||
Select Case CStr(ActionName)
|
||||
Case "inventory", "close_project", "close_without_save", _
|
||||
"open_project", "replace_part", "undo", "save", _
|
||||
"packager", "erc", "netlist"
|
||||
DxMenuIsBaseAction = True
|
||||
Case Else
|
||||
DxMenuIsBaseAction = False
|
||||
End Select
|
||||
End Function
|
||||
|
||||
Function DxMenuReadBoundCommand(ByVal Home, ByRef Manifest, ByRef Record)
|
||||
Dim Command
|
||||
Dim Failure
|
||||
Set Command = DxBridgeParseJson(DxReadUtf8( _
|
||||
DxResolveRunPath(Home, CStr(Record("command")))))
|
||||
If Not DxBridgeIsDictionary(Command) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"current bridge command must be an object"
|
||||
End If
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If Not DxBridgeValidateCommand(Command, _
|
||||
CStr(Manifest("current_action")), Failure) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"current bridge command is missing or stale"
|
||||
End If
|
||||
If StrComp(CStr(Command("command_id")), _
|
||||
CStr(Manifest("current_command_id")), _
|
||||
vbBinaryCompare) <> 0 Or _
|
||||
StrComp(CStr(Command("project_id")), _
|
||||
CStr(Manifest("current_project_id")), _
|
||||
vbBinaryCompare) <> 0 Or _
|
||||
StrComp(CStr(Command("project_id")), _
|
||||
CStr(Record("project_id")), _
|
||||
vbBinaryCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadBoundCommand", _
|
||||
"runtime manifest and command bindings do not match"
|
||||
End If
|
||||
Set DxMenuReadBoundCommand = Command
|
||||
End Function
|
||||
|
||||
Function DxMenuReadStatus(ByVal Home, ByRef Record)
|
||||
Dim Status
|
||||
Set Status = DxBridgeParseJson(DxReadUtf8( _
|
||||
DxResolveRunPath(Home, CStr(Record("status")))))
|
||||
If Not DxBridgeIsDictionary(Status) Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuReadStatus", _
|
||||
"bridge status must be an object"
|
||||
End If
|
||||
Set DxMenuReadStatus = Status
|
||||
End Function
|
||||
|
||||
Function DxMenuDispatchAction(ByVal Home, ByRef Record, _
|
||||
ByRef Command, ByVal BaseAction, ByRef ManualRoute)
|
||||
Dim Fso
|
||||
Dim StatusPath
|
||||
Dim Status
|
||||
Dim Failure
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
StatusPath = DxResolveRunPath(Home, CStr(Record("status")))
|
||||
ManualRoute = ""
|
||||
If Not Fso.FileExists(StatusPath) Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
If BaseAction <> "replace_part" And _
|
||||
BaseAction <> "undo" And BaseAction <> "save" And _
|
||||
BaseAction <> "open_project" And _
|
||||
BaseAction <> "close_project" And _
|
||||
BaseAction <> "close_without_save" Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
Set Status = DxMenuReadStatus(Home, Record)
|
||||
If BaseAction = "replace_part" Then
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
"manual_exact_selection", Failure) Then
|
||||
ManualRoute = "manual_exact_selection"
|
||||
DxMenuDispatchAction = "continue_after_manual_selection"
|
||||
Exit Function
|
||||
End If
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
"manual_native_dialog", Failure) Then
|
||||
ManualRoute = "manual_native_dialog"
|
||||
DxMenuDispatchAction = "continue_after_manual_dialog"
|
||||
Exit Function
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuDispatchAction", _
|
||||
"bridge status does not permit replacement continuation"
|
||||
End If
|
||||
|
||||
Select Case CStr(BaseAction)
|
||||
Case "undo"
|
||||
ManualRoute = "manual_native_undo"
|
||||
Case "save"
|
||||
ManualRoute = "manual_native_save"
|
||||
Case "open_project"
|
||||
ManualRoute = "manual_project_open"
|
||||
Case "close_project"
|
||||
ManualRoute = "manual_close_project"
|
||||
Case "close_without_save"
|
||||
ManualRoute = "manual_close_without_save"
|
||||
End Select
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateManualContinuation(Command, Status, _
|
||||
ManualRoute, Failure) Then
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
|
||||
If BaseAction = "undo" Or BaseAction = "save" Then
|
||||
Set Failure = DxBridgeNewFailure()
|
||||
If DxBridgeValidateControlStatus(Command, Status, Failure) Then
|
||||
ManualRoute = ""
|
||||
DxMenuDispatchAction = CStr(BaseAction)
|
||||
Exit Function
|
||||
End If
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuDispatchAction", _
|
||||
"bridge status does not permit control continuation"
|
||||
End Function
|
||||
|
||||
Sub DxMenuRequireProjectContext(ByRef Record, ByVal BaseAction, _
|
||||
ByVal ManualRoute)
|
||||
Dim Fso
|
||||
Dim ActiveValue
|
||||
Dim ActivePath
|
||||
Dim RecordPath
|
||||
Set Fso = CreateObject("Scripting.FileSystemObject")
|
||||
ActiveValue = Application.ProjectPath
|
||||
If VarType(ActiveValue) <> vbString Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"active project path must be a string"
|
||||
End If
|
||||
If Len(CStr(ActiveValue)) = 0 Then
|
||||
If BaseAction = "open_project" And Len(CStr(ManualRoute)) = 0 Then
|
||||
Exit Sub
|
||||
End If
|
||||
If (BaseAction = "close_project" Or _
|
||||
BaseAction = "close_without_save") And _
|
||||
Len(CStr(ManualRoute)) > 0 Then
|
||||
Exit Sub
|
||||
End If
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"there is no active project for the current command"
|
||||
End If
|
||||
|
||||
ActivePath = DxMenuCanonicalProjectPath(Fso, ActiveValue)
|
||||
RecordPath = DxMenuCanonicalProjectPath(Fso, Record("project_path"))
|
||||
If StrComp(ActivePath, RecordPath, vbTextCompare) <> 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"active project does not match the current command"
|
||||
End If
|
||||
If BaseAction = "open_project" And _
|
||||
CStr(ManualRoute) <> "manual_project_open" Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"project open requires a closed project or manual continuation"
|
||||
End If
|
||||
If (BaseAction = "close_project" Or _
|
||||
BaseAction = "close_without_save") And _
|
||||
Len(CStr(ManualRoute)) > 0 Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuRequireProjectContext", _
|
||||
"manual project close has not completed"
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub DxPartReplaceMenuDispatch(ByVal MenuAction)
|
||||
Dim Home
|
||||
Dim Manifest
|
||||
Dim Record
|
||||
Dim Command
|
||||
Dim BaseAction
|
||||
Dim DispatchAction
|
||||
Dim ManualRoute
|
||||
Dim ProfilePath
|
||||
Dim CommandPath
|
||||
Dim StatusPath
|
||||
Dim SnapshotPath
|
||||
Home = DxMenuHome()
|
||||
Set Manifest = DxMenuReadManifest(Home)
|
||||
BaseAction = CStr(Manifest("current_action"))
|
||||
If CStr(MenuAction) = "inventory" And _
|
||||
BaseAction <> "inventory" Then
|
||||
Err.Raise vbObjectError + 795, "DxMenuBridge", _
|
||||
"inventory menu action is not the current command"
|
||||
End If
|
||||
Set Record = DxMenuReadManifestRecord(Manifest, Home)
|
||||
Set Command = DxMenuReadBoundCommand(Home, Manifest, Record)
|
||||
DispatchAction = DxMenuDispatchAction(Home, Record, Command, _
|
||||
BaseAction, ManualRoute)
|
||||
DxMenuRequireProjectContext Record, BaseAction, ManualRoute
|
||||
ProfilePath = CStr(Record("profile"))
|
||||
CommandPath = CStr(Record("command"))
|
||||
StatusPath = CStr(Record("status"))
|
||||
SnapshotPath = CStr(Record("snapshot"))
|
||||
If BaseAction = "open_project" Then
|
||||
DxRunPartReplaceBridge DispatchAction, ProfilePath, CommandPath, _
|
||||
StatusPath, SnapshotPath, CStr(Record("project_path"))
|
||||
Else
|
||||
DxRunPartReplaceBridge DispatchAction, ProfilePath, CommandPath, _
|
||||
StatusPath, SnapshotPath, ""
|
||||
End If
|
||||
End Sub
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
function Assert-ExactObject {
|
||||
param([object]$Value, [string[]]$Fields, [string]$Context)
|
||||
if ($null -eq $Value -or
|
||||
$Value -isnot [System.Management.Automation.PSCustomObject]) {
|
||||
throw "$Context must be an object"
|
||||
}
|
||||
$actual = @($Value.PSObject.Properties.Name)
|
||||
if ($actual.Count -ne $Fields.Count) {
|
||||
throw "$Context fields are invalid"
|
||||
}
|
||||
foreach ($field in $Fields) {
|
||||
if (-not ($actual -ccontains $field)) {
|
||||
throw "$Context is missing $field"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-OptionalString {
|
||||
param([object]$Value, [string]$Name)
|
||||
if ($null -ne $Value -and
|
||||
($Value -isnot [string] -or [string]::IsNullOrWhiteSpace($Value))) {
|
||||
throw "$Name must be null or a nonempty string"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-OperatorStepResult {
|
||||
param([object]$Step, [string]$ExpectedJobId)
|
||||
Assert-ExactObject $Step @(
|
||||
"bridge_state", "command", "complete", "consumed_action",
|
||||
"instruction", "manual_route", "project", "state"
|
||||
) "operator-step result"
|
||||
if ($Step.complete -isnot [bool]) {
|
||||
throw "operator-step complete must be Boolean"
|
||||
}
|
||||
foreach ($name in @(
|
||||
"bridge_state", "consumed_action", "instruction", "manual_route"
|
||||
)) {
|
||||
Assert-OptionalString $Step.$name "operator-step $name"
|
||||
}
|
||||
if ($Step.complete) {
|
||||
if ($null -ne $Step.command -or $null -ne $Step.project -or
|
||||
$null -ne $Step.state) {
|
||||
throw "completed operator-step must not expose a current command"
|
||||
}
|
||||
return
|
||||
}
|
||||
Assert-ExactObject $Step.project @(
|
||||
"display_name", "project_id", "project_path"
|
||||
) "operator-step project"
|
||||
foreach ($name in @("display_name", "project_id", "project_path")) {
|
||||
if ($Step.project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Step.project.$name)) {
|
||||
throw "operator-step project $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($Step.state -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Step.state)) {
|
||||
throw "operator-step state is invalid"
|
||||
}
|
||||
Assert-ExactObject $Step.command @(
|
||||
"action", "command_id", "expected_count", "expected_fingerprint",
|
||||
"expected_logical_keys", "format_version", "job_id",
|
||||
"new_part_number", "old_part_number", "project_id", "scope"
|
||||
) "operator-step command"
|
||||
foreach ($name in @(
|
||||
"action", "command_id", "expected_fingerprint", "job_id",
|
||||
"new_part_number", "old_part_number", "project_id", "scope"
|
||||
)) {
|
||||
if ($Step.command.$name -isnot [string]) {
|
||||
throw "operator-step command $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($Step.command.action -notin @(
|
||||
"close_project", "close_without_save", "erc", "inventory",
|
||||
"netlist", "open_project", "packager", "replace_part", "save",
|
||||
"undo"
|
||||
)) {
|
||||
throw "operator-step command action is unsupported"
|
||||
}
|
||||
if ($Step.command.command_id -notmatch '^[0-9a-f]{32}$') {
|
||||
throw "operator-step command_id is invalid"
|
||||
}
|
||||
if ($Step.command.format_version -ne 1 -or
|
||||
$Step.command.format_version -isnot [int]) {
|
||||
throw "operator-step command format_version is invalid"
|
||||
}
|
||||
if ($Step.command.expected_count -isnot [int] -or
|
||||
$Step.command.expected_count -lt 0) {
|
||||
throw "operator-step expected_count is invalid"
|
||||
}
|
||||
$expectedKeys = @($Step.command.expected_logical_keys)
|
||||
if ($expectedKeys.Count -ne $Step.command.expected_count -or
|
||||
@($expectedKeys | Where-Object { $_ -isnot [string] }).Count -ne 0) {
|
||||
throw "operator-step expected logical keys are invalid"
|
||||
}
|
||||
if ($Step.command.scope -cne "full_project" -or
|
||||
$Step.command.job_id -cne $ExpectedJobId -or
|
||||
$Step.command.project_id -cne $Step.project.project_id) {
|
||||
throw "operator-step command identity is invalid"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-ResumeStatus {
|
||||
param([object]$Status)
|
||||
Assert-ExactObject $Status @("job_id", "projects") "status result"
|
||||
if ($Status.job_id -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($Status.job_id)) {
|
||||
throw "status result job_id is invalid"
|
||||
}
|
||||
if ($Status.projects -isnot [object[]] -or
|
||||
$Status.projects.Count -eq 0) {
|
||||
throw "status result projects must be a nonempty array"
|
||||
}
|
||||
$allowedActions = @(
|
||||
"await_inventory", "complete", "confirm-erc", "confirm-netlist",
|
||||
"confirm-packager", "confirm-saved", "confirm-undo", "ingest",
|
||||
"prepare", "prepare-close", "prepare-erc", "prepare-netlist",
|
||||
"prepare-open", "prepare-packager", "prepare-save", "prepare-undo",
|
||||
"reconcile"
|
||||
)
|
||||
$allowedStates = @(
|
||||
"apply_pending", "applying", "awaiting_external_checks",
|
||||
"awaiting_save_confirmation", "blocked", "inventory_complete",
|
||||
"inventory_pending", "verified_saved"
|
||||
)
|
||||
foreach ($project in $Status.projects) {
|
||||
Assert-ExactObject $project @(
|
||||
"action", "display_name", "project_id", "project_path", "state"
|
||||
) "status project"
|
||||
foreach ($name in @(
|
||||
"action", "display_name", "project_id", "project_path", "state"
|
||||
)) {
|
||||
if ($project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($project.$name)) {
|
||||
throw "status project $name is invalid"
|
||||
}
|
||||
}
|
||||
if ($project.action -cnotin $allowedActions) {
|
||||
throw "status project action is invalid"
|
||||
}
|
||||
if ($project.state -cnotin $allowedStates) {
|
||||
throw "status project state is invalid"
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted([string]$project.project_path)) {
|
||||
throw "status project path must be absolute"
|
||||
}
|
||||
if (($project.state -ceq "verified_saved") -ne
|
||||
($project.action -ceq "complete")) {
|
||||
throw "status project completion is inconsistent"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
function Assert-DxNoReparsePath {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Value,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Name
|
||||
)
|
||||
|
||||
$absolute = [IO.Path]::GetFullPath($Value)
|
||||
$driveRoot = [IO.Path]::GetPathRoot($absolute)
|
||||
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
||||
$driveRoot -notmatch '^[A-Za-z]:\\$') {
|
||||
throw "$Name must use a local drive: $absolute"
|
||||
}
|
||||
|
||||
$current = $driveRoot
|
||||
$remaining = $absolute.Substring($driveRoot.Length)
|
||||
$parts = $remaining.Split(
|
||||
[char[]]@('\', '/'),
|
||||
[StringSplitOptions]::RemoveEmptyEntries
|
||||
)
|
||||
foreach ($part in $parts) {
|
||||
$current = Join-Path $current $part
|
||||
try {
|
||||
$attributes = [IO.File]::GetAttributes($current)
|
||||
}
|
||||
catch {
|
||||
$pathFailure = $_.Exception
|
||||
while ($null -ne $pathFailure.InnerException) {
|
||||
$pathFailure = $pathFailure.InnerException
|
||||
}
|
||||
if ($pathFailure -is [IO.FileNotFoundException] -or
|
||||
$pathFailure -is [IO.DirectoryNotFoundException]) {
|
||||
return
|
||||
}
|
||||
throw "$Name cannot be validated at: $current"
|
||||
}
|
||||
if (($attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
||||
throw "$Name contains a reparse point: $current"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not ("DxProductivity.PathSafetyNative" -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace DxProductivity
|
||||
{
|
||||
public static class PathSafetyNative
|
||||
{
|
||||
private const uint FileReadAttributes = 0x00000080;
|
||||
private const uint GenericRead = 0x80000000;
|
||||
private const uint GenericWrite = 0x40000000;
|
||||
private const uint DeleteAccess = 0x00010000;
|
||||
private const uint FileShareRead = 0x00000001;
|
||||
private const uint FileShareWrite = 0x00000002;
|
||||
private const uint FileShareDelete = 0x00000004;
|
||||
private const uint CreateNew = 1;
|
||||
private const uint OpenExisting = 3;
|
||||
private const uint FileAttributeNormal = 0x00000080;
|
||||
private const uint FileFlagBackupSemantics = 0x02000000;
|
||||
private const uint FileFlagOpenReparsePoint = 0x00200000;
|
||||
private const int FileDispositionInfo = 4;
|
||||
private const int NativeFileRenameInformation = 10;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct IoStatusBlock
|
||||
{
|
||||
public IntPtr Status;
|
||||
public UIntPtr Information;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr CreateFile(
|
||||
string fileName,
|
||||
uint desiredAccess,
|
||||
uint shareMode,
|
||||
IntPtr securityAttributes,
|
||||
uint creationDisposition,
|
||||
uint flagsAndAttributes,
|
||||
IntPtr templateFile
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFinalPathNameByHandle(
|
||||
IntPtr handle,
|
||||
StringBuilder path,
|
||||
uint pathLength,
|
||||
uint flags
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool WriteFile(
|
||||
IntPtr handle,
|
||||
byte[] buffer,
|
||||
uint bytesToWrite,
|
||||
out uint bytesWritten,
|
||||
IntPtr overlapped
|
||||
);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool FlushFileBuffers(IntPtr handle);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool SetFileInformationByHandle(
|
||||
IntPtr handle,
|
||||
int informationClass,
|
||||
IntPtr information,
|
||||
uint bufferSize
|
||||
);
|
||||
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern int NtSetInformationFile(
|
||||
IntPtr handle,
|
||||
out IoStatusBlock ioStatus,
|
||||
IntPtr information,
|
||||
uint length,
|
||||
int informationClass
|
||||
);
|
||||
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern uint RtlNtStatusToDosError(int status);
|
||||
|
||||
public static IntPtr OpenDirectory(string path, bool denyRename)
|
||||
{
|
||||
uint access = FileReadAttributes;
|
||||
if (denyRename)
|
||||
{
|
||||
access |= DeleteAccess;
|
||||
}
|
||||
return CreateFile(
|
||||
path,
|
||||
access,
|
||||
FileShareRead | FileShareWrite,
|
||||
IntPtr.Zero,
|
||||
OpenExisting,
|
||||
FileFlagBackupSemantics | FileFlagOpenReparsePoint,
|
||||
IntPtr.Zero
|
||||
);
|
||||
}
|
||||
|
||||
public static IntPtr OpenStagedFile(string path)
|
||||
{
|
||||
IntPtr handle = CreateFile(
|
||||
path,
|
||||
GenericRead | GenericWrite | DeleteAccess,
|
||||
FileShareRead | FileShareDelete,
|
||||
IntPtr.Zero,
|
||||
CreateNew,
|
||||
FileAttributeNormal,
|
||||
IntPtr.Zero
|
||||
);
|
||||
if (handle == new IntPtr(-1))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
public static void WriteStagedFile(IntPtr handle, byte[] bytes)
|
||||
{
|
||||
if (bytes.LongLength > UInt32.MaxValue)
|
||||
{
|
||||
throw new IOException("Atomic publication payload is too large");
|
||||
}
|
||||
uint written;
|
||||
if (!WriteFile(handle, bytes, (uint)bytes.Length, out written,
|
||||
IntPtr.Zero))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
if (written != bytes.Length)
|
||||
{
|
||||
throw new IOException("Atomic publication staging write was incomplete");
|
||||
}
|
||||
if (!FlushFileBuffers(handle))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
public static void PublishStagedFile(
|
||||
IntPtr stagedHandle,
|
||||
IntPtr parentHandle,
|
||||
string destinationName
|
||||
)
|
||||
{
|
||||
if (String.IsNullOrEmpty(destinationName) ||
|
||||
destinationName == "." || destinationName == ".." ||
|
||||
destinationName.IndexOf('\\') >= 0 ||
|
||||
destinationName.IndexOf('/') >= 0)
|
||||
{
|
||||
throw new ArgumentException("Invalid atomic publication name");
|
||||
}
|
||||
byte[] name = Encoding.Unicode.GetBytes(destinationName);
|
||||
int pointerSize = IntPtr.Size;
|
||||
int rootOffset = (sizeof(uint) + pointerSize - 1) & -pointerSize;
|
||||
int lengthOffset = rootOffset + pointerSize;
|
||||
int nameOffset = lengthOffset + sizeof(uint);
|
||||
int bufferSize = nameOffset + name.Length + sizeof(char);
|
||||
IntPtr information = Marshal.AllocHGlobal(bufferSize);
|
||||
try
|
||||
{
|
||||
for (int index = 0; index < bufferSize; index++)
|
||||
{
|
||||
Marshal.WriteByte(information, index, 0);
|
||||
}
|
||||
Marshal.WriteByte(information, 0, 1);
|
||||
Marshal.WriteIntPtr(information, rootOffset, parentHandle);
|
||||
Marshal.WriteInt32(information, lengthOffset, name.Length);
|
||||
Marshal.Copy(name, 0, IntPtr.Add(information, nameOffset),
|
||||
name.Length);
|
||||
IoStatusBlock ioStatus;
|
||||
int status = NtSetInformationFile(
|
||||
stagedHandle,
|
||||
out ioStatus,
|
||||
information,
|
||||
(uint)bufferSize,
|
||||
NativeFileRenameInformation
|
||||
);
|
||||
if (status < 0)
|
||||
{
|
||||
throw new Win32Exception(
|
||||
(int)RtlNtStatusToDosError(status)
|
||||
);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(information);
|
||||
}
|
||||
}
|
||||
|
||||
public static void DeleteStagedFile(IntPtr stagedHandle)
|
||||
{
|
||||
IntPtr disposition = Marshal.AllocHGlobal(1);
|
||||
try
|
||||
{
|
||||
Marshal.WriteByte(disposition, 1);
|
||||
if (!SetFileInformationByHandle(
|
||||
stagedHandle,
|
||||
FileDispositionInfo,
|
||||
disposition,
|
||||
1))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(disposition);
|
||||
}
|
||||
}
|
||||
|
||||
public static string FinalPath(IntPtr handle)
|
||||
{
|
||||
uint capacity = 512;
|
||||
while (true)
|
||||
{
|
||||
StringBuilder buffer = new StringBuilder((int)capacity);
|
||||
uint result = GetFinalPathNameByHandle(
|
||||
handle,
|
||||
buffer,
|
||||
capacity,
|
||||
0
|
||||
);
|
||||
if (result == 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
if (result < capacity)
|
||||
{
|
||||
return buffer.ToString();
|
||||
}
|
||||
capacity = result + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Convert-DxHandlePath {
|
||||
param([string]$Value)
|
||||
$text = $Value
|
||||
if ($text.StartsWith("\\?\UNC\", [StringComparison]::OrdinalIgnoreCase)) {
|
||||
$text = "\\" + $text.Substring(8)
|
||||
}
|
||||
elseif ($text.StartsWith("\\?\", [StringComparison]::OrdinalIgnoreCase)) {
|
||||
$text = $text.Substring(4)
|
||||
}
|
||||
return ([IO.Path]::GetFullPath($text)).TrimEnd('\')
|
||||
}
|
||||
|
||||
function Close-DxPublicationLock {
|
||||
param([object]$Lock)
|
||||
if ($null -eq $Lock) {
|
||||
return
|
||||
}
|
||||
for ($index = $Lock.Handles.Count - 1; $index -ge 0; $index--) {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
||||
$Lock.Handles[$index]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-DxStagedIdentity {
|
||||
param([IntPtr]$Handle)
|
||||
[DxProductivity.PathSafetyNative]::DeleteStagedFile($Handle)
|
||||
}
|
||||
|
||||
function Open-DxDirectoryLock {
|
||||
param(
|
||||
[string]$Path,
|
||||
[bool]$DenyRename,
|
||||
[string]$Name
|
||||
)
|
||||
$handle = [DxProductivity.PathSafetyNative]::OpenDirectory(
|
||||
$Path,
|
||||
$DenyRename
|
||||
)
|
||||
if ($handle -eq [IntPtr](-1)) {
|
||||
$errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
||||
throw "$Name cannot lock directory: $Path (Windows error $errorCode)"
|
||||
}
|
||||
try {
|
||||
$expected = ([IO.Path]::GetFullPath($Path)).TrimEnd('\')
|
||||
$actual = Convert-DxHandlePath (
|
||||
[DxProductivity.PathSafetyNative]::FinalPath($handle)
|
||||
)
|
||||
if (-not [string]::Equals(
|
||||
$expected,
|
||||
$actual,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name directory handle resolves outside its lexical path: $Path"
|
||||
}
|
||||
Assert-DxNoReparsePath $Path $Name
|
||||
return $handle
|
||||
}
|
||||
catch {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle($handle)
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Enter-DxPublicationLock {
|
||||
param([string]$Destination, [string]$Name)
|
||||
$absolute = [IO.Path]::GetFullPath($Destination)
|
||||
$directory = Split-Path -Parent $absolute
|
||||
$driveRoot = [IO.Path]::GetPathRoot($directory)
|
||||
Assert-DxNoReparsePath $absolute $Name
|
||||
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
||||
[string]::Equals(
|
||||
$directory.TrimEnd('\'),
|
||||
$driveRoot.TrimEnd('\'),
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name destination parent must be below a local drive root"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $directory -PathType Container)) {
|
||||
throw "$Name destination directory does not exist: $directory"
|
||||
}
|
||||
|
||||
$handles = New-Object 'Collections.Generic.List[IntPtr]'
|
||||
$publicationLock = [pscustomobject]@{
|
||||
Handles = $handles
|
||||
Directory = $directory
|
||||
}
|
||||
try {
|
||||
$current = $driveRoot
|
||||
$handles.Add((Open-DxDirectoryLock $current $false $Name))
|
||||
$remaining = $directory.Substring($driveRoot.Length)
|
||||
$parts = $remaining.Split(
|
||||
[char[]]@('\', '/'),
|
||||
[StringSplitOptions]::RemoveEmptyEntries
|
||||
)
|
||||
for ($index = 0; $index -lt $parts.Count; $index++) {
|
||||
$current = Join-Path $current $parts[$index]
|
||||
$denyRename = $index -eq $parts.Count - 1
|
||||
$handles.Add((
|
||||
Open-DxDirectoryLock $current $denyRename $Name
|
||||
))
|
||||
}
|
||||
Assert-DxNoReparsePath $absolute $Name
|
||||
return $publicationLock
|
||||
}
|
||||
catch {
|
||||
Close-DxPublicationLock $publicationLock
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Write-DxBytesAtomic {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Destination,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[byte[]]$Bytes,
|
||||
[scriptblock]$AfterValidation
|
||||
)
|
||||
$absolute = [IO.Path]::GetFullPath($Destination)
|
||||
$publicationLock = $null
|
||||
$temporary = $null
|
||||
$stagedHandle = [IntPtr](-1)
|
||||
$published = $false
|
||||
$primaryError = $null
|
||||
$cleanupError = $null
|
||||
try {
|
||||
$publicationLock = Enter-DxPublicationLock $absolute `
|
||||
"atomic publication"
|
||||
$temporary = Join-Path $publicationLock.Directory (
|
||||
"." + [IO.Path]::GetFileName($absolute) + "." +
|
||||
[guid]::NewGuid().ToString("N") + ".tmp"
|
||||
)
|
||||
$stagedHandle = [DxProductivity.PathSafetyNative]::OpenStagedFile(
|
||||
$temporary
|
||||
)
|
||||
[DxProductivity.PathSafetyNative]::WriteStagedFile(
|
||||
$stagedHandle,
|
||||
$Bytes
|
||||
)
|
||||
$expectedTemporary = ([IO.Path]::GetFullPath($temporary)).TrimEnd('\')
|
||||
$actualTemporary = Convert-DxHandlePath (
|
||||
[DxProductivity.PathSafetyNative]::FinalPath($stagedHandle)
|
||||
)
|
||||
if (-not [string]::Equals(
|
||||
$expectedTemporary,
|
||||
$actualTemporary,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "atomic publication staging handle changed identity"
|
||||
}
|
||||
Assert-DxNoReparsePath $temporary "atomic publication temporary file"
|
||||
Assert-DxNoReparsePath $absolute "atomic publication destination"
|
||||
if ($null -ne $AfterValidation) {
|
||||
& $AfterValidation $absolute $temporary
|
||||
}
|
||||
$parentHandle = $publicationLock.Handles[
|
||||
$publicationLock.Handles.Count - 1
|
||||
]
|
||||
[DxProductivity.PathSafetyNative]::PublishStagedFile(
|
||||
$stagedHandle,
|
||||
$parentHandle,
|
||||
[IO.Path]::GetFileName($absolute)
|
||||
)
|
||||
$published = $true
|
||||
}
|
||||
catch {
|
||||
$primaryError = $_.Exception
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
if ($stagedHandle -ne [IntPtr](-1) -and -not $published) {
|
||||
try {
|
||||
Remove-DxStagedIdentity $stagedHandle
|
||||
}
|
||||
catch {
|
||||
$cleanupError = $_.Exception
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
if ($stagedHandle -ne [IntPtr](-1)) {
|
||||
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
||||
$stagedHandle
|
||||
)
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Close-DxPublicationLock $publicationLock
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($null -ne $primaryError) {
|
||||
throw $primaryError
|
||||
}
|
||||
if ($null -ne $cleanupError) {
|
||||
throw $cleanupError
|
||||
}
|
||||
}
|
||||
|
||||
function Write-DxUtf8Atomic {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Destination,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Text,
|
||||
[scriptblock]$AfterValidation
|
||||
)
|
||||
$utf8 = New-Object Text.UTF8Encoding($false)
|
||||
Write-DxBytesAtomic -Destination $Destination -Bytes $utf8.GetBytes($Text) `
|
||||
-AfterValidation $AfterValidation
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,460 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Mapping,
|
||||
[string]$Projects,
|
||||
[string]$DiscoveryRoot,
|
||||
[string]$CompatibilityProfile,
|
||||
[string]$PythonExecutable,
|
||||
[string]$RunRoot,
|
||||
[string]$DXToolsHome,
|
||||
[string]$Certifications,
|
||||
[string]$SettingsRoot,
|
||||
[string]$ResumeJob,
|
||||
[switch]$WhatIf
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
||||
. (Join-Path $PSScriptRoot "PathSafety.ps1")
|
||||
. (Join-Path $PSScriptRoot "PartReplacementContract.ps1")
|
||||
|
||||
function Resolve-FullPath {
|
||||
param([string]$Value)
|
||||
return [IO.Path]::GetFullPath($Value)
|
||||
}
|
||||
|
||||
function Resolve-RequiredPath {
|
||||
param([string]$Value, [string]$Name)
|
||||
if ([string]::IsNullOrWhiteSpace($Value)) {
|
||||
throw "$Name is required"
|
||||
}
|
||||
$resolved = Resolve-FullPath $Value
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
return $resolved
|
||||
}
|
||||
|
||||
function Test-SamePath {
|
||||
param([string]$Left, [string]$Right)
|
||||
return [string]::Equals(
|
||||
(Resolve-FullPath $Left).TrimEnd('\'),
|
||||
(Resolve-FullPath $Right).TrimEnd('\'),
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)
|
||||
}
|
||||
|
||||
function Test-DirectChildPath {
|
||||
param([string]$Parent, [string]$Child)
|
||||
$childParent = Split-Path -Parent (Resolve-FullPath $Child)
|
||||
return Test-SamePath $Parent $childParent
|
||||
}
|
||||
|
||||
function Convert-ToRunRelativePath {
|
||||
param([string]$ToolRoot, [string]$Path, [string]$Name)
|
||||
$resolvedRoot = Resolve-FullPath $ToolRoot
|
||||
Assert-DxNoReparsePath $resolvedRoot "DXTOOLS_HOME"
|
||||
$homePrefix = $resolvedRoot.TrimEnd('\') + "\"
|
||||
$resolved = Resolve-FullPath $Path
|
||||
Assert-DxNoReparsePath $resolved $Name
|
||||
if (-not $resolved.StartsWith(
|
||||
$homePrefix,
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
throw "$Name must be under DXTOOLS_HOME: $resolved"
|
||||
}
|
||||
return $resolved.Substring($homePrefix.Length).Replace('\', '/')
|
||||
}
|
||||
|
||||
function Read-Settings {
|
||||
param([string]$Base)
|
||||
$resolvedBase = Resolve-FullPath $Base
|
||||
Assert-DxNoReparsePath $resolvedBase "settings root"
|
||||
$settingsPath = Join-Path (Join-Path $resolvedBase "DxProductivity") "settings.json"
|
||||
Assert-DxNoReparsePath $settingsPath "settings path"
|
||||
try {
|
||||
$settings = Get-Content -LiteralPath $settingsPath -Raw -Encoding UTF8 |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "settings are invalid or missing: $settingsPath"
|
||||
}
|
||||
Assert-ExactObject $settings @(
|
||||
"compatibility_profile", "dxtools_home", "python_executable", "run_root"
|
||||
) "settings"
|
||||
foreach ($name in @(
|
||||
"compatibility_profile", "dxtools_home", "python_executable", "run_root"
|
||||
)) {
|
||||
if ($settings.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($settings.$name)) {
|
||||
throw "settings field is invalid: $name"
|
||||
}
|
||||
}
|
||||
return $settings
|
||||
}
|
||||
|
||||
$needsSettings = [string]::IsNullOrWhiteSpace($CompatibilityProfile) -or
|
||||
[string]::IsNullOrWhiteSpace($PythonExecutable) -or
|
||||
[string]::IsNullOrWhiteSpace($RunRoot) -or
|
||||
[string]::IsNullOrWhiteSpace($DXToolsHome)
|
||||
if ($needsSettings) {
|
||||
if ([string]::IsNullOrWhiteSpace($SettingsRoot)) {
|
||||
$SettingsRoot = [Environment]::GetFolderPath(
|
||||
[Environment+SpecialFolder]::LocalApplicationData
|
||||
)
|
||||
}
|
||||
$settingsBase = Resolve-FullPath $SettingsRoot
|
||||
Assert-DxNoReparsePath $settingsBase "settings root"
|
||||
$settings = Read-Settings $settingsBase
|
||||
if ([string]::IsNullOrWhiteSpace($CompatibilityProfile)) {
|
||||
$CompatibilityProfile = $settings.compatibility_profile
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($PythonExecutable)) {
|
||||
$PythonExecutable = $settings.python_executable
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($RunRoot)) {
|
||||
$RunRoot = $settings.run_root
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($DXToolsHome)) {
|
||||
$DXToolsHome = $settings.dxtools_home
|
||||
}
|
||||
}
|
||||
|
||||
$toolHome = Resolve-RequiredPath $DXToolsHome "DXToolsHome"
|
||||
$run = Resolve-RequiredPath $RunRoot "RunRoot"
|
||||
$profile = Resolve-RequiredPath $CompatibilityProfile "CompatibilityProfile"
|
||||
$python = Resolve-RequiredPath $PythonExecutable "PythonExecutable"
|
||||
if (-not (Test-Path -LiteralPath $toolHome -PathType Container)) {
|
||||
throw "DXTOOLS_HOME does not exist: $toolHome"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $python -PathType Leaf)) {
|
||||
throw "PythonExecutable does not exist: $python"
|
||||
}
|
||||
|
||||
$deployedRun = Join-Path $toolHome "runs"
|
||||
$deployedProfile = Join-Path $deployedRun "compatibility-profile.json"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
if (-not (Test-SamePath $run $deployedRun)) {
|
||||
throw "RunRoot must use the deployed DXTOOLS_HOME runs directory"
|
||||
}
|
||||
if (-not (Test-SamePath $profile $deployedProfile)) {
|
||||
throw "CompatibilityProfile must use the deployed compatibility profile"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $deployedProfile -PathType Leaf)) {
|
||||
throw "deployed compatibility profile does not exist: $deployedProfile"
|
||||
}
|
||||
|
||||
$discovery = $null
|
||||
$mappingPath = $null
|
||||
$projectsPath = $null
|
||||
$certificationPath = $null
|
||||
$resume = $null
|
||||
$resumeMode = -not [string]::IsNullOrWhiteSpace($ResumeJob)
|
||||
if ($resumeMode) {
|
||||
foreach ($value in @($Mapping, $Projects, $Certifications, $DiscoveryRoot)) {
|
||||
if (-not [string]::IsNullOrWhiteSpace($value)) {
|
||||
throw "ResumeJob cannot be combined with create or discovery inputs"
|
||||
}
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted($ResumeJob)) {
|
||||
throw "ResumeJob must be an absolute job directory"
|
||||
}
|
||||
$resume = Resolve-RequiredPath $ResumeJob "ResumeJob"
|
||||
if (-not (Test-DirectChildPath $deployedRun $resume)) {
|
||||
throw "ResumeJob must be a direct child of the deployed run root"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $resume -PathType Container)) {
|
||||
throw "ResumeJob does not exist: $resume"
|
||||
}
|
||||
}
|
||||
elseif (-not [string]::IsNullOrWhiteSpace($DiscoveryRoot)) {
|
||||
$discovery = Resolve-RequiredPath $DiscoveryRoot "DiscoveryRoot"
|
||||
}
|
||||
else {
|
||||
$mappingPath = Resolve-RequiredPath $Mapping "Mapping"
|
||||
$projectsPath = Resolve-RequiredPath $Projects "Projects"
|
||||
$certificationPath = Resolve-RequiredPath $Certifications "Certifications"
|
||||
}
|
||||
|
||||
if ($null -ne $mappingPath) {
|
||||
Write-Output "Mapping=$mappingPath"
|
||||
Write-Output "Certifications=$certificationPath"
|
||||
}
|
||||
if ($null -ne $resume) {
|
||||
Write-Output "ResumeJob=$resume"
|
||||
}
|
||||
Write-Output "CompatibilityProfile=$deployedProfile"
|
||||
Write-Output "PythonExecutable=$python"
|
||||
Write-Output "RunRoot=$deployedRun"
|
||||
Write-Output "DXToolsHome=$toolHome"
|
||||
if ($null -ne $discovery) {
|
||||
Write-Output "DiscoveryRoot=$discovery"
|
||||
}
|
||||
elseif ($null -ne $projectsPath) {
|
||||
Write-Output "Projects=$projectsPath"
|
||||
}
|
||||
if ($WhatIf) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-DxNoReparsePath $toolHome "DXTOOLS_HOME"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
if ($null -ne $resume) {
|
||||
Assert-DxNoReparsePath $resume "ResumeJob"
|
||||
}
|
||||
elseif ($null -ne $discovery) {
|
||||
Assert-DxNoReparsePath $discovery "DiscoveryRoot"
|
||||
}
|
||||
else {
|
||||
Assert-DxNoReparsePath $mappingPath "Mapping"
|
||||
Assert-DxNoReparsePath $projectsPath "Projects"
|
||||
Assert-DxNoReparsePath $certificationPath "Certifications"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $deployedRun | Out-Null
|
||||
if ($null -ne $discovery) {
|
||||
$discoveredProjects = Join-Path $deployedRun "discovered-projects.txt"
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $discovery "DiscoveryRoot"
|
||||
Assert-DxNoReparsePath $discoveredProjects "discovery output"
|
||||
$discoverArguments = @(
|
||||
"-m", "dx_productivity", "discover", $discovery,
|
||||
"--output", $discoveredProjects
|
||||
)
|
||||
& $python @discoverArguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
Write-Output "GeneratedProjects=$discoveredProjects"
|
||||
Write-Output "Review discovered candidates before creating a job."
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($null -ne $resume) {
|
||||
$job = $resume
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$statusArguments = @(
|
||||
"-m", "dx_productivity", "--json", "status", $job
|
||||
)
|
||||
$statusOutput = @(& $python @statusArguments)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
try {
|
||||
$resumeStatus = [string]::Join(
|
||||
[Environment]::NewLine,
|
||||
$statusOutput
|
||||
) | ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "status did not return valid JSON"
|
||||
}
|
||||
Assert-ResumeStatus $resumeStatus
|
||||
if ([string]$resumeStatus.job_id -cne (Split-Path -Leaf $job)) {
|
||||
throw "status result job_id does not match ResumeJob"
|
||||
}
|
||||
$jobId = [string]$resumeStatus.job_id
|
||||
$projectRecords = @(
|
||||
$resumeStatus.projects | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
display_name = [string]$_.display_name
|
||||
project_id = [string]$_.project_id
|
||||
project_path = [string]$_.project_path
|
||||
}
|
||||
}
|
||||
)
|
||||
$projectContext = "status"
|
||||
}
|
||||
else {
|
||||
$job = Join-Path $deployedRun (
|
||||
"part-replace-" + [guid]::NewGuid().ToString("N")
|
||||
)
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $mappingPath "Mapping"
|
||||
Assert-DxNoReparsePath $projectsPath "Projects"
|
||||
Assert-DxNoReparsePath $certificationPath "Certifications"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$createArguments = @(
|
||||
"-m", "dx_productivity", "--json", "create", $job,
|
||||
"--mapping", $mappingPath,
|
||||
"--projects", $projectsPath,
|
||||
"--certifications", $certificationPath
|
||||
)
|
||||
$createOutput = @(& $python @createArguments)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
try {
|
||||
$created = [string]::Join([Environment]::NewLine, $createOutput) |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "create did not return valid JSON"
|
||||
}
|
||||
Assert-ExactObject $created @("job_id", "projects", "states") "create result"
|
||||
if ($created.projects -isnot [object[]]) {
|
||||
throw "create result projects must be an array"
|
||||
}
|
||||
if ($created.projects.Count -eq 0) {
|
||||
throw "create returned no projects"
|
||||
}
|
||||
if ($created.job_id -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($created.job_id)) {
|
||||
throw "create result job_id is invalid"
|
||||
}
|
||||
$jobId = [string]$created.job_id
|
||||
$projectRecords = $created.projects
|
||||
$projectContext = "create"
|
||||
}
|
||||
|
||||
$entries = @()
|
||||
$seenProjectIds = New-Object 'Collections.Generic.HashSet[string]' (
|
||||
[StringComparer]::Ordinal
|
||||
)
|
||||
$seenProjectPaths = New-Object 'Collections.Generic.HashSet[string]' (
|
||||
[StringComparer]::OrdinalIgnoreCase
|
||||
)
|
||||
foreach ($project in $projectRecords) {
|
||||
Assert-ExactObject $project @(
|
||||
"display_name", "project_id", "project_path"
|
||||
) "$projectContext project"
|
||||
foreach ($name in @("display_name", "project_id", "project_path")) {
|
||||
if ($project.$name -isnot [string] -or
|
||||
[string]::IsNullOrWhiteSpace($project.$name)) {
|
||||
throw "$projectContext returned an invalid project $name"
|
||||
}
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted([string]$project.project_path)) {
|
||||
throw "$projectContext returned a relative project path"
|
||||
}
|
||||
$projectId = [string]$project.project_id
|
||||
if (-not $seenProjectIds.Add($projectId)) {
|
||||
throw "$projectContext returned duplicate project_id: $projectId"
|
||||
}
|
||||
if ($projectId.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0 -or
|
||||
$projectId.Contains('/') -or $projectId.Contains('\')) {
|
||||
throw "create returned an invalid project_id: $projectId"
|
||||
}
|
||||
$canonicalProjectPath = Resolve-FullPath ([string]$project.project_path)
|
||||
if (-not $seenProjectPaths.Add($canonicalProjectPath)) {
|
||||
throw "$projectContext returned duplicate project path"
|
||||
}
|
||||
$mailboxDirectory = Join-Path (Join-Path $job "mailbox") $projectId
|
||||
$commandPath = Join-Path $mailboxDirectory "command.json"
|
||||
Assert-DxNoReparsePath $mailboxDirectory "mailbox directory"
|
||||
Assert-DxNoReparsePath $commandPath "mailbox command"
|
||||
$entries += [ordered]@{
|
||||
project_id = $projectId
|
||||
project_path = [string]$project.project_path
|
||||
profile = "runs/compatibility-profile.json"
|
||||
command = Convert-ToRunRelativePath $toolHome $commandPath "command"
|
||||
status = Convert-ToRunRelativePath $toolHome (
|
||||
Join-Path $mailboxDirectory "status.json"
|
||||
) "status"
|
||||
snapshot = Convert-ToRunRelativePath $toolHome (
|
||||
Join-Path $mailboxDirectory "snapshot.json"
|
||||
) "snapshot"
|
||||
}
|
||||
}
|
||||
|
||||
$manifestPath = Join-Path $deployedRun "current-part-replacement.json"
|
||||
Assert-DxNoReparsePath $toolHome "DXTOOLS_HOME"
|
||||
Assert-DxNoReparsePath $deployedRun "deployed run root"
|
||||
Assert-DxNoReparsePath $deployedProfile "deployed compatibility profile"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
Assert-DxNoReparsePath $manifestPath "manifest destination"
|
||||
|
||||
while ($true) {
|
||||
Assert-DxNoReparsePath $python "PythonExecutable"
|
||||
Assert-DxNoReparsePath $job "job directory"
|
||||
$stepArguments = @(
|
||||
"-m", "dx_productivity", "--json", "operator-step", $job
|
||||
)
|
||||
$stepOutput = @(& $python @stepArguments)
|
||||
$stepExitCode = $LASTEXITCODE
|
||||
if ($stepExitCode -notin @(0, 4)) {
|
||||
exit $stepExitCode
|
||||
}
|
||||
try {
|
||||
$step = [string]::Join([Environment]::NewLine, $stepOutput) |
|
||||
ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "operator-step did not return valid JSON"
|
||||
}
|
||||
Assert-OperatorStepResult $step $jobId
|
||||
|
||||
if ($step.complete) {
|
||||
if ($stepExitCode -ne 0) {
|
||||
throw "completed operator-step returned a nonzero status"
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
complete = $true
|
||||
current_action = $null
|
||||
current_command_id = $null
|
||||
current_project_id = $null
|
||||
format_version = 2
|
||||
projects = $entries
|
||||
}
|
||||
$manifestText = ($manifest | ConvertTo-Json -Depth 7 -Compress) + "`n"
|
||||
Write-DxUtf8Atomic $manifestPath $manifestText
|
||||
Write-Output "Part replacement job complete: $job"
|
||||
break
|
||||
}
|
||||
if ($stepExitCode -ne 4) {
|
||||
throw "pending operator-step must return status 4"
|
||||
}
|
||||
$matchingEntries = @(
|
||||
$entries | Where-Object {
|
||||
$_.project_id -ceq [string]$step.project.project_id
|
||||
}
|
||||
)
|
||||
if ($matchingEntries.Count -ne 1 -or
|
||||
-not (Test-SamePath $matchingEntries[0].project_path `
|
||||
$step.project.project_path)) {
|
||||
throw "operator-step project is not an exact created-project match"
|
||||
}
|
||||
$currentEntry = $matchingEntries[0]
|
||||
$currentCommandPath = Join-Path $toolHome (
|
||||
[string]$currentEntry.command
|
||||
)
|
||||
Assert-DxNoReparsePath $currentCommandPath "current mailbox command"
|
||||
if (-not (Test-Path -LiteralPath $currentCommandPath -PathType Leaf)) {
|
||||
throw "operator-step did not publish its current command"
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
complete = $false
|
||||
current_action = [string]$step.command.action
|
||||
current_command_id = [string]$step.command.command_id
|
||||
current_project_id = [string]$step.project.project_id
|
||||
format_version = 2
|
||||
projects = $entries
|
||||
}
|
||||
$manifestText = ($manifest | ConvertTo-Json -Depth 7 -Compress) + "`n"
|
||||
Write-DxUtf8Atomic $manifestPath $manifestText
|
||||
|
||||
Write-Output ("CurrentProject=" + [string]$step.project.project_path)
|
||||
Write-Output ("CurrentAction=" + [string]$step.command.action)
|
||||
if ($null -ne $step.manual_route) {
|
||||
Write-Output ("ManualRoute=" + [string]$step.manual_route)
|
||||
}
|
||||
if ($null -ne $step.instruction) {
|
||||
Write-Output ("Instruction=" + [string]$step.instruction)
|
||||
}
|
||||
$operatorPrompt = (
|
||||
"Run current part replacement step in DxDesigner, " +
|
||||
"then press Enter to continue or Q to quit"
|
||||
)
|
||||
Write-Output $operatorPrompt
|
||||
$response = Read-Host "Enter/Q"
|
||||
if ([string]::Equals(
|
||||
[string]$response,
|
||||
"q",
|
||||
[StringComparison]::OrdinalIgnoreCase
|
||||
)) {
|
||||
Write-Output "Part replacement job paused: $job"
|
||||
break
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user