3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.ce.task.projectanalysis.issue;
22 import com.google.common.annotations.VisibleForTesting;
23 import com.google.common.base.Preconditions;
24 import java.util.Date;
25 import java.util.Optional;
26 import javax.inject.Inject;
27 import org.sonar.api.issue.Issue;
28 import org.sonar.api.rules.RuleType;
29 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
30 import org.sonar.core.issue.DefaultIssue;
31 import org.sonar.core.issue.DefaultIssueComment;
32 import org.sonar.core.issue.FieldDiffs;
33 import org.sonar.core.issue.IssueChangeContext;
34 import org.sonar.core.util.Uuids;
35 import org.sonar.db.component.BranchType;
36 import org.sonar.server.issue.IssueFieldsSetter;
37 import org.sonar.server.issue.workflow.IssueWorkflow;
39 import static java.util.Objects.requireNonNull;
42 * Sets the appropriate fields when an issue is :
44 * <li>newly created</li>
45 * <li>merged the related base issue</li>
46 * <li>relocated (only manual issues)</li>
49 public class IssueLifecycle {
51 private final IssueWorkflow workflow;
52 private final IssueChangeContext changeContext;
53 private final RuleRepository ruleRepository;
54 private final IssueFieldsSetter updater;
55 private final DebtCalculator debtCalculator;
56 private final AnalysisMetadataHolder analysisMetadataHolder;
59 public IssueLifecycle(AnalysisMetadataHolder analysisMetadataHolder, IssueWorkflow workflow, IssueFieldsSetter updater, DebtCalculator debtCalculator,
60 RuleRepository ruleRepository) {
61 this(analysisMetadataHolder, IssueChangeContext.createScan(new Date(analysisMetadataHolder.getAnalysisDate())), workflow, updater, debtCalculator, ruleRepository);
64 @VisibleForTesting IssueLifecycle(AnalysisMetadataHolder analysisMetadataHolder, IssueChangeContext changeContext, IssueWorkflow workflow, IssueFieldsSetter updater,
65 DebtCalculator debtCalculator, RuleRepository ruleRepository) {
66 this.analysisMetadataHolder = analysisMetadataHolder;
67 this.workflow = workflow;
68 this.updater = updater;
69 this.debtCalculator = debtCalculator;
70 this.changeContext = changeContext;
71 this.ruleRepository = ruleRepository;
74 public void initNewOpenIssue(DefaultIssue issue) {
75 Preconditions.checkArgument(issue.isFromExternalRuleEngine() != (issue.type() == null), "At this stage issue type should be set for and only for external issues");
76 Rule rule = ruleRepository.getByKey(issue.ruleKey());
77 issue.setKey(Uuids.create());
78 issue.setCreationDate(changeContext.date());
79 issue.setUpdateDate(changeContext.date());
80 issue.setEffort(debtCalculator.calculate(issue));
82 setStatus(issue, rule);
85 private static void setType(DefaultIssue issue, Rule rule) {
86 if (issue.isFromExternalRuleEngine()) {
89 issue.setType(requireNonNull(rule.getType(), "No rule type"));
92 private static void setStatus(DefaultIssue issue, Rule rule) {
93 if (rule.getType() == RuleType.SECURITY_HOTSPOT || issue.type() == RuleType.SECURITY_HOTSPOT) {
94 issue.setStatus(Issue.STATUS_TO_REVIEW);
96 issue.setStatus(Issue.STATUS_OPEN);
100 public void copyExistingOpenIssueFromBranch(DefaultIssue raw, DefaultIssue base, String branchName) {
101 raw.setKey(Uuids.create());
103 copyAttributesOfIssueFromAnotherBranch(raw, base);
104 raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, branchName, analysisMetadataHolder.getBranch().getName());
107 public void mergeConfirmedOrResolvedFromPrOrBranch(DefaultIssue raw, DefaultIssue base, BranchType branchType, String prOrBranchKey) {
108 copyAttributesOfIssueFromAnotherBranch(raw, base);
109 String from = (branchType == BranchType.PULL_REQUEST) ? "#" + prOrBranchKey : prOrBranchKey;
110 String to = analysisMetadataHolder.isPullRequest() ? ("#" + analysisMetadataHolder.getPullRequestKey()) : analysisMetadataHolder.getBranch().getName();
111 raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, from, to);
114 public void copyExistingIssueFromSourceBranchToPullRequest(DefaultIssue raw, DefaultIssue base) {
115 Preconditions.checkState(analysisMetadataHolder.isPullRequest(), "This operation should be done only on pull request analysis");
116 copyAttributesOfIssueFromAnotherBranch(raw, base);
117 String from = analysisMetadataHolder.getBranch().getName();
118 String to = "#" + analysisMetadataHolder.getPullRequestKey();
119 raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, from, to);
122 public void copyAttributesOfIssueFromAnotherBranch(DefaultIssue to, DefaultIssue from) {
124 copyFields(to, from);
125 if (from.manualSeverity()) {
126 to.setManualSeverity(true);
127 to.setSeverity(from.severity());
129 copyChangesOfIssueFromOtherBranch(to, from);
132 private static void copyChangesOfIssueFromOtherBranch(DefaultIssue raw, DefaultIssue base) {
133 base.defaultIssueComments().forEach(c -> raw.addComment(copyComment(raw.key(), c)));
134 base.changes().forEach(c -> copyFieldDiffOfIssueFromOtherBranch(raw.key(), c).ifPresent(raw::addChange));
138 * Copy a comment from another issue
140 private static DefaultIssueComment copyComment(String issueKey, DefaultIssueComment c) {
141 DefaultIssueComment comment = new DefaultIssueComment();
142 comment.setIssueKey(issueKey);
143 comment.setKey(Uuids.create());
144 comment.setUserUuid(c.userUuid());
145 comment.setMarkdownText(c.markdownText());
146 comment.setCreatedAt(c.createdAt()).setUpdatedAt(c.updatedAt());
147 comment.setNew(true);
152 * Copy a diff from another issue
154 private static Optional<FieldDiffs> copyFieldDiffOfIssueFromOtherBranch(String issueKey, FieldDiffs c) {
155 FieldDiffs result = new FieldDiffs();
156 result.setIssueKey(issueKey);
157 result.setUserUuid(c.userUuid());
158 result.setCreationDate(c.creationDate());
159 // Don't copy "file" changelogs as they refer to file uuids that might later be purged
160 c.diffs().entrySet().stream()
161 .filter(e -> !e.getKey().equals(IssueFieldsSetter.FILE))
162 .forEach(e -> result.setDiff(e.getKey(), e.getValue().oldValue(), e.getValue().newValue()));
163 if (result.diffs().isEmpty()) {
164 return Optional.empty();
166 return Optional.of(result);
169 public void mergeExistingOpenIssue(DefaultIssue raw, DefaultIssue base) {
170 Preconditions.checkArgument(raw.isFromExternalRuleEngine() != (raw.type() == null), "At this stage issue type should be set for and only for external issues");
171 Rule rule = ruleRepository.getByKey(raw.ruleKey());
172 raw.setKey(base.key());
174 if (base.isChanged()) {
175 // In case issue was moved from module or folder to the root project
176 raw.setChanged(true);
179 copyFields(raw, base);
180 base.changes().forEach(raw::addChange);
182 if (base.manualSeverity()) {
183 raw.setManualSeverity(true);
184 raw.setSeverity(base.severity());
186 updater.setPastSeverity(raw, base.severity(), changeContext);
188 // set component/module related fields from base in case current component has been moved
189 // (in which case base issue belongs to original file and raw issue to component)
190 raw.setComponentUuid(base.componentUuid());
191 raw.setComponentKey(base.componentKey());
192 raw.setModuleUuid(base.moduleUuid());
193 raw.setModuleUuidPath(base.moduleUuidPath());
195 // fields coming from raw
196 updater.setPastLine(raw, base.getLine());
197 updater.setPastLocations(raw, base.getLocations());
198 updater.setPastMessage(raw, base.getMessage(), changeContext);
199 updater.setPastGap(raw, base.gap(), changeContext);
200 updater.setPastEffort(raw, base.effort(), changeContext);
203 public void doAutomaticTransition(DefaultIssue issue) {
204 workflow.doAutomaticTransition(issue, changeContext);
207 private void copyFields(DefaultIssue toIssue, DefaultIssue fromIssue) {
208 toIssue.setType(fromIssue.type());
209 toIssue.setCreationDate(fromIssue.creationDate());
210 toIssue.setUpdateDate(fromIssue.updateDate());
211 toIssue.setCloseDate(fromIssue.closeDate());
212 toIssue.setResolution(fromIssue.resolution());
213 toIssue.setStatus(fromIssue.status());
214 toIssue.setAssigneeUuid(fromIssue.assignee());
215 toIssue.setAuthorLogin(fromIssue.authorLogin());
216 toIssue.setTags(fromIssue.tags());
217 toIssue.setAttributes(fromIssue.attributes());
218 toIssue.setEffort(debtCalculator.calculate(toIssue));
219 toIssue.setOnDisabledRule(fromIssue.isOnDisabledRule());
220 toIssue.setSelectedAt(fromIssue.selectedAt());
221 toIssue.setIsNewCodeReferenceIssue(fromIssue.isNewCodeReferenceIssue());