This repository was archived by the owner on Feb 12, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathProgram.cs
562 lines (519 loc) · 25.6 KB
/
Program.cs
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using ThoughtWorks.CruiseControl.Core;
using ThoughtWorks.CruiseControl.Remote;
using ThoughtWorks.CruiseControl.Remote.Mono;
using ThoughtWorks.CruiseControl.Remote.Parameters;
namespace ThoughtWorks.CruiseControl.CCCmd
{
class Program
{
private static bool help;
private static string server;
private static string target;
private static string project;
private static bool all;
private static bool quiet;
private static string string_params;
private static string params_filename;
private static CommandType command;
private static List<string> extra = new List<string>();
private static string userName;
private static string password;
private static bool xml;
private static string volunteer_name = Environment.UserName;
private static BuildCondition condition = BuildCondition.ForceBuild;
static void Main(string[] args)
{
OptionSet opts = new OptionSet();
opts.Add("h|?|help", "display this help screen", delegate(string v) { help = v != null; })
.Add("s|server=", "the CruiseControl.Net server to send the commands to (required for all actions except help)", delegate(string v) { server = v; })
.Add("t|target=", "the target server for all messages", delegate(string v) { target = v; })
.Add("p|project=", "the project to use (required for all actions except help and retrieve)", delegate(string v) { project = v; })
.Add("a|all", "lists all the projects (only valid for retrieve)", delegate(string v) { all = v != null; })
.Add("q|quiet", "run in quiet mode (do not print messages)", delegate(string v) { quiet = v != null; })
.Add("ime|ifmodificationexists", "only force the build if modification exist", delegate(string v) { condition = v != null ? BuildCondition.IfModificationExists : BuildCondition.ForceBuild; })
.Add("r|params=", "a semicolon separated list of name value pairs", delegate(string v) { string_params = v; })
.Add("f|params_file=", "the name of a XML file containing the parameters values to use when forcing a build. If specified at the same time as this flag, the values from the command line are ignored", delegate(string v) { params_filename = v; })
.Add("x|xml", "outputs the details in XML format instead of plain text (only valid for retrieve)", delegate(string v) { xml = v != null; })
.Add("user=", "the user of the user account to use", v => { userName = v; })
.Add("pwd=", "the password to use for the user", v => { password = v; })
.Add("volunteer_name=", "the name to use when volunteering (defaults to Environment.UserName)", v => { volunteer_name = v; });
try
{
extra = opts.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
if ((extra.Count == 1) && !help)
{
command = (CommandType)Enum.Parse(typeof(CommandType), extra[0], true);
}
else
{
DisplayHelp(opts);
return;
}
try
{
switch (command)
{
case CommandType.Help:
DisplayHelp(opts);
break;
case CommandType.Retrieve:
RunRetrive();
break;
case CommandType.ForceBuild:
RunForceBuild();
break;
case CommandType.CancelPending:
RunCancelPending();
break;
case CommandType.AbortBuild:
RunAbortBuild();
break;
case CommandType.StartProject:
RunStartProject();
break;
case CommandType.StopProject:
RunStopProject();
break;
case CommandType.Volunteer:
RunVolunteer();
break;
case CommandType.CancelVolunteer:
RunCancelVolunteer();
break;
default:
throw new CruiseControlException("Unknown action: " + command.ToString());
}
}
catch (Exception error)
{
WriteError("ERROR: An unknown error has occurred!", error);
}
}
private static CruiseServerClientBase GenerateClient()
{
var client = new CruiseServerClientFactory().GenerateClient(server, target);
if (!string.IsNullOrEmpty(userName))
{
client.Login(new { UserName = userName, Password = password });
}
return client;
}
private static void RunForceBuild()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
Dictionary<string, string> userParameters = new Dictionary<string, string>();
if (File.Exists(params_filename))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(params_filename);
XmlNodeList names = xmlDoc.GetElementsByTagName("name");
XmlNodeList values = xmlDoc.GetElementsByTagName("value");
for (int i = 0; i < names.Count; ++i)
userParameters.Add(names[i].InnerText, values[i].InnerText);
}
else if (!String.IsNullOrEmpty(string_params))
{
string[] splittedParams = string_params.Split(';');
foreach (string nameValuePair in splittedParams)
{
string[] splittedNameValuePair = nameValuePair.Split('=');
userParameters.Add(splittedNameValuePair[0], splittedNameValuePair[1]);
}
}
using (var client = GenerateClient())
{
List<ParameterBase> parameters = client.ListBuildParameters(project);
List<NameValuePair> buildParameters = new List<NameValuePair>();
foreach (ParameterBase parameter in parameters)
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Parameter: {0}", parameter.Name), ConsoleColor.Gray);
bool required = false;
PropertyInfo propInfos = parameter.GetType().GetProperty("IsRequired");
if (propInfos == null)
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "propInfos is null, considering that parameter {0} is not required", parameter.Name), ConsoleColor.DarkYellow);
else
required = (bool)propInfos.GetValue(parameter, null);
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Kind: {0}", parameter.ToString()), ConsoleColor.Gray);
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Data type: {0}", parameter.DataType), ConsoleColor.Gray);
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Required: {0}", required), ConsoleColor.Gray);
string userProvidedValue;
userParameters.TryGetValue(parameter.Name, out userProvidedValue);
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " User provided value: {0}", userProvidedValue), ConsoleColor.Gray);
var convertedValue = parameter.Convert(userProvidedValue);
string convertedValueString = userProvidedValue;
if (convertedValue != null)
{
convertedValueString = convertedValue.ToString();
}
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Converted value: {0}", convertedValueString), ConsoleColor.Gray);
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Default value: {0}", parameter.DefaultValue), ConsoleColor.Gray);
if (parameter.AllowedValues == null)
{
if (!quiet) WriteLine(" Allowed values: null", ConsoleColor.Gray);
}
else
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, " Allowed values: {0}", parameter.AllowedValues), ConsoleColor.Gray);
bool isAllowedValue = false;
int i = 0;
while (!isAllowedValue && (i < parameter.AllowedValues.Length))
{
isAllowedValue = parameter.AllowedValues[i].Equals(userProvidedValue);
++i;
}
if (!isAllowedValue)
throw new CruiseControlException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Parameter {0} was given value {1} which is not one of the allowed ones ({2})", parameter.Name, userProvidedValue, string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}", parameter.AllowedValues)));
}
if (required && String.IsNullOrEmpty(convertedValueString) && String.IsNullOrEmpty(parameter.DefaultValue))
throw new CruiseControlException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Parameter {0} is required but was not provided and does not have a default value", parameter.Name));
buildParameters.Add(new NameValuePair(parameter.Name, convertedValueString));
}
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Sending ForceBuild request for '{0}'", project), ConsoleColor.White);
client.ForceBuild(project, buildParameters, condition);
if (!quiet) WriteLine("ForceBuild request sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to send ForceBuild request", error);
}
}
}
private static void RunCancelPending()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Sending CancelPending request for '{0}'", project),
ConsoleColor.White);
client.CancelPendingRequest(project);
if (!quiet) WriteLine("CancelPending request sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to send CancelPending request", error);
}
}
}
private static void RunAbortBuild()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Sending AbortBuild request for '{0}'", project), ConsoleColor.White);
client.AbortBuild(project);
if (!quiet) WriteLine("AbortBuild request sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to send ForceBuild request", error);
}
}
}
private static void RunStartProject()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Sending StartProject request for '{0}'", project), ConsoleColor.White);
client.StartProject(project);
if (!quiet) WriteLine("StartProject request sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to send ForceBuild request", error);
}
}
}
private static void RunStopProject()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Sending StopProject request for '{0}'", project), ConsoleColor.White);
client.StopProject(project);
if (!quiet) WriteLine("StopProject request sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to send ForceBuild request", error);
}
}
}
private static void RunVolunteer()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Volunteering to fix '{0}'", project), ConsoleColor.White);
string message = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} is fixing the build.", volunteer_name);
client.SendMessage(project, new Message(message, Message.MessageKind.Fixer));
if (!quiet) WriteLine("Volunteer message sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to volunteer", error);
}
}
}
private static void RunCancelVolunteer()
{
if (ValidateParameter(server, "--server") &&
ValidateNotAll() &&
ValidateParameter(project, "--project"))
{
try
{
using (var client = GenerateClient())
{
if (!quiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Removing the fixer in '{0}'", project),
ConsoleColor.White);
client.SendMessage(project, new Message(string.Empty, Message.MessageKind.Fixer));
if (!quiet) WriteLine("CancelVolunteer message sent", ConsoleColor.White);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to volunteer", error);
}
}
}
private static void RunRetrive()
{
if (ValidateParameter(server, "--server"))
{
if (string.IsNullOrEmpty(project) && !all)
{
WriteLine("Must specify either a project or use the '-all' option", ConsoleColor.Red);
}
else
{
using (var client = GenerateClient())
{
if (all)
{
DisplayServerStatus(client, quiet);
}
else
{
DisplayProjectStatus(client, project, quiet);
}
}
}
}
}
private static void DisplayServerStatus(CruiseServerClientBase client, bool isQuiet)
{
try
{
if (!isQuiet) WriteLine("Retrieving snapshot from " + client.TargetServer, ConsoleColor.Gray);
CruiseServerSnapshot snapShot = client.GetCruiseServerSnapshot();
if (xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(CruiseServerSnapshot));
Stream console = Console.OpenStandardOutput();
serializer.Serialize(console, snapShot);
console.Close();
}
else
{
foreach (ProjectStatus prj in snapShot.ProjectStatuses)
{
DisplayProject(prj);
}
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to retrieve server details", error);
}
}
private static void DisplayProjectStatus(CruiseServerClientBase client, string projectName, bool isQuiet)
{
try
{
if (!isQuiet) WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Retrieving project '{0}' on server {1}", projectName, client.TargetServer), ConsoleColor.Gray);
CruiseServerSnapshot snapShot = client.GetCruiseServerSnapshot();
var wasFound = false;
foreach (ProjectStatus project in snapShot.ProjectStatuses)
{
if (string.Equals(project.Name, projectName, StringComparison.CurrentCultureIgnoreCase))
{
if (xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(ProjectStatus));
Stream console = Console.OpenStandardOutput();
serializer.Serialize(console, project);
console.Close();
}
else
{
DisplayProject(project);
}
wasFound = true;
break;
}
}
if (!wasFound)
{
WriteError("Project '" + projectName + "' was not found", null);
}
}
catch (Exception error)
{
WriteError("ERROR: Unable to retrieve project details", error);
}
}
private static void DisplayProject(ProjectStatus project)
{
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}: {1}", project.Name, project.Status), ConsoleColor.White);
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tActivity: {0}", project.Activity), ConsoleColor.White);
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tBuild Status: {0}", project.BuildStatus), ConsoleColor.White);
if (!string.IsNullOrEmpty(project.BuildStage))
{
XmlDocument stageXml = new XmlDocument();
try
{
stageXml.LoadXml(project.BuildStage);
foreach (XmlElement stageItem in stageXml.SelectNodes("/data/Item"))
{
string stageTime = stageItem.GetAttribute("Time");
string stageData = stageItem.GetAttribute("Data");
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tBuild Stage: {0} ({1})", stageData, stageTime), ConsoleColor.White);
}
}
catch
{
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tBuild Stage: {0}", project.BuildStage), ConsoleColor.White);
}
}
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tLast Build: {0:G}", project.LastBuildDate), ConsoleColor.White);
WriteLine(string.Format(System.Globalization.CultureInfo.CurrentCulture, "\tNext Build: {0:G}", project.NextBuildTime), ConsoleColor.White);
}
private static bool ValidateParameter(string value, string name)
{
if (string.IsNullOrEmpty(value))
{
WriteError(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Input parameter '{0}' is missing", name), null);
return false;
}
return true;
}
private static bool ValidateNotAll()
{
if (all)
{
WriteError(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Input parameter '--all' is not valid for {0}", command), null);
return false;
}
return true;
}
private static void WriteLine(string line, ConsoleColor colour)
{
ConsoleColor currentColor = Console.ForegroundColor;
Console.ForegroundColor = colour;
Console.WriteLine(line);
Console.ForegroundColor = currentColor;
}
private static void WriteError(string message, Exception error)
{
WriteLine(message, ConsoleColor.Red);
if (error != null)
{
WriteLine(error.ToString(), ConsoleColor.Red);
Environment.ExitCode = 2;
}
else
{
Environment.ExitCode = 1;
}
}
private static void DisplayHelp(OptionSet opts)
{
string xmlParamFileLayout =
@"<parameters>
<parameter>
<name>buildType</name>
<value>Development</value>
</parameter>
<parameter>
<name>DeployMsg</name>
<value>This is a test</value>
</parameter>
</parameters> ";
Assembly thisApp = Assembly.GetExecutingAssembly();
Stream helpStream = thisApp.GetManifestResourceStream("ThoughtWorks.CruiseControl.CCCmd.Help.txt");
try
{
StreamReader reader = new StreamReader(helpStream);
string data = reader.ReadToEnd();
Console.Write(data);
}
finally
{
helpStream.Close();
}
opts.WriteOptionDescriptions(Console.Out);
Console.WriteLine();
WriteLine("Layout of the parameter file :", ConsoleColor.Yellow);
WriteLine(xmlParamFileLayout, ConsoleColor.DarkGray);
Console.WriteLine();
WriteLine(" Examples :", ConsoleColor.Yellow);
WriteLine("-==========-", ConsoleColor.Yellow);
WriteLine(" CCCmd.exe retrieve -s=tcp://localhost:21234/CruiseManager.rem -a", ConsoleColor.White);
WriteLine(" CCCmd.exe retrieve -s=tcp://localhost:21234/CruiseManager.rem -a -x", ConsoleColor.White);
WriteLine(" CCCmd.exe retrieve -s=tcp://localhost:21234/CruiseManager.rem -p=ccnet", ConsoleColor.White);
WriteLine(" CCCmd.exe forcebuild -s=tcp://localhost:21234/CruiseManager.rem -p=ccnet", ConsoleColor.White);
WriteLine(" CCCmd.exe forcebuild -s=tcp://localhost:21234/CruiseManager.rem -p=ccnet -r=buildtype=fulltest", ConsoleColor.White);
WriteLine(" CCCmd.exe forcebuild -s=tcp://localhost:21234/CruiseManager.rem -p=ccnet -r=buildtype=fulltest;makepackage=true", ConsoleColor.White);
}
}
}