Skip to content

Commit

Permalink
Refactored to property & incoming web hook support
Browse files Browse the repository at this point in the history
* Added support to post message using incoming Slack web hook
* Refactored to property alias (method alias kept for backward compatibility)
  • Loading branch information
devlead committed Jun 27, 2015
1 parent af73abc commit 1c3d6ba
Show file tree
Hide file tree
Showing 15 changed files with 424 additions and 51 deletions.
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ Cake AddIn that extends Cake with Slack messaging features

## Usage

### Post message

### Using token
```csharp
#addin "Cake.Slack"
var slackToken = EnvironmentVariable("SLACK_TOKEN");
var slackChannel = "#cake";
var postMessageResult = SlackChatPostMessage(
var postMessageResult = Slack.Chat.PostMessage(
token:slackToken,
channel:slackChannel,
text:"This _is_ a `message` from *CakeBuild* :thumbsup:\r\n```Here is some code```"
Expand All @@ -28,4 +31,31 @@ Cake output will be similar to below:
Message 1420896696.000057 succcessfully sent
```
This will result in an message in your Slack channel similar to below:
![Sample message](https://github.com/WCOMAB/Cake.Slack/raw/master/samplemessage.png)

### Using incoming web hook url
```csharp
#addin "Cake.Slack"
var slackhookuri = EnvironmentVariable("slackhookuri");
var slackChannel = "#cake";
var postMessageResult = Slack.Chat.PostMessage(
channel:slackChannel,
text:"This _is_ a `message` from *CakeBuild* :thumbsup:\r\n```Here is some code```",
messageSettings:new SlackChatMessageSettings { IncomingWebHookUrl = slackhookuri }
);

if (postMessageResult.Ok)
{
Information("Message succcessfully sent");
}
else
{
Error("Failed to send message: {0}", postMessageResult.Error);
}
```
Cake output will be similar to below:
```
Message succcessfully sent
```
This will result in an message in your Slack channel similar to below:
![Sample message](https://github.com/WCOMAB/Cake.Slack/raw/master/samplemessage.png)
3 changes: 3 additions & 0 deletions ReleaseNotes.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
### New in 0.0.2 (Released 2015/06/27)
* Added support to post message using incoming Slack web hook
* Refactored to property alias (method alias kept for backward compatibility)
### New in 0.0.1 (Released 2015/01/13)
* First release of Cake.Slack
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build script
build_script:
- cmd: powershell -NoProfile -ExecutionPolicy unrestricted -Command .\build.ps1 -Target "AppVeyor"
- ps: .\build.ps1 -Target AppVeyor

# Tests
test: off
32 changes: 16 additions & 16 deletions build.cake
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var slackChannel = "#cake";
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var isPullRequest = AppVeyor.Environment.PullRequest.IsPullRequest;
var solutions = GetFiles("./**/*.sln");
var solutionDirs = solutions.Select(solution => solution.GetDirectory());
var solutionPaths = solutions.Select(solution => solution.GetDirectory());
var releaseNotes = ParseReleaseNotes("./ReleaseNotes.md");
var version = releaseNotes.Version.ToString();
var binDir = "./src/Cake.Slack/bin/" + configuration;
Expand All @@ -38,19 +38,19 @@ var nuGetPackSettings = new NuGetPackSettings {
Authors = new[] {assemblyInfo.Company},
Owners = new[] {assemblyInfo.Company},
Description = assemblyInfo.Description,
Summary = "Cake AddIn that extends Cake with Slack messaging features",
Summary = "Cake AddIn that extends Cake with Slack messaging features",
ProjectUrl = new Uri("https://github.com/WCOMAB/Cake.Slack/"),
IconUrl = new Uri("http://cdn.rawgit.com/WCOMAB/nugetpackages/master/Chocolatey/icons/wcom.png"),
LicenseUrl = new Uri("https://github.com/WCOMAB/Cake.Slack/blob/master/LICENSE"),
Copyright = assemblyInfo.Copyright,
ReleaseNotes = releaseNotes.Notes.ToArray(),
Tags = new [] {"Cake", "Script", "Build", "Slack"},
RequireLicenseAcceptance= false,
RequireLicenseAcceptance= false,
Symbols = false,
NoPackageAnalysis = true,
Files = new [] {new NuSpecContent {Source = "Cake.Slack.dll"}},
BasePath = binDir,
OutputDirectory = nugetRoot
BasePath = binDir,
OutputDirectory = nugetRoot
};

///////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -88,11 +88,11 @@ Task("Clean")
.Does(() =>
{
// Clean solution directories.
foreach(var solutionDir in solutionDirs)
foreach(var path in solutionPaths)
{
Information("Cleaning {0}", solutionDir);
CleanDirectories(solutionDir + "/**/bin/" + configuration);
CleanDirectories(solutionDir + "/**/obj/" + configuration);
Information("Cleaning {0}", path);
CleanDirectories(path + "/**/bin/" + configuration);
CleanDirectories(path + "/**/obj/" + configuration);
}
});

Expand All @@ -102,7 +102,7 @@ Task("Restore")
// Restore all NuGet packages.
foreach(var solution in solutions)
{
Information("Restoring {0}", solution);
Information("Restoring {0}...", solution);
NuGetRestore(solution);
}
});
Expand All @@ -126,7 +126,7 @@ Task("Build")
foreach(var solution in solutions)
{
Information("Building {0}", solution);
MSBuild(solution, settings =>
MSBuild(solution, settings =>
settings.SetPlatformTarget(PlatformTarget.MSIL)
.WithProperty("TreatWarningsAsErrors","true")
.WithTarget("Build")
Expand All @@ -139,17 +139,17 @@ Task("Create-NuGet-Package")
.IsDependentOn("Build")
.Does(() =>
{
if (!Directory.Exists(nugetRoot))
if (!DirectoryExists(nugetRoot))
{
CreateDirectory(nugetRoot);
CreateDirectory(nugetRoot);
}
NuGetPack("./nuspec/Cake.Slack.nuspec", nuGetPackSettings);
});
});

Task("Publish-MyGet")
.IsDependentOn("Create-NuGet-Package")
.WithCriteria(() => !isLocalBuild)
.WithCriteria(() => !isPullRequest)
.WithCriteria(() => !isPullRequest)
.Does(() =>
{
// Resolve the API key.
Expand All @@ -170,7 +170,7 @@ Task("Publish-MyGet")
NuGetPush(package, new NuGetPushSettings {
Source = source,
ApiKey = apiKey
});
});
});


Expand Down
69 changes: 63 additions & 6 deletions build.ps1
Original file line number Diff line number Diff line change
@@ -1,20 +1,73 @@
<#
.SYNOPSIS
This is a Powershell script to bootstrap a Cake build.
.DESCRIPTION
This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
and execute your Cake build script with the parameters you provide.
.PARAMETER Script
The build script to execute.
.PARAMETER Target
The build script target to run.
.PARAMETER Configuration
The build configuration to use.
.PARAMETER Verbosity
Specifies the amount of information to be displayed.
.PARAMETER WhatIf
Performs a dry run of the build script.
No tasks will be executed.
.PARAMETER Experimental
Tells Cake to use the latest Roslyn release.
.LINK
http://cakebuild.net
#>

Param(
[string]$Script = "build.cake",
[string]$Target = "Default",
[string]$Configuration = "Release",
[string]$Verbosity = "Verbose"
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity = "Verbose",
[Alias("DryRun","Noop")]
[switch]$Experimental,
[switch]$WhatIf
)

$TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe"
$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe"
$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config"

# Should we use the new Roslyn?
$UseExperimental = "";
if($Experimental.IsPresent) {
$UseExperimental = "-experimental"
}

# Is this a dry run?
$UseDryRun = "";
if($WhatIf.IsPresent) {
$UseDryRun = "-dryrun"
}

# Make sure tools folder exists
if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) {
New-Item -path $TOOLS_DIR -name logfiles -itemtype directory
}

# Try find NuGet.exe in path if not exists
if (!(Test-Path $NUGET_EXE)) {
"Trying to find nuget.exe in path"
$NUGET_EXE_IN_PATH = &where.exe nuget.exe
if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH)) {
"Found $($NUGET_EXE_IN_PATH)"
$NUGET_EXE = $NUGET_EXE_IN_PATH
}
}

