aboutsummaryrefslogtreecommitdiff
path: root/bdep/config.cxx
blob: 412b753b44b36f0676c5b1d084ceb888891cca46 (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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// file      : bdep/config.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <bdep/config.hxx>

#include <iostream> // cout

#include <bdep/database.hxx>
#include <bdep/project-odb.hxx>
#include <bdep/diagnostics.hxx>

using namespace std;

namespace bdep
{
  template <typename O>
  static void
  print_configuration (O& o,
                       const shared_ptr<configuration>& c,
                       bool flags = true)
  {
    if (c->name)
      o << '@' << *c->name << ' ';

    o << c->path << ' ' << *c->id;

    if (flags)
    {
      char s (' ');
      if (c->default_)  {o << s << "default";           s = ',';}
      if (c->forward)   {o << s << "forwarded";         s = ',';}
      if (c->auto_sync) {o << s << "auto-synchronized"; s = ',';}
    }
  }

  const char*
  cmd_config_validate_add (const configuration_add_options& o)
  {
    // --[no-]default
    //
    if (o.default_ () && o.no_default ())
      fail << "both --default and --no-default specified";

    // --[no-]forward
    //
    if (o.forward () && o.no_forward ())
      fail << "both --forward and --no-forward specified";

    // --[no-]auto-sync
    //
    if (o.auto_sync () && o.no_auto_sync ())
      fail << "both --auto-sync and --no-auto-sync specified";

    return (o.default_ ()     ? "--default"      :
            o.no_default ()   ? "--no-default"   :
            o.forward ()      ? "--forward"      :
            o.no_forward ()   ? "--no-forward"   :
            o.auto_sync ()    ? "--auto-sync"    :
            o.no_auto_sync () ? "--no-auto-sync" :
            o.wipe ()         ? "--wipe"         : nullptr);
  }

  void
  cmd_config_validate_add (const configuration_name_options& o,
                           const char* what,
                           optional<string>& name,
                           optional<uint64_t>& id)
  {
    name = nullopt;
    id = nullopt;

    if (size_t n = o.config_name ().size ())
    {
      if (n > 1)
        fail << "multiple configuration names specified for " << what;

      name = o.config_name ()[0];
    }

    if (size_t n = o.config_id ().size ())
    {
      if (n > 1)
        fail << "multiple configuration ids specified for " << what;

      id = o.config_id ()[0];
    }
  }

  // Translate the configuration directory that is actually a name (@foo or
  // -@foo) to the real directory (prj-foo) and name (@foo).
  //
  static inline void
  translate_path_name (const dir_path& prj,
                       dir_path& path,
                       optional<string>& name)
  {
    if (name || !path.simple ())
      return;

    size_t n;
    {
      const string& s (path.string ());
      if      (s.size () > 1 && s[0] == '@')                n = 1;
      else if (s.size () > 2 && s[0] == '-' && s[1] == '@') n = 2;
      else return;
    }

    string s (move (path).string ()); // Move out.
    s.erase (0, n);                   // Remove leading '@' or '-@'.

    path  = prj;
    path += '-';
    path += s;

    name = move (s);
  }

  // Verify the configuration directory is not inside one of the packages.
  //
  static void
  verify_configuration_path (const dir_path& cfg,
                             const dir_path& prj,
                             const package_locations& pkgs)
  {
    for (const package_location& p: pkgs)
    {
      dir_path d (prj / p.path); // Should already be normalized.

      if (cfg.sub (d))
        fail << "configuration directory " << cfg << " is inside package "
             << p.name << " (" << d << ")";
    }
  }

  shared_ptr<configuration>
  cmd_config_add (const configuration_add_options& ao,
                  const dir_path&                  prj,
                  const package_locations&         pkgs,
                  database&                        db,
                  dir_path                         path,
                  optional<string>                 name,
                  optional<uint64_t>               id,
                  const char*                      what)
  {
    translate_path_name (prj, path, name);

    if (name && name->empty ())
      fail << "empty configuration name specified";

    if (!exists (path))
      fail << "configuration directory " << path << " does not exist";

    // Make sure the configuration path is absolute and normalized. Also
    // derive relative to project directory path if possible.
    //
    path.complete ();
    path.normalize ();

    verify_configuration_path (path, prj, pkgs);

    optional<dir_path> rel_path;
    try {rel_path = path.relative (prj);} catch (const invalid_path&) {}

    transaction t (db.begin ());

    using count = configuration_count;

    optional<bool> def, fwd;
    {
      using query = bdep::query<configuration>;

      // By default the first added configuration is the default.
      //
      if (ao.default_ () || ao.no_default ())
        def = ao.default_ () && !ao.no_default ();

      if (!def)
        def = (db.query_value<count> () == 0);
      else if (*def)
      {
        if (auto p = db.query_one<configuration> (query::default_))
          fail << "configuration " << *p << " is already the default" <<
            info << "use 'bdep config set --no-default' to clear";
      }

      // By default the default configuration is forwarded unless another
      // is already forwarded.
      //
      if (ao.forward () || ao.no_forward ())
        fwd = ao.forward ()  && !ao.no_forward ();

      if (!fwd)
        fwd = *def && db.query_one<configuration> (query::forward) == nullptr;
      else if (*fwd)
      {
        if (auto p = db.query_one<configuration> (query::forward))
          fail << "configuration " << *p << " is already forwarded" <<
            info << "use 'bdep config set --no-forward' to clear";
      }
    }

    shared_ptr<configuration> r (
      new configuration {
        id,
        name,
        path,
        move (rel_path),
        *def,
        *fwd,
        !ao.no_auto_sync (),
        {} /* packages */});

    try
    {
      db.persist (r);
    }
    catch (const odb::exception&)
    {
      //@@ TODO: Maybe redo by querying the conflicting configuration and then
      //         printing its path, line in rename? Also do it before persist.

      using query = bdep::query<count>;

      // See if this is id, name, or path conflict.
      //
      if (id && db.query_value<count> (query::id == *id) != 0)
        fail << "configuration with id " << *id << " already exists "
             << "in project " << prj;

      if (name && db.query_value<count> (query::name == *name) != 0)
        fail << "configuration with name '" << *name << "' already exists "
             << "in project " << prj;

      if (db.query_value<count> (query::path == path.string ()) != 0)
        fail << "configuration with directory " << path << " already exists "
             << "in project " << prj;

      // Hm, what could that be?
      //
      throw;
    }

    t.commit ();

    if (verb)
    {
      diag_record dr (text);
      dr << what << " configuration ";
      print_configuration (dr, r);
    }

    return r;
  }

  shared_ptr<configuration>
  cmd_config_create (const common_options&            co,
                     const configuration_add_options& ao,
                     const dir_path&                  prj,
                     const package_locations&         pkgs,
                     database&                        db,
                     dir_path                         path,
                     cli::scanner&                    cfg_args,
                     optional<string>                 name,
                     optional<uint64_t>               id)
  {
    // Similar logic to *_add().
    //
    translate_path_name (prj, path, name);

    path.complete ();
    path.normalize ();

    verify_configuration_path (path, prj, pkgs);

    // Call bpkg to create the configuration.
    //
    {
      strings args;
      while (cfg_args.more ())
        args.push_back (cfg_args.next ());

      run_bpkg (2,
                co,
                "create",
                "-d", path,
                (ao.wipe () ? "--wipe" : nullptr),
                args);
    }

    return cmd_config_add (ao,
                           prj,
                           package_locations {}, // Already verified.
                           db,
                           move (path),
                           move (name),
                           id,
                           "created");
  }

  static int
  cmd_config_add (const cmd_config_options& o, cli::scanner& args)
  {
    tracer trace ("config_add");

    optional<string> name;
    optional<uint64_t> id;
    cmd_config_validate_add (o, "config add", name, id);

    string arg;
    if (args.more ())
      arg = args.next ();
    else if (name)
    {
      // Reverse into the shortcut form expected by translate_path_name().
      //
      arg = '@' + *name;
      name = nullopt;
    }
    else
      fail << "configuration directory argument expected";

    dir_path path;
    try
    {
      path = dir_path (move (arg));
    }
    catch (const invalid_path&)
    {
      fail << "invalid configuration directory '" << arg << "'";
    }

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    cmd_config_add (o,
                    prj,
                    load_packages (prj, true /* allow_empty */),
                    db,
                    move (path),
                    move (name),
                    move (id));
    return 0;
  }

  static int
  cmd_config_create (const cmd_config_options& o, cli::scanner& args)
  {
    tracer trace ("config_create");

    optional<string> name;
    optional<uint64_t> id;
    cmd_config_validate_add (o, "config create", name, id);

    // Note that the shortcut will only work if there are no cfg-args which
    // is not very likely. Oh, well.
    //
    string arg;
    if (args.more ())
      arg = args.next ();
    else if (name)
    {
      // Reverse into the shortcut form expected by translate_path_name().
      //
      arg = '@' + *name;
      name = nullopt;
    }
    else
      fail << "configuration directory argument expected";

    dir_path path;
    try
    {
      path = dir_path (move (arg));
    }
    catch (const invalid_path&)
    {
      fail << "invalid configuration directory '" << arg << "'";
    }

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    cmd_config_create (o,
                       o,
                       prj,
                       load_packages (prj, true /* allow_empty */),
                       db,
                       move (path),
                       args,
                       move (name),
                       move (id));
    return 0;
  }

  static int
  cmd_config_list (const cmd_config_options& o, cli::scanner&)
  {
    tracer trace ("config_list");

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    transaction t (db.begin ());

    configurations cfgs;
    if (o.config_specified ()    || // Note: handling --all|-a ourselves.
        o.config_id_specified () ||
        o.config_name_specified ())
    {
      cfgs = find_configurations (o,
                                  prj,
                                  t,
                                  false /* fallback_default */,
                                  false /* validate         */);
    }
    else
    {
      using query = bdep::query<configuration>;

      // We want to show the default configuration first, then sort them
      // by name, and then by path.
      //
      for (auto c: pointer_result (
             db.query<configuration> ("ORDER BY" +
                                      query::default_ + "DESC," +
                                      query::name     + "IS NULL," +
                                      query::name     + "," +
                                      query::path)))
        cfgs.push_back (move (c));
    }

    t.commit ();


    for (const shared_ptr<configuration>& c: cfgs)
    {
      //@@ TODO: use tabular layout facility when ready.

      print_configuration (cout, c);
      cout << endl;
    }

    return 0;
  }

  static int
  cmd_config_move (cmd_config_options& o, cli::scanner& args)
  {
    tracer trace ("config_move");

    if (!args.more ())
      fail << "configuration directory argument expected";

    dir_path prj (find_project (o));

    // Similar story to config-add.
    //
    dir_path path;
    optional<dir_path> rel_path;
    {
      const char* a (args.next ());
      try
      {
        path = dir_path (a);

        if (!exists (path))
          fail << "configuration directory " << path << " does not exist";

        path.complete ();
        path.normalize ();
      }
      catch (const invalid_path&)
      {
        fail << "invalid configuration directory '" << a << "'";
      }

      try {rel_path = path.relative (prj);} catch (const invalid_path&) {}
    }

    database db (open (prj, trace));

    session ses;
    transaction t (db.begin ());

    configurations cfgs (
      find_configurations (o,
                           prj,
                           t,
                           false /* fallback_default */,
                           false /* validate         */));

    if (cfgs.size () > 1)
      fail << "multiple configurations specified for config move";

    const shared_ptr<configuration>& c (cfgs.front ());

    // Check if there is already a configuration with this path.
    //
    using query = bdep::query<configuration>;

    if (auto p = db.query_one<configuration> (query::path == path.string ()))
    {
      // Note that this also covers the case where p == c.
      //
      fail << "configuration " << *p << " already uses directory " << path;
    }

    // Save the old path for diagnostics.
    //
    c->path.swap (path);
    c->relative_path = move (rel_path);

    db.update (c);
    t.commit ();

    if (verb)
    {
      // Restore the original path so that we can use print_configuration().
      //
      path.swap (c->path);

      diag_record dr (text);
      dr << "moved configuration ";
      print_configuration (dr, c, false /* flags */);
      dr << " to " << path;
    }

    return 0;
  }

  static int
  cmd_config_rename (cmd_config_options& o, cli::scanner& args)
  {
    tracer trace ("config_rename");

    // Let's be nice and allow specifying the new name as noth <name> and
    // @<name>.
    //
    string name;
    if (args.more ())
    {
      name = args.next ();

      if (name.empty ())
        fail << "empty configuration name specified";
    }
    else
    {
      strings& ns (o.config_name ());
      size_t n (ns.size ());

      if (n > 1 || (n == 1 && (o.config_specified () ||
                               o.config_id_specified ())))
      {
        name = move (ns.back ());
        ns.pop_back ();
      }
      else
        fail << "configuration name argument expected";
    }

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    session ses;
    transaction t (db.begin ());

    configurations cfgs (
      find_configurations (o,
                           prj,
                           t,
                           false /* fallback_default */,
                           false /* validate         */));

    if (cfgs.size () > 1)
      fail << "multiple configurations specified for config rename";

    const shared_ptr<configuration>& c (cfgs.front ());

    // Check if this name is already taken.
    //
    using query = bdep::query<configuration>;

    if (auto p = db.query_one<configuration> (query::name == name))
    {
      // Note that this also covers the case where p == c.
      //
      fail << "configuration " << p->path << " is already called " << name;
    }

    // Save the old name for diagnostics.
    //
    if (c->name)
      name.swap (*c->name);
    else
      c->name = move (name);

    db.update (c);
    t.commit ();

    if (verb)
    {
      // Restore the original name so that we can use print_configuration().
      //
      name.swap (*c->name);

      diag_record dr (text);
      dr << "renamed configuration ";
      print_configuration (dr, c, false /* flags */);
      dr << " to @" << name;
    }

    return 0;
  }

  static int
  cmd_config_remove (const cmd_config_options& o, cli::scanner&)
  {
    tracer trace ("config_remove");

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    transaction t (db.begin ());

    configurations cfgs (
      find_configurations (o,
                           prj,
                           t,
                           false /* fallback_default */,
                           false /* validate         */));

    for (const shared_ptr<configuration>& c: cfgs)
    {
      if (!c->packages.empty ())
      {
        bool e (exists (c->path));

        fail << "configuration " << *c << " contains initialized packages" <<
          info << "use deinit " << (e ? "" : "--force ") << "command to "
             << "deinitialize packages" <<
          info << "use status command to list initialized packages";
      }

      db.erase (c);
    }

    t.commit ();

    if (verb)
    {
      for (const shared_ptr<configuration>& c: cfgs)
      {
        diag_record dr (text);
        dr << "removed configuration ";
        print_configuration (dr, c, false /* flags */);
      }
    }

    return 0;
  }

  static int
  cmd_config_set (const cmd_config_options& o, cli::scanner&)
  {
    tracer trace ("config_set");

    // Note that these have been validate by cmd_config_validate_add().
    //
    optional<bool> d, f, s;
    if (o.default_  () || o.no_default   ()) d = o.default_  ();
    if (o.forward   () || o.no_forward   ()) f = o.forward   ();
    if (o.auto_sync () || o.no_auto_sync ()) s = o.auto_sync ();

    if (!d && !f && !s)
      fail << "nothing to set";

    dir_path prj (find_project (o));
    database db (open (prj, trace));

    session ses;
    transaction t (db.begin ());

    configurations cfgs (
      find_configurations (o,
                           prj,
                           t,
                           false /* fallback_default */,
                           false /* validate         */));

    for (const shared_ptr<configuration>& c: cfgs)
    {
      using query = bdep::query<configuration>;

      if (d)
      {
        if (*d && !c->default_)
        {
          if (auto p = db.query_one<configuration> (query::default_))
            fail << "configuration " << *p << " is already the default" <<
              info << "while updating configuration " << *c;
        }

        c->default_   = *d;
      }

      if (f)
      {
        if (*f && !c->forward)
        {
          if (auto p = db.query_one<configuration> (query::forward))
            fail << "configuration " << *p << " is already forwarded" <<
              info << "while updating configuration " << *c;
        }

        c->forward    = *f;
      }

      if (s)
        c->auto_sync  = *s;

      db.update (c);
    }

    t.commit ();

    if (verb)
    {
      for (const shared_ptr<configuration>& c: cfgs)
      {
        diag_record dr (text);
        dr << "updated configuration ";
        print_configuration (dr, c);
      }

      info << "explicit bdep-sync is required for changes to take effect";
    }

    return 0;
  }

  int
  cmd_config (cmd_config_options&& o, cli::scanner& scan)
  {
    tracer trace ("config");

    cmd_config_subcommands c (
      parse_command<cmd_config_subcommands> (scan,
                                             "config subcommand",
                                             "bdep help config"));
    // Validate options/subcommands.
    //
    if (const char* n = cmd_config_validate_add (o))
    {
      if (!c.add () && !c.create () && !c.set ())
        fail << n << " not valid for this subcommand";

      if (o.wipe () && !c.create ())
        fail << "--wipe is not valid for this subcommand";
    }

    // --all
    //
    if (o.all ())
    {
      if (!c.list () && !c.remove () && !c.set ())
        fail << "--all not valid for this subcommand";
    }

    // Dispatch to subcommand function.
    //
    if (c.add    ()) return cmd_config_add    (o, scan);
    if (c.create ()) return cmd_config_create (o, scan);
    if (c.list   ()) return cmd_config_list   (o, scan);
    if (c.move   ()) return cmd_config_move   (o, scan);
    if (c.rename ()) return cmd_config_rename (o, scan);
    if (c.remove ()) return cmd_config_remove (o, scan);
    if (c.set    ()) return cmd_config_set    (o, scan);

    assert (false); // Unhandled (new) subcommand.
    return 1;
  }
}