]> source.dussan.org Git - sonarqube.git/blob
b57b06cbd0096b0167f6f0b3dd8b4734e31b5c18
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2022 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.ce.task.projectanalysis.issue;
21
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;
38
39 import static java.util.Objects.requireNonNull;
40
41 /**
42  * Sets the appropriate fields when an issue is :
43  * <ul>
44  * <li>newly created</li>
45  * <li>merged the related base issue</li>
46  * <li>relocated (only manual issues)</li>
47  * </ul>
48  */
49 public class IssueLifecycle {
50
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;
57
58   @Inject
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);
62   }
63
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;
72   }
73
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));
81     setType(issue, rule);
82     setStatus(issue, rule);
83   }
84
85   private static void setType(DefaultIssue issue, Rule rule) {
86     if (issue.isFromExternalRuleEngine()) {
87       return;
88     }
89     issue.setType(requireNonNull(rule.getType(), "No rule type"));
90   }
91
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);
95     } else {
96       issue.setStatus(Issue.STATUS_OPEN);
97     }
98   }
99
100   public void copyExistingOpenIssueFromBranch(DefaultIssue raw, DefaultIssue base, String branchName) {
101     raw.setKey(Uuids.create());
102     raw.setNew(false);
103     copyAttributesOfIssueFromAnotherBranch(raw, base);
104     raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, branchName, analysisMetadataHolder.getBranch().getName());
105   }
106
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);
112   }
113
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);
120   }
121
122   public void copyAttributesOfIssueFromAnotherBranch(DefaultIssue to, DefaultIssue from) {
123     to.setCopied(true);
124     copyFields(to, from);
125     if (from.manualSeverity()) {
126       to.setManualSeverity(true);
127       to.setSeverity(from.severity());
128     }
129     copyChangesOfIssueFromOtherBranch(to, from);
130   }
131
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));
135   }
136
137   /**
138    * Copy a comment from another issue
139    */
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);
148     return comment;
149   }
150
151   /**
152    * Copy a diff from another issue
153    */
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();
165     }
166     return Optional.of(result);
167   }
168
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());
173     raw.setNew(false);
174     if (base.isChanged()) {
175       // In case issue was moved from module or folder to the root project
176       raw.setChanged(true);
177     }
178     setType(raw, rule);
179     copyFields(raw, base);
180     base.changes().forEach(raw::addChange);
181
182     if (base.manualSeverity()) {
183       raw.setManualSeverity(true);
184       raw.setSeverity(base.severity());
185     } else {
186       updater.setPastSeverity(raw, base.severity(), changeContext);
187     }
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());
194
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);
201   }
202
203   public void doAutomaticTransition(DefaultIssue issue) {
204     workflow.doAutomaticTransition(issue, changeContext);
205   }
206
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());
222   }
223 }