ide-build-pipeline.c 97.5 KB
Newer Older
1
2
/* ide-build-pipeline.c
 *
3
 * Copyright © 2016 Christian Hergert <chergert@redhat.com>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#define G_LOG_DOMAIN "ide-build-pipeline"

#include <glib/gi18n.h>
22
#include <dazzle.h>
23
24
#include <libpeas/peas.h>
#include <string.h>
25
#include <vte/vte.h>
26
27
28
29
30
31
32
33
34
35

#include "ide-context.h"
#include "ide-debug.h"
#include "ide-enums.h"

#include "application/ide-application.h"
#include "buildsystem/ide-build-log.h"
#include "buildsystem/ide-build-log-private.h"
#include "buildsystem/ide-build-pipeline.h"
#include "buildsystem/ide-build-pipeline-addin.h"
36
#include "buildsystem/ide-build-private.h"
37
38
39
40
#include "buildsystem/ide-build-stage.h"
#include "buildsystem/ide-build-stage-launcher.h"
#include "buildsystem/ide-build-stage-private.h"
#include "buildsystem/ide-build-system.h"
41
#include "buildsystem/ide-build-utils.h"
42
43
44
#include "diagnostics/ide-diagnostic.h"
#include "diagnostics/ide-source-location.h"
#include "diagnostics/ide-source-range.h"
45
#include "files/ide-file.h"
46
#include "plugins/ide-extension-util.h"
47
48
#include "projects/ide-project.h"
#include "runtimes/ide-runtime.h"
49
#include "terminal/ide-terminal-util.h"
50
51
#include "util/ide-line-reader.h"
#include "util/ptyintercept.h"
52
53
#include "vcs/ide-vcs.h"

54
DZL_DEFINE_COUNTER (Instances, "Pipeline", "N Pipelines", "Number of Pipeline instances")
55
56

/**
57
 * SECTION:idebuildpipeline
58
59
 * @title: IdeBuildPipeline
 * @short_description: Pluggable build pipeline
60
 * @include: ide.h
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
 *
 * The #IdeBuildPipeline is responsible for managing the build process
 * for Builder. It consists of multiple build "phases" (see #IdeBuildPhase
 * for the individual phases). An #IdeBuildStage can be attached with
 * a priority to each phase and is the primary mechanism that plugins
 * use to perform their operations in the proper ordering.
 *
 * For example, the flatpak plugin provides its download stage as part of the
 * %IDE_BUILD_PHASE_DOWNLOAD phase. The autotools plugin provides stages to
 * phases such as %IDE_BUILD_PHASE_AUTOGEN, %IDE_BUILD_PHASE_CONFIGURE,
 * %IDE_BUILD_PHASE_BUILD, and %IDE_BUILD_PHASE_INSTALL.
 *
 * If you want ensure a particular phase is performed as part of a build,
 * then fall ide_build_pipeline_request_phase() with the phase you are
 * interested in seeing complete successfully.
 *
 * If your plugin has discovered that something has changed that invalidates a
 * given phase, use ide_build_pipeline_invalidate_phase() to ensure that the
 * phase is re-executed the next time a requested phase of higher precidence
 * is requested.
 *
 * It can be useful to perform operations before or after a given stage (but
 * still be executed as part of that stage) so the %IDE_BUILD_PHASE_BEFORE and
 * %IDE_BUILD_PHASE_AFTER flags may be xor'd with the requested phase.  If more
 * precise ordering is required, you may use the priority parameter to order
 * the operation with regards to other stages in that phase.
 *
 * Transient stages may be added to the pipeline and they will be removed after
 * the ide_build_pipeline_execute_async() operation has completed successfully
 * or has failed. You can mark a stage as trandient with
 * ide_build_stage_set_transient(). This may be useful to perform operations
 * such as an "export tarball" stage which should only run once as determined
 * by the user requesting a "make dist" style operation.
 */

typedef struct
{
  guint          id;
  IdeBuildPhase  phase;
  gint           priority;
  IdeBuildStage *stage;
} PipelineEntry;

typedef struct
{
  guint   id;
  GRegex *regex;
} ErrorFormat;

struct _IdeBuildPipeline
{
112
113
114
115
116
117
118
119
  IdeObject parent_instance;

  /*
   * A cancellable we can use to chain to all incoming requests so that
   * all tasks may be cancelled at once when _ide_build_pipeline_cancel()
   * is called.
   */
  GCancellable *cancellable;
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

  /*
   * These are our extensions to the BuildPipeline. Plugins insert
   * them and they might go about adding stages to the pipeline,
   * add error formats, or just monitor logs.
   */
  PeasExtensionSet *addins;

  /*
   * This is the configuration for the build. It is a snapshot of
   * the real configuration so that we do not need to synchronize
   * with the UI process for accesses.
   */
  IdeConfiguration *configuration;

  /*
   * The IdeBuildLog is a private implementation that we use to
   * log things from addins via observer callbacks.
   */
  IdeBuildLog *log;

  /*
   * These are our builddir/srcdir paths. Useful for building paths
   * by addins. We try to create a new builddir that will be unique
   * based on hashing of the configuration.
   */
  gchar *builddir;
  gchar *srcdir;

  /*
   * This is an array of PipelineEntry, which contain information we
   * need about the stage and an identifier that addins can use to
   * remove their inserted stages.
   */
  GArray *pipeline;

156
157
158
159
160
161
  /*
   * This contains the GBinding objects used to keep the "completed"
   * property of chained stages updated.
   */
  GPtrArray *chained_bindings;

162
163
164
165
166
167
168
169
170
171
172
  /*
   * This are used for ErrorFormat registration so that we have a
   * single place to extract "GCC-style" warnings and errors. Other
   * languages can also register these so they show up in the build
   * errors panel.
   */
  GArray *errfmts;
  gchar  *errfmt_current_dir;
  gchar  *errfmt_top_dir;
  guint   errfmt_seqnum;

173
  /*
174
175
176
177
178
179
180
181
   * The VtePty is used to connect to a VteTerminal. It's basically
   * just a wrapper around a PTY master. We then add a pty_intercept_t
   * to proxy PTY data while allowing us to tap into the content being
   * transmitted. We can use that to run regexes against and perform
   * additional error extraction. Finally, pty_slave is the PTY device
   * we created that will get attached to stdin/stdout/stderr in our
   * spawned subprocesses. It is a slave to the PTY master owned by
   * the pty_intercept_t.
182
   */
183
184
185
  VtePty          *pty;
  pty_intercept_t  intercept;
  pty_fd_t         pty_slave;
186

187
188
189
190
191
192
193
  /*
   * If the terminal interpreting our Pty has received a terminal
   * title update, it might set this message which we can use for
   * better build messages.
   */
  gchar *message;

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
  /*
   * No reference to the current stage. It is only available during
   * the asynchronous execution of the stage.
   */
  IdeBuildStage *current_stage;

  /*
   * The index of our current PipelineEntry. This should start at -1
   * to indicate that no stage is currently active.
   */
  gint position;

  /*
   * This is the requested mask to be built. It should be reset after
   * performing a build so that a followup execute_async() would be
   * innocuous.
   */
  IdeBuildPhase requested_mask;

  /*
   * We queue incoming tasks in case we need for a finish task to
   * complete before our task can continue. The items in the queue
   * are DelayedTask structs with a GTask and the type id so we
   * can progress the task upon completion of the previous task.
   */
  GQueue task_queue;

  /*
   * We use this sequence number to give PipelineEntry instances a
   * unique identifier. The addins can use this to remove their
   * inserted build stages.
   */
  guint seqnum;

