Skip to content

Instantly share code, notes, and snippets.

@nkoneko
Created April 16, 2014 06:31
Show Gist options
  • Save nkoneko/10817093 to your computer and use it in GitHub Desktop.
Save nkoneko/10817093 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <memory>
#include <boost/filesystem.hpp>
#include <pstream.h>
namespace toy
{
namespace fs = boost::filesystem;
using ps = redi::pstreams;
template <typename Streams>
struct script
{
script(fs::path const& path, std::vector<std::string> const& args)
: path_(path), args_(args), out_(Streams::out), err_(Streams::err) {}
void run() const;
private:
fs::path const path_;
std::vector<std::string> args_;
std::ostream& out_;
std::ostream& err_;
};
template <typename Streams>
void script<Streams>::run() const
{
const ps::pmode mode = ps::pstdout | ps::pstderr;
redi::ipstream in(path_.c_str(), args_, mode);
std::streamsize m, n;
char outbuf[1024], errbuf[1024];
while (!in.eof())
{
m = in.out().readsome(outbuf, sizeof(outbuf));
n = in.err().readsome(errbuf, sizeof(errbuf));
out_.write(outbuf, m);
err_.write(errbuf, n);
}
}
struct streams
{
static constexpr std::ostream& out = std::cout;
static constexpr std::ostream& err = std::cerr;
};
static std::ofstream fout("foo.out");
static std::ofstream ferr("foo.err");
struct fstreams
{
static constexpr std::ostream& out = fout;
static constexpr std::ostream& err = ferr;
};
}
void usage()
{
std::cerr << "Usage: invoke <SCRIPT_PATH>" << std::endl;
exit(1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
usage();
}
boost::filesystem::path const script_path(boost::filesystem::canonical(argv[1]));
if (!boost::filesystem::exists(script_path) ||
!boost::filesystem::is_regular_file(script_path))
{
usage();
}
std::vector<std::string> args;
for (int i = 1; i < argc; args.push_back(argv[i++])) {}
toy::script<toy::streams> s(script_path, args);
s.run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment