aboutsummaryrefslogtreecommitdiff
path: root/tests/test/script/runner/driver.cxx
blob: a82b083844406b8c55d97d590a25106c1c656080 (plain)
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
// file      : tests/test/script/runner/driver.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2016 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <limits>    // numeric_limits
#include <string>
#include <cassert>
#include <ostream>   // endl, *bit
#include <istream>   // istream::traits_type::eof()
#include <iostream>
#include <exception>

#include <butl/path>
#include <butl/fdstream>
#include <butl/filesystem>

using namespace std;
using namespace butl;

int
main (int argc, char* argv[])
{
  // Usage: driver [-i <int>] [-s <int>] (-o <string>)* (-e <string>)*
  //        (-f <file>)* (-d <dir>)*
  //
  int status (256);
  int ifd (3);

  cout.exceptions (ostream::failbit | ostream::badbit);
  cerr.exceptions (ostream::failbit | ostream::badbit);

  for (int i (1); i < argc; ++i)
  {
    string o (argv[i++]);
    assert (i < argc);

    string v (argv[i]);

    auto toi = [] (const string& s) -> int
    {
      int r (-1);

      try
      {
        size_t n;
        r = stoi (s, &n);
        assert (n == s.size ());
      }
      catch (const exception&)
      {
        assert (false);
      }

      return r;
    };

    if (o == "-i")
    {
      assert (ifd == 3); // Make sure is not set yet.

      ifd = toi (v);
      assert (ifd >= 0 && ifd < 3);

      if (ifd == 0)
        cin.ignore (numeric_limits<streamsize>::max ());
      else if (cin.peek () != istream::traits_type::eof ())
        (ifd == 1 ? cout : cerr) << cin.rdbuf ();
    }
    else if (o == "-o")
    {
      cout << v << endl;
    }
    else if (o == "-e")
    {
      cerr << v << endl;
    }
    else if (o == "-s")
    {
      assert (status == 256); // Make sure is not set yet.

      status = toi (v);
      assert (status >= 0 && status < 256);
    }
    else if (o == "-f")
    {
      ofdstream os (v);
      os.close ();
    }
    else if (o == "-d")
    {
      try_mkdir_p (dir_path (v));
    }
    else
      assert (false);
  }

  return status == 256 ? 0 : status;
}