  /*
   * If we failed to build, this should be set.
   */
  guint failed : 1;

  /*
234
   * If we are within a build, this should be set.
235
236
237
238
239
240
241
   */
  guint busy : 1;

  /*
   * If we are in the middle of a clean operation.
   */
  guint in_clean : 1;
242
243
244
245
246
247
248

  /*
   * Precalculation if we need to look for errors on stdout. We can't rely
   * on @current_stage for this, becase log entries might come in
   * asynchronously and after the processes/stage has completed.
   */
  guint errors_on_stdout : 1;
249
250
251
252
253
254
255

  /*
   * This is set to TRUE if the pipeline has failed initialization. That means
   * that all future operations will fail (but we can keep the object alive to
   * ensure that the manager has a valid object instance for the pipeline).
   */
  guint broken : 1;
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
};

typedef enum
{
  TASK_BUILD   = 1,
  TASK_CLEAN   = 2,
  TASK_REBUILD = 3,
} TaskType;

typedef struct
{
  /*
   * Our operation type. This will indicate one of the TaskType enum
   * which corellate to the various async functions of the pipeline.
   */
  TaskType type;

  /*
   * This is an unowned pointer to the task. Since the Operation structure is
   * the task data, we cannot reference as that would create a cycle. Instead,
   * we just rely on this becoming invalid during the task cleanup.
   */
  GTask *task;

  /*
   * The phase that should be met for the given pipeline operation.
   */
  IdeBuildPhase phase;

  union {
    struct {
      GPtrArray *stages;
    } clean;
  };
} TaskData;

292
293
294
295
296
297
298
299
300
301
302
303
304
static void ide_build_pipeline_queue_flush  (IdeBuildPipeline    *self);
static void ide_build_pipeline_tick_execute (IdeBuildPipeline    *self,
                                             GTask               *task);
static void ide_build_pipeline_tick_clean   (IdeBuildPipeline    *self,
                                             GTask               *task);
static void ide_build_pipeline_tick_rebuild (IdeBuildPipeline    *self,
                                             GTask               *task);
static void initable_iface_init             (GInitableIface      *iface);
static void list_model_iface_init           (GListModelInterface *iface);

G_DEFINE_TYPE_WITH_CODE (IdeBuildPipeline, ide_build_pipeline, IDE_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (G_TYPE_LIST_MODEL, list_model_iface_init)
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))
305
306
307
308
309
310
311

enum {
  PROP_0,
  PROP_BUSY,
  PROP_CONFIGURATION,
  PROP_MESSAGE,
  PROP_PHASE,
312
  PROP_PTY,
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
  N_PROPS
};

enum {
  DIAGNOSTIC,
  STARTED,
  FINISHED,
  N_SIGNALS
};

static GParamSpec *properties [N_PROPS];
static guint signals [N_SIGNALS];
static const gchar *task_type_names[] = {
  NULL,
  "build",
  "clean",
  "rebuild",
};

332
333
334
335
336
337
338
339
340
static void
chained_binding_clear (gpointer data)
{
  GBinding *binding = data;

  g_binding_unbind (binding);
  g_object_unref (binding);
}

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
static void
task_data_free (gpointer data)
{
  TaskData *td = data;

  if (td != NULL)
    {
      if (td->type == TASK_CLEAN)
        g_clear_pointer (&td->clean.stages, g_ptr_array_unref);
      td->type = 0;
      td->task = NULL;
      g_slice_free (TaskData, td);
    }
}

static TaskData *
task_data_new (GTask    *task,
               TaskType  type)
{
  TaskData *td;

  g_assert (G_IS_TASK (task));
  g_assert (type > 0);
  g_assert (type <= TASK_REBUILD);

  td = g_slice_new0 (TaskData);
  td->type = type;
  td->task = task;

  return td;
}

static void
clear_error_format (gpointer data)
{
  ErrorFormat *errfmt = data;

  errfmt->id = 0;
  g_clear_pointer (&errfmt->regex, g_regex_unref);
}

static inline const gchar *
build_phase_nick (IdeBuildPhase phase)
{
  GFlagsClass *klass = g_type_class_peek (IDE_TYPE_BUILD_PHASE);
  GFlagsValue *value;

  g_assert (klass != NULL);

  phase &= IDE_BUILD_PHASE_MASK;
  value = g_flags_get_first_value (klass, phase);

  if (value != NULL)
    return value->value_nick;

  return "unknown";
}

static IdeDiagnosticSeverity
parse_severity (const gchar *str)
{
  g_autofree gchar *lower = NULL;

  if (str == NULL)
    return IDE_DIAGNOSTIC_WARNING;

  lower = g_utf8_strdown (str, -1);

  if (strstr (lower, "fatal") != NULL)
    return IDE_DIAGNOSTIC_FATAL;

  if (strstr (lower, "error") != NULL)
    return IDE_DIAGNOSTIC_ERROR;

  if (strstr (lower, "warning") != NULL)
    return IDE_DIAGNOSTIC_WARNING;

  if (strstr (lower, "ignored") != NULL)
    return IDE_DIAGNOSTIC_IGNORED;

  if (strstr (lower, "deprecated") != NULL)
    return IDE_DIAGNOSTIC_DEPRECATED;

  if (strstr (lower, "note") != NULL)
    return IDE_DIAGNOSTIC_NOTE;

  return IDE_DIAGNOSTIC_WARNING;
}

static IdeDiagnostic *
create_diagnostic (IdeBuildPipeline *self,
                   GMatchInfo       *match_info)
{
  g_autofree gchar *filename = NULL;
  g_autofree gchar *line = NULL;
  g_autofree gchar *column = NULL;
  g_autofree gchar *message = NULL;
  g_autofree gchar *level = NULL;
  g_autoptr(IdeFile) file = NULL;
  g_autoptr(IdeSourceLocation) location = NULL;
  IdeContext *context;
  struct {
    gint64 line;
    gint64 column;
    IdeDiagnosticSeverity severity;
  } parsed = { 0 };

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (match_info != NULL);

  message = g_match_info_fetch_named (match_info, "message");

  /* XXX: This is a hack to ignore a common but unuseful error message.
   *      This really belongs somewhere else, but it's easier to do the
   *      check here for now. We need proper callback for ErrorRegex in
   *      the future so they can ignore it.
   */
  if (message == NULL || strncmp (message, "#warning _FORTIFY_SOURCE requires compiling with optimization", 61) == 0)
    return NULL;

  filename = g_match_info_fetch_named (match_info, "filename");
  line = g_match_info_fetch_named (match_info, "line");
  column = g_match_info_fetch_named (match_info, "column");
  level = g_match_info_fetch_named (match_info, "level");

  if (line != NULL)
    {
      parsed.line = g_ascii_strtoll (line, NULL, 10);
      if (parsed.line < 1 || parsed.line > G_MAXINT32)
        return NULL;
      parsed.line--;
    }

  if (column != NULL)
    {
      parsed.column = g_ascii_strtoll (column, NULL, 10);
      if (parsed.column < 1 || parsed.column > G_MAXINT32)
        return NULL;
      parsed.column--;
    }

  parsed.severity = parse_severity (level);

484
  if (!g_path_is_absolute (filename))
485
486
487
    {
      gchar *path;

488
      if (self->errfmt_current_dir != NULL)
489
        {
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
          const gchar *basedir = self->errfmt_current_dir;

          if (g_str_has_prefix (basedir, self->errfmt_top_dir))
            {
              basedir += strlen (self->errfmt_top_dir);
              if (*basedir == G_DIR_SEPARATOR)
                basedir++;
            }

          path = g_build_filename (basedir, filename, NULL);
          g_free (filename);
          filename = path;
        }
      else
        {
          path = g_build_filename (self->builddir, filename, NULL);
          g_free (filename);
          filename = path;
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
        }
    }

  context = ide_object_get_context (IDE_OBJECT (self));

  if (!g_path_is_absolute (filename))
    {
      g_autoptr(GFile) child = NULL;
      IdeVcs *vcs;
      GFile *workdir;
      gchar *path;

      vcs = ide_context_get_vcs (context);
      workdir = ide_vcs_get_working_directory (vcs);

      child = g_file_get_child (workdir, filename);
      path = g_file_get_path (child);

      g_free (filename);
      filename = path;
    }

  file = ide_file_new_for_path (context, filename);
  location = ide_source_location_new (file, parsed.line, parsed.column, 0);

  return ide_diagnostic_new (parsed.severity, message, location);
}

