]> git.tdb.fi Git - builder.git/blob - source/externaltask.h
Rewrite ExternalTask to use Msp::Process
[builder.git] / source / externaltask.h
1 #ifndef EXTERNALTASK_H_
2 #define EXTERNALTASK_H_
3
4 #include <string>
5 #include <vector>
6 #include <msp/core/process.h>
7 #include <msp/fs/path.h>
8 #include <msp/io/pipe.h>
9 #include "task.h"
10
11 /**
12 Runs an external command.  A zero exit status is translated to a SUCCESS status
13 for the task, and anything else is treated as an error.  Output can optionally
14 be captured.
15 */
16 class ExternalTask: public Task
17 {
18 public:
19         enum Destination
20         {
21                 PASSTHROUGH,  //< Do not touch the stream
22                 CAPTURE,      //< Capture the stream
23                 IGNORE        //< Redirect the stream to oblivion
24         };
25
26         typedef Msp::Process::Arguments Arguments;
27
28 private:
29         Arguments argv;
30         Msp::FS::Path work_dir;
31         Msp::Process *process;
32         int exit_code;
33         Destination stdout_dest;
34         Destination stderr_dest;
35         Msp::IO::Pipe *capture_pipe;
36         std::string output;
37
38 public:
39         /** Creates an ExternalTask with an argument array and an optional working
40         directory.  The first element of the argument array should be the command
41         name.  If the working directory is not specified, no chdir is done. */
42         ExternalTask(const Arguments &, const Msp::FS::Path & = Msp::FS::Path());
43
44         virtual ~ExternalTask();
45
46         virtual std::string get_command() const;
47         virtual void start();
48         virtual Status check();
49         virtual Status wait();
50 private:
51         Status do_wait(bool);
52
53 public:
54         /// Sets destination for stdout.  Has no effect after the task is started.
55         void set_stdout(Destination);
56
57         /// Sets destination for stderr.  Has no effect after the task is started.
58         void set_stderr(Destination);
59
60         /** Returns captured output, if any.  This may be called while the task is
61         still running, but it will always return all output. */
62         const std::string &get_output() const { return output; }
63
64         /** Executes a command and captures its output.  Stderr is ignored, but if
65         the command exits with a nonzero status, an exception is thrown. */
66         static std::string run_and_capture_output(const Arguments &, const Msp::FS::Path & = Msp::FS::Path());
67 };
68
69 #endif