aboutsummaryrefslogtreecommitdiff
path: root/butl/curl.txx
blob: fe8a25f468c59caf4ff179724322653ce6c97b65 (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
99
// file      : butl/curl.txx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <utility>   // move(), forward()
#include <exception> // invalid_argument

namespace butl
{
  template <typename I>
  typename std::enable_if<curl::is_other<I>::value, I>::type curl::
  map_in (I&& in, method_proto mp, io_data& d)
  {
    switch (mp)
    {
    case ftp_put:
      {
        d.options.push_back ("--upload-file");
        d.options.push_back ("-");
        break;
      }
    case http_post:
      {
        d.options.push_back ("--data-binary");
        d.options.push_back ("@-");
        break;
      }
    case ftp_get:
    case http_get:
      {
        throw std::invalid_argument ("input specified for GET method");
      }
    }

    return std::forward<I> (in);
  }

  template <typename O>
  typename std::enable_if<curl::is_other<O>::value, O>::type curl::
  map_out (O&& out, method_proto mp, io_data&)
  {
    switch (mp)
    {
    case ftp_get:
    case http_get:
    case http_post:
      {
        // Note: no need for any options, curl writes to stdout by default.
        //
        break;
      }
    case ftp_put:
      {
        throw std::invalid_argument ("output specified for PUT method");
      }
    }

    return std::forward<O> (out);
  }

  template <typename C,
            typename I,
            typename O,
            typename E,
            typename... A>
  curl::
  curl (const C& cmdc,
        I&& in,
        O&& out,
        E&& err,
        method_type m,
        const std::string& url,
        A&&... options)
  {
    method_proto_options mpo;
    method_proto mp (translate (m, url, mpo));

    io_data in_data;
    io_data out_data;

    process& p (*this);
    p = process_start (
      cmdc,
      map_in  (std::forward<I> (in),  mp, in_data),
      map_out (std::forward<O> (out), mp, out_data),
      std::forward<E> (err),
      dir_path (),
      "curl",
      "-s", // Silent.
      "-S", // But do show diagnostics.
      mpo,
      in_data.options,
      out_data.options,
      std::forward<A> (options)...,
      url);

    // Note: leaving this scope closes any open ends of the pipes in io_data.
  }
}