aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-web/src/main/js/app/components/ComponentContainer.tsx
blob: 181517004f8f19fe163003cffe0833dc156d1393 (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
/*
 * SonarQube
 * Copyright (C) 2009-2022 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
import { differenceBy } from 'lodash';
import * as React from 'react';
import { Outlet } from 'react-router-dom';
import { getProjectAlmBinding, validateProjectAlmBinding } from '../../api/alm-settings';
import { getBranches, getPullRequests } from '../../api/branches';
import { getAnalysisStatus, getTasksForComponent } from '../../api/ce';
import { getComponentData } from '../../api/components';
import { getComponentNavigation } from '../../api/navigation';
import { Location, Router, withRouter } from '../../components/hoc/withRouter';
import {
  getBranchLikeQuery,
  isBranch,
  isMainBranch,
  isPullRequest,
} from '../../helpers/branch-like';
import { HttpStatus } from '../../helpers/request';
import { getPortfolioUrl } from '../../helpers/urls';
import {
  ProjectAlmBindingConfigurationErrors,
  ProjectAlmBindingResponse,
} from '../../types/alm-settings';
import { BranchLike } from '../../types/branch-like';
import { ComponentQualifier, isPortfolioLike } from '../../types/component';
import { Feature } from '../../types/features';
import { Task, TaskStatuses, TaskTypes, TaskWarning } from '../../types/tasks';
import { Component, Status } from '../../types/types';
import handleRequiredAuthorization from '../utils/handleRequiredAuthorization';
import withAvailableFeatures, {
  WithAvailableFeaturesProps,
} from './available-features/withAvailableFeatures';
import withBranchStatusActions from './branch-status/withBranchStatusActions';
import ComponentContainerNotFound from './ComponentContainerNotFound';
import { ComponentContext } from './componentContext/ComponentContext';
import PageUnavailableDueToIndexation from './indexation/PageUnavailableDueToIndexation';
import ComponentNav from './nav/component/ComponentNav';

interface Props extends WithAvailableFeaturesProps {
  location: Location;
  updateBranchStatus: (branchLike: BranchLike, component: string, status: Status) => void;
  router: Router;
}

interface State {
  branchLike?: BranchLike;
  branchLikes: BranchLike[];
  component?: Component;
  currentTask?: Task;
  isPending: boolean;
  loading: boolean;
  projectBinding?: ProjectAlmBindingResponse;
  projectBindingErrors?: ProjectAlmBindingConfigurationErrors;
  tasksInProgress?: Task[];
  warnings: TaskWarning[];
}

const FETCH_STATUS_WAIT_TIME = 3000;

export class ComponentContainer extends React.PureComponent<Props, State> {
  watchStatusTimer?: number;
  mounted = false;
  state: State = { branchLikes: [], isPending: false, loading: true, warnings: [] };

  componentDidMount() {
    this.mounted = true;
    this.fetchComponent();
  }

  componentDidUpdate(prevProps: Props) {
    if (
      prevProps.location.query.id !== this.props.location.query.id ||
      prevProps.location.query.branch !== this.props.location.query.branch ||
      prevProps.location.query.pullRequest !== this.props.location.query.pullRequest
    ) {
      this.fetchComponent();
    }
  }

  componentWillUnmount() {
    this.mounted = false;
    window.clearTimeout(this.watchStatusTimer);
  }

  fetchComponent = async () => {
    const { branch, id: key, pullRequest } = this.props.location.query;
    this.setState({ loading: true });

    let componentWithQualifier;
    try {
      const [nav, { component }] = await Promise.all([
        getComponentNavigation({ component: key, branch, pullRequest }),
        getComponentData({ component: key, branch, pullRequest }),
      ]);
      componentWithQualifier = this.addQualifier({ ...nav, ...component });
    } catch (e) {
      if (this.mounted) {
        if (e && e instanceof Response && e.status === HttpStatus.Forbidden) {
          handleRequiredAuthorization();
        } else {
          this.setState({ component: undefined, loading: false });
        }
      }
      return;
    }

    /*
     * There used to be a redirect from /dashboard to /portfolio which caused issues.
     * Links should be fixed to not rely on this redirect, but:
     * This is a fail-safe in case there are still some faulty links remaining.
     */
    if (
      this.props.location.pathname.match('dashboard') &&
      isPortfolioLike(componentWithQualifier.qualifier)
    ) {
      this.props.router.replace(getPortfolioUrl(componentWithQualifier.key));
    }

    const { branchLike, branchLikes } = await this.fetchBranches(componentWithQualifier);

    let projectBinding;
    if (componentWithQualifier.qualifier === ComponentQualifier.Project) {
      projectBinding = await getProjectAlmBinding(key).catch(() => undefined);
    }

    if (this.mounted) {
      this.setState({
        branchLike,
        branchLikes,
        component: componentWithQualifier,
        projectBinding,
        loading: false,
      });

      this.fetchStatus(componentWithQualifier.key);
      this.fetchWarnings(componentWithQualifier, branchLike);
      this.fetchProjectBindingErrors(componentWithQualifier);
    }
  };

  fetchBranches = async (componentWithQualifier: Component) => {
    const { hasFeature } = this.props;

    const breadcrumb = componentWithQualifier.breadcrumbs.find(({ qualifier }) => {
      return ([ComponentQualifier.Application, ComponentQualifier.Project] as string[]).includes(
        qualifier
      );
    });

    let branchLike = undefined;
    let branchLikes: BranchLike[] = [];

    if (breadcrumb) {
      const { key } = breadcrumb;
      const [branches, pullRequests] = await Promise.all([
        getBranches(key),
        !hasFeature(Feature.BranchSupport) ||
        breadcrumb.qualifier === ComponentQualifier.Application
          ? Promise.resolve([])
          : getPullRequests(key),
      ]);

      branchLikes = [...branches, ...pullRequests];
      branchLike = this.getCurrentBranchLike(branchLikes);

      this.registerBranchStatuses(branchLikes, componentWithQualifier);
    }

    return { branchLike, branchLikes };
  };

  fetchStatus = (componentKey: string) => {
    getTasksForComponent(componentKey).then(
      ({ current, queue }) => {
        if (this.mounted) {
          let shouldFetchComponent = false;
          this.setState(
            ({ branchLike, component, currentTask, tasksInProgress }) => {
              const newCurrentTask = this.getCurrentTask(current, branchLike);
              const pendingTasks = this.getPendingTasksForBranchLike(queue, branchLike);
              const newTasksInProgress = this.getInProgressTasks(pendingTasks);

              shouldFetchComponent = this.computeShouldFetchComponent(
                tasksInProgress,
                newTasksInProgress,
                currentTask,
                newCurrentTask,
                component
              );

              if (this.needsAnotherCheck(shouldFetchComponent, component, newTasksInProgress)) {
                // Refresh the status as long as there is tasks in progress or no analysis
                window.clearTimeout(this.watchStatusTimer);
                this.watchStatusTimer = window.setTimeout(
                  () => this.fetchStatus(componentKey),
                  FETCH_STATUS_WAIT_TIME
                );
              }

              const isPending = pendingTasks.some((task) => task.status === TaskStatuses.Pending);
              return {
                currentTask: newCurrentTask,
                isPending,
                tasksInProgress: newTasksInProgress,
              };
            },
            () => {
              if (shouldFetchComponent) {
                this.fetchComponent();
              }
            }
          );
        }
      },
      () => {}
    );
  };

  fetchWarnings = (component: Component, branchLike?: BranchLike) => {
    if (component.qualifier === ComponentQualifier.Project) {
      getAnalysisStatus({
        component: component.key,
        ...getBranchLikeQuery(branchLike),
      }).then(
        ({ component }) => {
          this.setState({ warnings: component.warnings });
        },
        () => {}
      );
    }
  };

  fetchProjectBindingErrors = async (component: Component) => {
    if (
      component.qualifier === ComponentQualifier.Project &&
      component.analysisDate === undefined &&
      this.props.hasFeature(Feature.BranchSupport)
    ) {
      const projectBindingErrors = await validateProjectAlmBinding(component.key).catch(
        () => undefined
      );
      if (this.mounted) {
        this.setState({ projectBindingErrors });
      }
    }
  };

  addQualifier = (component: Component) => ({
    ...component,
    qualifier: component.breadcrumbs[component.breadcrumbs.length - 1].qualifier,
  });

  getCurrentBranchLike = (branchLikes: BranchLike[]) => {
    const { query } = this.props.location;
    return query.pullRequest
      ? branchLikes.find((b) => isPullRequest(b) && b.key === query.pullRequest)
      : branchLikes.find((b) => isBranch(b) && (query.branch ? b.name === query.branch : b.isMain));
  };

  getCurrentTask = (current: Task, branchLike?: BranchLike) => {
    if (!current || !this.isReportRelatedTask(current)) {
      return undefined;
    }

    return current.status === TaskStatuses.Failed || this.isSameBranch(current, branchLike)
      ? current
      : undefined;
  };

  getPendingTasksForBranchLike = (pendingTasks: Task[], branchLike?: BranchLike) => {
    return pendingTasks.filter(
      (task) => this.isReportRelatedTask(task) && this.isSameBranch(task, branchLike)
    );
  };

  getInProgressTasks = (pendingTasks: Task[]) => {
    return pendingTasks.filter((task) => task.status === TaskStatuses.InProgress);
  };

  isReportRelatedTask = (task: Task) => {
    return [TaskTypes.AppRefresh, TaskTypes.Report, TaskTypes.ViewRefresh].includes(task.type);
  };

  computeShouldFetchComponent = (
    tasksInProgress: Task[] | undefined,
    newTasksInProgress: Task[],
    currentTask: Task | undefined,
    newCurrentTask: Task | undefined,
    component: Component | undefined
  ) => {
    const progressHasChanged = Boolean(
      tasksInProgress &&
        (newTasksInProgress.length !== tasksInProgress.length ||
          differenceBy(newTasksInProgress, tasksInProgress, 'id').length > 0)
    );

    const currentTaskHasChanged = Boolean(
      (!currentTask && newCurrentTask) ||
        (currentTask && newCurrentTask && currentTask.id !== newCurrentTask.id)
    );

    if (progressHasChanged) {
      return true;
    } else if (currentTaskHasChanged && component) {
      // We return true if:
      // - there was no prior analysis date (means this is an empty project, and
      //   a new analysis came in)
      // - OR, there was a prior analysis date (non-empty project) AND there were
      //   some tasks in progress before
      return (
        Boolean(!component.analysisDate) ||
        Boolean(component.analysisDate && tasksInProgress?.length)
      );
    }
    return false;
  };

  needsAnotherCheck = (
    shouldFetchComponent: boolean,
    component: Component | undefined,
    newTasksInProgress: Task[]
  ) => {
    return (
      !shouldFetchComponent &&
      component &&
      (newTasksInProgress.length > 0 || !component.analysisDate)
    );
  };

  isSameBranch = (task: Pick<Task, 'branch' | 'pullRequest'>, branchLike?: BranchLike) => {
    if (branchLike) {
      if (isMainBranch(branchLike)) {
        return (!task.pullRequest && !task.branch) || branchLike.name === task.branch;
      }
      if (isPullRequest(branchLike)) {
        return branchLike.key === task.pullRequest;
      }
      if (isBranch(branchLike)) {
        return branchLike.name === task.branch;
      }
    }
    return !task.branch && !task.pullRequest;
  };

  registerBranchStatuses = (branchLikes: BranchLike[], component: Component) => {
    branchLikes.forEach((branchLike) => {
      if (branchLike.status) {
        this.props.updateBranchStatus(
          branchLike,
          component.key,
          branchLike.status.qualityGateStatus
        );
      }
    });
  };

  handleComponentChange = (changes: Partial<Component>) => {
    if (this.mounted) {
      this.setState((state) => {
        if (state.component) {
          const newComponent: Component = { ...state.component, ...changes };
          return { component: newComponent };
        }
        return null;
      });
    }
  };

  handleBranchesChange = () => {
    if (this.mounted && this.state.component) {
      this.fetchBranches(this.state.component).then(
        ({ branchLike, branchLikes }) => {
          if (this.mounted) {
            this.setState({ branchLike, branchLikes });
          }
        },
        () => {}
      );
    }
  };

  handleWarningDismiss = () => {
    const { component } = this.state;
    if (component !== undefined) {
      this.fetchWarnings(component);
    }
  };

  render() {
    const { component, loading } = this.state;

    if (!loading && !component) {
      return <ComponentContainerNotFound />;
    }

    if (component?.needIssueSync) {
      return <PageUnavailableDueToIndexation component={component} />;
    }

    const {
      branchLike,
      branchLikes,
      currentTask,
      isPending,
      projectBinding,
      projectBindingErrors,
      tasksInProgress,
      warnings,
    } = this.state;
    const isInProgress = tasksInProgress && tasksInProgress.length > 0;

    return (
      <div>
        {component &&
          !([ComponentQualifier.File, ComponentQualifier.TestFile] as string[]).includes(
            component.qualifier
          ) && (
            <ComponentNav
              branchLikes={branchLikes}
              component={component}
              currentBranchLike={branchLike}
              currentTask={currentTask}
              currentTaskOnSameBranch={currentTask && this.isSameBranch(currentTask, branchLike)}
              isInProgress={isInProgress}
              isPending={isPending}
              onComponentChange={this.handleComponentChange}
              onWarningDismiss={this.handleWarningDismiss}
              projectBinding={projectBinding}
              projectBindingErrors={projectBindingErrors}
              warnings={warnings}
            />
          )}
        {loading ? (
          <div className="page page-limited">
            <i className="spinner" />
          </div>
        ) : (
          <ComponentContext.Provider
            value={{
              branchLike,
              branchLikes,
              component,
              isInProgress,
              isPending,
              onBranchesChange: this.handleBranchesChange,
              onComponentChange: this.handleComponentChange,
              projectBinding,
            }}
          >
            <Outlet />
          </ComponentContext.Provider>
        )}
      </div>
    );
  }
}

export default withRouter(withAvailableFeatures(withBranchStatusActions(ComponentContainer)));