PowerShell_Scripts/docker/Switch-DockerCompose.ps1

77 lines
2.9 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 # |
# Where-Object { $Force -or -not (Test-Path $(Join-Path $_ .noauto.all)) }
}
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 = "$_"
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"
} elseif( ($QueryOnly -and -not $IsOff) -or (-not $QueryOnly -and $SetOn) ) {
if( -not $QueryOnly -and $IsOff ) {
Move-Item $NoAutoPath $NoAutoOffPath
}
Write-Host -ForegroundColor Gree -NoNewline "On "
}
Write-Host -ForegroundColor Cyan " $name"
}