Public/DrawFile.ps1
|
#Requires -Version 7.0 # ============================================================ # DrawManagement — File Management Public Functions # # REVIEW CHANGES vs original: # [FILE-01] New-DrawFile: removed the conditional on Vars.Count — # always assign the parameter so an explicit empty @{} # resets any prior value; also added Version validation. # [FILE-02] Save-DrawFile: replaced [System.IO.File]::WriteAllText # with Set-Content so the operation participates in the # normal PS provider pipeline (respects PSDrive, transcript, # -WhatIf) — this is the PS-idiomatic approach. # [FILE-03] Save-DrawFile: added -LiteralPath on Test-Path / Split-Path # to handle paths with [ ] characters correctly. # [FILE-04] Save-DrawFile: the ShouldProcess check was only guarding # the overwrite case; restructured so -WhatIf is respected # for all writes, not just overwrites. # [FILE-05] Open-DrawFile: removed ?? null-coalescing operator (PS 5.1 # incompatible) — replaced with if/else guards throughout. # [FILE-06] Open-DrawFile: -AsHashtable on ConvertFrom-Json is PS 6+ # only — replaced with a manual PSObject-to-hashtable # conversion for PS 5.1 compatibility. # [FILE-07] Open-DrawFile: XML parse wrapped in try/catch with a # descriptive error rather than letting the raw [xml] cast # throw an unhelpful .NET exception. # [FILE-08] Get-DrawFileInfo: TotalCells calculation wrapped with a # null check so a DrawFile with no pages doesn't throw. # [FILE-09] Set-DrawFileVar: added validation that variable name # contains only characters valid in a draw.io placeholder # (%name% — letters, digits, underscore). # ============================================================ function New-DrawFile { <# .SYNOPSIS Creates a new empty draw.io file object in memory. .DESCRIPTION Returns a [DrawFile] object. Add pages with Add-DrawPage, then save with Save-DrawFile. The file is self-contained: all stencils, metadata and variables are embedded in the XML. .PARAMETER FilePath Optional. The output .drawio file path. Can also be supplied later when calling Save-DrawFile. .PARAMETER Vars Hashtable of global placeholder variables, saved on each page's root cell where draw.io resolves them. Use %varname% in any shape label or tooltip whose cell has placeholders enabled (metadata key 'placeholders' = '1'). Keys: letters, digits, '_' or '-'. .PARAMETER Version draw.io version string written to the file header. Default: '21.0.0'. .EXAMPLE $doc = New-DrawFile -FilePath 'C:\diagrams\arch.drawio' ` -Vars @{ env = 'production'; team = 'infra' } .OUTPUTS [DrawFile] #> [CmdletBinding()] [OutputType([DrawFile])] param( [Parameter()][string] $FilePath, [Parameter()][hashtable] $Vars = @{}, [Parameter()][ValidateNotNullOrEmpty()][string] $Version = '21.0.0' ) $file = New-Object DrawFile if (-not [string]::IsNullOrWhiteSpace($FilePath)) { $file.FilePath = $FilePath } # [FILE-01] always assign Vars — an explicit empty @{} should clear $file.Vars = $Vars $file.Version = $Version Write-Verbose "New-DrawFile: created DrawFile (FilePath='$FilePath')" return $file } function Save-DrawFile { <# .SYNOPSIS Serialises a DrawFile to an XML .drawio file on disk. .DESCRIPTION Writes uncompressed UTF-8 mxfile XML. The resulting file is fully self-contained — no external assets required to open it. .PARAMETER DrawFile The [DrawFile] object returned by New-DrawFile. .PARAMETER Path Output file path. Overrides DrawFile.FilePath when specified. .PARAMETER Force Overwrite an existing file without prompting. .EXAMPLE Save-DrawFile -DrawFile $doc -Path 'C:\out\diagram.drawio' -Force .INPUTS [DrawFile] via pipeline. .OUTPUTS [System.IO.FileInfo] #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] [OutputType([System.IO.FileInfo])] param( [Parameter(Mandatory, ValueFromPipeline)][DrawFile] $DrawFile, [Parameter()][string] $Path, [Parameter()][switch] $Force ) process { $outPath = if (-not [string]::IsNullOrWhiteSpace($Path)) { $Path } else { $DrawFile.FilePath } if ([string]::IsNullOrWhiteSpace($outPath)) { throw "Save-DrawFile: no output path supplied and DrawFile.FilePath is not set." } # [FILE-03] -LiteralPath prevents [ ] expansion $fileExists = Test-Path -LiteralPath $outPath if ($fileExists -and -not $Force) { # [FILE-04] ShouldProcess covers both the overwrite prompt # and -WhatIf for ALL writes if (-not $PSCmdlet.ShouldProcess($outPath, 'Overwrite existing file')) { return } } elseif (-not $fileExists) { if (-not $PSCmdlet.ShouldProcess($outPath, 'Create new file')) { return } } # Ensure parent directory exists $dir = [System.IO.Path]::GetDirectoryName($outPath) if (-not [string]::IsNullOrWhiteSpace($dir) -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force -ErrorAction Stop | Out-Null Write-Verbose "Save-DrawFile: created directory '$dir'" } $xml = $DrawFile.ToXml() # [FILE-02] Set-Content is PS-idiomatic and provider-aware Set-Content -LiteralPath $outPath -Value $xml -Encoding UTF8 -Force -ErrorAction Stop $sizeKb = [Math]::Round($xml.Length / 1KB, 1) Write-Verbose "Save-DrawFile: saved '$outPath' ($sizeKb KB)" return Get-Item -LiteralPath $outPath } } function Open-DrawFile { <# .SYNOPSIS Parses an existing .drawio XML file into a [DrawFile] object. .DESCRIPTION Reads the mxfile XML and reconstructs pages, cells, edges and embedded vars. Supports full round-trip: Open → modify → Save. UserObject metadata is also restored if present in the source file. .PARAMETER Path Path to the .drawio file. .EXAMPLE $doc = Open-DrawFile -Path 'C:\diagrams\arch.drawio' .OUTPUTS [DrawFile] #> [CmdletBinding()] [OutputType([DrawFile])] param( [Parameter(Mandatory)][string]$Path ) # [FILE-03] -LiteralPath if (-not (Test-Path -LiteralPath $Path)) { throw "Open-DrawFile: file not found: '$Path'" } # [FILE-07] wrap XML parse with a descriptive error $rawXml = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 -ErrorAction Stop try { $xml = [xml]$rawXml } catch { throw "Open-DrawFile: '$Path' is not valid XML. Error: $_" } # [FIX-26] DocumentElement, not $xml.mxfile. This guard exists to turn # "you handed me the wrong kind of file" into a sentence a user can act # on — but under Set-StrictMode -Version Latest the property read in its # own condition threw first, so the message was never reachable. Opening # an .html, an .svg, or an .xml from some other tool reported # The property 'mxfile' cannot be found on this object. # which says nothing about draw.io and points at no file. Same defect # family as FIX-21: a bare XML property access standing in for a test of # whether that property exists. $xml.DocumentElement is a real property # of XmlDocument, so reading it is always safe, and comparing .Name is # the test that was intended all along. $mxfile = $xml.DocumentElement if ($null -eq $mxfile -or $mxfile.Name -ne 'mxfile') { $found = if ($null -eq $mxfile) { 'nothing' } else { "<$($mxfile.Name)>" } throw ("Open-DrawFile: '$Path' does not contain an <mxfile> root element " + "(found $found) — is this a draw.io file?") } $file = [DrawFile]::new($Path) # Parse file-level vars. [FIX-39] Files written before v1.3.0 carry them # in <mxfile vars="{json}">; current files put them on each page's root # cell, which is read below and wins. $varsAttr = $mxfile.GetAttribute('vars') if (-not [string]::IsNullOrWhiteSpace($varsAttr)) { try { # [FILE-06] PS 5.1-compatible JSON → hashtable conversion $parsedVars = $varsAttr | ConvertFrom-Json $ht = @{} $parsedVars.PSObject.Properties | ForEach-Object { $ht[$_.Name] = $_.Value } $file.Vars = $ht } catch { Write-Warning "Open-DrawFile: could not parse file-level vars: $_" } } # [FILE-05] PS 5.1-safe version assignment — no ?? # [FIX-21] via Get-XmlAttr. $xml.mxfile.version threw # PropertyNotFoundStrict on any <mxfile> that carries no version # attribute, so a hand-written or third-party file could not be opened # AT ALL — and the message named a property instead of the cause. $file.Version = Get-XmlAttr -Node $mxfile -Name 'version' -Default '21.0.0' # Parse diagram pages. SelectNodes, not $xml.mxfile.diagram: the # property access throws when there are no <diagram> children, which is # exactly the case the warning below is meant to report. $diagrams = @($mxfile.SelectNodes('diagram')) if ($diagrams.Count -eq 0) { Write-Warning "Open-DrawFile: no <diagram> elements found in '$Path'." return $file } foreach ($diag in $diagrams) { # [FIX-21] name/id through Get-XmlAttr for the same reason: draw.io # always writes both, but nothing in the format requires them. $pageName = Get-XmlAttr -Node $diag -Name 'name' -Default 'Page' $page = [DrawPage]::new($pageName) $pageId = Get-XmlAttr -Node $diag -Name 'id' $page.Id = if ([string]::IsNullOrWhiteSpace($pageId)) { [DrawCell]::NewId() } else { $pageId } # [FIX-20] A <diagram> may hold its page compressed (base64 of raw # deflate of the percent-encoded XML) rather than as a child # <mxGraphModel> — that is draw.io's DEFAULT on save. Reading # $diag.mxGraphModel threw outright on those files under # Set-StrictMode. Get-DrawDiagramModel handles both layouts. $model = Get-DrawDiagramModel -Diagram $diag -PageName $pageName if ($null -ne $model) { # [FIX-21] Every one of these was a bare property read, and every # one threw when draw.io happened not to write that attribute — # 'tooltips' is omitted whenever tooltips are on, which is the # default. The FIX-04 comment below already stated the rule; it # had simply only been applied to 'background'. $pw = Get-XmlAttr -Node $model -Name 'pageWidth' $ph = Get-XmlAttr -Node $model -Name 'pageHeight' $page.PageWidth = if ([string]::IsNullOrWhiteSpace($pw)) { 1100 } else { [int][double]$pw } $page.PageHeight = if ([string]::IsNullOrWhiteSpace($ph)) { 850 } else { [int][double]$ph } # [FIX-24] gridSize was WRITTEN by DrawPage.ToXml but never read # back, so a page saved with GridSize 25 reopened as 10 and the # next save silently rewrote the user's grid. $gs = Get-XmlAttr -Node $model -Name 'gridSize' if (-not [string]::IsNullOrWhiteSpace($gs)) { $page.GridSize = [int][double]$gs } $page.Grid = ((Get-XmlAttr -Node $model -Name 'grid') -eq '1') $page.Tooltips = ((Get-XmlAttr -Node $model -Name 'tooltips' -Default '1') -eq '1') # [FIX-04] preserve the canvas background on round-trip. # HasAttribute, not $model.background — under Set-StrictMode # -Version Latest a missing XML attribute throws on access. $page.Background = Get-XmlAttr -Node $model -Name 'background' # [FIX-05] Walk root's child ELEMENTS rather than $model.root.mxCell. # Two reasons: # 1. Every attribute read must go through Get-XmlAttr — under # Set-StrictMode -Version Latest, $node.missingAttr throws. # The previous code hit this on $mxCell.edge for the first # vertex in any non-empty file, so Open-DrawFile only ever # worked on pages with no shapes at all. # 2. Cells carrying metadata/tooltip/link are written as # <UserObject><mxCell/></UserObject>. The old loop looked # only at direct mxCell children, so those were dropped. # [FIX-21] SelectSingleNode, not $model.root — the property read # throws on an <mxGraphModel/> that has no root child. $rootNode = $model.SelectSingleNode('root') if ($null -ne $rootNode) { foreach ($node in @($rootNode.ChildNodes)) { if ($node -isnot [System.Xml.XmlElement]) { continue } # Unwrap UserObject: the geometry lives on the inner mxCell, # the label and custom properties on the wrapper. $isUserObj = ($node.LocalName -eq 'UserObject' -or $node.LocalName -eq 'object') if ($isUserObj) { $mxCell = @($node.ChildNodes | Where-Object { $_ -is [System.Xml.XmlElement] -and $_.LocalName -eq 'mxCell' })[0] if ($null -eq $mxCell) { continue } $wrapper = $node } elseif ($node.LocalName -eq 'mxCell') { $mxCell = $node $wrapper = $null } else { continue } $id = Get-XmlAttr -Node $mxCell -Name 'id' if ([string]::IsNullOrEmpty($id) -and $null -ne $wrapper) { $id = Get-XmlAttr -Node $wrapper -Name 'id' } if ($id -eq '0' -and $null -ne $wrapper) { # [FIX-39] file-level vars live on the root cell; they # override the legacy <mxfile vars> attribute foreach ($a in @($wrapper.Attributes)) { if ($a.Name -in 'id', 'label', 'placeholders') { continue } $file.Vars[$a.Name] = $a.Value } continue } if ($id -eq '0' -or $id -eq '1' -or [string]::IsNullOrEmpty($id)) { continue } # Label: UserObject carries it as 'label', plain cell as 'value' $label = if ($null -ne $wrapper) { Get-XmlAttr -Node $wrapper -Name 'label' } else { Get-XmlAttr -Node $mxCell -Name 'value' } if ((Get-XmlAttr -Node $mxCell -Name 'edge') -eq '1') { $edge = New-Object DrawEdge $edge.Id = $id $edge.Label = $label $edge.SourceId = Get-XmlAttr -Node $mxCell -Name 'source' $edge.TargetId = Get-XmlAttr -Node $mxCell -Name 'target' $edge.Style = Get-XmlAttr -Node $mxCell -Name 'style' ` -Default 'edgeStyle=orthogonalEdgeStyle;html=1;' $edge.ParentId = Get-XmlAttr -Node $mxCell -Name 'parent' -Default '1' # [FIX-25] The tooltip belongs on the UserObject # wrapper — that is the only place draw.io reads it # from. Fall back to the inner mxCell so files written # by earlier versions of this module, which put it # there, still round-trip their tooltip text. $edge.Tooltip = Get-XmlAttr -Node $wrapper -Name 'tooltip' if ([string]::IsNullOrEmpty($edge.Tooltip)) { $edge.Tooltip = Get-XmlAttr -Node $mxCell -Name 'tooltip' } if ($null -ne $wrapper) { $edge.Link = Get-XmlAttr -Node $wrapper -Name 'link' $edge.Metadata = ConvertFrom-UserObjectAttr -Wrapper $wrapper # [FIX-16] structural — ConvertFrom-UserObjectAttr # deliberately keeps it out of the metadata bag, so # it has to be restored onto the field explicitly. $edge.Placeholders = (Get-XmlAttr -Node $wrapper -Name 'placeholders') -eq '1' } $page.AddEdge($edge) } else { $c = [DrawCell]::new($label) $c.Id = $id $c.Style = Get-XmlAttr -Node $mxCell -Name 'style' $c.ParentId = Get-XmlAttr -Node $mxCell -Name 'parent' -Default '1' if ($null -ne $wrapper) { $c.Metadata = ConvertFrom-UserObjectAttr -Wrapper $wrapper $c.Tooltip = Get-XmlAttr -Node $wrapper -Name 'tooltip' $c.Link = Get-XmlAttr -Node $wrapper -Name 'link' # [FIX-16] draw.io resolves %var% only on a # UserObject carrying placeholders="1". Dropping it # here silently killed the variable feature on every # Open -> Save: the label came back as the literal # text "%env%". $c.Placeholders = (Get-XmlAttr -Node $wrapper -Name 'placeholders') -eq '1' } $geom = @($mxCell.ChildNodes | Where-Object { $_ -is [System.Xml.XmlElement] -and $_.LocalName -eq 'mxGeometry' })[0] if ($null -ne $geom) { $c.X = [double](Get-XmlAttr -Node $geom -Name 'x' -Default '0') $c.Y = [double](Get-XmlAttr -Node $geom -Name 'y' -Default '0') $c.Width = [double](Get-XmlAttr -Node $geom -Name 'width' -Default '120') $c.Height = [double](Get-XmlAttr -Node $geom -Name 'height' -Default '60') } # A swimlane is a container; keep it in the Containers # list so ToXml re-emits it ahead of its children. if ($c.Style -match '(^|;)\s*swimlane\b') { $page.AddContainer($c) } else { $page.AddCell($c) } } } } } $file.AddPage($page) } # [FIX-13] Restore embedded stencils from the mxlibrary comment. # # Be clear about what this comment is: it is DrawManagement's own # sidecar, not something draw.io reads. draw.io loads shape palettes # from separate <mxlibrary> files (File > Open Library), and an XML # comment inside an mxfile is invisible to it either way. # Without this block the module could not even round-trip its own # output — saving 3 stencils and reopening gave back 0. $libMatch = [regex]::Match($rawXml, '<!--\s*mxlibrary:\s*(\[.*?\])\s*-->', 'Singleline') if ($libMatch.Success) { try { foreach ($entry in (@($libMatch.Groups[1].Value | ConvertFrom-Json))) { $title = Get-DrawObjectProperty -InputObject $entry -Name 'title' if ([string]::IsNullOrWhiteSpace($title)) { continue } $stencil = [DrawStencil]::new([string]$title) $w = Get-DrawObjectProperty -InputObject $entry -Name 'w' $h = Get-DrawObjectProperty -InputObject $entry -Name 'h' if ($null -ne $w) { $stencil.Width = [int]$w } if ($null -ne $h) { $stencil.Height = [int]$h } $stencil.AspectFixed = ((Get-DrawObjectProperty -InputObject $entry -Name 'aspect') -eq 'fixed') $data = Get-DrawObjectProperty -InputObject $entry -Name 'data' $xmlD = Get-DrawObjectProperty -InputObject $entry -Name 'xml' if (-not [string]::IsNullOrWhiteSpace($data)) { $stencil.ImageData = [string]$data } elseif (-not [string]::IsNullOrWhiteSpace($xmlD)) { $stencil.MxGraphXml = [string]$xmlD } $file.AddStencil($stencil) } Write-Verbose "Open-DrawFile: restored $($file.EmbeddedStencils.Count) embedded stencils" } catch { Write-Warning ("Open-DrawFile: the mxlibrary block in '$Path' could not be parsed " + "($($_.Exception.Message)); embedded stencils were skipped.") } } Write-Verbose "Open-DrawFile: loaded '$Path' ($($file.Pages.Count) pages)" return $file } function Get-DrawFileInfo { <# .SYNOPSIS Returns a structured summary of the draw.io file. .PARAMETER DrawFile The [DrawFile] to inspect. .EXAMPLE $doc | Get-DrawFileInfo .INPUTS [DrawFile] via pipeline. .OUTPUTS [PSCustomObject] #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile ) process { # [FILE-08] guard against empty pages list $totalCells = 0 if ($DrawFile.Pages.Count -gt 0) { $totalCells = ($DrawFile.Pages | ForEach-Object { $_.Cells.Count + $_.Edges.Count + $_.Containers.Count } | Measure-Object -Sum).Sum } [PSCustomObject]@{ PSTypeName = 'DrawManagement.FileInfo' FilePath = $DrawFile.FilePath Version = $DrawFile.Version Pages = $DrawFile.Pages.Count PageNames = @($DrawFile.Pages | ForEach-Object { $_.Name }) GlobalVars = $DrawFile.Vars EmbeddedStencils = $DrawFile.EmbeddedStencils.Count TotalCells = $totalCells } } } function Set-DrawFileVar { <# .SYNOPSIS Sets or updates a global placeholder variable on a DrawFile. .DESCRIPTION Variables are stored as attributes of each page's root cell — the place draw.io itself keeps them (Edit Data on the canvas) — and substituted at render time in any label or tooltip whose cell has placeholders="1". .PARAMETER DrawFile The target [DrawFile]. .PARAMETER Name Variable name (without % delimiters). Must contain only letters, digits, hyphens and underscores. .PARAMETER Value Variable value string. .EXAMPLE Set-DrawFileVar -DrawFile $doc -Name 'env' -Value 'staging' .INPUTS [DrawFile] via pipeline. .OUTPUTS None #> [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Name, [Parameter(Mandatory)][string]$Value ) process { # [FILE-09] validate name — draw.io placeholders use %name% syntax; # spaces and special chars in the key break the substitution if ($Name -notmatch '^[a-zA-Z0-9_\-]+$') { throw ("Set-DrawFileVar: variable name '$Name' is invalid. " + "Use only letters, digits, hyphens and underscores.") } $DrawFile.Vars[$Name] = $Value Write-Verbose "Set-DrawFileVar: %$Name% = '$Value'" } } |