Skip to content

Commit 9d9505d

Browse files
committed
Rollback-Refactor-1
Signed-off-by: Nick2bad4u <20943337+Nick2bad4u@users.noreply.github.com>
1 parent 95e03c5 commit 9d9505d

17 files changed

Lines changed: 4281 additions & 4154 deletions

ColorScripts-Enhanced/ColorScripts-Enhanced.psm1

Lines changed: 86 additions & 4077 deletions
Large diffs are not rendered by default.

ColorScripts-Enhanced/Private/PrivateFunctions.ps1

Lines changed: 2607 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
function Add-ColorScriptProfile {
2+
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Function already implements explicit ShouldProcess semantics.')]
3+
[CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://nick2bad4u.github.io/PS-Color-Scripts-Enhanced/docs/help-redirect.html?cmdlet=Add-ColorScriptProfile')]
4+
param(
5+
[Alias('help')]
6+
[switch]$h,
7+
8+
[Parameter()]
9+
[ValidateScript({ Test-ColorScriptPathValue $_ })]
10+
[string]$ProfilePath,
11+
12+
[Parameter()]
13+
[ValidateScript({ Test-ColorScriptNameValue $_ -AllowEmpty })]
14+
[string]$DefaultStartupScript,
15+
16+
[Parameter()]
17+
[switch]$AutoShow,
18+
19+
[Parameter()]
20+
[switch]$Force
21+
)
22+
23+
if ($h) {
24+
Show-ColorScriptHelp -CommandName 'Add-ColorScriptProfile'
25+
return
26+
}
27+
28+
Initialize-Configuration
29+
30+
$profilePath = if ($ProfilePath) { $ProfilePath } else { $PROFILE }
31+
$profilePath = [string]$profilePath
32+
33+
if ([string]::IsNullOrWhiteSpace($profilePath)) {
34+
Invoke-ColorScriptError -Message $script:Messages.ProfilePathNotSpecified -ErrorId 'ColorScriptsEnhanced.ProfilePathMissing' -Category ([System.Management.Automation.ErrorCategory]::InvalidArgument) -Cmdlet $PSCmdlet
35+
}
36+
37+
$resolvedProfile = Resolve-CachePath -Path $profilePath
38+
if ($resolvedProfile) {
39+
$profilePath = $resolvedProfile
40+
}
41+
else {
42+
if (-not [System.IO.Path]::IsPathRooted($profilePath)) {
43+
$profilePath = [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $profilePath))
44+
}
45+
}
46+
47+
$profileDirectory = Split-Path -Parent $profilePath
48+
if (-not (Test-Path $profileDirectory)) {
49+
New-Item -ItemType Directory -Path $profileDirectory -Force | Out-Null
50+
}
51+
52+
$existingContent = ''
53+
if (Test-Path -LiteralPath $profilePath) {
54+
$existingContent = Get-Content -LiteralPath $profilePath -Raw
55+
}
56+
57+
$newline = if ($existingContent -match "`r`n") {
58+
"`r`n"
59+
}
60+
elseif ($existingContent -match "`n") {
61+
"`n"
62+
}
63+
else {
64+
[Environment]::NewLine
65+
}
66+
$timestamp = (Get-Date).ToString('u')
67+
$snippetLines = @(
68+
"# Added by ColorScripts-Enhanced on $timestamp",
69+
'Import-Module ColorScripts-Enhanced'
70+
)
71+
72+
if ($AutoShow) {
73+
if (-not [string]::IsNullOrWhiteSpace($DefaultStartupScript)) {
74+
$safeName = $DefaultStartupScript -replace "'", "''"
75+
$snippetLines += "Show-ColorScript -Name '$safeName'"
76+
}
77+
else {
78+
$snippetLines += 'Show-ColorScript'
79+
}
80+
}
81+
82+
$snippet = ($snippetLines -join $newline)
83+
$updatedContent = $existingContent
84+
85+
$pattern = '(?ms)^# Added by ColorScripts-Enhanced.*?(?:\r?\n){2}'
86+
if ($updatedContent -match $pattern) {
87+
if (-not $Force) {
88+
Write-Verbose $script:Messages.ProfileAlreadyContainsSnippet
89+
return [pscustomobject]@{
90+
Path = $profilePath
91+
Changed = $false
92+
Message = $script:Messages.ProfileAlreadyConfigured
93+
}
94+
}
95+
96+
$updatedContent = [System.Text.RegularExpressions.Regex]::Replace($updatedContent, $pattern, '', 'MultiLine')
97+
}
98+
99+
$importPattern = '(?mi)^\s*Import-Module\s+ColorScripts-Enhanced\b.*$'
100+
101+
if (-not $Force -and $existingContent -match $importPattern) {
102+
Write-Verbose $script:Messages.ProfileAlreadyImportsModule
103+
return [pscustomobject]@{
104+
Path = $profilePath
105+
Changed = $false
106+
Message = $script:Messages.ProfileAlreadyConfigured
107+
}
108+
}
109+
110+
if ($Force) {
111+
$updatedContent = [System.Text.RegularExpressions.Regex]::Replace($updatedContent, $importPattern + '(?:\r?\n)?', '', 'Multiline')
112+
$showPattern = '(?mi)^\s*(Show-ColorScript|scs)\b.*(?:\r?\n)?'
113+
$updatedContent = [System.Text.RegularExpressions.Regex]::Replace($updatedContent, $showPattern, '', 'Multiline')
114+
}
115+
116+
if ($PSCmdlet.ShouldProcess($profilePath, 'Add ColorScripts-Enhanced profile snippet')) {
117+
$trimmedExisting = $updatedContent.TrimEnd()
118+
if ($trimmedExisting) {
119+
$updatedContent = $trimmedExisting + $newline + $newline + $snippet
120+
}
121+
else {
122+
$updatedContent = $snippet
123+
}
124+
125+
[System.IO.File]::WriteAllText($profilePath, $updatedContent + $newline, $script:Utf8NoBomEncoding)
126+
127+
Write-Host ($script:Messages.ProfileSnippetAdded -f $profilePath) -ForegroundColor Green
128+
129+
return [pscustomobject]@{
130+
Path = $profilePath
131+
Changed = $true
132+
Message = $script:Messages.ProfileSnippetAddedMessage
133+
}
134+
}
135+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
function Clear-ColorScriptCache {
2+
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium', HelpUri = 'https://nick2bad4u.github.io/PS-Color-Scripts-Enhanced/docs/help-redirect.html?cmdlet=Clear-ColorScriptCache')]
3+
param(
4+
[Alias('help')]
5+
[switch]$h,
6+
7+
[switch]$Force,
8+
9+
[switch]$PassThru
10+
)
11+
12+
if ($h) {
13+
Show-ColorScriptHelp -CommandName 'Clear-ColorScriptCache'
14+
return
15+
}
16+
17+
Initialize-CacheDirectory
18+
19+
if (-not $script:CacheDir) {
20+
Write-Warning $script:Messages.CacheDirectoryUnavailable
21+
return
22+
}
23+
24+
if (-not (Test-Path -LiteralPath $script:CacheDir)) {
25+
Write-Verbose $script:Messages.CacheDirectoryMissing
26+
return
27+
}
28+
29+
$cacheFiles = Get-ChildItem -Path $script:CacheDir -Filter '*.cache' -File -ErrorAction SilentlyContinue
30+
31+
if (-not $cacheFiles -or $cacheFiles.Count -eq 0) {
32+
Write-Verbose $script:Messages.CacheAlreadyEmpty
33+
return
34+
}
35+
36+
if (-not $Force -and -not (Invoke-ShouldProcess -Cmdlet $PSCmdlet -Target $script:CacheDir -Action 'Clear colorscript cache')) {
37+
return
38+
}
39+
40+
$removed = 0
41+
foreach ($file in $cacheFiles) {
42+
try {
43+
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
44+
$removed++
45+
}
46+
catch {
47+
Write-Warning ($script:Messages.FailedToRemoveCacheFile -f $file.Name, $_.Exception.Message)
48+
}
49+
}
50+
51+
if ($PassThru) {
52+
return [pscustomobject]@{
53+
RemovedCount = $removed
54+
CachePath = $script:CacheDir
55+
}
56+
}
57+
58+
Write-ColorScriptInformation -Message ($script:Messages.CacheFilesRemoved -f $removed) -Quiet:$false
59+
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
function Export-ColorScriptMetadata {
2+
<#
3+
.SYNOPSIS
4+
Export the module's colorscript metadata as structured objects or JSON.
5+
.DESCRIPTION
6+
Retrieves metadata for each colorscript, including categories and tags, and optionally augments it with
7+
file system and cache information. The result can be written to a JSON file for consumption by external
8+
tooling or returned directly to the pipeline.
9+
.PARAMETER Path
10+
Destination file path for the JSON output. When omitted, objects are emitted to the pipeline.
11+
.PARAMETER IncludeFileInfo
12+
Attach file system information (full path, file size, and last write time) for each colorscript.
13+
.PARAMETER IncludeCacheInfo
14+
Attach cache metadata including the cache location, whether a cache file exists, and its timestamp.
15+
.PARAMETER PassThru
16+
Return the in-memory objects even when writing to a file.
17+
.LINK
18+
https://nick2bad4u.github.io/PS-Color-Scripts-Enhanced/docs/help-redirect.html?cmdlet=Export-ColorScriptMetadata
19+
#>
20+
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Metadata is a collective noun representing the exported dataset.')]
21+
[OutputType([pscustomobject])]
22+
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium', HelpUri = 'https://nick2bad4u.github.io/PS-Color-Scripts-Enhanced/docs/help-redirect.html?cmdlet=Export-ColorScriptMetadata')]
23+
param(
24+
[Alias('help')]
25+
[switch]$h,
26+
27+
[Parameter()]
28+
[ValidateScript({ Test-ColorScriptPathValue $_ })]
29+
[string]$Path,
30+
31+
[Parameter()]
32+
[switch]$IncludeFileInfo,
33+
34+
[Parameter()]
35+
[switch]$IncludeCacheInfo,
36+
37+
[Parameter()]
38+
[switch]$PassThru
39+
)
40+
41+
if ($h) {
42+
Show-ColorScriptHelp -CommandName 'Export-ColorScriptMetadata'
43+
return
44+
}
45+
46+
$records = Get-ColorScriptEntry | Sort-Object Name
47+
Initialize-CacheDirectory
48+
49+
$payload = @()
50+
51+
foreach ($record in $records) {
52+
$entry = [ordered]@{
53+
Name = $record.Name
54+
Category = $record.Category
55+
Categories = [string[]]$record.Categories
56+
Tags = [string[]]$record.Tags
57+
Description = $record.Description
58+
}
59+
60+
if ($IncludeFileInfo) {
61+
try {
62+
$fileInfo = Get-Item -LiteralPath $record.Path -ErrorAction Stop
63+
$entry['ScriptPath'] = $fileInfo.FullName
64+
$entry['ScriptSizeBytes'] = [int64]$fileInfo.Length
65+
$entry['ScriptLastWriteTimeUtc'] = $fileInfo.LastWriteTimeUtc
66+
}
67+
catch {
68+
$entry['ScriptPath'] = $record.Path
69+
$entry['ScriptSizeBytes'] = $null
70+
$entry['ScriptLastWriteTimeUtc'] = $null
71+
Write-Verbose ($script:Messages.UnableToRetrieveFileInfo -f $record.Name, $_.Exception.Message)
72+
}
73+
}
74+
75+
if ($IncludeCacheInfo) {
76+
$cacheFile = if ($script:CacheDir) { Join-Path -Path $script:CacheDir -ChildPath "$( $record.Name ).cache" } else { $null }
77+
$cacheExists = $false
78+
$cacheTimestamp = $null
79+
80+
if ($cacheFile -and (Test-Path -LiteralPath $cacheFile)) {
81+
$cacheExists = $true
82+
try {
83+
$cacheInfo = Get-Item -LiteralPath $cacheFile -ErrorAction Stop
84+
$cacheTimestamp = $cacheInfo.LastWriteTimeUtc
85+
}
86+
catch {
87+
Write-Verbose ($script:Messages.UnableToReadCacheInfo -f $record.Name, $_.Exception.Message)
88+
}
89+
}
90+
91+
$entry['CachePath'] = $cacheFile
92+
$entry['CacheExists'] = $cacheExists
93+
$entry['CacheLastWriteTimeUtc'] = $cacheTimestamp
94+
}
95+
96+
$payload += [pscustomobject]$entry
97+
}
98+
99+
if ($Path) {
100+
$resolvedPath = Resolve-CachePath -Path $Path
101+
if (-not $resolvedPath) {
102+
Invoke-ColorScriptError -Message ($script:Messages.UnableToResolveOutputPath -f $Path) -ErrorId 'ColorScriptsEnhanced.InvalidOutputPath' -Category ([System.Management.Automation.ErrorCategory]::InvalidArgument) -TargetObject $Path -Cmdlet $PSCmdlet
103+
}
104+
105+
if (-not (Invoke-ShouldProcess -Cmdlet $PSCmdlet -Target $resolvedPath -Action 'Export colorscript metadata')) {
106+
if ($PassThru) {
107+
return $payload
108+
}
109+
110+
return
111+
}
112+
113+
$outputDirectory = Split-Path -Path $resolvedPath -Parent
114+
$directoryReady = $true
115+
116+
if ($outputDirectory -and -not (Test-Path -LiteralPath $outputDirectory)) {
117+
$directoryReady = Invoke-ShouldProcess -Cmdlet $PSCmdlet -Target $outputDirectory -Action 'Create export directory'
118+
119+
if ($directoryReady) {
120+
New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null
121+
}
122+
}
123+
124+
if (-not $directoryReady) {
125+
if ($PassThru) {
126+
return $payload
127+
}
128+
129+
return
130+
}
131+
132+
$json = $payload | ConvertTo-Json -Depth 6
133+
Set-Content -Path $resolvedPath -Value ($json + [Environment]::NewLine) -Encoding UTF8
134+
135+
if ($PassThru) {
136+
return $payload
137+
}
138+
139+
return
140+
}
141+
142+
return $payload
143+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function Get-ColorScriptConfiguration {
2+
<#
3+
.EXTERNALHELP ColorScripts-Enhanced-help.xml
4+
#>
5+
[OutputType([hashtable])]
6+
[CmdletBinding(HelpUri = 'https://nick2bad4u.github.io/PS-Color-Scripts-Enhanced/docs/help-redirect.html?cmdlet=Get-ColorScriptConfiguration')]
7+
param(
8+
[Alias('help')]
9+
[switch]$h
10+
)
11+
12+
if ($h) {
13+
Show-ColorScriptHelp -CommandName 'Get-ColorScriptConfiguration'
14+
return
15+
}
16+
17+
$data = Copy-ColorScriptHashtable (Get-ConfigurationDataInternal)
18+
return $data
19+
}

0 commit comments

Comments
 (0)