536
537
538
539
static gboolean
extract_directory_change (IdeBuildPipeline *self,
                          const guint8     *data,
                          gsize             len)
540
{
541
542
  g_autofree gchar *dir = NULL;
  const guint8 *begin;
543
544

  g_assert (IDE_IS_BUILD_PIPELINE (self));
545
546
547

  if (len == 0)
    return FALSE;
548
549

#define ENTERING_DIRECTORY_BEGIN "Entering directory '"
550
#define ENTERING_DIRECTORY_END   "'"
551

552
553
554
  begin = memmem (data, len, ENTERING_DIRECTORY_BEGIN, strlen (ENTERING_DIRECTORY_BEGIN));
  if (begin == NULL)
    return FALSE;
555

556
557
558
559
  begin += strlen (ENTERING_DIRECTORY_BEGIN);

  if (data[len - 1] != '\'')
    return FALSE;
560

561
562
  len = &data[len - 1] - begin;
  dir = g_memdup (begin, len);
563

564
  if (g_utf8_validate (dir, len, NULL))
565
    {
566
      g_free (self->errfmt_current_dir);
567

568
569
570
571
      if (len == 0)
        self->errfmt_current_dir = g_strdup (self->errfmt_top_dir);
      else
        self->errfmt_current_dir = g_strndup (dir, len);
572

573
574
575
      if (self->errfmt_top_dir == NULL)
        self->errfmt_top_dir = g_strdup (self->errfmt_current_dir);

576
577
      return TRUE;
    }
578

579
580
#undef ENTERING_DIRECTORY_BEGIN
#undef ENTERING_DIRECTORY_END
581

582
583
  return FALSE;
}
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
static void
extract_diagnostics (IdeBuildPipeline *self,
                     const guint8     *data,
                     gsize             len)
{
  g_autofree guint8 *unescaped = NULL;
  IdeLineReader reader;
  gchar *line;
  gsize line_len;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (data != NULL);

  if (len == 0 || self->errfmts->len == 0)
    return;

  /* If we have any color escape sequences, remove them */
  if G_UNLIKELY (memchr (data, '\033', len) || memmem (data, len, "\\e", 2))
    {
      gsize out_len = 0;

      unescaped = ide_build_utils_filter_color_codes (data, len, &out_len);
      if (out_len == 0)
        return;

      data = unescaped;
      len = out_len;
612
    }
613

614
615
616
  ide_line_reader_init (&reader, (gchar *)data, len);

  while (NULL != (line = ide_line_reader_next (&reader, &line_len)))
617
    {
618
619
620
      if (extract_directory_change (self, (const guint8 *)line, line_len))
        continue;

621
      for (guint i = 0; i < self->errfmts->len; i++)
622
        {
623
624
          const ErrorFormat *errfmt = &g_array_index (self->errfmts, ErrorFormat, i);
          g_autoptr(GMatchInfo) match_info = NULL;
625

626
          if (g_regex_match_full (errfmt->regex, line, line_len, 0, 0, &match_info, NULL))
627
            {
628
629
630
631
632
              g_autoptr(IdeDiagnostic) diagnostic = create_diagnostic (self, match_info);

              if (diagnostic != NULL)
                {
                  ide_build_pipeline_emit_diagnostic (self, diagnostic);
633
                  break;
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
static void
ide_build_pipeline_log_observer (IdeBuildLogStream  stream,
                                 const gchar       *message,
                                 gssize             message_len,
                                 gpointer           user_data)
{
  IdeBuildPipeline *self = user_data;

  g_assert (stream == IDE_BUILD_LOG_STDOUT || stream == IDE_BUILD_LOG_STDERR);
  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (message != NULL);

  if (message_len < 0)
    message_len = strlen (message);

  if (self->log != NULL)
    ide_build_log_observer (stream, message, message_len, self->log);

  extract_diagnostics (self, (const guint8 *)message, message_len);
}

static void
ide_build_pipeline_intercept_pty_master_cb (const pty_intercept_t      *intercept,
                                            const pty_intercept_side_t *side,
                                            const guint8               *data,
                                            gsize                       len,
                                            gpointer                    user_data)
{
  IdeBuildPipeline *self = user_data;

  g_assert (intercept != NULL);
  g_assert (side != NULL);
  g_assert (data != NULL);
  g_assert (len > 0);
  g_assert (IDE_IS_BUILD_PIPELINE (self));

  extract_diagnostics (self, data, len);
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
}

static void
ide_build_pipeline_release_transients (IdeBuildPipeline *self)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (self->pipeline != NULL);

  for (guint i = self->pipeline->len; i > 0; i--)
    {
      const PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, i - 1);

      g_assert (IDE_IS_BUILD_STAGE (entry->stage));

      if (ide_build_stage_get_transient (entry->stage))
        {
          IDE_TRACE_MSG ("Releasing transient stage %s at index %u",
                         G_OBJECT_TYPE_NAME (entry->stage),
                         i - 1);
          g_array_remove_index (self->pipeline, i);
        }
    }

  IDE_EXIT;
}

705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
static gboolean
ide_build_pipeline_check_ready (IdeBuildPipeline *self,
                                GTask            *task)
{
  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (G_IS_TASK (task));

  if (self->broken)
    {
      g_task_return_new_error (task,
                               G_IO_ERROR,
                               G_IO_ERROR_FAILED,
                               _("The build pipeline is in a failed state"));
      return FALSE;
    }

  return TRUE;
}

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/**
 * ide_build_pipeline_get_phase:
 *
 * Gets the current phase that is executing. This is only useful during
 * execution of the pipeline.
 */
IdeBuildPhase
ide_build_pipeline_get_phase (IdeBuildPipeline *self)
{
  g_return_val_if_fail (IDE_IS_BUILD_PIPELINE (self), 0);

  if (self->position < 0)
    return IDE_BUILD_PHASE_NONE;
  else if (self->failed)
    return IDE_BUILD_PHASE_FAILED;
739
  else if ((guint)self->position < self->pipeline->len)
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    return g_array_index (self->pipeline, PipelineEntry, self->position).phase & IDE_BUILD_PHASE_MASK;
  else
    return IDE_BUILD_PHASE_FINISHED;
}

/**
 * ide_build_pipeline_get_configuration:
 *
 * Gets the #IdeConfiguration to use for the pipeline.
 *
 * Returns: (transfer none): An #IdeConfiguration
 */
IdeConfiguration *
ide_build_pipeline_get_configuration (IdeBuildPipeline *self)
{
  g_return_val_if_fail (IDE_IS_BUILD_PIPELINE (self), NULL);

  return self->configuration;
}

static void
clear_pipeline_entry (gpointer data)
{
  PipelineEntry *entry = data;

  if (entry->stage != NULL)
    {
      ide_build_stage_set_log_observer (entry->stage, NULL, NULL, NULL);
      g_clear_object (&entry->stage);
    }
}

static gint
pipeline_entry_compare (gconstpointer a,
                        gconstpointer b)
{
  const PipelineEntry *entry_a = a;
  const PipelineEntry *entry_b = b;
  gint ret;

  ret = (gint)(entry_a->phase & IDE_BUILD_PHASE_MASK)
      - (gint)(entry_b->phase & IDE_BUILD_PHASE_MASK);

  if (ret == 0)
    {
      gint whence_a = (entry_a->phase & IDE_BUILD_PHASE_WHENCE_MASK);
      gint whence_b = (entry_b->phase & IDE_BUILD_PHASE_WHENCE_MASK);

      if (whence_a != whence_b)
        {
          if (whence_a == IDE_BUILD_PHASE_BEFORE)
            return -1;

          if (whence_b == IDE_BUILD_PHASE_BEFORE)
            return 1;

          if (whence_a == 0)
            return -1;

          if (whence_b == 0)
            return 1;

          g_assert_not_reached ();
        }
    }

  if (ret == 0)
    ret = entry_a->priority - entry_b->priority;

  return ret;
}

static void
ide_build_pipeline_real_started (IdeBuildPipeline *self)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));

819
820
821
822
823
824
825
826
827
828
829
830
831
  self->errors_on_stdout = FALSE;

  for (guint i = 0; i < self->pipeline->len; i++)
    {
      PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, i);

      if (ide_build_stage_get_check_stdout (entry->stage))
        {
          self->errors_on_stdout = TRUE;
          break;
        }
    }

