3 * Copyright (C) 2009-2024 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.step;
22 import java.util.Collection;
23 import java.util.Date;
25 import java.util.Optional;
27 import java.util.function.Function;
28 import java.util.stream.Collectors;
29 import org.apache.commons.lang.StringUtils;
30 import org.sonar.api.resources.Qualifiers;
31 import org.sonar.api.resources.Scopes;
32 import org.sonar.api.utils.System2;
33 import org.sonar.ce.task.projectanalysis.component.BranchPersister;
34 import org.sonar.ce.task.projectanalysis.component.Component;
35 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
36 import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder;
37 import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
38 import org.sonar.ce.task.projectanalysis.component.PathAwareVisitor;
39 import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
40 import org.sonar.ce.task.projectanalysis.component.ProjectPersister;
41 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
42 import org.sonar.ce.task.step.ComputationStep;
43 import org.sonar.db.DbClient;
44 import org.sonar.db.DbSession;
45 import org.sonar.db.component.ComponentDto;
46 import org.sonar.db.component.ComponentUpdateDto;
48 import static java.util.Optional.ofNullable;
49 import static org.sonar.api.resources.Qualifiers.PROJECT;
50 import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
51 import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
52 import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent;
55 * Persist report components
57 public class PersistComponentsStep implements ComputationStep {
58 private final DbClient dbClient;
59 private final TreeRootHolder treeRootHolder;
60 private final System2 system2;
61 private final MutableDisabledComponentsHolder disabledComponentsHolder;
62 private final BranchPersister branchPersister;
63 private final ProjectPersister projectPersister;
65 public PersistComponentsStep(DbClient dbClient, TreeRootHolder treeRootHolder, System2 system2,
66 MutableDisabledComponentsHolder disabledComponentsHolder, BranchPersister branchPersister, ProjectPersister projectPersister) {
67 this.dbClient = dbClient;
68 this.treeRootHolder = treeRootHolder;
69 this.system2 = system2;
70 this.disabledComponentsHolder = disabledComponentsHolder;
71 this.branchPersister = branchPersister;
72 this.projectPersister = projectPersister;
76 public String getDescription() {
77 return "Persist components";
81 public void execute(ComputationStep.Context context) {
82 try (DbSession dbSession = dbClient.openSession(false)) {
83 branchPersister.persist(dbSession);
84 projectPersister.persist(dbSession);
86 String projectUuid = treeRootHolder.getRoot().getUuid();
88 // safeguard, reset all rows to b-changed=false
89 dbClient.componentDao().resetBChangedForBranchUuid(dbSession, projectUuid);
91 Map<String, ComponentDto> existingDtosByUuids = indexExistingDtosByUuids(dbSession);
92 boolean isRootPrivate = isRootPrivate(treeRootHolder.getRoot(), existingDtosByUuids);
94 // Insert or update the components in database. They are removed from existingDtosByUuids
96 new PathAwareCrawler<>(new PersistComponentStepsVisitor(existingDtosByUuids, dbSession))
97 .visit(treeRootHolder.getRoot());
99 disableRemainingComponents(dbSession, existingDtosByUuids.values());
100 dbClient.componentDao().setPrivateForBranchUuidWithoutAudit(dbSession, projectUuid, isRootPrivate);
105 private void disableRemainingComponents(DbSession dbSession, Collection<ComponentDto> dtos) {
106 Set<String> uuids = dtos.stream()
107 .filter(ComponentDto::isEnabled)
108 .map(ComponentDto::uuid)
109 .collect(Collectors.toSet());
110 dbClient.componentDao().updateBEnabledToFalse(dbSession, uuids);
111 disabledComponentsHolder.setUuids(uuids);
114 private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByUuids) {
115 ComponentDto rootDto = existingDtosByUuids.get(root.getUuid());
116 if (rootDto == null) {
117 if (Component.Type.VIEW == root.getType()) {
120 throw new IllegalStateException(String.format("The project '%s' is not stored in the database, during a project analysis.", root.getKey()));
122 return rootDto.isPrivate();
126 * Returns a mutable map of the components currently persisted in database for the project, including
127 * disabled components.
129 private Map<String, ComponentDto> indexExistingDtosByUuids(DbSession session) {
130 return dbClient.componentDao().selectByBranchUuid(treeRootHolder.getRoot().getUuid(), session)
132 .collect(Collectors.toMap(ComponentDto::uuid, Function.identity()));
135 private class PersistComponentStepsVisitor extends PathAwareVisitorAdapter<ComponentDtoHolder> {
137 private final Map<String, ComponentDto> existingComponentDtosByUuids;
138 private final DbSession dbSession;
140 PersistComponentStepsVisitor(Map<String, ComponentDto> existingComponentDtosByUuids, DbSession dbSession) {
142 CrawlerDepthLimit.LEAVES,
144 new SimpleStackElementFactory<>() {
146 public ComponentDtoHolder createForAny(Component component) {
147 return new ComponentDtoHolder();
151 public ComponentDtoHolder createForFile(Component file) {
152 // no need to create holder for file since they are always leaves of the Component tree
157 public ComponentDtoHolder createForProjectView(Component projectView) {
158 // no need to create holder for file since they are always leaves of the Component tree
162 this.existingComponentDtosByUuids = existingComponentDtosByUuids;
163 this.dbSession = dbSession;
167 public void visitProject(Component project, Path<ComponentDtoHolder> path) {
168 ComponentDto dto = createForProject(project);
169 path.current().setDto(persistComponent(dto));
173 public void visitDirectory(Component directory, Path<ComponentDtoHolder> path) {
174 ComponentDto dto = createForDirectory(directory, path);
175 path.current().setDto(persistComponent(dto));
179 public void visitFile(Component file, Path<ComponentDtoHolder> path) {
180 ComponentDto dto = createForFile(file, path);
181 persistComponent(dto);
185 public void visitView(Component view, Path<ComponentDtoHolder> path) {
186 ComponentDto dto = createForView(view);
187 path.current().setDto(persistComponent(dto));
191 public void visitSubView(Component subView, Path<ComponentDtoHolder> path) {
192 ComponentDto dto = createForSubView(subView, path);
193 path.current().setDto(persistComponent(dto));
197 public void visitProjectView(Component projectView, Path<ComponentDtoHolder> path) {
198 ComponentDto dto = createForProjectView(projectView, path);
199 persistComponent(dto, false);
202 private ComponentDto persistComponent(ComponentDto componentDto) {
203 return persistComponent(componentDto, true);
206 private ComponentDto persistComponent(ComponentDto componentDto, boolean shouldPersistAudit) {
207 ComponentDto existingComponent = existingComponentDtosByUuids.remove(componentDto.uuid());
208 if (existingComponent == null) {
209 if (componentDto.qualifier().equals("APP") && componentDto.scope().equals("PRJ")) {
210 throw new IllegalStateException("Application should already exists: " + componentDto);
212 dbClient.componentDao().insert(dbSession, componentDto, shouldPersistAudit);
215 Optional<ComponentUpdateDto> update = compareForUpdate(existingComponent, componentDto);
216 if (update.isPresent()) {
217 ComponentUpdateDto updateDto = update.get();
218 dbClient.componentDao().update(dbSession, updateDto, componentDto.qualifier());
220 // update the fields in memory in order the PathAwareVisitor.Path
222 existingComponent.setKey(updateDto.getBKey());
223 existingComponent.setCopyComponentUuid(updateDto.getBCopyComponentUuid());
224 existingComponent.setDescription(updateDto.getBDescription());
225 existingComponent.setEnabled(updateDto.isBEnabled());
226 existingComponent.setUuidPath(updateDto.getBUuidPath());
227 existingComponent.setLanguage(updateDto.getBLanguage());
228 existingComponent.setLongName(updateDto.getBLongName());
229 existingComponent.setName(updateDto.getBName());
230 existingComponent.setPath(updateDto.getBPath());
231 // We don't have a b_scope. The applyBChangesForRootComponentUuid query is using a case ... when to infer scope from the qualifier
232 existingComponent.setScope(componentDto.scope());
233 existingComponent.setQualifier(updateDto.getBQualifier());
235 return existingComponent;
238 public ComponentDto createForProject(Component project) {
239 ComponentDto res = createBase(project);
241 res.setScope(Scopes.PROJECT);
242 res.setQualifier(PROJECT);
243 res.setName(project.getName());
244 res.setLongName(res.name());
245 res.setDescription(project.getDescription());
247 res.setBranchUuid(res.uuid());
248 res.setUuidPath(UUID_PATH_OF_ROOT);
253 public ComponentDto createForDirectory(Component directory, PathAwareVisitor.Path<ComponentDtoHolder> path) {
254 ComponentDto res = createBase(directory);
256 res.setScope(Scopes.DIRECTORY);
257 res.setQualifier(Qualifiers.DIRECTORY);
258 res.setName(directory.getShortName());
259 res.setLongName(directory.getName());
260 res.setPath(directory.getName());
267 public ComponentDto createForFile(Component file, PathAwareVisitor.Path<ComponentDtoHolder> path) {
268 ComponentDto res = createBase(file);
270 res.setScope(Scopes.FILE);
271 res.setQualifier(getFileQualifier(file));
272 res.setName(file.getShortName());
273 res.setLongName(file.getName());
274 res.setPath(file.getName());
275 res.setLanguage(file.getFileAttributes().getLanguageKey());
282 private ComponentDto createForView(Component view) {
283 ComponentDto res = createBase(view);
285 res.setScope(Scopes.PROJECT);
286 res.setQualifier(view.getViewAttributes().getType().getQualifier());
287 res.setName(view.getName());
288 res.setDescription(view.getDescription());
289 res.setLongName(res.name());
291 res.setBranchUuid(res.uuid());
292 res.setUuidPath(UUID_PATH_OF_ROOT);
297 private ComponentDto createForSubView(Component subView, PathAwareVisitor.Path<ComponentDtoHolder> path) {
298 ComponentDto res = createBase(subView);
300 res.setScope(Scopes.PROJECT);
301 res.setQualifier(Qualifiers.SUBVIEW);
302 res.setName(subView.getName());
303 res.setDescription(subView.getDescription());
304 res.setLongName(res.name());
305 res.setCopyComponentUuid(subView.getSubViewAttributes().getOriginalViewUuid());
307 setRootAndParentModule(res, path);
312 private ComponentDto createForProjectView(Component projectView, PathAwareVisitor.Path<ComponentDtoHolder> path) {
313 ComponentDto res = createBase(projectView);
315 res.setScope(Scopes.FILE);
316 res.setQualifier(PROJECT);
317 res.setName(projectView.getName());
318 res.setLongName(res.name());
319 res.setCopyComponentUuid(projectView.getProjectViewAttributes().getUuid());
321 setRootAndParentModule(res, path);
326 private ComponentDto createBase(Component component) {
327 String componentKey = component.getKey();
328 String componentUuid = component.getUuid();
330 ComponentDto componentDto = new ComponentDto();
331 componentDto.setUuid(componentUuid);
332 componentDto.setKey(componentKey);
333 componentDto.setEnabled(true);
334 componentDto.setCreatedAt(new Date(system2.now()));
340 * Applies to a node of type either SUBVIEW or PROJECT_VIEW
342 private void setRootAndParentModule(ComponentDto res, PathAwareVisitor.Path<ComponentDtoHolder> path) {
343 ComponentDto rootDto = path.root().getDto();
344 res.setBranchUuid(rootDto.uuid());
346 ComponentDto parent = path.parent().getDto();
347 res.setUuidPath(formatUuidPathFromParent(parent));
352 * Applies to a node of type either DIRECTORY or FILE
354 private static void setUuids(ComponentDto componentDto, PathAwareVisitor.Path<ComponentDtoHolder> path) {
355 componentDto.setBranchUuid(path.root().getDto().uuid());
356 componentDto.setUuidPath(formatUuidPathFromParent(path.parent().getDto()));
359 private static Optional<ComponentUpdateDto> compareForUpdate(ComponentDto existing, ComponentDto target) {
360 boolean hasDifferences = !StringUtils.equals(existing.getCopyComponentUuid(), target.getCopyComponentUuid()) ||
361 !StringUtils.equals(existing.description(), target.description()) ||
362 !StringUtils.equals(existing.getKey(), target.getKey()) ||
363 !existing.isEnabled() ||
364 !StringUtils.equals(existing.getUuidPath(), target.getUuidPath()) ||
365 !StringUtils.equals(existing.language(), target.language()) ||
366 !StringUtils.equals(existing.longName(), target.longName()) ||
367 !StringUtils.equals(existing.name(), target.name()) ||
368 !StringUtils.equals(existing.path(), target.path()) ||
369 !StringUtils.equals(existing.scope(), target.scope()) ||
370 !StringUtils.equals(existing.qualifier(), target.qualifier());
372 ComponentUpdateDto update = null;
373 if (hasDifferences) {
374 update = ComponentUpdateDto
378 return ofNullable(update);
381 private static String getFileQualifier(Component component) {
382 return component.getFileAttributes().isUnitTest() ? Qualifiers.UNIT_TEST_FILE : Qualifiers.FILE;
385 private static class ComponentDtoHolder {
386 private ComponentDto dto;
388 public ComponentDto getDto() {
392 public void setDto(ComponentDto dto) {