提交 f55b42b8 编写于 作者: T thierry habart

Feature : Add EFCore.Cassandra project

上级 866db91f
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
bower_components/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
log-*.txt
docs/_build/
\ No newline at end of file
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [habarthierry@hotmail.fr]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
<Project>
<PropertyGroup>
<VersionPrefix>1.0.0</VersionPrefix>
<Authors>SimpleIdServer</Authors>
<Owners>SimpleIdServer</Owners>
</PropertyGroup>
</Project>
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01. Core Layer", "01. Core Layer", "{4920F8DE-E217-452A-865A-E47DAC924B5F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02. Testing Layer", "02. Testing Layer", "{BCAC9560-F9EC-4C11-A0E2-D3CAC0759519}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03. Samples Layer", "03. Samples Layer", "{D43C01D1-8661-4A06-B3D8-5CD1A9AC1DB3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EFCore.Cassandra", "src\EFCore.Cassandra\EFCore.Cassandra.csproj", "{2D74D363-66B9-424B-BB34-468BEF0A2F07}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6C0BCFE7-0F0A-4551-8FDE-BCC408B0A4EB}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EFCore.Cassandra.Tests", "tests\EFCore.Cassandra.Tests\EFCore.Cassandra.Tests.csproj", "{BE0A2541-1253-4917-A070-4BB8F71F4704}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EFCore.Cassandra.Samples", "samples\EFCore.Cassandra.Samples\EFCore.Cassandra.Samples.csproj", "{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2D74D363-66B9-424B-BB34-468BEF0A2F07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2D74D363-66B9-424B-BB34-468BEF0A2F07}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D74D363-66B9-424B-BB34-468BEF0A2F07}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2D74D363-66B9-424B-BB34-468BEF0A2F07}.Release|Any CPU.Build.0 = Release|Any CPU
{BE0A2541-1253-4917-A070-4BB8F71F4704}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BE0A2541-1253-4917-A070-4BB8F71F4704}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BE0A2541-1253-4917-A070-4BB8F71F4704}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BE0A2541-1253-4917-A070-4BB8F71F4704}.Release|Any CPU.Build.0 = Release|Any CPU
{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{2D74D363-66B9-424B-BB34-468BEF0A2F07} = {4920F8DE-E217-452A-865A-E47DAC924B5F}
{BE0A2541-1253-4917-A070-4BB8F71F4704} = {BCAC9560-F9EC-4C11-A0E2-D3CAC0759519}
{84CB9B7A-BDCF-4AF6-8C02-80405EB54C93} = {D43C01D1-8661-4A06-B3D8-5CD1A9AC1DB3}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {13BDB38B-AFCC-4B2C-B0F9-404FB6249216}
EndGlobalSection
EndGlobal
extensions: designer.cs generated.cs
extensions: .cs .cpp .h
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
extensions: .aspx .ascx
<%--
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
--%>
extensions: .xml .config .xsd
<!--
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
-->
\ No newline at end of file
......@@ -178,7 +178,7 @@
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
......@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright 2015 Habart Thierry
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
......@@ -198,4 +198,4 @@
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="sid" value="https://www.myget.org/F/advance-ict/api/v3/index.json" />
</packageSources>
</configuration>
\ No newline at end of file
# Cassandra Entity Framework Core provider
[![Build status](https://ci.appveyor.com/api/projects/status/jf8jb043a1m722jq?svg=true)](https://ci.appveyor.com/project/simpleidserver/efcore-cassandra)
[![MyGet (dev)](https://img.shields.io/myget/advance-ict/v/EFCore.Cassandra.svg)](https://www.myget.org/gallery/advance-ict)
EFCore.Cassandra is an Entity Framework Core provider built on top of [CassandraCSharpDriver](https://github.com/datastax/csharp-driver). It allows you to use EF Core O/RM with cassandra.
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
\ No newline at end of file
version: '{build}'
pull_requests:
do_not_increment_build_number: true
branches:
only:
- master
image: Visual Studio 2017
nuget:
disable_publish_on_pr: true
build_script:
- cmd: .\psake.cmd ci
test: off
artifacts:
- path: build\results\*.nupkg
name: NuGet
deploy:
- provider: NuGet
server: https://www.myget.org/F/advance-ict/api/v2/package
api_key:
secure: zs1JVjFHRdvB36fGq2rN8MR7QeJnCVkt7VTG4ZHT5OYDNpuh2AlGHqK+rseevn8l
skip_symbols: true
on:
branch: master
- provider: NuGet
name: production
api_key:
secure: sCWC9q0qyTq//EuhS9kjMCqRDWaH5iF//mQrkraUiYoEjbVIWc/YQ3z3cB+wsbce
on:
branch: master
appveyor_repo_tag: true
properties {
$base_dir = resolve-path .
$build_dir = "$base_dir\build"
$source_dir = "$base_dir\src"
$result_dir = "$build_dir\results"
$global:config = "debug"
$tag = $(git tag -l --points-at HEAD)
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "ci-$revision"}[$tag -ne $NULL -and $revision -ne "local"]
$commitHash = $(git rev-parse --short HEAD)
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
$versionSuffix = @{ $true = "--version-suffix=$($suffix)"; $false = ""}[$suffix -ne ""]
}
task default -depends local
task local -depends compile, test
task ci -depends clean, release, local, pack
# task ci -depends clean, release, local, pack, benchmark
task clean {
rd "$source_dir\artifacts" -recurse -force -ErrorAction SilentlyContinue | out-null
rd "$base_dir\build" -recurse -force -ErrorAction SilentlyContinue | out-null
}
task release {
$global:config = "release"
}
task compile -depends clean {
echo "build: Tag is $tag"
echo "build: Package version suffix is $suffix"
echo "build: Build version suffix is $buildSuffix"
exec { dotnet --version }
exec { dotnet --info }
exec { msbuild -version }
exec { dotnet build .\EFCore.Cassandra.sln -c $config --version-suffix=$buildSuffix }
}
task pack -depends compile {
exec { dotnet pack $source_dir\EFCore.Cassandra\EFCore.Cassandra.csproj -c $config --no-build $versionSuffix --output $result_dir }
}
task test {
Push-Location -Path $base_dir\tests\EFCore.Cassandra.Tests
try {
exec { & dotnet test -c $config --no-build --no-restore }
} finally {
Pop-Location
}
}
\ No newline at end of file
此差异已折叠。
function CleanupEnvironment {
if ($psake.context.Count -gt 0) {
$currentContext = $psake.context.Peek()
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')]
$env:PATH = $currentContext.originalEnvPath
Set-Location $currentContext.originalDirectory
$global:ErrorActionPreference = $currentContext.originalErrorActionPreference
[void] $psake.context.Pop()
}
}
function ConfigureBuildEnvironment {
if (!(Test-Path Variable:\IsWindows) -or $IsWindows) {
$framework = $psake.context.peek().config.framework
if ($framework -cmatch '^((?:\d+\.\d+)(?:\.\d+){0,1})(x86|x64){0,1}$') {
$versionPart = $matches[1]
$bitnessPart = $matches[2]
}
else {
throw ($msgs.error_invalid_framework -f $framework)
}
$versions = $null
$buildToolsVersions = $null
switch ($versionPart) {
'1.0' {
$versions = @('v1.0.3705')
}
'1.1' {
$versions = @('v1.1.4322')
}
'1.1.0' {
$versions = @()
}
'2.0' {
$versions = @('v2.0.50727')
}
'2.0.0' {
$versions = @()
}
'3.0' {
$versions = @('v2.0.50727')
}
'3.5' {
$versions = @('v3.5', 'v2.0.50727')
}
'4.0' {
$versions = @('v4.0.30319')
}
{($_ -eq '4.5') -or ($_ -eq '4.5.1') -or ($_ -eq '4.5.2')} {
$versions = @('v4.0.30319')
$buildToolsVersions = @('15.0', '14.0', '12.0')
}
{($_ -eq '4.6') -or ($_ -eq '4.6.1') -or ($_ -eq '4.6.2')} {
$versions = @('v4.0.30319')
$buildToolsVersions = @('15.0', '14.0')
}
{($_ -eq '4.7') -or ($_ -eq '4.7.1') -or ($_ -eq '4.7.2')} {
$versions = @('v4.0.30319')
$buildToolsVersions = @('15.0')
}
default {
throw ($msgs.error_unknown_framework -f $versionPart, $framework)
}
}
$bitness = 'Framework'
if ($versionPart -ne '1.0' -and $versionPart -ne '1.1') {
switch ($bitnessPart) {
'x86' {
$bitness = 'Framework'
$buildToolsKey = 'MSBuildToolsPath32'
}
'x64' {
$bitness = 'Framework64'
$buildToolsKey = 'MSBuildToolsPath'
}
{ [string]::IsNullOrEmpty($_) } {
$ptrSize = [System.IntPtr]::Size
switch ($ptrSize) {
4 {
$bitness = 'Framework'
$buildToolsKey = 'MSBuildToolsPath32'
}
8 {
$bitness = 'Framework64'
$buildToolsKey = 'MSBuildToolsPath'
}
default {
throw ($msgs.error_unknown_pointersize -f $ptrSize)
}
}
}
default {
throw ($msgs.error_unknown_bitnesspart -f $bitnessPart, $framework)
}
}
}
$frameworkDirs = @()
if ($null -ne $buildToolsVersions) {
foreach($ver in $buildToolsVersions) {
if ($ver -eq "15.0") {
if ($null -eq (Get-Module -Name VSSetup)) {
if ($null -eq (Get-Module -Name VSSetup -ListAvailable)) {
WriteColoredOutput ($msgs.warning_missing_vsssetup_module -f $ver) -foregroundcolor Yellow
continue
}
Import-Module VSSetup
}
# borrowed from nightroman https://github.com/nightroman/Invoke-Build
if ($vsInstances = Get-VSSetupInstance) {
$vs = @($vsInstances | Select-VSSetupInstance -Version '[15.0,16.0)' -Require Microsoft.Component.MSBuild)
if ($vs) {
if ($buildToolsKey -eq 'MSBuildToolsPath32') {
$frameworkDirs += Join-Path ($vs[0].InstallationPath) MSBuild\15.0\Bin
}
else {
$frameworkDirs += Join-Path ($vs[0].InstallationPath) MSBuild\15.0\Bin\amd64
}
}
$vs = @($vsInstances | Select-VSSetupInstance -Version '[15.0,16.0)' -Product Microsoft.VisualStudio.Product.BuildTools)
if ($vs) {
if ($buildToolsKey -eq 'MSBuildToolsPath32') {
$frameworkDirs += Join-Path ($vs[0].InstallationPath) MSBuild\15.0\Bin
}
else {
$frameworkDirs += Join-Path ($vs[0].InstallationPath) MSBuild\15.0\Bin\amd64
}
}
}
else {
if (!($root = ${env:ProgramFiles(x86)})) {$root = $env:ProgramFiles}
if (Test-Path -LiteralPath "$root\Microsoft Visual Studio\2017") {
if ($buildToolsKey -eq 'MSBuildToolsPath32') {
$rp = @(Resolve-Path "$root\Microsoft Visual Studio\2017\*\MSBuild\15.0\Bin" -ErrorAction SilentlyContinue)
}
else {
$rp = @(Resolve-Path "$root\Microsoft Visual Studio\2017\*\MSBuild\15.0\Bin\amd64" -ErrorAction SilentlyContinue)
}
if ($rp) {
$frameworkDirs += $rp[-1].ProviderPath
}
}
}
}
elseif (Test-Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$ver") {
$frameworkDirs += (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$ver" -Name $buildToolsKey).$buildToolsKey
}
}
}
$frameworkDirs = $frameworkDirs + @($versions | ForEach-Object { "$env:windir\Microsoft.NET\$bitness\$_\" })
for ($i = 0; $i -lt $frameworkDirs.Count; $i++) {
$dir = $frameworkDirs[$i]
if ($dir -Match "\$\(Registry:HKEY_LOCAL_MACHINE(.*?)@(.*)\)") {
$key = "HKLM:" + $matches[1]
$name = $matches[2]
$dir = (Get-ItemProperty -Path $key -Name $name).$name
$frameworkDirs[$i] = $dir
}
}
$frameworkDirs | ForEach-Object { Assert (test-path $_ -pathType Container) ($msgs.error_no_framework_install_dir_found -f $_)}
$env:PATH = ($frameworkDirs -join ";") + ";$env:PATH"
}
# if any error occurs in a PS function then "stop" processing immediately
# this does not effect any external programs that return a non-zero exit code
$global:ErrorActionPreference = "Stop"
}
function CreateConfigurationForNewContext {
param(
[string] $buildFile,
[string] $framework
)
$previousConfig = GetCurrentConfigurationOrDefault
$config = new-object psobject -property @{
buildFileName = $previousConfig.buildFileName;
framework = $previousConfig.framework;
taskNameFormat = $previousConfig.taskNameFormat;
verboseError = $previousConfig.verboseError;
coloredOutput = $previousConfig.coloredOutput;
modules = $previousConfig.modules;
moduleScope = $previousConfig.moduleScope;
}
if ($framework) {
$config.framework = $framework;
}
if ($buildFile) {
$config.buildFileName = $buildFile;
}
return $config
}
function ExecuteInBuildFileScope {
param([string]$buildFile, $module, [scriptblock]$sb)
# Execute the build file to set up the tasks and defaults
Assert (test-path $buildFile -pathType Leaf) ($msgs.error_build_file_not_found -f $buildFile)
$psake.build_script_file = get-item $buildFile
$psake.build_script_dir = $psake.build_script_file.DirectoryName
$psake.build_success = $false
$psake.context.push(@{
"taskSetupScriptBlock" = {};
"taskTearDownScriptBlock" = {};
"executedTasks" = new-object System.Collections.Stack;
"callStack" = new-object System.Collections.Stack;
"originalEnvPath" = $env:PATH;
"originalDirectory" = get-location;
"originalErrorActionPreference" = $global:ErrorActionPreference;
"tasks" = @{};
"aliases" = @{};
"properties" = @();
"includes" = new-object System.Collections.Queue;
"config" = CreateConfigurationForNewContext $buildFile $framework
})
LoadConfiguration $psake.build_script_dir
set-location $psake.build_script_dir
LoadModules
$frameworkOldValue = $framework
. $psake.build_script_file.FullName
$currentContext = $psake.context.Peek()
if ($framework -ne $frameworkOldValue) {
writecoloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow
$currentContext.config.framework = $framework
}
ConfigureBuildEnvironment
while ($currentContext.includes.Count -gt 0) {
$includeFilename = $currentContext.includes.Dequeue()
. $includeFilename
}
& $sb $currentContext $module
}
# Attempt to find the default build file given the config_default of
# buildFileName and legacyBuildFileName. If neither exist optionally
# return the buildFileName or $null
function Get-DefaultBuildFile {
param(
[boolean] $UseDefaultIfNoneExist = $true
)
if (test-path $psake.config_default.buildFileName -pathType Leaf) {
Write-Output $psake.config_default.buildFileName
} elseif (test-path $psake.config_default.legacyBuildFileName -pathType Leaf) {
Write-Warning "The default configuration file of default.ps1 is deprecated. Please use psakefile.ps1"
Write-Output $psake.config_default.legacyBuildFileName
} elseif ($UseDefaultIfNoneExist) {
Write-Output $psake.config_default.buildFileName
}
}
function GetCurrentConfigurationOrDefault() {
if ($psake.context.count -gt 0) {
return $psake.context.peek().config
} else {
return $psake.config_default
}
}
function GetTasksFromContext($currentContext) {
$docs = $currentContext.tasks.Keys | foreach-object {
$task = $currentContext.tasks.$_
new-object PSObject -property @{
Name = $task.Name;
Alias = $task.Alias;
Description = $task.Description;
DependsOn = $task.DependsOn;
}
}
return $docs
}
function LoadConfiguration {
<#
.SYNOPSIS
Load psake-config.ps1 file
.DESCRIPTION
Load psake-config.ps1 if present in the directory of the current build script.
If that file doesn't exist, load the default psake-config.ps1 file from the module directory.
#>
param(
[string]$configdir = (Split-Path -Path $PSScriptRoot -Parent)
)
$configFilePath = Join-Path -Path $configdir -ChildPath $script:psakeConfigFile
$defaultConfigFilePath = Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -ChildPath $script:psakeConfigFile
if (Test-Path -LiteralPath $configFilePath -PathType Leaf) {
$configFileToLoad = $configFilePath
} elseIf (Test-Path -LiteralPath $defaultConfigFilePath -PathType Leaf) {
$configFileToLoad = $defaultConfigFilePath
} else {
throw 'Cannot find psake-config.ps1'
}
try {
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')]
$config = GetCurrentConfigurationOrDefault
. $configFileToLoad
} catch {
throw 'Error Loading Configuration from {0}: {1}' -f $configFileToLoad, $_
}
}
function LoadModules {
$currentConfig = $psake.context.peek().config
if ($currentConfig.modules) {
$scope = $currentConfig.moduleScope
$global = [string]::Equals($scope, "global", [StringComparison]::CurrentCultureIgnoreCase)
$currentConfig.modules | ForEach-Object {
resolve-path $_ | ForEach-Object {
"Loading module: $_"
$module = Import-Module $_ -passthru -DisableNameChecking -global:$global
if (!$module) {
throw ($msgs.error_loading_module -f $_.Name)
}
}
}
""
}
}
# 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 ($null -ne $ex) {
$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
}
$lastException = @()
while ($null -ne $ex) {
$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
$header = (($_.InvocationInfo |
SelectObjectWithDefault -Name 'PositionMessage' -Value '') -replace "`n", ' '),
($_ | SelectObjectWithDefault -Name 'Message' -Value ''),
($_ | SelectObjectWithDefault -Name 'Exception' -Value '') |
Where-Object { -not [String]::IsNullOrEmpty($_) } |
Select-Object -First 1
$delimiter = ''
if ((-not [String]::IsNullOrEmpty($header)) -and
(-not [String]::IsNullOrEmpty($shortException)))
{ $delimiter = ' [<<==>>] ' }
return "$($header)$($delimiter)Exception: $($shortException)"
}
}
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 }
}
}
function WriteColoredOutput {
param(
[string] $message,
[System.ConsoleColor] $foregroundcolor
)
$currentConfig = GetCurrentConfigurationOrDefault
if ($currentConfig.coloredOutput -eq $true) {
if (($null -ne $Host.UI) -and ($null -ne $Host.UI.RawUI) -and ($null -ne $Host.UI.RawUI.ForegroundColor)) {
$previousColor = $Host.UI.RawUI.ForegroundColor
$Host.UI.RawUI.ForegroundColor = $foregroundcolor
}
}
$message
if ($null -ne $previousColor) {
$Host.UI.RawUI.ForegroundColor = $previousColor
}
}
function WriteDocumentation($showDetailed) {
$currentContext = $psake.context.Peek()
if ($currentContext.tasks.default) {
$defaultTaskDependencies = $currentContext.tasks.default.DependsOn
} else {
$defaultTaskDependencies = @()
}
$docs = GetTasksFromContext $currentContext |
Where-Object {$_.Name -ne 'default'} |
ForEach-Object {
$isDefault = $null
if ($defaultTaskDependencies -contains $_.Name) {
$isDefault = $true
}
return Add-Member -InputObject $_ 'Default' $isDefault -PassThru
}
if ($showDetailed) {
$docs | Sort-Object 'Name' | format-list -property Name,Alias,Description,@{Label="Depends On";Expression={$_.DependsOn -join ', '}},Default
} else {
$docs | Sort-Object 'Name' | format-table -autoSize -wrap -property Name,Alias,@{Label="Depends On";Expression={$_.DependsOn -join ', '}},Default,Description
}
}
function WriteTaskTimeSummary($invokePsakeDuration) {
if ($psake.context.count -gt 0) {
$currentContext = $psake.context.Peek()
if ($currentContext.config.taskNameFormat -is [ScriptBlock]) {
& $currentContext.config.taskNameFormat "Build Time Report"
} elseif ($currentContext.config.taskNameFormat -ne "Executing {0}") {
$currentContext.config.taskNameFormat -f "Build Time Report"
}
else {
"-" * 70
"Build Time Report"
"-" * 70
}
$list = @()
while ($currentContext.executedTasks.Count -gt 0) {
$taskKey = $currentContext.executedTasks.Pop()
$task = $currentContext.tasks.$taskKey
if ($taskKey -eq "default") {
continue
}
$list += new-object PSObject -property @{
Name = $task.Name;
Duration = $task.Duration.ToString("hh\:mm\:ss\.fff")
}
}
[Array]::Reverse($list)
$list += new-object PSObject -property @{
Name = "Total:";
Duration = $invokePsakeDuration.ToString("hh\:mm\:ss\.fff")
}
# using "out-string | where-object" to filter out the blank line that format-table prepends
$list | format-table -autoSize -property Name,Duration | out-string -stream | where-object { $_ }
}
}
$config.buildFileName="default.ps1"
$config.framework = "4.6.1"
$config.taskNameFormat="Executing {0}"
$config.verboseError= $true
$config.coloredOutput = $true
$config.moduleScope="global"
$config.taskNameFormat= { param($taskName) "Executing $taskName at $(get-date)" }
\ No newline at end of file
@echo off
rem Helper script for those who want to run psake from cmd.exe
rem Example run from cmd.exe:
rem psake "psakefile.ps1" "BuildHelloWord" "4.0"
if '%1'=='/?' goto help
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 }"
exit /B %errorlevel%
:help
powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0\psake.ps1' -help"
# Helper script for those who want to run psake without importing the module.
# Example run from PowerShell:
# .\psake.ps1 "psakefile.ps1" "BuildHelloWord" "4.0"
# Must match parameter definitions for psake.psm1/invoke-psake
# otherwise named parameter binding fails
[cmdletbinding()]
param(
[Parameter(Position = 0, Mandatory = $false)]
[string]$buildFile,
[Parameter(Position = 1, Mandatory = $false)]
[string[]]$taskList = @(),
[Parameter(Position = 2, Mandatory = $false)]
[string]$framework,
[Parameter(Position = 3, Mandatory = $false)]
[switch]$docs = $false,
[Parameter(Position = 4, Mandatory = $false)]
[System.Collections.Hashtable]$parameters = @{},
[Parameter(Position = 5, Mandatory = $false)]
[System.Collections.Hashtable]$properties = @{},
[Parameter(Position = 6, Mandatory = $false)]
[alias("init")]
[scriptblock]$initialization = {},
[Parameter(Position = 7, Mandatory = $false)]
[switch]$nologo = $false,
[Parameter(Position = 8, Mandatory = $false)]
[switch]$help = $false,
[Parameter(Position = 9, Mandatory = $false)]
[string]$scriptPath,
[Parameter(Position = 10, Mandatory = $false)]
[switch]$detailedDocs = $false,
[Parameter(Position = 11, Mandatory = $false)]
[switch]$notr = $false
)
# setting $scriptPath here, not as default argument, to support calling as "powershell -File psake.ps1"
if (-not $scriptPath) {
$scriptPath = $(Split-Path -Path $MyInvocation.MyCommand.path -Parent)
}
# '[p]sake' is the same as 'psake' but $Error is not polluted
Remove-Module -Name [p]sake -Verbose:$false
Import-Module -Name (Join-Path -Path $scriptPath -ChildPath 'psake.psd1') -Verbose:$false
if ($help) {
Get-Help -Name Invoke-psake -Full
return
}
if ($buildFile -and (-not (Test-Path -Path $buildFile))) {
$absoluteBuildFile = (Join-Path -Path $scriptPath -ChildPath $buildFile)
if (Test-path -Path $absoluteBuildFile) {
$buildFile = $absoluteBuildFile
}
}
Invoke-psake $buildFile $taskList $framework $docs $parameters $properties $initialization $nologo $detailedDocs $notr
@{
RootModule = 'psake.psm1'
ModuleVersion = '4.7.4'
GUID = 'cfb53216-072f-4a46-8975-ff7e6bda05a5'
Author = 'James Kovacs'
Copyright = 'Copyright (c) 2010-18 James Kovacs, Damian Hickey, Brandon Olin, and Contributors'
PowerShellVersion = '3.0'
Description = 'psake is a build automation tool written in PowerShell.'
FunctionsToExport = @('Invoke-psake',
'Invoke-Task',
'Get-PSakeScriptTasks',
'Task',
'Properties',
'Include',
'FormatTaskName',
'TaskSetup',
'TaskTearDown',
'Framework',
'Assert',
'Exec')
VariablesToExport = 'psake'
PrivateData = @{
PSData = @{
ReleaseNotes = 'https://raw.githubusercontent.com/psake/psake/master/CHANGELOG.md'
LicenseUri = 'https://raw.githubusercontent.com/psake/psake/master/license.txt'
ProjectUri = 'https://github.com/psake/psake'
Tags = @('Build', 'Task')
IconUri = 'https://raw.githubusercontent.com/psake/graphics/master/png/psake-single-icon-teal-bg-256x256.png'
}
}
}
# 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.
#Requires -Version 2.0
if ($PSVersionTable.PSVersion.Major -ge 3)
{
$script:IgnoreError = 'Ignore'
}
else
{
$script:IgnoreError = 'SilentlyContinue'
}
# Dot source public/private functions
$public = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'public/*.ps1') -Recurse -ErrorAction Stop)
$private = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'private/*.ps1') -Recurse -ErrorAction Stop)
foreach ($import in @($public + $private)) {
try {
. $import.FullName
}
catch {
throw "Unable to dot source [$($import.FullName)]"
}
}
DATA msgs {
convertfrom-stringdata @'
error_invalid_task_name = Task name should not be null or empty string.
error_task_name_does_not_exist = Task {0} does not exist.
error_circular_reference = Circular reference found for task {0}.
error_missing_action_parameter = Action parameter must be specified when using PreAction or PostAction parameters for task {0}.
error_corrupt_callstack = Call stack was corrupt. Expected {0}, but got {1}.
error_invalid_framework = Invalid .NET Framework version, {0} specified.
error_unknown_framework = Unknown .NET Framework version, {0} specified in {1}.
error_unknown_pointersize = Unknown pointer size ({0}) returned from System.IntPtr.
error_unknown_bitnesspart = Unknown .NET Framework bitness, {0}, specified in {1}.
error_no_framework_install_dir_found = No .NET Framework installation directory found at {0}.
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.
error_loading_module = Error loading module {0}.
warning_deprecated_framework_variable = Warning: Using global variable $framework to set .NET framework version used is deprecated. Instead use Framework function or configuration file psake-config.ps1.
warning_missing_vsssetup_module = Warning: Cannot find build tools version {0} without the module VSSetup. You can install this module with the command: Install-Module VSSetup -Scope CurrentUser
required_variable_not_set = Variable {0} must be set to run task {1}.
postcondition_failed = Postcondition failed for task {0}.
precondition_was_false = Precondition was false, not executing task {0}.
continue_on_error = Error in task {0}. {1}
psake_success = psake succeeded executing {0}
'@
}
Import-LocalizedData -BindingVariable msgs -FileName messages.psd1 -ErrorAction $script:IgnoreError
$scriptDir = Split-Path $MyInvocation.MyCommand.Path
$manifestPath = Join-Path $scriptDir psake.psd1
$manifest = Test-ModuleManifest -Path $manifestPath -WarningAction SilentlyContinue
$script:psakeConfigFile = 'psake-config.ps1'
$script:psake = @{}
$psake.version = $manifest.Version.ToString()
$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 = "psakefile.ps1";
legacyBuildFileName = "default.ps1";
framework = "4.0";
taskNameFormat = "Executing {0}";
verboseError = $false;
coloredOutput = $true;
modules = $null;
moduleScope = "";
} # contains default configuration, can be overridden in psake-config.ps1 in directory with psake.psm1 or in directory with current build script
$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
$psake.error_message = $null # contains the error message which caused the script to fail
LoadConfiguration
export-modulemember -function Invoke-psake, Invoke-Task, Get-PSakeScriptTasks, Task, Properties, Include, FormatTaskName, TaskSetup, TaskTearDown, Framework, Assert, Exec -variable psake
function Assert {
<#
.SYNOPSIS
Helper function for "Design by Contract" assertion checking.
.DESCRIPTION
This is a helper function that makes the code less noisy by eliminating many of the "if" statements that are normally required to verify assumptions in the code.
.PARAMETER conditionToCheck
The boolean condition to evaluate
.PARAMETER failureMessage
The error message used for the exception if the conditionToCheck parameter is false
.EXAMPLE
C:\PS>Assert $false "This always throws an exception"
Example of an assertion that will always fail.
.EXAMPLE
C:\PS>Assert ( ($i % 2) -eq 0 ) "$i is not an even number"
This exmaple may throw an exception if $i is not an even number
Note:
It might be necessary to wrap the condition with paranthesis to force PS to evaluate the condition
so that a boolean value is calculated and passed into the 'conditionToCheck' parameter.
Example:
Assert 1 -eq 2 "1 doesn't equal 2"
PS will pass 1 into the condtionToCheck variable and PS will look for a parameter called "eq" and
throw an exception with the following message "A parameter cannot be found that matches parameter name 'eq'"
The solution is to wrap the condition in () so that PS will evaluate it first.
Assert (1 -eq 2) "1 doesn't equal 2"
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
$conditionToCheck,
[Parameter(Mandatory = $true)]
[string]$failureMessage
)
if (-not $conditionToCheck) {
throw ('Assert: {0}' -f $failureMessage)
}
}
function Exec {
<#
.SYNOPSIS
Helper function for executing command-line programs.
.DESCRIPTION
This is a helper function that runs a scriptblock and checks the PS variable $lastexitcode to see if an error occcured.
If an error is detected then an exception is thrown.
This function allows you to run command-line programs without having to explicitly check fthe $lastexitcode variable.
.PARAMETER cmd
The scriptblock to execute. This scriptblock will typically contain the command-line invocation.
.PARAMETER errorMessage
The error message to display if the external command returned a non-zero exit code.
.PARAMETER maxRetries
The maximum number of times to retry the command before failing.
.PARAMETER retryTriggerErrorPattern
If the external command raises an exception, match the exception against this regex to determine if the command can be retried.
If a match is found, the command will be retried provided [maxRetries] has not been reached.
.PARAMETER workingDirectory
The working directory to set before running the external command.
.EXAMPLE
exec { svn info $repository_trunk } "Error executing SVN. Please verify SVN command-line client is installed"
This example calls the svn command-line client.
.LINK
Assert
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
.LINK
Properties
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$cmd,
[string]$errorMessage = ($msgs.error_bad_command -f $cmd),
[int]$maxRetries = 0,
[string]$retryTriggerErrorPattern = $null,
[string]$workingDirectory = $null
)
if ($workingDirectory) {
Push-Location -Path $workingDirectory
}
$tryCount = 1
do {
try {
$global:lastexitcode = 0
& $cmd
if ($global:lastexitcode -ne 0) {
throw "Exec: $errorMessage"
}
break
}
catch [Exception] {
if ($tryCount -gt $maxRetries) {
throw $_
}
if ($retryTriggerErrorPattern -ne $null) {
$isMatch = [regex]::IsMatch($_.Exception.Message, $retryTriggerErrorPattern)
if ($isMatch -eq $false) {
throw $_
}
}
"Try $tryCount failed, retrying again in 1 second..."
$tryCount++
[System.Threading.Thread]::Sleep([System.TimeSpan]::FromSeconds(1))
}
finally {
if ($workingDirectory) {
Pop-Location
}
}
}
while ($true)
}
function FormatTaskName {
<#
.SYNOPSIS
This function allows you to change how psake renders the task name during a build.
.DESCRIPTION
This function takes either a string which represents a format string (formats using the -f format operator see "help about_operators") or it can accept a script block that has a single parameter that is the name of the task that will be executed.
.PARAMETER format
A format string or a scriptblock to execute
.EXAMPLE
A sample build script that uses a format string is shown below:
Task default -depends TaskA, TaskB, TaskC
FormatTaskName "-------- {0} --------"
Task TaskA {
"TaskA is executing"
}
Task TaskB {
"TaskB is executing"
}
Task TaskC {
"TaskC is executing"
-----------
The script above produces the following output:
-------- TaskA --------
TaskA is executing
-------- TaskB --------
TaskB is executing
-------- TaskC --------
TaskC is executing
Build Succeeded!
.EXAMPLE
A sample build script that uses a ScriptBlock is shown below:
Task default -depends TaskA, TaskB, TaskC
FormatTaskName {
param($taskName)
write-host "Executing Task: $taskName" -foregroundcolor blue
}
Task TaskA {
"TaskA is executing"
}
Task TaskB {
"TaskB is executing"
}
Task TaskC {
"TaskC is executing"
}
-----------
The above example uses the scriptblock parameter to the FormatTaskName function to render each task name in the color blue.
Note: the $taskName parameter is arbitrary, it could be named anything.
.LINK
Assert
.LINK
Exec
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
$format
)
$psake.context.Peek().config.taskNameFormat = $format
}
function Framework {
<#
.SYNOPSIS
Sets the version of the .NET framework you want to use during build.
.DESCRIPTION
This function will accept a string containing version of the .NET framework to use during build.
Possible values: '1.0', '1.1', '2.0', '2.0x86', '2.0x64', '3.0', '3.0x86', '3.0x64', '3.5', '3.5x86', '3.5x64', '4.0', '4.0x86', '4.0x64', '4.5', '4.5x86', '4.5x64', '4.5.1', '4.5.1x86', '4.5.1x64'.
Default is '3.5*', where x86 or x64 will be detected based on the bitness of the PowerShell process.
.PARAMETER framework
Version of the .NET framework to use during build.
.EXAMPLE
Framework "4.0"
Task default -depends Compile
Task Compile -depends Clean {
msbuild /version
}
-----------
The script above will output detailed version of msbuid v4
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$framework
)
$psake.context.Peek().config.framework = $framework
ConfigureBuildEnvironment
}
function Get-PSakeScriptTasks {
<#
.SYNOPSIS
Returns meta data about all the tasks defined in the provided psake script.
.DESCRIPTION
Returns meta data about all the tasks defined in the provided psake script.
.PARAMETER buildFile
The path to the psake build script to read the tasks from.
.EXAMPLE
PS C:\>Get-PSakeScriptTasks -buildFile '.\build.ps1'
DependsOn Alias Name Description
--------- ----- ---- -----------
{} Compile
{} Clean
{Test} Default
{Clean, Compile} Test
Gets the psake tasks contained in the 'build.ps1' file.
.LINK
Invoke-psake
#>
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseSingularNouns', '')]
[CmdletBinding()]
param(
[string]$buildFile
)
if (-not $buildFile) {
$buildFile = $psake.config_default.buildFileName
}
try {
ExecuteInBuildFileScope $buildFile $MyInvocation.MyCommand.Module {
param($currentContext, $module)
return GetTasksFromContext $currentContext
}
} finally {
CleanupEnvironment
}
}
function Include {
<#
.SYNOPSIS
Include the functions or code of another powershell script file into the current build script's scope
.DESCRIPTION
A build script may declare an "includes" function which allows you to define a file containing powershell code to be included
and added to the scope of the currently running build script. Code from such file will be executed after code from build script.
.PARAMETER fileNamePathToInclude
A string containing the path and name of the powershell file to include
.EXAMPLE
A sample build script is shown below:
Include ".\build_utils.ps1"
Task default -depends Test
Task Test -depends Compile, Clean {
}
Task Compile -depends Clean {
}
Task Clean {
}
-----------
The script above includes all the functions and variables defined in the ".\build_utils.ps1" script into the current build script's scope
Note: You can have more than 1 "Include" function defined in the build script.
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$fileNamePathToInclude
)
Assert (test-path $fileNamePathToInclude -pathType Leaf) ($msgs.error_invalid_include_path -f $fileNamePathToInclude)
$psake.context.Peek().includes.Enqueue((Resolve-Path $fileNamePathToInclude));
}
function Invoke-Task {
<#
.SYNOPSIS
Executes another task in the current build script.
.DESCRIPTION
This is a function that will allow you to invoke a Task from within another Task in the current build script.
.PARAMETER taskName
The name of the task to execute.
.EXAMPLE
Invoke-Task "Compile"
This example calls the "Compile" task.
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$taskName
)
Assert $taskName ($msgs.error_invalid_task_name)
$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)
if ($currentContext.executedTasks.Contains($taskKey)) { return }
Assert (!$currentContext.callStack.Contains($taskKey)) ($msgs.error_circular_reference -f $taskName)
$currentContext.callStack.Push($taskKey)
$task = $currentContext.tasks.$taskKey
$precondition_is_valid = & $task.Precondition
if (!$precondition_is_valid) {
WriteColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan
} else {
if ($taskKey -ne 'default') {
if ($task.PreAction -or $task.PostAction) {
Assert ($null -ne $task.Action) ($msgs.error_missing_action_parameter -f $taskName)
}
if ($task.Action) {
$stopwatch = new-object System.Diagnostics.Stopwatch
try {
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
$stopwatch.Start()
$currentContext.currentTaskName = $taskName
try {
& $currentContext.taskSetupScriptBlock
try {
if ($task.PreAction) {
& $task.PreAction
}
if ($currentContext.config.taskNameFormat -is [ScriptBlock]) {
$taskHeader = & $currentContext.config.taskNameFormat $taskName
} else {
$taskHeader = $currentContext.config.taskNameFormat -f $taskName
}
WriteColoredOutput $taskHeader -foregroundcolor Cyan
foreach ($variable in $task.requiredVariables) {
Assert ((Test-Path "variable:$variable") -and ($null -ne (Get-Variable $variable).Value)) ($msgs.required_variable_not_set -f $variable, $taskName)
}
& $task.Action
} finally {
if ($task.PostAction) {
& $task.PostAction
}
}
} finally {
& $currentContext.taskTearDownScriptBlock
}
} catch {
if ($task.ContinueOnError) {
"-"*70
WriteColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow
"-"*70
} else {
throw $_
}
} finally {
$task.Duration = $stopwatch.Elapsed
}
} else {
# no action was specified but we still execute all the dependencies
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
}
} else {
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
}
Assert (& $task.Postcondition) ($msgs.postcondition_failed -f $taskName)
}
$poppedTaskKey = $currentContext.callStack.Pop()
Assert ($poppedTaskKey -eq $taskKey) ($msgs.error_corrupt_callstack -f $taskKey,$poppedTaskKey)
$currentContext.executedTasks.Push($taskKey)
}
function Invoke-psake {
<#
.SYNOPSIS
Runs a psake build script.
.DESCRIPTION
This function runs a psake build script
.PARAMETER buildFile
The path to the psake build script to execute
.PARAMETER taskList
A comma-separated list of task names to execute
.PARAMETER framework
The version of the .NET framework you want to use during build. You can append x86 or x64 to force a specific framework.
If not specified, x86 or x64 will be detected based on the bitness of the PowerShell process.
Possible values: '1.0', '1.1', '2.0', '2.0x86', '2.0x64', '3.0', '3.0x86', '3.0x64', '3.5', '3.5x86', '3.5x64', '4.0', '4.0x86', '4.0x64', '4.5', '4.5x86', '4.5x64', '4.5.1', '4.5.1x86', '4.5.1x64'
.PARAMETER docs
Prints a list of tasks and their descriptions
.PARAMETER parameters
A hashtable containing parameters to be passed into the current build script.
These parameters will be processed before the 'Properties' function of the script is processed.
This means you can access parameters from within the 'Properties' function!
.PARAMETER properties
A hashtable containing properties to be passed into the current build script.
These properties will override matching properties that are found in the 'Properties' function of the script.
.PARAMETER initialization
Parameter description
.PARAMETER nologo
Do not display the startup banner and copyright message.
.PARAMETER detailedDocs
Prints a more descriptive list of tasks and their descriptions.
.PARAMETER notr
Do not display the time report.
.EXAMPLE
Invoke-psake
Runs the 'default' task in the '.build.ps1' build script
.EXAMPLE
Invoke-psake '.\build.ps1' Tests,Package
Runs the 'Tests' and 'Package' tasks in the '.build.ps1' build script
.EXAMPLE
Invoke-psake Tests
This example will run the 'Tests' tasks in the 'psakefile.ps1' build script. The 'psakefile.ps1' is assumed to be in the current directory.
.EXAMPLE
Invoke-psake 'Tests, Package'
This example will run the 'Tests' and 'Package' tasks in the 'psakefile.ps1' build script. The 'psakefile.ps1' is assumed to be in the current directory.
.EXAMPLE
Invoke-psake .\build.ps1 -docs
Prints a report of all the tasks and their dependencies and descriptions and then exits
.EXAMPLE
Invoke-psake .\parameters.ps1 -parameters @{"p1"="v1";"p2"="v2"}
Runs the build script called 'parameters.ps1' and passes in parameters 'p1' and 'p2' with values 'v1' and 'v2'
Here's the .\parameters.ps1 build script:
properties {
$my_property = $p1 + $p2
}
task default -depends TestParams
task TestParams {
Assert ($my_property -ne $null) '$my_property should not be null'
}
Notice how you can refer to the parameters that were passed into the script from within the "properties" function.
The value of the $p1 variable should be the string "v1" and the value of the $p2 variable should be "v2".
.EXAMPLE
Invoke-psake .\properties.ps1 -properties @{"x"="1";"y"="2"}
Runs the build script called 'properties.ps1' and passes in parameters 'x' and 'y' with values '1' and '2'
This feature allows you to override existing properties in your build script.
Here's the .\properties.ps1 build script:
properties {
$x = $null
$y = $null
$z = $null
}
task default -depends TestProperties
task TestProperties {
Assert ($x -ne $null) "x should not be null"
Assert ($y -ne $null) "y should not be null"
Assert ($z -eq $null) "z should be null"
}
.NOTES
---- Exceptions ----
If there is an exception thrown during the running of a build script psake will set the '$psake.build_success' variable to $false.
To detect failue outside PowerShell (for example by build server), finish PowerShell process with non-zero exit code when '$psake.build_success' is $false.
Calling psake from 'cmd.exe' with 'psake.cmd' will give you that behaviour.
---- $psake variable ----
When the psake module is loaded a variable called $psake is created which is a hashtable
containing some variables:
$psake.version # contains the current version of psake
$psake.context # holds onto the current state of all variables
$psake.run_by_psake_build_tester # indicates that build is being run by psake-BuildTester
$psake.config_default # contains default configuration
# can be overriden in psake-config.ps1 in directory with psake.psm1 or in directory with current build script
$psake.build_success # indicates that the current build was successful
$psake.build_script_file # contains a System.IO.FileInfo for the current build script
$psake.build_script_dir # contains the fully qualified path to the current build script
$psake.error_message # contains the error message which caused the script to fail
You should see the following when you display the contents of the $psake variable right after importing psake
PS projects:\psake\> Import-Module .\psake.psm1
PS projects:\psake\> $psake
Name Value
---- -----
run_by_psake_build_tester False
version 4.2
build_success False
build_script_file
build_script_dir
config_default @{framework=3.5; ...
context {}
error_message
After a build is executed the following $psake values are updated: build_script_file, build_script_dir, build_success
PS projects:\psake\> Invoke-psake .\examples\psakefile.ps1
Executing task: Clean
Executed Clean!
Executing task: Compile
Executed Compile!
Executing task: Test
Executed Test!
Build Succeeded!
----------------------------------------------------------------------
Build Time Report
----------------------------------------------------------------------
Name Duration
---- --------
Clean 00:00:00.0798486
Compile 00:00:00.0869948
Test 00:00:00.0958225
Total: 00:00:00.2712414
PS projects:\psake\> $psake
Name Value
---- -----
build_script_file YOUR_PATH\examples\psakefile.ps1
run_by_psake_build_tester False
build_script_dir YOUR_PATH\examples
context {}
version 4.2
build_success True
config_default @{framework=3.5; ...
error_message
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
.LINK
Properties
#>
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory = $false)]
[string]$buildFile,
[Parameter(Position = 1, Mandatory = $false)]
[string[]]$taskList = @(),
[Parameter(Position = 2, Mandatory = $false)]
[string]$framework,
[Parameter(Position = 3, Mandatory = $false)]
[switch]$docs = $false,
[Parameter(Position = 4, Mandatory = $false)]
[hashtable]$parameters = @{},
[Parameter(Position = 5, Mandatory = $false)]
[hashtable]$properties = @{},
[Parameter(Position = 6, Mandatory = $false)]
[alias("init")]
[scriptblock]$initialization = {},
[Parameter(Position = 7, Mandatory = $false)]
[switch]$nologo,
[Parameter(Position = 8, Mandatory = $false)]
[switch]$detailedDocs,
[Parameter(Position = 9, Mandatory = $false)]
[switch]$notr # disable time report
)
try {
if (-not $nologo) {
"psake version {0}`nCopyright (c) 2010-2017 James Kovacs & Contributors`n" -f $psake.version
}
if (!$buildFile) {
$buildFile = Get-DefaultBuildFile
}
elseif (!(Test-Path $buildFile -PathType Leaf) -and ($null -ne (Get-DefaultBuildFile -UseDefaultIfNoneExist $false))) {
# If the default file exists and the given "buildfile" isn't found assume that the given
# $buildFile is actually the target Tasks to execute in the $config.buildFileName script.
$taskList = $buildFile.Split(', ')
$buildFile = Get-DefaultBuildFile
}
ExecuteInBuildFileScope $buildFile $MyInvocation.MyCommand.Module {
param($currentContext, $module)
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
if ($docs -or $detailedDocs) {
WriteDocumentation($detailedDocs)
return
}
foreach ($key in $parameters.keys) {
if (test-path "variable:\$key") {
set-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null
} else {
new-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null
}
}
# The initial dot (.) indicates that variables initialized/modified in the propertyBlock are available in the parent scope.
foreach ($propertyBlock in $currentContext.properties) {
. $propertyBlock
}
foreach ($key in $properties.keys) {
if (test-path "variable:\$key") {
set-item -path "variable:\$key" -value $properties.$key -WhatIf:$false -Confirm:$false | out-null
}
}
# Simple dot sourcing will not work. We have to force the script block into our
# module's scope in order to initialize variables properly.
. $module $initialization
# Execute the list of tasks or the default task
if ($taskList) {
foreach ($task in $taskList) {
invoke-task $task
}
} elseif ($currentContext.tasks.default) {
invoke-task default
} else {
throw $msgs.error_no_default_task
}
$successMsg = $msgs.psake_success -f $buildFile
WriteColoredOutput ("`n${successMsg}`n") -foregroundcolor Green
$psake.error_message = $null
$stopwatch.Stop()
if (-not $notr) {
WriteTaskTimeSummary $stopwatch.Elapsed
}
}
$psake.build_success = $true
} catch {
$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 += "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 = "Error: {0}: `n{1}" -f (Get-Date), (ResolveError $_ -Short)
}
$psake.build_success = $false
$psake.error_message = $error_message
# if we are running in a nested scope (i.e. running a psake script from a psake script) then we need to re-throw the exception
# so that the parent script will fail otherwise the parent script will report a successful build
$inNestedScope = ($psake.context.count -gt 1)
if ( $inNestedScope ) {
throw $_
} else {
if (!$psake.run_by_psake_build_tester) {
WriteColoredOutput $error_message -foregroundcolor Red
}
}
} finally {
CleanupEnvironment
}
}
function Properties {
<#
.SYNOPSIS
Define a scriptblock that contains assignments to variables that will be available to all tasks in the build script
.DESCRIPTION
A build script may declare a "Properies" function which allows you to define variables that will be available to all the "Task" functions in the build script.
.PARAMETER properties
The script block containing all the variable assignment statements
.EXAMPLE
A sample build script is shown below:
Properties {
$build_dir = "c:\build"
$connection_string = "datasource=localhost;initial catalog=northwind;integrated security=sspi"
}
Task default -depends Test
Task Test -depends Compile, Clean {
}
Task Compile -depends Clean {
}
Task Clean {
}
Note: You can have more than one "Properties" function defined in the build script.
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Task
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$properties
)
$psake.context.Peek().properties += $properties
}
function Task {
<#
.SYNOPSIS
Defines a build task to be executed by psake
.DESCRIPTION
This function creates a 'task' object that will be used by the psake engine to execute a build task.
Note: There must be at least one task called 'default' in the build script
.PARAMETER name
The name of the task
.PARAMETER action
A scriptblock containing the statements to execute for the task.
.PARAMETER preaction
A scriptblock to be executed before the 'Action' scriptblock.
Note: This parameter is ignored if the 'Action' scriptblock is not defined.
.PARAMETER postaction
A scriptblock to be executed after the 'Action' scriptblock.
Note: This parameter is ignored if the 'Action' scriptblock is not defined.
.PARAMETER precondition
A scriptblock that is executed to determine if the task is executed or skipped.
This scriptblock should return $true or $false
.PARAMETER postcondition
A scriptblock that is executed to determine if the task completed its job correctly.
An exception is thrown if the scriptblock returns $false.
.PARAMETER continueOnError
If this switch parameter is set then the task will not cause the build to fail when an exception is thrown by the task
.PARAMETER depends
An array of task names that this task depends on.
These tasks will be executed before the current task is executed.
.PARAMETER requiredVariables
An array of names of variables that must be set to run this task.
.PARAMETER description
A description of the task.
.PARAMETER alias
An alternate name for the task.
.EXAMPLE
A sample build script is shown below:
Task default -Depends Test
Task Test -Depends Compile, Clean {
"This is a test"
}
Task Compile -Depends Clean {
"Compile"
}
Task Clean {
"Clean"
}
The 'default' task is required and should not contain an 'Action' parameter.
It uses the 'Depends' parameter to specify that 'Test' is a dependency
The 'Test' task uses the 'Depends' parameter to specify that 'Compile' and 'Clean' are dependencies
The 'Compile' task depends on the 'Clean' task.
Note:
The 'Action' parameter is defaulted to the script block following the 'Clean' task.
An equivalent 'Test' task is shown below:
Task Test -Depends Compile, Clean -Action {
$testMessage
}
The output for the above sample build script is shown below:
Executing task, Clean...
Clean
Executing task, Compile...
Compile
Executing task, Test...
This is a test
Build Succeeded!
----------------------------------------------------------------------
Build Time Report
----------------------------------------------------------------------
Name Duration
---- --------
Clean 00:00:00.0065614
Compile 00:00:00.0133268
Test 00:00:00.0225964
Total: 00:00:00.0782496
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
TaskSetup
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$name,
[scriptblock]$action = $null,
[scriptblock]$preaction = $null,
[scriptblock]$postaction = $null,
[scriptblock]$precondition = {$true},
[scriptblock]$postcondition = {$true},
[switch]$continueOnError,
[string[]]$depends = @(),
[string[]]$requiredVariables = @(),
[string]$description = $null,
[string]$alias = $null
)
if ($name -eq 'default') {
Assert (!$action) ($msgs.error_default_task_cannot_have_action)
}
$newTask = @{
Name = $name
DependsOn = $depends
PreAction = $preaction
Action = $action
PostAction = $postaction
Precondition = $precondition
Postcondition = $postcondition
ContinueOnError = $continueOnError
Description = $description
Duration = [System.TimeSpan]::Zero
RequiredVariables = $requiredVariables
Alias = $alias
}
$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
}
}
function TaskSetup {
<#
.SYNOPSIS
Adds a scriptblock that will be executed before each task
.DESCRIPTION
This function will accept a scriptblock that will be executed before each task in the build script.
.PARAMETER setup
A scriptblock to execute
.EXAMPLE
A sample build script is shown below:
Task default -depends Test
Task Test -depends Compile, Clean {
}
Task Compile -depends Clean {
}
Task Clean {
}
TaskSetup {
"Running 'TaskSetup' for task $context.Peek().currentTaskName"
}
The script above produces the following output:
Running 'TaskSetup' for task Clean
Executing task, Clean...
Running 'TaskSetup' for task Compile
Executing task, Compile...
Running 'TaskSetup' for task Test
Executing task, Test...
Build Succeeded
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskTearDown
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$setup
)
$psake.context.Peek().taskSetupScriptBlock = $setup
}
function TaskTearDown {
<#
.SYNOPSIS
Adds a scriptblock to the build that will be executed after each task
.DESCRIPTION
This function will accept a scriptblock that will be executed after each task in the build script.
.PARAMETER teardown
A scriptblock to execute
.EXAMPLE
A sample build script is shown below:
Task default -depends Test
Task Test -depends Compile, Clean {
}
Task Compile -depends Clean {
}
Task Clean {
}
TaskTearDown {
"Running 'TaskTearDown' for task $context.Peek().currentTaskName"
}
The script above produces the following output:
Executing task, Clean...
Running 'TaskTearDown' for task Clean
Executing task, Compile...
Running 'TaskTearDown' for task Compile
Executing task, Test...
Running 'TaskTearDown' for task Test
Build Succeeded
.LINK
Assert
.LINK
Exec
.LINK
FormatTaskName
.LINK
Framework
.LINK
Get-PSakeScriptTasks
.LINK
Include
.LINK
Invoke-psake
.LINK
Properties
.LINK
Task
.LINK
TaskSetup
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$teardown
)
$psake.context.Peek().taskTearDownScriptBlock = $teardown
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\EFCore.Cassandra\EFCore.Cassandra.csproj" />
</ItemGroup>
</Project>
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using EFCore.Cassandra.Samples.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Cassandra.Storage;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCore.Cassandra.Samples
{
public class FakeDbContext : DbContext
{
public DbSet<Applicant> Applicants { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseCassandra("Contact Points=127.0.0.1;", opt =>
{
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName, "cv");
});
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var timeUuidConverter = new TimeUuidToGuidConverter();
modelBuilder.ForCassandraAddKeyspace("cv", new KeyspaceReplicationSimpleStrategyClass(2));
modelBuilder.Entity<Applicant>()
.ToTable("applicants", "cv")
.HasKey(p => new { p.Id, p.LastName });
modelBuilder.Entity<Applicant>()
.ForCassandraSetClusterColumns(s => new { s.LastName });
modelBuilder.Entity<Applicant>()
.Property(p => p.TimeUuid)
.HasConversion(timeUuidConverter);
modelBuilder.Entity<Applicant>()
.Property(p => p.Id)
.HasColumnName("id");
modelBuilder.Entity<CV>()
.ToTable("cvs", "cv")
.HasKey(c => c.Id);
}
}
}
\ No newline at end of file
// <auto-generated />
using Cassandra;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Collections.Generic;
using System.Net;
using System.Numerics;
namespace EFCore.Cassandra.Samples.Migrations
{
[DbContext(typeof(FakeDbContext))]
[Migration("20191003081312_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Cassandra:Keyspacecv", "{\"ReplicationFactor\":2,\"ReplicationClass\":0}")
.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");
modelBuilder.Entity("EFCore.Cassandra.Integration.Tests.Models.Applicant", b =>
{
b.Property<Guid>("Id")
.HasColumnName("id");
b.Property<string>("LastName");
b.Property<BigInteger>("BigInteger");
b.Property<byte[]>("Blob");
b.Property<bool>("Bool");
b.Property<DateTimeOffset>("DateTimeOffset");
b.Property<decimal>("Decimal");
b.Property<IDictionary<string, string>>("Dic");
b.Property<double>("Double");
b.Property<float>("Float");
b.Property<int>("Integer");
b.Property<IPAddress>("Ip");
b.Property<LocalDate>("LocalDate");
b.Property<LocalTime>("LocalTime");
b.Property<long>("Long");
b.Property<IList<string>>("Lst");
b.Property<IList<int>>("LstInt");
b.Property<sbyte>("Sbyte");
b.Property<short>("SmallInt");
b.Property<Guid>("TimeUuid")
.HasConversion(new ValueConverter<Guid, Guid>(v => default(Guid), v => default(Guid), new ConverterMappingHints(size: 36)));
b.HasKey("Id", "LastName");
b.ToTable("applicants","cv");
b.HasAnnotation("Cassandra:ClusterColumns", new[] { "LastName" });
});
#pragma warning restore 612, 618
}
}
}
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Numerics;
using Cassandra;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCore.Cassandra.Samples.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "cv");
migrationBuilder.CreateTable(
name: "applicants",
schema: "cv",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
LastName = table.Column<string>(nullable: false),
Long = table.Column<long>(nullable: false),
Bool = table.Column<bool>(nullable: false),
Decimal = table.Column<decimal>(nullable: false),
Double = table.Column<double>(nullable: false),
Float = table.Column<float>(nullable: false),
Integer = table.Column<int>(nullable: false),
SmallInt = table.Column<short>(nullable: false),
DateTimeOffset = table.Column<DateTimeOffset>(nullable: false),
TimeUuid = table.Column<Guid>(nullable: false),
Sbyte = table.Column<sbyte>(nullable: false),
BigInteger = table.Column<BigInteger>(nullable: false),
Blob = table.Column<byte[]>(nullable: true),
LocalDate = table.Column<LocalDate>(nullable: true),
Ip = table.Column<IPAddress>(nullable: true),
LocalTime = table.Column<LocalTime>(nullable: true),
Lst = table.Column<IEnumerable<string>>(nullable: true),
LstInt = table.Column<IEnumerable<int>>(nullable: true),
Dic = table.Column<IDictionary<string, string>>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_applicants", x => new { x.id, x.LastName });
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "applicants",
schema: "cv");
}
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.EntityFrameworkCore.Design;
[assembly: DesignTimeProviderServices("Microsoft.EntityFrameworkCore.Cassandra.Design.Internal.CassandraDesignTimeServices")]
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册