aboutsummaryrefslogtreecommitdiff
path: root/bpkg/utility.cxx
blob: f48d96d3cbea308896d868ca6bd944d6facdc630 (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// file      : bpkg/utility.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <bpkg/utility.hxx>

#include <iostream>     // cout, cin

#include <libbutl/process.mxx>
#include <libbutl/fdstream.mxx>

#include <bpkg/diagnostics.hxx>
#include <bpkg/common-options.hxx>

using namespace std;
using namespace butl;

namespace bpkg
{
  const string empty_string;
  const path empty_path;
  const dir_path empty_dir_path;

  const dir_path bpkg_dir (".bpkg");

  // Keep these directory names short, lowering the probability of hitting the
  // path length limit on Windows.
  //
  const dir_path certs_dir (dir_path (bpkg_dir) /= "certs");
  const dir_path repos_dir (dir_path (bpkg_dir) /= "repos");

  const dir_path current_dir (".");

  dir_path temp_dir;

  auto_rmfile
  tmp_file (const string& p)
  {
    assert (!temp_dir.empty ());
    return auto_rmfile (temp_dir / path::traits::temp_name (p));
  }

  auto_rmdir
  tmp_dir (const string& p)
  {
    assert (!temp_dir.empty ());
    return auto_rmdir (temp_dir / dir_path (path::traits::temp_name (p)));
  }

  void
  init_tmp (const dir_path& cfg)
  {
    // Whether the configuration is required or optional depends on the
    // command so if the configuration directory does not exist or it is not a
    // bpkg configuration directory, we simply create tmp in a system one and
    // let the command complain if necessary.
    //
    dir_path d (cfg.empty () ||
                !exists (cfg / bpkg_dir, true /* ignore_error */)
                ? dir_path::temp_path ("bpkg")
                : cfg / bpkg_dir / dir_path ("tmp"));

    if (exists (d))
      rm_r (d, true /* dir_itself */, 1); // Verbose to avoid surprises.

    mk (d); // We shouldn't need mk_p().

    temp_dir = move (d);
  }

  void
  clean_tmp (bool ignore_error)
  {
    if (!temp_dir.empty ())
    {
      rm_r (temp_dir,
            true /* dir_itself */,
            3,
            ignore_error ? rm_error_mode::ignore : rm_error_mode::fail);

      temp_dir.clear ();
    }
  }

  bool stderr_term;

  bool
  yn_prompt (const char* prompt, char def)
  {
    // Writing a robust Y/N prompt is more difficult than one would
    // expect...
    //
    string a;
    do
    {
      *diag_stream << prompt << ' ';

      // getline() will set the failbit if it failed to extract anything,
      // not even the delimiter and eofbit if it reached eof before seeing
      // the delimiter.
      //
      getline (cin, a);

      bool f (cin.fail ());
      bool e (cin.eof ());

      if (f || e)
        *diag_stream << endl; // Assume no delimiter (newline).

      if (f)
        fail << "unable to read y/n answer from STDOUT";

      if (a.empty () && def != '\0')
      {
        // Don't treat eof as the default answer. We need to see the
        // actual newline.
        //
        if (!e)
          a = def;
      }
    } while (a != "y" && a != "n");

    return a == "y";
  }

  bool
  exists (const path& f, bool ignore_error)
  {
    try
    {
      return file_exists (f, true /* follow_symlinks */, ignore_error);
    }
    catch (const system_error& e)
    {
      fail << "unable to stat path " << f << ": " << e << endf;
    }
  }

  bool
  exists (const dir_path& d, bool ignore_error)
  {
    try
    {
      return dir_exists (d, ignore_error);
    }
    catch (const system_error& e)
    {
      fail << "unable to stat path " << d << ": " << e << endf;
    }
  }

  bool
  empty (const dir_path& d)
  {
    try
    {
      return dir_empty (d);
    }
    catch (const system_error& e)
    {
      fail << "unable to scan directory " << d << ": " << e << endf;
    }
  }

  void
  mk (const dir_path& d)
  {
    if (verb >= 3)
      text << "mkdir " << d;

    try
    {
      try_mkdir (d);
    }
    catch (const system_error& e)
    {
      fail << "unable to create directory " << d << ": " << e;
    }
  }

  void
  mk_p (const dir_path& d)
  {
    if (verb >= 3)
      text << "mkdir -p " << d;

    try
    {
      try_mkdir_p (d);
    }
    catch (const system_error& e)
    {
      fail << "unable to create directory " << d << ": " << e;
    }
  }

  void
  rm (const path& f, uint16_t v)
  {
    if (verb >= v)
      text << "rm " << f;

    try
    {
      if (try_rmfile (f) == rmfile_status::not_exist)
        fail << "unable to remove file " << f << ": file does not exist";
    }
    catch (const system_error& e)
    {
      fail << "unable to remove file " << f << ": " << e;
    }
  }

  void
  rm_r (const dir_path& d, bool dir, uint16_t v, rm_error_mode m)
  {
    if (verb >= v)
      text << (dir ? "rmdir -r " : "rm -r ") << (dir ? d : d / dir_path ("*"));

    try
    {
      rmdir_r (d, dir, m == rm_error_mode::ignore);
    }
    catch (const system_error& e)
    {
      bool w (m == rm_error_mode::warn);

      (w ? warn : error) << "unable to remove " << (dir ? "" : "contents of ")
                         << "directory " << d << ": " << e;

      if (!w)
        throw failed ();
    }
  }

  void
  mv (const dir_path& from, const dir_path& to)
  {
    if (verb >= 3)
      text << "mv " << from << " to " << to; // Prints trailing slashes.

    try
    {
      mvdir (from, to);
    }
    catch (const system_error& e)
    {
      fail << "unable to move directory " << from << " to " << to << ": " << e;
    }
  }

  fdpipe
  open_pipe ()
  {
    try
    {
      return fdopen_pipe ();
    }
    catch (const io_error& e)
    {
      fail << "unable to open pipe: " << e << endf;
    }
  }

  auto_fd
  open_dev_null ()
  {
    try
    {
      return fdnull ();
    }
    catch (const io_error& e)
    {
      fail << "unable to open null device: " << e << endf;
    }
  }

  dir_path exec_dir;

  void
  run (const char* args[], const dir_path& fallback)
  {
    try
    {
      process_path pp (process::path_search (args[0], fallback));

      if (verb >= 2)
        print_process (args);

      process pr (pp, args);

      if (pr.wait ())
        return;

      assert (pr.exit);
      const process_exit& pe (*pr.exit);

      if (pe.normal ())
        throw failed (); // Assume the child issued diagnostics.

      diag_record dr (fail);
      print_process (dr, args);
      dr << " " << pe;
    }
    catch (const process_error& e)
    {
      error << "unable to execute " << args[0] << ": " << e;

      if (e.child)
        exit (1);

      throw failed ();
    }
  }

  const char*
  name_b (const common_options& co)
  {
    return co.build_specified ()
      ? co.build ().string ().c_str ()
      : "b" BPKG_EXE_SUFFIX;
  }

  void
  run_b (const common_options& co,
         const dir_path& c,
         const string& bspec,
         verb_b v,
         const strings& pvars,
         const strings& cvars)
  {
    cstrings args {name_b (co)};

    // Map verbosity level. If we are running quiet or at level 1,
    // then run build2 quiet. Otherwise, run it at the same level
    // as us.
    //
    string vl;

    if (verb == 0)
      args.push_back ("-q");
    else if (verb == 1)
    {
      if (v != verb_b::normal)
      {
        args.push_back ("-q");

        if (v == verb_b::progress && stderr_term)
          args.push_back ("--progress");
      }
    }
    else if (verb == 2)
      args.push_back ("-v");
    else
    {
      vl = to_string (verb);
      args.push_back ("--verbose");
      args.push_back (vl.c_str ());
    }

    // Add user options.
    //
    for (const string& o: co.build_option ())
      args.push_back (o.c_str ());

    // Add config vars.
    //
    strings storage;
    storage.reserve (cvars.size ());
    for (const string& v: cvars)
    {
      // Don't scope-qualify global variables.
      //
      if (v[0] != '!')
      {
        // Use path representation to get canonical trailing slash.
        //
        storage.push_back (c.representation () + ':' + v);
        args.push_back (storage.back ().c_str ());
      }
      else
        args.push_back (v.c_str ());
    }

    for (const string& v: pvars)
      args.push_back (v.c_str ());

    // Add buildspec.
    //
    args.push_back (bspec.c_str ());

    args.push_back (nullptr);

    // Use our executable directory as a fallback search since normally the
    // entire toolchain is installed into one directory. This way, for
    // example, if we installed into /opt/build2 and run bpkg with absolute
    // path (and without PATH), then bpkg will be able to find "its" b.
    //
    run (args, exec_dir);
  }
}