832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
  IDE_EXIT;
}

static void
ide_build_pipeline_real_finished (IdeBuildPipeline *self,
                                  gboolean          failed)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));

  IDE_EXIT;
}

static void
ide_build_pipeline_extension_added (PeasExtensionSet *set,
                                    PeasPluginInfo   *plugin_info,
                                    PeasExtension    *exten,
                                    gpointer          user_data)
{
  IdeBuildPipeline *self = user_data;
  IdeBuildPipelineAddin *addin = (IdeBuildPipelineAddin *)exten;

  IDE_ENTRY;

  g_assert (PEAS_IS_EXTENSION_SET (set));
  g_assert (plugin_info != NULL);
  g_assert (IDE_IS_BUILD_PIPELINE_ADDIN (addin));
  g_assert (IDE_IS_BUILD_PIPELINE (self));

  ide_build_pipeline_addin_load (addin, self);

  IDE_EXIT;
}

static void
ide_build_pipeline_extension_removed (PeasExtensionSet *set,
                                      PeasPluginInfo   *plugin_info,
                                      PeasExtension    *exten,
                                      gpointer          user_data)
{
  IdeBuildPipeline *self = user_data;
  IdeBuildPipelineAddin *addin = (IdeBuildPipelineAddin *)exten;

  IDE_ENTRY;

  g_assert (PEAS_IS_EXTENSION_SET (set));
  g_assert (plugin_info != NULL);
  g_assert (IDE_IS_BUILD_PIPELINE_ADDIN (addin));
  g_assert (IDE_IS_BUILD_PIPELINE (self));

  ide_build_pipeline_addin_unload (addin, self);

  IDE_EXIT;
}

888
889
890
891
892
893
894
895
896
897
898
static void
register_build_commands_stage (IdeBuildPipeline *self,
                               IdeContext       *context)
{
  g_autoptr(GError) error = NULL;
  const gchar * const *build_commands;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (IDE_IS_CONTEXT (context));
  g_assert (IDE_IS_CONFIGURATION (self->configuration));

Christian Hergert's avatar
Christian Hergert committed
899
  if (NULL == (build_commands = ide_configuration_get_build_commands (self->configuration)))
900
    return;
Christian Hergert's avatar
Christian Hergert committed
901

902
903
904
905
906
907
908
909
910
911
912
  for (guint i = 0; build_commands[i]; i++)
    {
      g_autoptr(IdeSubprocessLauncher) launcher = NULL;
      g_autoptr(IdeBuildStage) stage = NULL;

      if (NULL == (launcher = ide_build_pipeline_create_launcher (self, &error)))
        {
          g_warning ("%s", error->message);
          return;
        }

913
914
915
      /* Request deprecation warnings from the GLib stack by default */
      ide_subprocess_launcher_setenv (launcher, "G_ENABLE_DIAGNOSTIC", "1", FALSE);

916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
      ide_subprocess_launcher_push_argv (launcher, "/bin/sh");
      ide_subprocess_launcher_push_argv (launcher, "-c");
      ide_subprocess_launcher_push_argv (launcher, build_commands[i]);

      stage = g_object_new (IDE_TYPE_BUILD_STAGE_LAUNCHER,
                            "context", context,
                            "launcher", launcher,
                            NULL);

      ide_build_pipeline_connect (self,
                                  IDE_BUILD_PHASE_BUILD | IDE_BUILD_PHASE_AFTER,
                                  i,
                                  stage);
    }
}

static void
register_post_install_commands_stage (IdeBuildPipeline *self,
                                      IdeContext       *context)
{
  g_autoptr(GError) error = NULL;
  const gchar * const *post_install_commands;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (IDE_IS_CONTEXT (context));
  g_assert (IDE_IS_CONFIGURATION (self->configuration));

  post_install_commands = ide_configuration_get_post_install_commands (self->configuration);
  if (post_install_commands == NULL)
    return;
  for (guint i = 0; post_install_commands[i]; i++)
    {
      g_autoptr(IdeSubprocessLauncher) launcher = NULL;
      g_autoptr(IdeBuildStage) stage = NULL;

      if (NULL == (launcher = ide_build_pipeline_create_launcher (self, &error)))
        {
953
          ide_object_warning (self, "%s", error->message);
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
          return;
        }

      ide_subprocess_launcher_push_argv (launcher, "/bin/sh");
      ide_subprocess_launcher_push_argv (launcher, "-c");
      ide_subprocess_launcher_push_argv (launcher, post_install_commands[i]);

      stage = g_object_new (IDE_TYPE_BUILD_STAGE_LAUNCHER,
                            "context", context,
                            "launcher", launcher,
                            NULL);

      ide_build_pipeline_connect (self,
                                  IDE_BUILD_PHASE_INSTALL | IDE_BUILD_PHASE_AFTER,
                                  i,
                                  stage);
    }
}

973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/**
 * ide_build_pipeline_load:
 *
 * This manages the loading of addins which will register their necessary build
 * stages.  We do this separately from ::constructed so that we can
 * enable/disable the pipeline as the IdeConfiguration:ready property changes.
 * This could happen when the device or runtime is added/removed while the
 * application is running.
 */
static void
ide_build_pipeline_load (IdeBuildPipeline *self)
{
  IdeContext *context;

  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (self->addins == NULL);

  context = ide_object_get_context (IDE_OBJECT (self));

994
995
996
  register_build_commands_stage (self, context);
  register_post_install_commands_stage (self, context);

997
998
999
1000
  self->addins = ide_extension_set_new (peas_engine_get_default (),
                                        IDE_TYPE_BUILD_PIPELINE_ADDIN,
                                        "context", context,
                                        NULL);
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018

  g_signal_connect (self->addins,
                    "extension-added",
                    G_CALLBACK (ide_build_pipeline_extension_added),
                    self);

  g_signal_connect (self->addins,
                    "extension-removed",
                    G_CALLBACK (ide_build_pipeline_extension_removed),
                    self);

  peas_extension_set_foreach (self->addins,
                              ide_build_pipeline_extension_added,
                              self);

  IDE_EXIT;
}

