Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Load psake-config.ps1 from module directory when there is no one in configdir #55

Closed
wants to merge 30 commits into from
@lanwin
Owner

Try load psake-config.ps1 from module directory when there if no psake-config.ps1 in configdir. If you want to put your default modules next to your psake distribution, you need a way to change the default configuration from you psake folder instead from the folder where the build script is.

pedroreys and others added some commits
@pedroreys pedroreys Adds support to defining an alias to a task.
Example:
  task Task_With_Descriptive_Name -alias twdn {}

By doing that I can now call .\psake.ps1 twdn and have the
Task_With_Descriptive_Name executed
560bfb2
@pedroreys pedroreys fixes the task name when using aliases so that the casing is correct 9098c89
@JamesKovacs JamesKovacs Defaulted psake to .NET 4.0 9f91d9f
@JamesKovacs JamesKovacs Switched to semantic versioning 48d56a6
@JamesKovacs JamesKovacs Fixed formatting in .nuspec c78ee26
@kblooie kblooie Added test for issue with running a module function that depends on a…
… function from another module
f38b0ab
@idavis idavis Adding ability to use a scriptblock when initializing an invoke-psake…
… call in builds.
7137545
@Iristyle Iristyle Internal function names have been changed from Verb-Noun to VerbNoun …
…(without dash) in an effort to reduce potential for external collisions. Since external modules may be loaded with Verb-Noun naming after these internal functions are brought into scope, common functions like Resolve-Error are prone to get wiped out.. and to further lead to difficult to diagnose build problems.

See discussion psake#33
fabcda0
@Iristyle Iristyle Minor tweaks to error output to make it consistent with what a build …
…server like Jenkins might expect based on similarity to MSBuild output -- this is part one of the modification

Part two will involve incorporating a friendlier single line error message

psake#32
808148c
@Iristyle Iristyle Replaced existing ResolveError with a modified variant that includes …
…a short view, so that exceptions can be represented as one-liners for build output parsing purposes (it special cases Sql Exceptions as well to dig into the real errors)

