1 /*
2 * LICENSE
3 *
4 * "THE BEER-WARE LICENSE" (Revision 43):
5 * "Sven Strittmatter" <weltraumschaf@googlemail.com> wrote this file.
6 * As long as you retain this notice you can do whatever you want with
7 * this stuff. If we meet some day, and you think this stuff is worth it,
8 * you can buy me a non alcohol-free beer in return.
9 *
10 * Copyright (C) 2012 "Sven Strittmatter" <weltraumschaf@googlemail.com>
11 */
12 package org.jenkinsci.plugins.darcs.cmd;
13
14 import hudson.Launcher;
15 import hudson.util.ArgumentListBuilder;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19
20 /**
21 * Abstracts Darcs command.
22 *
23 * @author Sven Strittmatter <weltraumschaf@googlemail.com>
24 */
25 public class DarcsCommand {
26
27 /**
28 * Argument list representing the command.
29 */
30 private final ArgumentListBuilder args;
31 /**
32 * Records STDOUT of command.
33 */
34 private final OutputStream out = new ByteArrayOutputStream();
35 /**
36 * Records STDERR of command.
37 */
38 private final OutputStream err = new ByteArrayOutputStream();
39
40 /**
41 * Default constructor.
42 *
43 * Not instantiated outside of the builders.
44 *
45 * @param args generated argument list from a builder
46 */
47 DarcsCommand(final ArgumentListBuilder args) {
48 this.args = args;
49 }
50
51 /**
52 * Main entry point to obtain a command builder.
53 *
54 * @param darcsExe name of Darcs executable, e.g. "darcs" or "/usr/local/bin/darcs"
55 * @return always new instance
56 */
57 public static DarcsCommandBuilder builder(final String darcsExe) {
58 return new DarcsCommandBuilder(darcsExe);
59 }
60
61 /**
62 * Executes the command by joining the passed in process starter.
63 *
64 * @param proc used to join the command
65 * @return the return code of the executed command
66 * @throws IOException if there's an error launching/joining a process
67 * @throws InterruptedException if a thread is waiting, sleeping, or otherwise occupied, and the thread is
68 * interrupted, either before or during the activity
69 */
70 public int execute(final Launcher.ProcStarter proc) throws IOException, InterruptedException {
71 proc.cmds(args);
72 proc.stdout(out);
73 proc.stderr(err);
74 return proc.join();
75 }
76
77 /**
78 * Get output stream which records STDOUT.
79 *
80 * @return reference to the output stream
81 */
82 public OutputStream getOut() {
83 return out;
84 }
85
86 /**
87 * Get output stream which records STDOUT.
88 *
89 * @return reference to the output stream
90 */
91 public OutputStream getErr() {
92 return err;
93 }
94
95 /**
96 * Get the arguments.
97 *
98 * @return reference of internal argument list object
99 */
100 ArgumentListBuilder getArgs() {
101 return args;
102 }
103
104 }