Christian Hergert's avatar
Christian Hergert committed
1019
/**
1020
 * ide_build_pipeline_unload:
Christian Hergert's avatar
Christian Hergert committed
1021
 * @self: an #IdeBuildPipeline
1022
 *
Christian Hergert's avatar
Christian Hergert committed
1023
1024
1025
1026
 * This clears things up that were initialized in ide_build_pipeline_load().
 * This function is safe to run even if load has not been called. We will not
 * clean things up if the pipeline is currently executing (we can wait until
 * its finished or dispose/finalize to cleanup up further.
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
 */
static void
ide_build_pipeline_unload (IdeBuildPipeline *self)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));

  g_clear_object (&self->addins);

  IDE_EXIT;
}

static void
ide_build_pipeline_notify_ready (IdeBuildPipeline *self,
                                 GParamSpec       *pspec,
                                 IdeConfiguration *configuration)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (IDE_IS_CONFIGURATION (configuration));

1050
1051
1052
1053
1054
1055
1056
  /*
   * If we're being realistic, we can only really setup the build pipeline one
   * time, once the configuration is ready. So cancel all tracking after that
   * so that and just rely on the build manager to create a new pipeline when
   * the active configuration changes.
   */

1057
  if (ide_configuration_get_ready (configuration))
1058
1059
1060
1061
1062
1063
    {
      ide_build_pipeline_load (self);
      g_signal_handlers_disconnect_by_func (configuration,
                                            G_CALLBACK (ide_build_pipeline_notify_ready),
                                            self);
    }
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

  IDE_EXIT;
}

static void
ide_build_pipeline_finalize (GObject *object)
{
  IdeBuildPipeline *self = (IdeBuildPipeline *)object;

  IDE_ENTRY;

  g_assert (self->task_queue.length == 0);
  g_queue_clear (&self->task_queue);

1078
  g_clear_object (&self->cancellable);
1079
1080
1081
1082
1083
1084
1085
1086
  g_clear_object (&self->log);
  g_clear_object (&self->configuration);
  g_clear_pointer (&self->pipeline, g_array_unref);
  g_clear_pointer (&self->srcdir, g_free);
  g_clear_pointer (&self->builddir, g_free);
  g_clear_pointer (&self->errfmts, g_array_unref);
  g_clear_pointer (&self->errfmt_top_dir, g_free);
  g_clear_pointer (&self->errfmt_current_dir, g_free);
1087
  g_clear_pointer (&self->chained_bindings, g_ptr_array_free);
1088
1089
1090

  G_OBJECT_CLASS (ide_build_pipeline_parent_class)->finalize (object);

1091
  DZL_COUNTER_DEC (Instances);
1092
1093
1094
1095
1096
1097
1098
1099

  IDE_EXIT;
}

static void
ide_build_pipeline_dispose (GObject *object)
{
  IdeBuildPipeline *self = IDE_BUILD_PIPELINE (object);
1100
  g_auto(pty_fd_t) fd = PTY_FD_INVALID;
1101
1102
1103
1104
1105

  IDE_ENTRY;

  ide_build_pipeline_unload (self);

1106
  g_clear_pointer (&self->message, g_free);
1107

1108
1109
1110
  g_clear_object (&self->pty);
  pty_intercept_clear (&self->intercept);
  fd = pty_fd_steal (&self->pty_slave);
1111

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
  G_OBJECT_CLASS (ide_build_pipeline_parent_class)->dispose (object);

  IDE_EXIT;
}

static gboolean
ide_build_pipeline_initable_init (GInitable     *initable,
                                  GCancellable  *cancellable,
                                  GError       **error)
{
  IdeBuildPipeline *self = (IdeBuildPipeline *)initable;
1123
  pty_fd_t master_fd;
1124
1125
1126
1127
1128

  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (IDE_IS_CONFIGURATION (self->configuration));
1129
  g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));
1130

1131
1132
1133
1134
1135
  /*
   * Create a PTY for subprocess launchers. PTY initialization does not
   * support cancellation, so do not pass @cancellable along to it.
   */
  self->pty = vte_pty_new_sync (VTE_PTY_DEFAULT, NULL, error);
1136
  if (self->pty == NULL)
1137
    IDE_RETURN (FALSE);
1138

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
  master_fd = vte_pty_get_fd (self->pty);

  if (!pty_intercept_init (&self->intercept, master_fd, NULL))
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_FAILED,
                   "Failed to initialize PTY intercept");
      IDE_RETURN (FALSE);
    }

  pty_intercept_set_callback (&self->intercept,
                              &self->intercept.master,
                              ide_build_pipeline_intercept_pty_master_cb,
                              self);

1155
1156
1157
1158
1159
1160
  g_signal_connect_object (self->configuration,
                           "notify::ready",
                           G_CALLBACK (ide_build_pipeline_notify_ready),
                           self,
                           G_CONNECT_SWAPPED);

1161
  ide_build_pipeline_notify_ready (self, NULL, self->configuration);
1162

1163
1164
  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_PTY]);

1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
  IDE_RETURN (TRUE);
}

static void
initable_iface_init (GInitableIface *iface)
{
  iface->init = ide_build_pipeline_initable_init;
}

static void
ide_build_pipeline_constructed (GObject *object)
{
  IdeBuildPipeline *self = IDE_BUILD_PIPELINE (object);
  IdeBuildSystem *build_system;
  IdeContext *context;
  IdeVcs *vcs;
  GFile *workdir;

  IDE_ENTRY;

  G_OBJECT_CLASS (ide_build_pipeline_parent_class)->constructed (object);

  g_assert (IDE_IS_CONFIGURATION (self->configuration));

  context = ide_object_get_context (IDE_OBJECT (self));
  build_system = ide_context_get_build_system (context);
  vcs = ide_context_get_vcs (context);
  workdir = ide_vcs_get_working_directory (vcs);

  self->srcdir = g_file_get_path (workdir);
  self->builddir = ide_build_system_get_builddir (build_system, self->configuration);

  IDE_EXIT;
}

