This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdotnetCore.ts
224 lines (207 loc) · 7.33 KB
/
dotnetCore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
* Copyright © 2019 Atomist, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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.
*/
import { GitHubRepoRef } from "@atomist/automation-client";
import { scanFreePort } from "@atomist/automation-client/lib/util/port";
import {
actionableButton,
CommandHandlerRegistration,
DoNotSetAnyGoals,
execPromise,
GeneratorRegistration,
goal,
hasFileWithExtension,
not,
SdmGoalState,
slackSuccessMessage,
} from "@atomist/sdm";
import {
configure,
Version,
} from "@atomist/sdm-core";
import {
dotnetCoreBuilder,
DotnetCoreProjectFileCodeTransform,
DotnetCoreProjectVersioner,
DotnetCoreVersionProjectListener,
getDockerfile,
} from "@atomist/sdm-pack-analysis-dotnet";
import { Build } from "@atomist/sdm-pack-build";
import {
DockerBuild,
HasDockerfile,
} from "@atomist/sdm-pack-docker";
import {
bold,
codeLine,
url,
} from "@atomist/slack-messages";
import { replaceSeedSlug } from "../transform/replaceSeedSlug";
import { UpdateReadmeTitle } from "../transform/updateReadmeTitle";
/**
* Atomist SDM Sample
* @description SDM to create and build .NET Core projects
* @tag sdm,generator,dotnet-core
* @instructions <p>Now that the SDM is up and running, create a new .NET Core
* project by running '@atomist create dotnet-core project' and
* observe how the SDM will build and dockerize the new project.
*
* The docker build and run goals require a locally accessible
* docker daemon. Please make sure to configure your terminal for
* docker access.</p>
*/
// atomist:code-snippet:start=dotnetGenerator
/**
* .NET Core generator registration
*/
const DotnetCoreGenerator: GeneratorRegistration = {
name: "DotnetCoreGenerator",
intent: "create dotnet-core project",
description: "Creates a new .NET Core project",
tags: ["dotnet"],
autoSubmit: true,
startingPoint: GitHubRepoRef.from({ owner: "atomist-seeds", repo: "dotnet-core-service", branch: "master" }),
transform: [
UpdateReadmeTitle,
replaceSeedSlug("atomist-seeds", "dotnet-core-service"),
DotnetCoreProjectFileCodeTransform,
],
};
// atomist:code-snippet:end
/**
* Command to stop a container by provided container id
*/
const StopDockerContainerCommand: CommandHandlerRegistration<{ containerId: string }> = {
name: "StopDockerContainer",
description: "Stop a running Docker container",
intent: "stop container",
parameters: {
containerId: { description: "Id of the container to stop" },
},
listener: async ci => {
await execPromise("docker", ["stop", ci.parameters.containerId]);
await ci.addressChannels(
slackSuccessMessage(
"Docker Deployment",
`Successfully stopped deployment`),
{ id: ci.parameters.containerId },
);
},
};
export const configuration = configure(async sdm => {
// Register the generator and stop command with the SDM
sdm.addGeneratorCommand(DotnetCoreGenerator);
sdm.addCommand(StopDockerContainerCommand);
// Version goal calculates a timestamped version for the build goal
const versionGoal = new Version()
.withVersioner(DotnetCoreProjectVersioner);
// Build goal that runs "dotnet build"
const buildGoal = new Build(
{ displayName: "dotnet build" })
.with({
name: "dotnet-build",
builder: dotnetCoreBuilder(),
}).withProjectListener(DotnetCoreVersionProjectListener);
// Docker build to wrap the app into a container image
const dockerBuildGoal = new DockerBuild()
.with({
dockerfileFinder: getDockerfile, // where to find the Dockerfile
push: false, // skip pushing the image to a remote repository; can be enabled by providing credentials
dockerImageNameCreator: async (p, sdmGoal) => [{
registry: p.id.owner,
name: p.id.repo,
tags: [
`${sdmGoal.branch}-${sdmGoal.sha.slice(0, 7)}`,
"latest",
],
}],
});
// Docker run goal to start the application in a container
const dockerRunGoal = goal(
{ displayName: "docker run" },
async gi => {
const { goalEvent, progressLog } = gi;
const host = readDockerHost();
const port = await scanFreePort(8000, 8100);
const appUrl = `http://${host}:${port}`;
const slug = `${goalEvent.repo.owner}/${goalEvent.repo.name}`;
const image = `${slug}:${goalEvent.branch}-${goalEvent.sha.slice(0, 7)}`;
try {
const result = await execPromise(
"docker",
["run", "-d", "-p", `${port}:8080`, image],
);
const containerId = result.stdout.trim();
await gi.addressChannels(
slackSuccessMessage(
"Docker Deployment",
`Successfully started ${codeLine(goalEvent.sha.slice(0, 7))} of ${bold(slug)} at ${url(appUrl)}`,
{
actions: [
actionableButton(
{ text: "Stop" },
StopDockerContainerCommand,
{
containerId,
}),
],
},
),
{ id: containerId });
return {
state: SdmGoalState.success,
externalUrls: [
{ label: "http", url: appUrl },
],
};
} catch (e) {
progressLog.write(`Container run command failed: %s`, e.message);
return {
code: 1,
};
}
});
// This SDM has three PushRules: no goals, build and docker
return {
no_goals: {
test: not(hasFileWithExtension("csproj")),
goals: DoNotSetAnyGoals.andLock(),
},
build: {
goals: [
versionGoal,
buildGoal,
],
},
docker: {
test: HasDockerfile,
dependsOn: "build",
goals: [
dockerBuildGoal,
dockerRunGoal,
],
},
};
}, { name: "dotnetCore" });
/**
* Read the Docker hostname from the DOCKER_HOST environment variable
*/
function readDockerHost(): string | undefined {
const dockerhost = process.env.DOCKER_HOST;
if (!dockerhost) {
throw new Error("DOCKER_HOST environment variable not set");
}
return new URL(dockerhost).hostname;
}