PowerShell_Scripts/base/Set-MyPackage.ps1

82 lines
3.1 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[Parameter(mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Pipe")]
[szPackage]$InputObject,
[Parameter(mandatory=$true, ParameterSetName="LocalHost")]
[switch]$LocalHost,
[Parameter(mandatory=$true, ParameterSetName="LocalUser")]
[switch]$LocalUser,
[switch]$Force,
[switch]$PassThru,
[switch]$DryRun,
[ValidateSet("Default","None")]
[string]$Template="Default"
)
process {
$local:iObj = $_
if( $LocalHost ) {
$iObj = New-MyPackage -Name "$(hostname).local" |
Add-PackageCondition -Hostname "$(hostname)"
} elseif( $LocalUser ) {
$iObj = New-MyPackage -Name "$($USER).local" |
Add-PackageCondition -Username $USER
}
Write-Verbose "Set-MyPackage called with $($iObj | Out-String)..."
$local:outObj = @{ package = @{ Name = $iObj.Name; Condition = @() } }
foreach( $local:c in $iObj.Condition ) {
$local:newC = [ordered]@{}
foreach( $local:p in $c.PSObject.Properties ) {
if( $p.TypeNameOfValue -match 'ScriptBlock' -and $p.Value ) {
$newC[$p.Name] = $p.Value.ToString().Trim()
} else {
$newC[$p.Name] = $p.Value
}
}
$outObj.package.Condition += $newC;
}
$local:jsonOut = $outObj | ConvertTo-Json -Depth 4
if( -not $DryRun ) {
$local:pkgPath = Join-Path $MyPSScriptRoot $iObj.name
Write-Verbose "pkgPath=$pkgPath"
if( -not (Test-Path $pkgPath) ) {
$null = New-Item -Type Directory $pkgPath -Force:$Force
} elseif ( -not $Force ) {
$Template = "None"
}
switch($Template){
"Default" {
function SafeMk{param([string]$Path,[string]$PathType="Directory")
if( Test-Path $Path ) { return }
$local:newItemParam = @{
Type = $PathType
Path = $Path
}
if( $PathType -eq 'File' ) { $newItemParam.Value = '' }
New-Item -Type $PathType $Path
}
SafeMk (Join-Path $pkgPath 'profile.d')
SafeMk (Join-Path $pkgPath 'Aliases')
SafeMk (Join-Path $pkgPath 'src')
SafeMk -PathType 'File' (Join-Path (Join-Path $pkgPath 'profile.d') 'env.local.ps1')
}
}
$jsonPath = Join-Path $pkgPath '_.package.json'
if( $Force -or -not (Test-Path $jsonPath) ) {
$jsonOut | Out-File $jsonPath -Force:$Force
$local:profilePath = $(Join-Path $pkgPath 'profile.d')
if( $LocalHost -or $LocalUser -and -not (Test-Path $profilePath) ) {
$null = New-Item -Type Directory $profilePath -Force:$Force
$null = New-Item -Type File $(Join-Path $profilePath env.ps1) -Value "# local environment"
}
} elseif ( Test-Path $jsonPath ) {
throw 'Package already exists!'
}
}
if( $PassThru ) {
$jsonOut
}
}