Relies on new SelectObjectWithDefault function that can safely read properties off of objects w/out adding to the $Error collection (oddly, I've found this necessary when using WinRM, so I left that code in)

For instance, a short representation of an Error looks like this:
Error:  At C:\source\project\build\modules\Sql.psm1:175 char:36 +   [Void]$database.ExecuteNonQuery <<<< ($commands) [<<==>>] Exception: Exception calling "ExecuteNonQuery" with "1" argument(s): "ExecuteNonQuery failed for Database 'a73fa37f891e46bbab9e2b23b8f87c56'. " --> ExecuteNonQuery failed for Database 'a73fa37f891e46bbab9e2b23b8f87c56'.  --> An exception occurred while executing a Transact-SQL statement or batch. --> Foreign key 'fk_file_cabinet_num' references invalid column 'file_cabinet_num' in referencing table 'file_cabinet_files'.Could not create constraint. See previous errors. --> (Line [4] Proc
edure [] Class [16]  Number [1769] State [1] )

This is much more actionable / easier to read than 50 lines of output from an Exception with 4 InnerExceptions
fff5f6f
@jpoehls jpoehls The exit code from PowerShell was not being used as the exit code fro…
…m the CMD script. This update fixes that so that the CMD script will exit with the same code that the PowerShell script exited with.
68fe0e6
@ferventcoder ferventcoder wrapping the chocolateyInstall in a try catch and changing the path t…
…o chocolatey install to use the environment variable ($env:ChocolateyInstall)
976466f
@damianh damianh Added NuGet.exe so NuGetPackageBuilder.cmd will run without nuget hav…
…ing to be on the path.
a1a1a5e
@damianh damianh Replaced NuGetPackageBuilder.cmd with a powershell equivalent (it's a…
… powershell lib after all)
0df4889
@damianh damianh Bumped version to 4.2 fed1fa6
@damianh damianh Fixed package script to exclude nuget directory and nuget.ext. Bumped…
… package version to 4.2.0.1
53bb4f7
@kblooie kblooie Added config option to import modules into global scope. Disabled nam…
…e checking for modules
c589ff6
@mwrock mwrock add alias to task documentation and format as list to allow for wide …
…descriptions
83c44db
@yadazula yadazula turkish i problem fix 3a93504
@JamesKovacs JamesKovacs Renamed spec to follow naming convention 1409b20
@JamesKovacs JamesKovacs Fixed missing default task in task_with_alias_should_pass.ps1 ba38ea4
@jeffreyabecker jeffreyabecker fixed bug in write-coloredoutput. under alternative hosts that dont s…
…upport coloring it wasnt checking for color support and crashing
1c722b0
@jeffreyabecker jeffreyabecker Fixed spec writing_psake_variables_should_pass.ps1 failure. The spec …
…was checking .framework -eq '3.5' when this was never explicitly set. it seems like this spec was making incorrect assumptions about the framework it would be executed under.
3ac381c
@jeffreyabecker jeffreyabecker deleted test that doesnt seem to have ever worked e4351e6
@JamesKovacs JamesKovacs Extracted license.txt and updated copyright date 8ee664b
@JamesKovacs JamesKovacs Added link to MIT license to README.markdown 3d00688
@JamesKovacs JamesKovacs Fixed markdown for link to license 59541e8
@JamesKovacs JamesKovacs Really fixed markdown for link to license 6ae7e29
@ArturDorochowicz ArturDorochowicz Ensure TabExpansion function exists before rename.
Prevents an error in environment where there is no initial TabExpansion function defined.
fcd09c6
@lanwin lanwin Try load psake-config.ps1 from module directory
when there if no psake-config.ps1 in configdir. If you want to put your
default modules next to your psake distribution, you need a way to
change the default configuration from you psake folder instead from the
folder where the build script is.
b703f3b
@damianh
Owner

A lot of activity in this PR, was it completed? Anyone care to comment on it's status?

@damianh
Owner

Closing due to high probability this is just plain out of date. Re-open if not the case.

@damianh damianh closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 30, 2013
  1. @pedroreys @lanwin

    Adds support to defining an alias to a task.

    pedroreys authored lanwin committed
    Example:
      task Task_With_Descriptive_Name -alias twdn {}
    
    By doing that I can now call .\psake.ps1 twdn and have the
    Task_With_Descriptive_Name executed
  2. @pedroreys @lanwin
  3. @JamesKovacs @lanwin

    Defaulted psake to .NET 4.0

    JamesKovacs authored lanwin committed
  4. @JamesKovacs @lanwin

    Switched to semantic versioning

    JamesKovacs authored lanwin committed
  5. @JamesKovacs @lanwin

    Fixed formatting in .nuspec

    JamesKovacs authored lanwin committed
  6. @kblooie @lanwin

    Added test for issue with running a module function that depends on a…

    kblooie authored lanwin committed
    … function from another module
  7. @idavis @lanwin

    Adding ability to use a scriptblock when initializing an invoke-psake…

    idavis authored lanwin committed
    … call in builds.
  8. @Iristyle @lanwin

    Internal function names have been changed from Verb-Noun to VerbNoun …

    Iristyle authored lanwin committed
    …(without dash) in an effort to reduce potential for external collisions. Since external modules may be loaded with Verb-Noun naming after these internal functions are brought into scope, common functions like Resolve-Error are prone to get wiped out.. and to further lead to difficult to diagnose build problems.
    
    See discussion psake#33
  9. @Iristyle @lanwin

    Minor tweaks to error output to make it consistent with what a build …

    Iristyle authored lanwin committed
    …server like Jenkins might expect based on similarity to MSBuild output -- this is part one of the modification
    
    Part two will involve incorporating a friendlier single line error message
    
    psake#32
  10. @Iristyle @lanwin

    Replaced existing ResolveError with a modified variant that includes …

    Iristyle authored lanwin committed
    …a short view, so that exceptions can be represented as one-liners for build output parsing purposes (it special cases Sql Exceptions as well to dig into the real errors)
    
    Relies on new SelectObjectWithDefault function that can safely read properties off of objects w/out adding to the $Error collection (oddly, I've found this necessary when using WinRM, so I left that code in)
    
    For instance, a short representation of an Error looks like this:
    Error:  At C:\source\project\build\modules\Sql.psm1:175 char:36 +   [Void]$database.ExecuteNonQuery <<<< ($commands) [<<==>>] Exception: Exception calling "ExecuteNonQuery" with "1" argument(s): "ExecuteNonQuery failed for Database 'a73fa37f891e46bbab9e2b23b8f87c56'. " --> ExecuteNonQuery failed for Database 'a73fa37f891e46bbab9e2b23b8f87c56'.  --> An exception occurred while executing a Transact-SQL statement or batch. --> Foreign key 'fk_file_cabinet_num' references invalid column 'file_cabinet_num' in referencing table 'file_cabinet_files'.Could not create constraint. See previous errors. --> (Line [4] Proc
    edure [] Class [16]  Number [1769] State [1] )
    
    This is much more actionable / easier to read than 50 lines of output from an Exception with 4 InnerExceptions
  11. @jpoehls @lanwin

    The exit code from PowerShell was not being used as the exit code fro…

    jpoehls authored lanwin committed
    …m the CMD script. This update fixes that so that the CMD script will exit with the same code that the PowerShell script exited with.
  12. @ferventcoder @lanwin

    wrapping the chocolateyInstall in a try catch and changing the path t…

    ferventcoder authored lanwin committed
    …o chocolatey install to use the environment variable ($env:ChocolateyInstall)
  13. @damianh @lanwin

    Added NuGet.exe so NuGetPackageBuilder.cmd will run without nuget hav…

    damianh authored lanwin committed
    …ing to be on the path.
  14. @damianh @lanwin

    Replaced NuGetPackageBuilder.cmd with a powershell equivalent (it's a…

    damianh authored lanwin committed
    … powershell lib after all)
  15. @damianh @lanwin

    Bumped version to 4.2

    damianh authored lanwin committed
  16. @damianh @lanwin

    Fixed package script to exclude nuget directory and nuget.ext. Bumped…

    damianh authored lanwin committed
    … package version to 4.2.0.1
  17. @kblooie @lanwin

    Added config option to import modules into global scope. Disabled nam…

    kblooie authored lanwin committed
    …e checking for modules
  18. @mwrock @lanwin

    add alias to task documentation and format as list to allow for wide …

    mwrock authored lanwin committed
    …descriptions
  19. @yadazula @lanwin

    turkish i problem fix

    yadazula authored lanwin committed
  20. @JamesKovacs @lanwin

    Renamed spec to follow naming convention

    JamesKovacs authored lanwin committed
  21. @JamesKovacs @lanwin
  22. @jeffreyabecker @lanwin

    fixed bug in write-coloredoutput. under alternative hosts that dont s…

    jeffreyabecker authored lanwin committed
    …upport coloring it wasnt checking for color support and crashing
  23. @jeffreyabecker @lanwin

    Fixed spec writing_psake_variables_should_pass.ps1 failure. The spec …

    jeffreyabecker authored lanwin committed
    …was checking .framework -eq '3.5' when this was never explicitly set. it seems like this spec was making incorrect assumptions about the framework it would be executed under.
  24. @jeffreyabecker @lanwin

    deleted test that doesnt seem to have ever worked

    jeffreyabecker authored lanwin committed
  25. @JamesKovacs @lanwin

    Extracted license.txt and updated copyright date

    JamesKovacs authored lanwin committed
  26. @JamesKovacs @lanwin

    Added link to MIT license to README.markdown

    JamesKovacs authored lanwin committed
  27. @JamesKovacs @lanwin

    Fixed markdown for link to license

    JamesKovacs authored lanwin committed
  28. @JamesKovacs @lanwin

    Really fixed markdown for link to license

    JamesKovacs authored lanwin committed
  29. @ArturDorochowicz @lanwin

    Ensure TabExpansion function exists before rename.

    ArturDorochowicz authored lanwin committed
    Prevents an error in environment where there is no initial TabExpansion function defined.
  30. @lanwin

    Try load psake-config.ps1 from module directory

    lanwin authored
    when there if no psake-config.ps1 in configdir. If you want to put your
    default modules next to your psake distribution, you need a way to
    change the default configuration from you psake folder instead from the
    folder where the build script is.
This page is out of date. Refresh to see the latest.
View
BIN  NuGet.exe
Binary file not shown
View
27 NuGetPackageBuilder.cmd
@@ -1,27 +0,0 @@
-@echo on
-
-:: Assumes robocopy and nuget.exe both on the path
-
-SET DIR=%~dp0%
-SET DESTDIR=%DIR%bin
-
-IF EXIST %DESTDIR% goto deletebin
-
-goto prepare
-
-:deletebin
-rmdir /s /q %DESTDIR%
-if %ERRORLEVEL% NEQ 0 goto errors
-
-:prepare
-robocopy %DIR% %DESTDIR%\tools /E /B /NP /R:0 /W:0 /NJH /NJS /NS /NFL /NDL /XF ".git*" "Nuget*" "*.nupkg" /XD "%DIR%nuget" "%DIR%.git" "%DIR%bin"
-robocopy %DIR%nuget %DESTDIR% /E /B /NP /R:0 /W:0 /NJH /NJS /NS /NFL /NDL
-
-:build
-nuget pack %DESTDIR%\psake.nuspec
-if %ERRORLEVEL% NEQ 0 goto errors
-
-goto :eof
-
-:errors
-EXIT /B %ERRORLEVEL%
View
13 NuGetPackageBuilder.ps1
@@ -0,0 +1,13 @@
+# Assumes robocopy on the path
+
+$scriptpath = $MyInvocation.MyCommand.Path
+$dir = Split-Path $scriptpath
+$destDir = "$dir\bin"
+if(Test-Path $destDir -PathType container){
+ Remove-Item $destDir -Recurse -Force
+}
+
+robocopy $dir "$destDir\tools" /E /B /NP /R:0 /W:0 /NJH /NJS /NS /NFL /NDL /XF ".git*" "Nuget*" "*.nupkg" /XD "$dir\nuget" "$dir\.git" "$destDir" "$dir\nuget.exe"
+robocopy "$dir\nuget" $destDir /E /B /NP /R:0 /W:0 /NJH /NJS /NS /NFL /NDL
+
+.\nuget pack "$destDir\psake.nuspec"
View
6 README.markdown
@@ -51,4 +51,8 @@ Many thanks for contributions to psake are due (in alphabetical order):
* Staxmanade
* lanwin
* smbecker
-* stej
+* stej
+
+## License
+
+psake is released under the [MIT license](http://www.opensource.org/licenses/MIT).
View
19 license.txt
@@ -0,0 +1,19 @@
+psake
+Copyright (c) 2012 James Kovacs
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
View
16 nuget/psake.nuspec
@@ -2,18 +2,14 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>psake</id>
- <version>4.2</version>
+ <version>4.2.0.1</version>
<authors>James Kovacs</authors>
- <owners>Damian Hickey, Rob Reynolds</owners>
- <projectUrl>https://github.com/JamesKovacs/psake</projectUrl>
+ <owners>James Kovacs, Damian Hickey, Rob Reynolds</owners>
+ <projectUrl>https://github.com/psake/psake</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
- <summary>PSake is a build automation tool written in PowerShell</summary>
- <description>psake is a build automation tool written in PowerShell. It avoids the angle-bracket tax associated with executable XML by leveraging the PowerShell syntax in your build scripts. psake has a syntax inspired by rake (aka make in Ruby) and bake (aka make in Boo), but is easier to script because it leverages your existent command-line knowledge.
-
-psake is pronounced sake – as in Japanese rice wine. It does NOT rhyme with make, bake, or rake. |
-You can also install with chocolatey (http://nuget.org/List/Packages/chocolatey) and have global psake.
- </description>
+ <summary>psake is a build automation tool written in PowerShell</summary>
+ <description>psake is a build automation tool written in PowerShell. It avoids the angle-bracket tax associated with executable XML by leveraging the PowerShell syntax in your build scripts. psake has a syntax inspired by rake (aka make in Ruby) and bake (aka make in Boo), but is easier to script because it leverages your existent command-line knowledge. psake is pronounced sake - as in Japanese rice wine. It does NOT rhyme with make, bake, or rake. You can also install with chocolatey (http://nuget.org/List/Packages/chocolatey) and have global psake.</description>
<language>en-US</language>
<tags>build powershell chocolatey</tags>
</metadata>
-</package>
+</package>
View
27 nuget/tools/chocolateyInstall.ps1
@@ -1,14 +1,19 @@
-$nugetPath = 'C:\NuGet'
-$nugetExePath = Join-Path $nuGetPath 'bin'
-$packageBatchFileName = Join-Path $nugetExePath "psake.bat"
+try {
+ $nugetPath = $env:ChocolateyInstall
+ $nugetExePath = Join-Path $nuGetPath 'bin'
+ $packageBatchFileName = Join-Path $nugetExePath "psake.bat"
-$psakeDir = (Split-Path -parent $MyInvocation.MyCommand.Definition)
-#$path = ($psakeDir | Split-Path | Join-Path -ChildPath 'psake.cmd')
-$path = Join-Path $psakeDir 'psake.cmd'
-Write-Host "Adding $packageBatchFileName and pointing to $path"
-"@echo off
-""$path"" %*" | Out-File $packageBatchFileName -encoding ASCII
+ $psakeDir = (Split-Path -parent $MyInvocation.MyCommand.Definition)
+ #$path = ($psakeDir | Split-Path | Join-Path -ChildPath 'psake.cmd')
+ $path = Join-Path $psakeDir 'psake.cmd'
+ Write-Host "Adding $packageBatchFileName and pointing to $path"
+ "@echo off
+ ""$path"" %*" | Out-File $packageBatchFileName -encoding ASCII
+ write-host "PSake is now ready. You can type 'psake' from any command line at any path. Get started by typing 'psake /?'"
-write-host "PSake is now ready. You can type 'psake' from any command line at any path. Get started by typing 'psake /?'"
-Start-Sleep 6
+ Write-ChocolateySuccess 'psake'
+} catch {
+ Write-ChocolateyFailure 'psake' "$($_.Exception.Message)"
+ throw
+}
View
3  psake-buildTester.ps1
@@ -40,8 +40,7 @@ function runBuilds()
{
$testResult = "" | select Name, Result
$testResult.Name = $buildFile.Name
-
- invoke-psake $buildFile.FullName -Parameters @{'p1'='v1'; 'p2'='v2'} -Properties @{'x'='1'; 'y'='2'} | Out-Null
+ invoke-psake $buildFile.FullName -Parameters @{'p1'='v1'; 'p2'='v2'} -Properties @{'x'='1'; 'y'='2'} -Initialization { if(!$container) { $container = @{}; } $container.bar = "bar"; $container.baz = "baz"; $bar = 2; $baz = 3 } | Out-Null
$testResult.Result = (getResult $buildFile.Name $psake.build_success)
$testResults += $testResult
if ($testResult.Result -eq "Passed")
View
2  psake-config.ps1
@@ -3,7 +3,7 @@
Defaults
-------------------------------------------------------------------
$config.buildFileName="default.ps1"
-$config.framework = "3.5"
+$config.framework = "4.0"
$config.taskNameFormat="Executing {0}"
$config.verboseError=$false
$config.coloredOutput = $true
View
2  psake.cmd
@@ -5,7 +5,7 @@ if '%1'=='-help' goto help
if '%1'=='-h' goto help
powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0\psake.ps1' %*; if ($psake.build_success -eq $false) { exit 1 } else { exit 0 }"
-goto :eof
+exit /B %errorlevel%
:help
powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0\psake.ps1' -help"
View
16 psake.ps1
@@ -18,13 +18,21 @@ param(
[Parameter(Position=5, Mandatory=0)]
[System.Collections.Hashtable]$properties = @{},
[Parameter(Position=6, Mandatory=0)]
- [switch]$nologo = $false,
+ [alias("init")]
+ [scriptblock]$initialization = {},
[Parameter(Position=7, Mandatory=0)]
- [switch]$help = $false,
+ [switch]$nologo = $false,
[Parameter(Position=8, Mandatory=0)]
+ [switch]$help = $false,
+ [Parameter(Position=9, Mandatory=0)]
[string]$scriptPath = $(Split-Path -parent $MyInvocation.MyCommand.path)
)
+$currentThread = [System.Threading.Thread]::CurrentThread
+$invariantCulture = [System.Globalization.CultureInfo]::InvariantCulture
+$currentThread.CurrentCulture = $invariantCulture
+$currentThread.CurrentUICulture = $invariantCulture
+
# '[p]sake' is the same as 'psake' but $Error is not polluted
remove-module [p]sake
import-module (join-path $scriptPath psake.psm1)
@@ -35,9 +43,9 @@ if ($help) {
if (-not(test-path $buildFile)) {
$absoluteBuildFile = (join-path $scriptPath $buildFile)
- if (test-path $absoluteBuildFile) {
+ if (test-path $absoluteBuildFile) {
$buildFile = $absoluteBuildFile
}
}
-invoke-psake $buildFile $taskList $framework $docs $parameters $properties $nologo
+invoke-psake $buildFile $taskList $framework $docs $parameters $properties $initialization $nologo
View
214 psake.psm1
@@ -1,5 +1,5 @@
# psake
-# Copyright (c) 2010 James Kovacs
+# Copyright (c) 2012 James Kovacs
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
@@ -34,6 +34,11 @@ function Invoke-Task
$taskKey = $taskName.ToLower()
+ if ($currentContext.aliases.Contains($taskKey)) {
+ $taskName = $currentContext.aliases.$taskKey.Name
+ $taskKey = $taskName.ToLower()
+ }
+
$currentContext = $psake.context.Peek()
Assert ($currentContext.tasks.Contains($taskKey)) ($msgs.error_task_name_does_not_exist -f $taskName)
@@ -49,7 +54,7 @@ function Invoke-Task
$precondition_is_valid = & $task.Precondition
if (!$precondition_is_valid) {
- Write-ColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan
+ WriteColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan
} else {
if ($taskKey -ne 'default') {
@@ -75,7 +80,7 @@ function Invoke-Task
if ($currentContext.config.taskNameFormat -is [ScriptBlock]) {
& $currentContext.config.taskNameFormat $taskName
} else {
- Write-ColoredOutput ($currentContext.config.taskNameFormat -f $taskName) -foregroundcolor Cyan
+ WriteColoredOutput ($currentContext.config.taskNameFormat -f $taskName) -foregroundcolor Cyan
}
foreach ($variable in $task.requiredVariables) {
@@ -93,7 +98,7 @@ function Invoke-Task
} catch {
if ($task.ContinueOnError) {
"-"*70
- Write-ColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow
+ WriteColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow
"-"*70
$task.Duration = $stopwatch.Elapsed
} else {
@@ -162,7 +167,8 @@ function Task
[Parameter(Position=6,Mandatory=0)][switch]$continueOnError = $false,
[Parameter(Position=7,Mandatory=0)][string[]]$depends = @(),
[Parameter(Position=8,Mandatory=0)][string[]]$requiredVariables = @(),
- [Parameter(Position=9,Mandatory=0)][string]$description = $null
+ [Parameter(Position=9,Mandatory=0)][string]$description = $null,
+ [Parameter(Position=10,Mandatory=0)][string]$alias = $null
)
if ($name -eq 'default') {
Assert (!$action) ($msgs.error_default_task_cannot_have_action)
@@ -180,15 +186,25 @@ function Task
Description = $description
Duration = [System.TimeSpan]::Zero
RequiredVariables = $requiredVariables
+ Alias = $alias
}
- $taskKey = $name.ToLower()
+ $taskKey = $name.ToLower()
$currentContext = $psake.context.Peek()
Assert (!$currentContext.tasks.ContainsKey($taskKey)) ($msgs.error_duplicate_task_name -f $name)
$currentContext.tasks.$taskKey = $newTask
+
+ if($alias)
+ {
+ $aliasKey = $alias.ToLower()
+
+ Assert (!$currentContext.aliases.ContainsKey($aliasKey)) ($msgs.error_duplicate_alias_name -f $alias)
+
+ $currentContext.aliases.$aliasKey = $newTask
+ }
}
# .ExternalHelp psake.psm1-help.xml
@@ -256,7 +272,8 @@ function Invoke-psake {
[Parameter(Position = 3, Mandatory = 0)][switch] $docs = $false,
[Parameter(Position = 4, Mandatory = 0)][hashtable] $parameters = @{},
[Parameter(Position = 5, Mandatory = 0)][hashtable] $properties = @{},
- [Parameter(Position = 6, Mandatory = 0)][switch] $nologo = $false
+ [Parameter(Position = 6, Mandatory = 0)][alias("init")][scriptblock] $initialization = {},
+ [Parameter(Position = 7, Mandatory = 0)][switch] $nologo = $false
)
try {
if (-not $nologo) {
@@ -286,14 +303,15 @@ function Invoke-psake {
"originalDirectory" = get-location;
"originalErrorActionPreference" = $global:ErrorActionPreference;
"tasks" = @{};
+ "aliases" = @{};
"properties" = @();
"includes" = new-object System.Collections.Queue;
- "config" = Create-ConfigurationForNewContext $buildFile $framework
+ "config" = CreateConfigurationForNewContext $buildFile $framework
})
- Load-Configuration $psake.build_script_dir
+ LoadConfiguration $psake.build_script_dir
- Load-Modules
+ LoadModules
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
@@ -305,17 +323,17 @@ function Invoke-psake {
$currentContext = $psake.context.Peek()
if ($framework -ne $frameworkOldValue) {
- write-coloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow
+ writecoloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow
$currentContext.config.framework = $framework
}
if ($docs) {
- Write-Documentation
- Cleanup-Environment
+ WriteDocumentation
+ CleanupEnvironment
return
}
- Configure-BuildEnvironment
+ ConfigureBuildEnvironment
while ($currentContext.includes.Count -gt 0) {
$includeFilename = $currentContext.includes.Dequeue()
@@ -341,6 +359,10 @@ function Invoke-psake {
}
}
+ # Simple dot sourcing will not work. We have to force the script block into our
+ # module's scope in order to initialize variables properly.
+ . $MyInvocation.MyCommand.Module $initialization
+
# Execute the list of tasks or the default task
if ($taskList) {
foreach ($task in $taskList) {
@@ -352,24 +374,26 @@ function Invoke-psake {
throw $msgs.error_no_default_task
}
- Write-ColoredOutput ("`n" + $msgs.build_success + "`n") -foregroundcolor Green
+ WriteColoredOutput ("`n" + $msgs.build_success + "`n") -foregroundcolor Green
- Write-TaskTimeSummary $stopwatch.Elapsed
+ WriteTaskTimeSummary $stopwatch.Elapsed
$psake.build_success = $true
} catch {
- $currentConfig = Get-CurrentConfigurationOrDefault
+ $currentConfig = GetCurrentConfigurationOrDefault
if ($currentConfig.verboseError) {
$error_message = "{0}: An Error Occurred. See Error Details Below: `n" -f (Get-Date)
$error_message += ("-" * 70) + "`n"
- $error_message += Resolve-Error $_
+ $error_message += "Error: {0}`n" -f (ResolveError $_ -Short)
+ $error_message += ("-" * 70) + "`n"
+ $error_message += ResolveError $_
$error_message += ("-" * 70) + "`n"
$error_message += "Script Variables" + "`n"
$error_message += ("-" * 70) + "`n"
$error_message += get-variable -scope script | format-table | out-string
} else {
# ($_ | Out-String) gets error messages with source information included.
- $error_message = "{0}: An Error Occurred: `n{1}" -f (Get-Date), ($_ | Out-String)
+ $error_message = "Error: {0}: `n{1}" -f (Get-Date), (ResolveError $_ -Short)
}
$psake.build_success = $false
@@ -381,25 +405,25 @@ function Invoke-psake {
if ( $inNestedScope ) {
throw $_
} else {
- Write-ColoredOutput $error_message -foregroundcolor Red
+ WriteColoredOutput $error_message -foregroundcolor Red
}
}
} finally {
- Cleanup-Environment
+ CleanupEnvironment
}
}
#-- Private Module Functions --#
-function Write-ColoredOutput {
+function WriteColoredOutput {
param(
[string] $message,
[System.ConsoleColor] $foregroundcolor
)
- $currentConfig = Get-CurrentConfigurationOrDefault
+ $currentConfig = GetCurrentConfigurationOrDefault
if ($currentConfig.coloredOutput -eq $true) {
- if (($Host.UI -ne $null) -and ($Host.UI.RawUI -ne $null)) {
+ if (($Host.UI -ne $null) -and ($Host.UI.RawUI -ne $null) -and ($Host.UI.RawUI.ForegroundColor -ne $null)) {
$previousColor = $Host.UI.RawUI.ForegroundColor
$Host.UI.RawUI.ForegroundColor = $foregroundcolor
}
@@ -412,13 +436,18 @@ function Write-ColoredOutput {
}
}
-function Load-Modules {
+function LoadModules {
$currentConfig = $psake.context.peek().config
if ($currentConfig.modules) {
+
+ $scope = $currentConfig.moduleScope
+
+ $global = [string]::Equals($scope, "global", [StringComparison]::CurrentCultureIgnoreCase)
+
$currentConfig.modules | foreach {
resolve-path $_ | foreach {
"Loading module: $_"
- $module = import-module $_ -passthru
+ $module = import-module $_ -passthru -DisableNameChecking -global:$global
if (!$module) {
throw ($msgs.error_loading_module -f $_.Name)
}
@@ -428,16 +457,22 @@ function Load-Modules {
}
}
-function Load-Configuration {
+function LoadConfiguration {
param(
[string] $configdir = $PSScriptRoot
)
$psakeConfigFilePath = (join-path $configdir "psake-config.ps1")
+ # if there is no config file found in configdir, try load default
+ # one next to the psake module.
+ if (-not (test-path $psakeConfigFilePath -pathType Leaf)) {
+ $psakeConfigFilePath = (join-path $PSScriptRoot "psake-config.ps1")
+ }
+
if (test-path $psakeConfigFilePath -pathType Leaf) {
try {
- $config = Get-CurrentConfigurationOrDefault
+ $config = GetCurrentConfigurationOrDefault
. $psakeConfigFilePath
} catch {
throw "Error Loading Configuration from psake-config.ps1: " + $_
@@ -445,7 +480,7 @@ function Load-Configuration {
}
}
-function Get-CurrentConfigurationOrDefault() {
+function GetCurrentConfigurationOrDefault() {
if ($psake.context.count -gt 0) {
return $psake.context.peek().config
} else {
@@ -453,13 +488,13 @@ function Get-CurrentConfigurationOrDefault() {
}
}
-function Create-ConfigurationForNewContext {
+function CreateConfigurationForNewContext {
param(
[string] $buildFile,
[string] $framework
)
- $previousConfig = Get-CurrentConfigurationOrDefault
+ $previousConfig = GetCurrentConfigurationOrDefault
$config = new-object psobject -property @{
buildFileName = $previousConfig.buildFileName;
@@ -467,7 +502,8 @@ function Create-ConfigurationForNewContext {
taskNameFormat = $previousConfig.taskNameFormat;
verboseError = $previousConfig.verboseError;
coloredOutput = $previousConfig.coloredOutput;
- modules = $previousConfig.modules
+ modules = $previousConfig.modules;
+ moduleScope = $previousConfig.moduleScope;
}
if ($framework) {
@@ -481,7 +517,7 @@ function Create-ConfigurationForNewContext {
return $config
}
-function Configure-BuildEnvironment {
+function ConfigureBuildEnvironment {
$framework = $psake.context.peek().config.framework
if ($framework.Length -ne 3 -and $framework.Length -ne 6) {
throw ($msgs.error_invalid_framework -f $framework)
@@ -551,7 +587,7 @@ function Configure-BuildEnvironment {
$global:ErrorActionPreference = "Stop"
}
-function Cleanup-Environment {
+function CleanupEnvironment {
if ($psake.context.Count -gt 0) {
$currentContext = $psake.context.Peek()
$env:path = $currentContext.originalEnvPath
@@ -561,23 +597,95 @@ function Cleanup-Environment {
}
}
-# borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx
-function Resolve-Error($ErrorRecord = $Error[0]) {
- $error_message = "`nErrorRecord:{0}ErrorRecord.InvocationInfo:{1}Exception:{2}"
- $formatted_errorRecord = $ErrorRecord | format-list * -force | out-string
- $formatted_invocationInfo = $ErrorRecord.InvocationInfo | format-list * -force | out-string
- $formatted_exception = ""
- $Exception = $ErrorRecord.Exception
- for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) {
- $formatted_exception += ("$i" * 70) + "`n"
- $formatted_exception += $Exception | format-list * -force | out-string
- $formatted_exception += "`n"
+function SelectObjectWithDefault
+{
+ [CmdletBinding()]
+ param(
+ [Parameter(ValueFromPipeline=$true)]
+ [PSObject]
+ $InputObject,
+ [string]
+ $Name,
+ $Value
+ )
+
+ process {
+ if ($_ -eq $null) { $Value }
+ elseif ($_ | Get-Member -Name $Name) {
+ $_.$Name
+ }
+ elseif (($_ -is [Hashtable]) -and ($_.Keys -contains $Name)) {
+ $_.$Name
+ }
+ else { $Value }
}
+}
+
+# borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx
+# modified to better handle SQL errors
+function ResolveError
+{
+ [CmdletBinding()]
+ param(
+ [Parameter(ValueFromPipeline=$true)]
+ $ErrorRecord=$Error[0],
+ [Switch]
+ $Short
+ )
+
+ process {
+ if ($_ -eq $null) { $_ = $ErrorRecord }
+ $ex = $_.Exception
+
+ if (-not $Short) {
+ $error_message = "`nErrorRecord:{0}ErrorRecord.InvocationInfo:{1}Exception:`n{2}"
+ $formatted_errorRecord = $_ | format-list * -force | out-string
+ $formatted_invocationInfo = $_.InvocationInfo | format-list * -force | out-string
+ $formatted_exception = ''
+
+ $i = 0
+ while ($ex -ne $null) {
+ $i++
+ $formatted_exception += ("$i" * 70) + "`n" +
+ ($ex | format-list * -force | out-string) + "`n"
+ $ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null
+ }
+
+ return $error_message -f $formatted_errorRecord, $formatted_invocationInfo, $formatted_exception
+ }
- return $error_message -f $formatted_errorRecord, $formatted_invocationInfo, $formatted_exception
+ $lastException = @()
+ while ($ex -ne $null) {
+ $lastMessage = $ex | SelectObjectWithDefault -Name 'Message' -Value ''
+ $lastException += ($lastMessage -replace "`n", '')
+ if ($ex -is [Data.SqlClient.SqlException]) {
+ $lastException += "(Line [$($ex.LineNumber)] " +
+ "Procedure [$($ex.Procedure)] Class [$($ex.Class)] " +
+ " Number [$($ex.Number)] State [$($ex.State)] )"
+ }
+ $ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null
+ }
+ $shortException = $lastException -join ' --> '
+
+ $header = $null
+ $current = $_
+ $header = (($_.InvocationInfo |
+ SelectObjectWithDefault -Name 'PositionMessage' -Value '') -replace "`n", ' '),
+ ($_ | SelectObjectWithDefault -Name 'Message' -Value ''),
+ ($_ | SelectObjectWithDefault -Name 'Exception' -Value '') |
+ ? { -not [String]::IsNullOrEmpty($_) } |
+ Select -First 1
+
+ $delimiter = ''
+ if ((-not [String]::IsNullOrEmpty($header)) -and
+ (-not [String]::IsNullOrEmpty($shortException)))
+ { $delimiter = ' [<<==>>] ' }
+
+ return "$($header)$($delimiter)Exception: $($shortException)"
+ }
}
-function Write-Documentation {
+function WriteDocumentation {
$currentContext = $psake.context.Peek()
if ($currentContext.tasks.default) {
@@ -594,14 +702,15 @@ function Write-Documentation {
$task = $currentContext.tasks.$_
new-object PSObject -property @{
Name = $task.Name;
+ Alias = $task.Alias;
Description = $task.Description;
"Depends On" = $task.DependsOn -join ", "
Default = if ($defaultTaskDependencies -contains $task.Name) { $true }
}
- } | sort 'Name' | format-table -autoSize -property Name,Description,"Depends On",Default
+ } | sort 'Name' | format-list -property Name,Alias,Description,"Depends On",Default
}
-function Write-TaskTimeSummary($invokePsakeDuration) {
+function WriteTaskTimeSummary($invokePsakeDuration) {
"-" * 70
"Build Time Report"
"-" * 70
@@ -642,6 +751,7 @@ convertfrom-stringdata @'
error_bad_command = Error executing command {0}.
error_default_task_cannot_have_action = 'default' task cannot specify an action.
error_duplicate_task_name = Task {0} has already been defined.
+ error_duplicate_alias_name = Alias {0} has already been defined.
error_invalid_include_path = Unable to include {0}. File not found.
error_build_file_not_found = Could not find the build file {0}.
error_no_default_task = 'default' task required.
@@ -658,12 +768,12 @@ convertfrom-stringdata @'
import-localizeddata -bindingvariable msgs -erroraction silentlycontinue
$script:psake = @{}
-$psake.version = "4.00" # contains the current version of psake
+$psake.version = "4.2.0" # contains the current version of psake
$psake.context = new-object system.collections.stack # holds onto the current state of all variables
$psake.run_by_psake_build_tester = $false # indicates that build is being run by psake-BuildTester
$psake.config_default = new-object psobject -property @{
buildFileName = "default.ps1";
- framework = "3.5";
+ framework = "4.0";
taskNameFormat = "Executing {0}";
verboseError = $false;
coloredOutput = $true;
@@ -674,6 +784,6 @@ $psake.build_success = $false # indicates that the current build was successful
$psake.build_script_file = $null # contains a System.IO.FileInfo for the current build script
$psake.build_script_dir = "" # contains a string with fully-qualified path to current build script
-Load-Configuration
+LoadConfiguration
export-modulemember -function invoke-psake, invoke-task, task, properties, include, formattaskname, tasksetup, taskteardown, framework, assert, exec -variable psake
View
4 specs/duplicate_alias_should_fail.ps1
@@ -0,0 +1,4 @@
+task default
+task A -alias a {}
+task B -alias b {}
+task C -alias a {}
View
5 specs/task_with_alias_and_dependencies_should_pass.ps1
@@ -0,0 +1,5 @@
+task default -depends Task_With_Alias
+
+task Task_With_Alias -depends Task_Dependency -alias twa {}
+
+task Task_Dependency {}
View
5 specs/task_with_alias_should_pass.ps1
@@ -0,0 +1,5 @@
+task default -depends twbdn
+
+task Task_With_Big_Descriptve_Name -alias twbdn {
+ "Doing stuff inside task with alias"
+}
View
23 specs/using_initialization_block_should_pass.ps1
@@ -0,0 +1,23 @@
+properties {
+ $container = @{}
+ $container.foo = "foo"
+ $container.bar = $null
+ $foo = 1
+ $bar = 1
+}
+
+task default -depends TestInit
+
+task TestInit {
+ # values are:
+ # 1: original
+ # 2: overide
+ # 3: new
+
+ Assert ($container.foo -eq "foo") "$container.foo should be foo"
+ Assert ($container.bar -eq "bar") "$container.bar should be bar"
+ Assert ($container.baz -eq "baz") "$container.baz should be baz"
+ Assert ($foo -eq 1) "$foo should be 1"
+ Assert ($bar -eq 2) "$bar should be 2"
+ Assert ($baz -eq 3) "$baz should be 3"
+}
View
2  specs/writing_psake_variables_should_pass.ps1
@@ -26,7 +26,7 @@ task Verify -description "This task verifies psake's variables" {
$config = $psake.context.peek().config
Assert ($config) '$psake.config is $null'
Assert ((new-object "System.IO.FileInfo" $config.buildFileName).FullName -eq $psake.build_script_file.FullName) ('$psake.context.peek().config.buildFileName not equal to "{0}"' -f $psake.build_script_file.FullName)
- Assert ($config.framework -eq "3.5") '$psake.context.peek().config.framework not equal to "3.5"'
+ #Assert ($config.framework -eq "3.5") '$psake.context.peek().config.framework not equal to "3.5"'
Assert ($config.taskNameFormat -eq "Executing {0}") '$psake.context.peek().config.taskNameFormat not equal to "Executing {0}"'
Assert (!$config.verboseError) '$psake.context.peek().config.verboseError should be $false'
Assert ($config.coloredOutput) '$psake.context.peek().config.coloredOutput should be $false'
View
2  tabexpansion/Readme.PsakeTab.txt
@@ -12,7 +12,7 @@ Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent)
. ./PsakeTabExpansion.ps1
Pop-Location
-if(-not (Test-Path Function:\DefaultTabExpansion)) {
+if((Test-Path Function:\TabExpansion) -and (-not (Test-Path Function:\DefaultTabExpansion))) {
Rename-Item Function:\TabExpansion DefaultTabExpansion
}
Something went wrong with that request. Please try again.