|
| 1 | +function Optimize-Module { |
| 2 | + <# |
| 3 | + .Synopsis |
| 4 | + Compile a module from ps1 files to a single psm1 |
| 5 | + .Description |
| 6 | + Compiles modules from source according to conventions: |
| 7 | + 1. A single ModuleName.psd1 manifest file with metadata |
| 8 | + 2. Source subfolders in the same directory as the manifest: |
| 9 | + Classes, Private, Public contain ps1 files |
| 10 | + 3. Optionally, a build.psd1 file containing settings for this function |
| 11 | +
|
| 12 | + The optimization process: |
| 13 | + 1. The OutputDirectory is created |
| 14 | + 2. All psd1/psm1/ps1xml files in the root will be copied to the output |
| 15 | + 3. If specified, $CopyDirectories will be copied to the output |
| 16 | + 4. The ModuleName.psm1 will be generated (overwritten completely) by concatenating all .ps1 files in subdirectories (that aren't specified in CopySubdirectories) |
| 17 | + 5. The ModuleName.psd1 will be updated (based on existing data) |
| 18 | + #> |
| 19 | + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCmdletCorrectly", "")] |
| 20 | + param( |
| 21 | + # The path to the module folder, manifest or build.psd1 |
| 22 | + [Parameter(Position = 0, ValueFromPipelineByPropertyName)] |
| 23 | + [ValidateScript( { |
| 24 | + if (Test-Path $_) { |
| 25 | + $true |
| 26 | + } else { |
| 27 | + throw "Source must point to a valid module" |
| 28 | + } |
| 29 | + } )] |
| 30 | + [Alias("ModuleManifest")] |
| 31 | + [string]$Path, |
| 32 | + |
| 33 | + # Where to build the module. |
| 34 | + # Defaults to a version number folder, adjacent to the module folder |
| 35 | + [Alias("Destination")] |
| 36 | + [string]$OutputDirectory, |
| 37 | + |
| 38 | + [version]$ModuleVersion, |
| 39 | + |
| 40 | + # Folders which should be copied intact to the module output |
| 41 | + # Can be relative to the module folder |
| 42 | + [AllowEmptyCollection()] |
| 43 | + [string[]]$CopyDirectories = @(), |
| 44 | + |
| 45 | + # A Filter (relative to the module folder) for public functions |
| 46 | + # If non-empty, ExportedFunctions will be set with the file BaseNames of matching files |
| 47 | + # Defaults to Public\*.ps1 |
| 48 | + [AllowEmptyString()] |
| 49 | + [string[]]$PublicFilter = "Public\*.ps1", |
| 50 | + |
| 51 | + # File encoding for output RootModule (defaults to UTF8) |
| 52 | + [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] |
| 53 | + $Encoding = "UTF8", |
| 54 | + |
| 55 | + # A line which will be added at the bottom of the psm1. The intention is to allow you to add an export like: |
| 56 | + # Export-ModuleMember -Alias *-QM* -Functions * -Variables QMConstant_* |
| 57 | + # |
| 58 | + # The default is nothing |
| 59 | + $ExportModuleMember, |
| 60 | + |
| 61 | + # Controls whether or not there is a build or cleanup performed |
| 62 | + [ValidateSet("Clean", "Build", "CleanBuild")] |
| 63 | + [string]$Target = "CleanBuild", |
| 64 | + |
| 65 | + # Output the ModuleInfo of the "built" module |
| 66 | + [switch]$Passthru |
| 67 | + ) |
| 68 | + |
| 69 | + process { |
| 70 | + try { |
| 71 | + # If a path is $passed, use that |
| 72 | + if ($Path) { |
| 73 | + $ModuleBase = Split-Path $Path -Parent |
| 74 | + # Do not use GetFileNameWithoutExtension, some module names have dots in them |
| 75 | + $ModuleName = (Split-Path $Path -Leaf) -replace ".psd1$" |
| 76 | + |
| 77 | + # Support passing the path to a module folder |
| 78 | + if (Test-Path $Path -PathType Container) { |
| 79 | + if ( (Test-Path (Join-Path $Path build.psd1)) -or |
| 80 | + (Test-Path (Join-Path $Path "$ModuleName.psd1")) |
| 81 | + ) { |
| 82 | + $ModuleBase = $Path |
| 83 | + $Path = Join-Path $Path "$ModuleName.psd1" |
| 84 | + if (Test-Path $Path) { |
| 85 | + $PSBoundParameters["Path"] = $Path |
| 86 | + } else { |
| 87 | + $null = $PSBoundParameters.Remove("Path") |
| 88 | + } |
| 89 | + } else { |
| 90 | + throw "Module not found in $Path. Try passing the full path to the manifest file." |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + # Add support for passing the path to a build.psd1 |
| 95 | + if ( (Test-Path $Path -PathType Leaf) -and ($ModuleName -eq "build") ) { |
| 96 | + $null = $PSBoundParameters.Remove("Path") |
| 97 | + } |
| 98 | + |
| 99 | + Push-Location $ModuleBase -StackName Optimize-Module |
| 100 | + # Otherwise, look for a local build.psd1 |
| 101 | + } elseif (Test-Path Build.psd1) { |
| 102 | + Push-Location -StackName Optimize-Module |
| 103 | + } else { |
| 104 | + throw "Build.psd1 not found in PWD. You must specify the -Path to the build" |
| 105 | + } |
| 106 | + |
| 107 | + # Read build.psd1 for defaults |
| 108 | + if (Test-Path Build.psd1) { |
| 109 | + $BuildInfo = Import-LocalizedData -BaseDirectory $Pwd.Path -FileName Build |
| 110 | + } else { |
| 111 | + $BuildInfo = @{} |
| 112 | + } |
| 113 | + |
| 114 | + # Overwrite with parameter values |
| 115 | + foreach ($property in $PSBoundParameters.Keys) { |
| 116 | + $BuildInfo.$property = $PSBoundParameters.$property |
| 117 | + } |
| 118 | + |
| 119 | + $BuildInfo.Path = Resolve-Path $BuildInfo.Path |
| 120 | + |
| 121 | + # Read Module Manifest for details |
| 122 | + $ModuleInfo = Get-Module $BuildInfo.Path -ListAvailable -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -ErrorVariable Problems |
| 123 | + if ($Problems) { |
| 124 | + $Problems = $Problems.Where{ $_.FullyQualifiedErrorId -notmatch "^Modules_InvalidRequiredModulesinModuleManifest"} |
| 125 | + if ($Problems) { |
| 126 | + foreach ($problem in $Problems) { |
| 127 | + Write-Error $problem |
| 128 | + } |
| 129 | + throw "Unresolvable problems in module manifest" |
| 130 | + } |
| 131 | + } |
| 132 | + foreach ($property in $BuildInfo.Keys) { |
| 133 | + # Note:we can't overwrite the Path from the Build.psd1 |
| 134 | + Add-Member -Input $ModuleInfo -Type NoteProperty -Name $property -Value $BuildInfo.$property -ErrorAction SilentlyContinue |
| 135 | + } |
| 136 | + |
| 137 | + # Copy in default parameters |
| 138 | + if (!(Get-Member -InputObject $ModuleInfo -Name PublicFilter)) { |
| 139 | + Add-Member -Input $ModuleInfo -Type NoteProperty -Name PublicFilter -Value $PublicFilter |
| 140 | + } |
| 141 | + if (!(Get-Member -InputObject $ModuleInfo -Name Encoding)) { |
| 142 | + Add-Member -Input $ModuleInfo -Type NoteProperty -Name Encoding -Value $Encoding |
| 143 | + } |
| 144 | + # Fix the version before making the folder |
| 145 | + if ($ModuleVersion) { |
| 146 | + Add-Member -Input $ModuleInfo -Type NoteProperty -Name Version -Value $ModuleVersion -Force |
| 147 | + } |
| 148 | + |
| 149 | + # Ensure OutputDirectory |
| 150 | + if (!$ModuleInfo.OutputDirectory) { |
| 151 | + $OutputDirectory = Join-Path (Split-Path $ModuleInfo.ModuleBase -Parent) $ModuleInfo.Version |
| 152 | + Add-Member -Input $ModuleInfo -Type NoteProperty -Name OutputDirectory -Value $OutputDirectory -Force |
| 153 | + } |
| 154 | + $OutputDirectory = $ModuleInfo.OutputDirectory |
| 155 | + Write-Progress "Building $($ModuleInfo.ModuleBase)" -Status "Use -Verbose for more information" |
| 156 | + Write-Verbose "Building $($ModuleInfo.ModuleBase)" |
| 157 | + Write-Verbose " Output to: $OutputDirectory" |
| 158 | + |
| 159 | + if ($Target -match "Clean") { |
| 160 | + Write-Verbose "Cleaning $OutputDirectory" |
| 161 | + if (Test-Path $OutputDirectory) { |
| 162 | + Remove-Item $OutputDirectory -Recurse -Force |
| 163 | + } |
| 164 | + if ($Target -notmatch "Build") { |
| 165 | + return # No build, just cleaning |
| 166 | + } |
| 167 | + } else { |
| 168 | + # If we're not cleaning, skip the build if it's up to date already |
| 169 | + Write-Verbose "Target $Target" |
| 170 | + $NewestBuild = Get-ChildItem $OutputDirectory -Recurse | |
| 171 | + Sort-Object LastWriteTime -Descending | |
| 172 | + Select-Object -First 1 -ExpandProperty LastWriteTime |
| 173 | + $IsNew = Get-ChildItem $ModuleInfo.ModuleBase -Recurse | |
| 174 | + Where-Object LastWriteTime -gt $NewestBuild | |
| 175 | + Select-Object -First 1 -ExpandProperty LastWriteTime |
| 176 | + if ($null -eq $IsNew) { |
| 177 | + return # Skip the build |
| 178 | + } |
| 179 | + } |
| 180 | + $null = mkdir $OutputDirectory -Force |
| 181 | + |
| 182 | + Write-Verbose "Copy files to $OutputDirectory" |
| 183 | + # Copy the files and folders which won't be processed |
| 184 | + Copy-Item *.psm1, *.psd1, *.ps1xml -Exclude "build.psd1" -Destination $OutputDirectory -Force |
| 185 | + if ($ModuleInfo.CopyDirectories) { |
| 186 | + Write-Verbose "Copy Entire Directories: $($ModuleInfo.CopyDirectories)" |
| 187 | + Copy-Item -Path $ModuleInfo.CopyDirectories -Recurse -Destination $OutputDirectory -Force |
| 188 | + } |
| 189 | + |
| 190 | + # Output psm1 |
| 191 | + $RootModule = Join-Path $OutputDirectory "$($ModuleInfo.Name).psm1" |
| 192 | + $OutputManifest = Join-Path $OutputDirectory "$($ModuleInfo.Name).psd1" |
| 193 | + |
| 194 | + Write-Verbose "Combine scripts to $RootModule" |
| 195 | + # Prefer pipeline to speed for the sake of memory and file IO |
| 196 | + # SilentlyContinue because there don't *HAVE* to be functions at all |
| 197 | + $AllScripts = Get-ChildItem -Path $ModuleInfo.ModuleBase -Exclude $ModuleInfo.CopyDirectories -Directory -ErrorAction SilentlyContinue | |
| 198 | + Get-ChildItem -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue |
| 199 | + |
| 200 | + if ($AllScripts) { |
| 201 | + $AllScripts | ForEach-Object { |
| 202 | + $SourceName = Resolve-Path $_.FullName -Relative |
| 203 | + Write-Verbose "Adding $SourceName" |
| 204 | + "# BEGIN $SourceName" |
| 205 | + Get-Content $SourceName |
| 206 | + "# END $SourceName" |
| 207 | + } | Set-Content -Path $RootModule -Encoding $ModuleInfo.Encoding |
| 208 | + |
| 209 | + if ($ModuleInfo.ExportModuleMember) { |
| 210 | + Add-Content -Path $RootModule -Value $ModuleInfo.ExportModuleMember -Encoding $ModuleInfo.Encoding |
| 211 | + } |
| 212 | + |
| 213 | + # If there is a PublicFilter, update ExportedFunctions |
| 214 | + if ($ModuleInfo.PublicFilter) { |
| 215 | + # SilentlyContinue because there don't *HAVE* to be public functions |
| 216 | + if ($PublicFunctions = Get-ChildItem $ModuleInfo.PublicFilter -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty BaseName) { |
| 217 | + # TODO: Remove the _Public hack |
| 218 | + Update-Metadata -Path $OutputManifest -PropertyName FunctionsToExport -Value ($PublicFunctions -replace "_Public$") |
| 219 | + } |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + Write-Verbose "Update Manifest to $OutputManifest" |
| 224 | + |
| 225 | + Update-Metadata -Path $OutputManifest -PropertyName Copyright -Value ($ModuleInfo.Copyright -replace "20\d\d", (Get-Date).Year) |
| 226 | + |
| 227 | + if ($ModuleVersion) { |
| 228 | + Update-Metadata -Path $OutputManifest -PropertyName ModuleVersion -Value $ModuleVersion |
| 229 | + } |
| 230 | + |
| 231 | + # This is mostly for testing ... |
| 232 | + if ($Passthru) { |
| 233 | + Get-Module $OutputManifest -ListAvailable |
| 234 | + } |
| 235 | + } finally { |
| 236 | + Pop-Location -StackName Optimize-Module -ErrorAction SilentlyContinue |
| 237 | + } |
| 238 | + } |
| 239 | +} |
0 commit comments