static void
ide_build_pipeline_get_property (GObject    *object,
                                 guint       prop_id,
                                 GValue     *value,
                                 GParamSpec *pspec)
{
  IdeBuildPipeline *self = IDE_BUILD_PIPELINE (object);

  switch (prop_id)
    {
    case PROP_BUSY:
      g_value_set_boolean (value, self->busy);
      break;

    case PROP_CONFIGURATION:
      g_value_set_object (value, ide_build_pipeline_get_configuration (self));
      break;

    case PROP_MESSAGE:
      g_value_set_string (value, ide_build_pipeline_get_message (self));
      break;

    case PROP_PHASE:
      g_value_set_flags (value, ide_build_pipeline_get_phase (self));
      break;

1226
1227
1228
1229
    case PROP_PTY:
      g_value_set_object (value, ide_build_pipeline_get_pty (self));
      break;

1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
ide_build_pipeline_set_property (GObject      *object,
                                 guint         prop_id,
                                 const GValue *value,
                                 GParamSpec   *pspec)
{
  IdeBuildPipeline *self = IDE_BUILD_PIPELINE (object);

  switch (prop_id)
    {
    case PROP_CONFIGURATION:
      self->configuration = g_value_dup_object (value);
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
ide_build_pipeline_class_init (IdeBuildPipelineClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->constructed = ide_build_pipeline_constructed;
  object_class->dispose = ide_build_pipeline_dispose;
  object_class->finalize = ide_build_pipeline_finalize;
  object_class->get_property = ide_build_pipeline_get_property;
  object_class->set_property = ide_build_pipeline_set_property;

  /**
   * IdeBuildPipeline:busy:
   *
   * Gets the "busy" property. If %TRUE, the pipeline is busy executing.
   */
  properties [PROP_BUSY] =
    g_param_spec_boolean ("busy",
                          "Busy",
                          "If the pipeline is busy",
                          FALSE,
                          (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * IdeBuildPipeline:configuration:
   *
   * The configuration to use for the build pipeline.
   */
  properties [PROP_CONFIGURATION] =
    g_param_spec_object ("configuration",
                         "Configuration",
                         "Configuration",
                         IDE_TYPE_CONFIGURATION,
                         (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

  properties [PROP_MESSAGE] =
    g_param_spec_string ("message",
                         "Message",
                         "The message for the build phase",
                         NULL,
                         (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

  /**
   * IdeBuildPipeline:phase:
   *
   * The current build phase during execution of the pipeline.
   */
  properties [PROP_PHASE] =
    g_param_spec_flags ("phase",
                        "Phase",
                        "The phase that is being executed",
                        IDE_TYPE_BUILD_PHASE,
                        IDE_BUILD_PHASE_NONE,
                        (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
  /**
   * IdeBuildPipeline:pty:
   *
   * The "pty" property is the #VtePty that is used by build stages that
   * execute subprocesses with a pseudo terminal.
   *
   * Since: 3.28
   */
  properties [PROP_PTY] =
    g_param_spec_object ("pty",
                         "PTY",
                         "The PTY used by the pipeline",
                         VTE_TYPE_PTY,
                         (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
  g_object_class_install_properties (object_class, N_PROPS, properties);

  /**
   * IdeBuildPipeline::diagnostic:
   * @self: An #IdeBuildPipeline
   * @diagnostic: The newly created diagnostic
   *
   * This signal is emitted when a plugin has detected a diagnostic while
   * building the pipeline.
   */
  signals [DIAGNOSTIC] =
    g_signal_new_class_handler ("diagnostic",
                                G_TYPE_FROM_CLASS (klass),
                                G_SIGNAL_RUN_LAST,
                                NULL, NULL, NULL, NULL,
                                G_TYPE_NONE, 1, IDE_TYPE_DIAGNOSTIC);

  /**
   * IdeBuildPipeline::started:
   * @self: An #IdeBuildPipeline
1344
   * @phase: the #IdeBuildPhase for which we are advancing
1345
1346
1347
1348
1349
1350
1351
1352
1353
   *
   * This signal is emitted when the pipeline has started executing in
   * response to ide_build_pipeline_execute_async() being called.
   */
  signals [STARTED] =
    g_signal_new_class_handler ("started",
                                G_TYPE_FROM_CLASS (klass),
                                G_SIGNAL_RUN_LAST,
                                G_CALLBACK (ide_build_pipeline_real_started),
1354
1355
                                NULL, NULL, NULL,
                                G_TYPE_NONE, 1, IDE_TYPE_BUILD_PHASE);
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377

  /**
   * IdeBuildPipeline::finished:
   * @self: An #IdeBuildPipeline
   * @failed: If the build was a failure
   *
   * This signal is emitted when the build process has finished executing.
   * If the build failed to complete all requested stages, then @failed will
   * be set to %TRUE, otherwise %FALSE.
   */
  signals [FINISHED] =
    g_signal_new_class_handler ("finished",
                                G_TYPE_FROM_CLASS (klass),
                                G_SIGNAL_RUN_LAST,
                                G_CALLBACK (ide_build_pipeline_real_finished),
                                NULL, NULL, NULL,
                                G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
}

static void
ide_build_pipeline_init (IdeBuildPipeline *self)
{
1378
  DZL_COUNTER_INC (Instances);
1379

1380
1381
  self->cancellable = g_cancellable_new ();

1382
  self->position = -1;
1383
  self->pty_slave = -1;
1384
1385
1386
1387
1388
1389
1390

  self->pipeline = g_array_new (FALSE, FALSE, sizeof (PipelineEntry));
  g_array_set_clear_func (self->pipeline, clear_pipeline_entry);

  self->errfmts = g_array_new (FALSE, FALSE, sizeof (ErrorFormat));
  g_array_set_clear_func (self->errfmts, clear_error_format);

1391
1392
  self->chained_bindings = g_ptr_array_new_with_free_func ((GDestroyNotify)chained_binding_clear);

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
  self->log = ide_build_log_new ();
}

static void
ide_build_pipeline_stage_execute_cb (GObject      *object,
                                     GAsyncResult *result,
                                     gpointer      user_data)
{
  IdeBuildStage *stage = (IdeBuildStage *)object;
  IdeBuildPipeline *self;
  g_autoptr(GTask) task = user_data;
  g_autoptr(GError) error = NULL;

  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_STAGE (stage));
  g_assert (G_IS_ASYNC_RESULT (result));
  g_assert (G_IS_TASK (task));

  self = g_task_get_source_object (task);
  g_assert (IDE_IS_BUILD_PIPELINE (self));

  if (!_ide_build_stage_execute_with_query_finish (stage, result, &error))
    {
      g_debug ("stage of type %s failed: %s",
               G_OBJECT_TYPE_NAME (stage),
               error->message);
      self->failed = TRUE;
      g_task_return_error (task, g_steal_pointer (&error));
    }

1424
1425
1426
1427
1428
1429
1430
  ide_build_stage_set_completed (stage, !self->failed);

  g_clear_pointer (&self->chained_bindings, g_ptr_array_free);
  self->chained_bindings = g_ptr_array_new_with_free_func (g_object_unref);

  if (self->failed == FALSE)
    ide_build_pipeline_tick_execute (self, task);
1431
1432
1433
1434

  IDE_EXIT;
}

1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
static void
ide_build_pipeline_try_chain (IdeBuildPipeline *self,
                              IdeBuildStage    *stage,
                              guint             position)
{
  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (IDE_IS_BUILD_STAGE (stage));

  for (; position < self->pipeline->len; position++)
    {
      const PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, position);
      gboolean chained;
1447
      GBinding *chained_binding;
1448
1449
1450
1451
1452
1453
1454
1455

      /*
       * Ignore all future stages if they were not requested by the current
       * pipeline execution.
       */
      if (((entry->phase & IDE_BUILD_PHASE_MASK) & self->requested_mask) == 0)
        return;

1456
1457
1458
1459
      /* Skip past the stage if it is disabled. */
      if (ide_build_stage_get_disabled (entry->stage))
        continue;

1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
      chained = ide_build_stage_chain (stage, entry->stage);

      IDE_TRACE_MSG ("Checking if %s chains to stage[%d] (%s) = %s",
                     G_OBJECT_TYPE_NAME (stage),
                     position,
                     G_OBJECT_TYPE_NAME (entry->stage),
                     chained ? "yes" : "no");

      if (!chained)
        return;

1471
1472
      chained_binding = g_object_bind_property (stage, "completed", entry->stage, "completed", 0);
      g_ptr_array_add (self->chained_bindings, g_object_ref (chained_binding));
1473
1474
1475
1476
1477

      self->position = position;
    }
}

1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
static void
complete_queued_before_phase (IdeBuildPipeline *self,
                              IdeBuildPhase     phase)
{
  g_assert (IDE_IS_BUILD_PIPELINE (self));

  phase = phase & IDE_BUILD_PHASE_MASK;

  for (GList *iter = self->task_queue.head; iter; iter = iter->next)
    {
      GTask *task;
      TaskData *task_data;

1491
    again:
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
      task = iter->data;
      task_data = g_task_get_task_data (task);

      g_assert (G_IS_TASK (task));
      g_assert (task_data->task == task);

      /*
       * If this task has a phase that is less-than the phase given
       * to us, we can complete the task immediately.
       */
      if (task_data->phase < phase)
        {
          GList *to_remove = iter;

          iter = iter->next;
          g_queue_delete_link (&self->task_queue, to_remove);
          g_task_return_boolean (task, TRUE);
          g_object_unref (task);

          if (iter == NULL)
            break;

          goto again;
        }
    }
}

1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
static void
ide_build_pipeline_tick_execute (IdeBuildPipeline *self,
                                 GTask            *task)
{
  GCancellable *cancellable;
  TaskData *td;

  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (G_IS_TASK (task));

  self->current_stage = NULL;

  td = g_task_get_task_data (task);
  cancellable = g_task_get_cancellable (task);

  g_assert (td != NULL);
  g_assert (td->type == TASK_BUILD || td->type == TASK_REBUILD);
  g_assert (td->task == task);
  g_assert (td->phase != IDE_BUILD_PHASE_NONE);
  g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));

1542
1543
1544
  /* Clear any message from the previous stage */
  _ide_build_pipeline_set_message (self, NULL);

1545
1546
1547
1548
  /* Short circuit now if the task was cancelled */
  if (g_task_return_error_if_cancelled (task))
    IDE_EXIT;

1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
  /* If we can skip walking the pipeline, go ahead and do so now. */
  if (!ide_build_pipeline_request_phase (self, td->phase))
    {
      g_task_return_boolean (task, TRUE);
      IDE_EXIT;
    }

  /*
   * Walk forward to the next stage requiring execution and asynchronously
   * execute it. The stage may also need to perform an async ::query signal
   * delaying pipeline execution. _ide_build_stage_execute_with_query_async()
   * will handle all of that for us, in cause they call ide_build_stage_pause()
   * during the ::query callback.
   */
1563
  for (self->position++; (guint)self->position < self->pipeline->len; self->position++)
1564
1565
1566
1567
1568
1569
    {
      const PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, self->position);

      g_assert (entry->stage != NULL);
      g_assert (IDE_IS_BUILD_STAGE (entry->stage));

1570
1571
1572
      /* Complete any tasks that are waiting for this to complete */
      complete_queued_before_phase (self, entry->phase);

1573
1574
1575
1576
      /* Ignore the stage if it is disabled */
      if (ide_build_stage_get_disabled (entry->stage))
        continue;

1577
1578
1579
1580
      if ((entry->phase & IDE_BUILD_PHASE_MASK) & self->requested_mask)
        {
          self->current_stage = entry->stage;

1581
1582
1583
1584
1585
1586
1587
          /*
           * We might be able to chain upcoming stages to this stage and avoid
           * duplicate work. This will also advance self->position based on
           * how many stages were chained.
           */
          ide_build_pipeline_try_chain (self, entry->stage, self->position + 1);

1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
          _ide_build_stage_execute_with_query_async (entry->stage,
                                                     self,
                                                     cancellable,
                                                     ide_build_pipeline_stage_execute_cb,
                                                     g_object_ref (task));

          g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_MESSAGE]);
          g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_PHASE]);

          IDE_EXIT;
        }
    }

  g_task_return_boolean (task, TRUE);

  IDE_EXIT;
}

static void
ide_build_pipeline_task_notify_completed (IdeBuildPipeline *self,
                                          GParamSpec       *pspec,
                                          GTask            *task)
{
  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));
  g_assert (G_IS_TASK (task));

  IDE_TRACE_MSG ("Clearing busy bit for pipeline");

  self->current_stage = NULL;
  self->busy = FALSE;
  self->requested_mask = 0;
  self->in_clean = FALSE;

1623
1624
1625
  g_clear_pointer (&self->message, g_free);
  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_MESSAGE]);

1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
  /*
   * XXX: How do we ensure transients are executed with the part of the
   *      pipeline we care about? We might just need to ensure that :busy is
   *      FALSE before adding transients.
   */
  ide_build_pipeline_release_transients (self);

  g_signal_emit (self, signals [FINISHED], 0, self->failed);

  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_BUSY]);
  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_PHASE]);

  /*
   * We might have a delayed addin unloading that needs to occur after the
   * build operation completes. If the configuration is no longer valid,
   * go ahead and unload the pipeline.
   */
  if (!ide_configuration_get_ready (self->configuration))
    ide_build_pipeline_unload (self);
  else
    ide_build_pipeline_queue_flush (self);

  IDE_EXIT;
}