# Try download NuGet.exe if not exists
if (!(Test-Path $NUGET_EXE)) {
Invoke-WebRequest -Uri http://nuget.org/nuget.exe -OutFile $NUGET_EXE
Expand All @@ -25,17 +78,22 @@ if (!(Test-Path $NUGET_EXE)) {
Throw "Could not find NuGet.exe"
}

# Save nuget.exe path to environment to be available to child processed
$ENV:NUGET_EXE = $NUGET_EXE

# Restore tools from NuGet.
Push-Location
Set-Location $TOOLS_DIR

# Restore packages
if (Test-Path $PACKAGES_CONFIG)
{
Invoke-Expression "$NUGET_EXE install -ExcludeVersion"
Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion"
}
# Install just Cake if missing config
else
{
Invoke-Expression "$NUGET_EXE install Cake -ExcludeVersion"
Invoke-Expression "$NUGET_EXE install xunit.runners -ExcludeVersion"
Invoke-Expression "&`"$NUGET_EXE`" install Cake -ExcludeVersion -PreRelease -Source `"https://www.myget.org/F/cake`""
}
Pop-Location
if ($LASTEXITCODE -ne 0)
Expand All @@ -49,6 +107,5 @@ if (!(Test-Path $CAKE_EXE)) {
}

# Start Cake
Invoke-Expression "$CAKE_EXE `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`""
Invoke-Expression "$CAKE_EXE `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseDryRun $UseExperimental"
exit $LASTEXITCODE

5 changes: 4 additions & 1 deletion src/Cake.Slack/Cake.Slack.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Chat\SlackChatProvider.cs" />
<Compile Include="Chat\SlackChatApi.cs" />
<Compile Include="Chat\SlackChatMessageSettings.cs" />
<Compile Include="Chat\SlackChatMessageResult.cs" />
Expand All @@ -64,11 +65,13 @@
<DesignTime>True</DesignTime>
<DependentUpon>Include_T4Include.tt</DependentUpon>
</Compile>
<Compile Include="Chat\SlackChatExtensions.cs" />
<Compile Include="Chat\SlackChatAliases.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="..\SolutionInfo.cs">
<Link>Properties\SolutionInfo.cs</Link>
</Compile>
<Compile Include="SlackProvider.cs" />
<Compile Include="SlackAliases.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Include_T4Include.tt">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
using Cake.Core;
using System;
using Cake.Core;
using Cake.Core.Annotations;

// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Cake.Slack.Chat
{
/// <summary>
/// Contains Slack Chat Extensions
/// Contains SlackProvider Chat Aliases
/// </summary>
[CakeAliasCategory("Slack.Chat")]
public static class SlackChatExtensions
[Obsolete("Should now use SlackProvider property instead now SlackProvider.Chat")]
[CakeAliasCategory("SlackProvider.Chat")]
public static class SlackChatAliases
{
/// <summary>
/// Post message to Slack Channel
/// </summary>
/// <param name="context">Cake context</param>
/// <param name="token">Slack auth token</param>
/// <param name="token">SlackProvider auth token</param>
/// <param name="channel">Channel to send message to. Can be a public channel, private group or IM channel. Can be an encoded ID, or a name.</param>
/// <param name="text">Text of the message to send. For message formatting see https://api.slack.com/docs/formatting</param>
/// <returns>Returns success/error/timestamp <see cref="SlackChatMessageResult"/></returns>
[CakeMethodAlias]
[Obsolete("Should now use SlackProvider property instead now SlackProvider.Chat.PostMessage()")]
public static SlackChatMessageResult SlackChatPostMessage(
this ICakeContext context,
string token,
Expand All @@ -40,11 +43,12 @@ string text
/// Post message to Slack Channel
/// </summary>
/// <param name="context">Cake context</param>
/// <param name="token">Slack auth token</param>
/// <param name="token">SlackProvider auth token</param>
/// <param name="channel">Channel to send message to. Can be a public channel, private group or IM channel. Can be an encoded ID, or a name.</param>
/// <param name="text">Text of the message to send. For message formatting see https://api.slack.com/docs/formatting</param>
/// <param name="messageSettings">Lets you override default settings like UserName, IconUrl or if it should ThrowOnFail</param>
/// <returns>Returns success/error/timestamp <see cref="SlackChatMessageResult"/></returns>
[Obsolete("Should now use SlackProvider property instead now SlackProvider.Chat.PostMessage()")]
[CakeMethodAlias]
public static SlackChatMessageResult SlackChatPostMessage(
this ICakeContext context,
Expand All @@ -54,8 +58,14 @@ public static SlackChatMessageResult SlackChatPostMessage(
SlackChatMessageSettings messageSettings
)
{
if (messageSettings == null)
{
throw new ArgumentNullException("messageSettings", "Invalid message settings supplied");
}

messageSettings.Token = token;

return context.PostMessage(
token,
channel,
text,
messageSettings
Expand Down
Loading

0 comments on commit 1c3d6ba

Please sign in to comment.