PowerShell_Scripts/docker/Switch-DockerCompose.ps1

90 lines
3.3 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[Parameter(ParameterSetName="On",Mandatory)]
[switch]$On,
[Parameter(ParameterSetName="Off",Mandatory)]
[switch]$Off,
[Parameter(ParameterSetName="Toggle",Mandatory)]
[switch]$Toggle,
[switch]$Recurse,
[int]$Depth=1,
[Parameter(ParameterSetName="On",Position = 0, ValueFromRemainingArguments)]
[Parameter(ParameterSetName="Off",Position = 0, ValueFromRemainingArguments)]
[Parameter(ParameterSetName="Toggle",Position = 0, ValueFromRemainingArguments)]
[Parameter(ParameterSetName="Query",Position = 0, ValueFromRemainingArguments)]
[ArgumentCompleter({Invoke-Command -ScriptBlock $_DockerComposeDirsCompleter -ArgumentList $args})]
[string[]]$ProjectPath
)
if( -not $ProjectPath ) { $ProjectPath=@($PWD) }
$local:ext = ".yml"
$local:dcPathList = @()
$ProjectPath | ForEach-Object {
while( $true ) {
if( (Test-Path (Join-Path $_ "docker-compose$ext")) -and -not $Recurse ) {
$dcPathList += Resolve-Path $_
} elseif( $Recurse ) {
$local:gciParams = [ordered]@{
Recurse = $true
}
if( $Depth ) {
$gciParams.Depth = $Depth
}
$dcPathList += Get-ChildItem -Path $_ -Include "docker-compose$ext" @gciParams |
Select-Object -ExpandProperty Directory
}
if( ($dcPathList -and -not $Recure) -or $ext -eq '.yaml' ) {
break
}
$ext = '.yaml'
}
}
if( -not $dcPathList ) { return }
$local:QueryOnly = -not $On -and -not $Off -and -not $Toggle
$dcPathList | ForEach-Object {
$local:name = "$_"
$local:c = Get-Content -Head 3 (Join-Path $_ "docker-compose$ext")
$local:r = [ordered]@{
Dir = Split-Path -Leaf $_
State = ""
Version = ($c[0] -replace 'Version: ','' -replace "[`"']",'').Trim()
Stack = "?"
}
if( $c[1] -match "^# stack(?:\W*): ?(\w+)\W*$" ) { $r.Stack = $matches[1] }
if( $c[2] -match "^# ports prefix: ([\dx#]{4,5})" ) { $r.Stack = $matches[1] + " | " + $r.Stack }
if( $PWD -like $name ) {
$name = Split-Path -Leaf $name
} else {
$name = $($name.Replace($PWD.Path,'').Substring(1))
}
$local:NoAutoPath = $(Join-Path $_ '.noauto.all')
$local:NoAutoOffPath = "${NoAutoPath}.off"
$local:IsOff = Test-Path $NoAutoPath
$local:IsExplicitOn = Test-Path $NoAutoOffPath
$local:SetOff = $Off -or ($Toggle -and -not $IsOff)
$local:SetOn = $On -or ($Toggle -and $IsOff)
if( ($QueryOnly -and $IsOff) -or (-not $QueryOnly -and $SetOff) ) {
if( -not $QueryOnly -and $IsExplicitOn ) {
Move-Item $NoAutoOffPath $NoAutoPath
} elseif( -not $QueryOnly -and -not $IsOff ) {
$null = New-Item -ItemType File -Path $NoAutoPath -Value ""
}
# Write-Host -ForegroundColor Magenta -NoNewline "Off"
$r.State = "Off"
} elseif( ($QueryOnly -and -not $IsOff) -or (-not $QueryOnly -and $SetOn) ) {
if( -not $QueryOnly -and $IsOff ) {
Move-Item $NoAutoPath $NoAutoOffPath
}
# Write-Host -ForegroundColor Green -NoNewline "On "
$r.State = "On"
}
# Write-Host -ForegroundColor Cyan " $name"
[PSCustomObject]$r
}