/**
1652
 * ide_build_pipeline_build_async:
1653
 * @self: A @IdeBuildPipeline
1654
 * @phase: the requested build phase
1655
 * @cancellable: (nullable): a #GCancellable or %NULL
1656
1657
1658
1659
1660
 * @callback: a callback to execute upon completion
 * @user_data: data for @callback
 *
 * Asynchronously starts the build pipeline.
 *
1661
1662
1663
1664
1665
1666
1667
1668
1669
 * The @phase parameter should contain the #IdeBuildPhase that is
 * necessary to complete. If you simply want to trigger a generic
 * build, you probably want %IDE_BUILD_PHASE_BUILD. If you only
 * need to configure the project (and necessarily the dependencies
 * up to that phase) you might want %IDE_BUILD_PHASE_CONFIGURE.
 *
 * You may not specify %IDE_BUILD_PHASE_AFTER or
 * %IDE_BUILD_PHASE_BEFORE flags as those must always be processed
 * with the underlying phase they are attached to.
1670
1671
1672
1673
 *
 * Upon completion, @callback will be executed and should call
 * ide_build_pipeline_execute_finish() to get the status of the
 * operation.
1674
1675
 *
 * Since: 3.28
1676
1677
 */
void
1678
1679
1680
1681
1682
ide_build_pipeline_build_async (IdeBuildPipeline    *self,
                                IdeBuildPhase        phase,
                                GCancellable        *cancellable,
                                GAsyncReadyCallback  callback,
                                gpointer             user_data)
1683
1684
1685
1686
1687
1688
{
  g_autoptr(GTask) task = NULL;
  TaskData *task_data;

  IDE_ENTRY;

1689
1690
1691
1692
  g_return_if_fail (IDE_IS_BUILD_PIPELINE (self));
  g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable));

  cancellable = dzl_cancellable_chain (cancellable, self->cancellable);
1693

1694
  task = g_task_new (self, cancellable, callback, user_data);
1695
  g_task_set_source_tag (task, ide_build_pipeline_build_async);
1696
  g_task_set_priority (task, G_PRIORITY_LOW);
1697

1698
1699
  if (!ide_build_pipeline_check_ready (self, task))
    return;
1700

1701
  /*
1702
1703
1704
   * If the requested phase has already been met (by a previous build
   * or by an active build who has already surpassed this build phase,
   * we can return a result immediately.
1705
1706
1707
   *
   * Only short circuit if we're running a build, otherwise we need to
   * touch each entry and ::query() to see if it needs execution.
1708
   */
1709
1710

  if (self->busy && !self->in_clean)
1711
    {
1712
1713
1714
1715
1716
1717
1718
      if (self->position >= self->pipeline->len)
        {
          goto short_circuit;
        }
      else if (self->position >= 0)
        {
          const PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, self->position);
1719

1720
1721
1722
1723
1724
1725
          /* This phase is past the requested phase, we can complete the
           * task immediately.
           */
          if (entry->phase > phase)
            goto short_circuit;
        }
1726
    }
1727
1728

  task_data = task_data_new (task, TASK_BUILD);
1729
  task_data->phase = 1 << g_bit_nth_msf (phase, -1);
1730
1731
1732
1733
1734
  g_task_set_task_data (task, task_data, task_data_free);

  g_queue_push_tail (&self->task_queue, g_steal_pointer (&task));

  ide_build_pipeline_queue_flush (self);
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745

  IDE_EXIT;

short_circuit:
  g_task_return_boolean (task, TRUE);
  IDE_EXIT;
}

/**
 * ide_build_pipeline_build_finish:
 * @self: An #IdeBuildPipeline
1746
 * @result: a #GAsyncResult provided to callback
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
 * @error: A location for a #GError, or %NULL
 *
 * This function completes the asynchronous request to build
 * up to a particular phase of the build pipeline.
 *
 * Returns: %TRUE if the build stages were executed successfully
 *   up to the requested build phase provided to
 *   ide_build_pipeline_build_async().
 *
 * Since: 3.28
 */
gboolean
ide_build_pipeline_build_finish (IdeBuildPipeline  *self,
                                 GAsyncResult      *result,
                                 GError           **error)
{
  gboolean ret;

  IDE_ENTRY;

  g_return_val_if_fail (IDE_IS_BUILD_PIPELINE (self), FALSE);
  g_return_val_if_fail (G_IS_TASK (result), FALSE);

  ret = g_task_propagate_boolean (G_TASK (result), error);

  IDE_RETURN (ret);
}

/**
 * ide_build_pipeline_execute_async:
 * @self: A @IdeBuildPipeline
1778
 * @cancellable: (nullable): a #GCancellable or %NULL
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
 * @callback: a callback to execute upon completion
 * @user_data: data for @callback
 *
 * Asynchronously starts the build pipeline.
 *
 * Any phase that has been invalidated up to the requested phase
 * will be executed until a stage has failed.
 *
 * Upon completion, @callback will be executed and should call
 * ide_build_pipeline_execute_finish() to get the status of the
 * operation.
 *
 * Since: 3.24
 */
void
ide_build_pipeline_execute_async (IdeBuildPipeline    *self,
                                  GCancellable        *cancellable,
                                  GAsyncReadyCallback  callback,
                                  gpointer             user_data)
{
  IDE_ENTRY;

  g_return_if_fail (IDE_IS_BUILD_PIPELINE (self));
  g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable));

  ide_build_pipeline_build_async (self, self->requested_mask, cancellable, callback, user_data);

  IDE_EXIT;
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
}

static gboolean
ide_build_pipeline_do_flush (gpointer data)
{
  IdeBuildPipeline *self = data;
  g_autoptr(GTask) task = NULL;
  g_autoptr(GFile) builddir = NULL;
  g_autoptr(GError) error = NULL;
  TaskData *task_data;

  IDE_ENTRY;

  g_assert (IDE_IS_BUILD_PIPELINE (self));

  /*
   * If the busy bit is set, there is nothing to do right now.
   */
  if (self->busy)
1826
1827
1828
1829
    {
      IDE_TRACE_MSG ("pipeline already busy, defering flush");
      IDE_RETURN (G_SOURCE_REMOVE);
    }
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851

  /* Ensure our builddir is created, or else we will fail all pending tasks. */
  builddir = g_file_new_for_path (self->builddir);
  if (!g_file_make_directory_with_parents (builddir, NULL, &error) &&
      !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS))
    {
      GTask *failed_task;

      while (NULL != (failed_task = g_queue_pop_head (&self->task_queue)))
        {
          g_task_return_error (failed_task, g_error_copy (error));
          g_object_unref (failed_task);
        }

      IDE_RETURN (G_SOURCE_REMOVE);
    }

  /*
   * Pop the next task off the queue from the head (we push to the
   * tail and we want FIFO semantics).
   */
  task = g_queue_pop_head (&self->task_queue);
1852

1853
  if (task == NULL)
1854
1855
1856
1857
    {
      IDE_TRACE_MSG ("No tasks to process");
      IDE_RETURN (G_SOURCE_REMOVE);
    }
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879

  g_assert (G_IS_TASK (task));
  g_assert (self->busy == FALSE);

  /*
   * Now prepare the task so that when it completes we can make
   * forward progress again.
   */
  g_signal_connect_object (task,
                           "notify::completed",
                           G_CALLBACK (ide_build_pipeline_task_notify_completed),
                           self,
                           G_CONNECT_SWAPPED);

  /* We need access to the task data to determine how to process the task. */
  task_data = g_task_get_task_data (task);

  g_assert (task_data != NULL);
  g_assert (task_data->type > 0);
  g_assert (task_data->type <= TASK_REBUILD);
  g_assert (G_IS_TASK (task_data->task));

1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
  /*
   * If this build request could cause us to spin while we are continually
   * failing to reach the CONFIGURE stage, protect ourselves as early as we
   * can. We'll defer to a rebuild request to cause the full thing to build.
   */
  if (self->failed &&
      task_data->type == TASK_BUILD &&
      task_data->phase <= IDE_BUILD_PHASE_CONFIGURE)
    {
      g_task_return_new_error (task,
                               G_IO_ERROR,
                               G_IO_ERROR_FAILED,
                               "The build pipeline is in a failed state and requires a rebuild");
      IDE_RETURN (G_SOURCE_REMOVE);
    }

1896
1897
1898
1899
1900
1901
1902
1903
1904
  /*
   * Now mark the pipeline as busy to protect ourself from anything recursively
   * calling into the pipeline.
   */
  self->busy = TRUE;
  self->failed = FALSE;
  self->position = -1;
  self->in_clean = (task_data->type == TASK_CLEAN);

1905
1906
1907
  /* Clear any lingering message */
  g_clear_pointer (&self->message, g_free);

1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
  /*
   * The following logs some helpful information about the build to our
   * debug log. This is useful to allow users to debug some problems
   * with our assistance (using gnome-builder -vvv).
   */
  {
    g_autoptr(GString) str = g_string_new (NULL);
    GFlagsClass *klass;
    IdeBuildPhase phase = self->requested_mask;

    klass = g_type_class_peek (IDE_TYPE_BUILD_PHASE);

    for (guint i = 0; i < klass->n_values; i++)
      {
        const GFlagsValue *value = &klass->values[i];

        if (phase & value->value)
          {
            if (str->len > 0)
              g_string_append (str, ", ");
            g_string_append (str, value->value_nick);
          }
      }

    g_debug ("Executing pipeline %s stages %s with %u pipeline entries",
             task_type_names[task_data->type],
             str->str,
             self->pipeline->len);

    for (guint i = 0; i < self->pipeline->len; i++)
      {
        const PipelineEntry *entry = &g_array_index (self->pipeline, PipelineEntry, i);

        g_debug (" pipeline[%u]: %12s: %s [%s]",
                 i,
                 build_phase_nick (entry->phase),
                 G_OBJECT_TYPE_NAME (entry->stage),
                 ide_build_stage_get_completed (entry->stage) ? "completed" : "pending");
      }
  }

1949
1950
  /* Notify any observers that a build (of some sort) is about to start. */
  g_signal_emit (self, signals [STARTED], 0, task_data->phase);
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970

  switch (task_data->type)
    {
    case TASK_BUILD:
      ide_build_pipeline_tick_execute (self, task);
      break;

    case TASK_CLEAN:
      ide_build_pipeline_tick_clean (self, task);
      break;

    case TASK_REBUILD:
      ide_build_pipeline_tick_rebuild (self, task);
      break;

    default:
      g_assert_not_reached ();
    }

  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_BUSY]);