You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScmAction.java 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.server.source.ws;
  21. import com.google.common.base.Strings;
  22. import com.google.common.io.Resources;
  23. import java.util.Date;
  24. import org.apache.commons.lang3.ObjectUtils;
  25. import org.apache.commons.lang3.builder.EqualsBuilder;
  26. import org.sonar.api.server.ws.Request;
  27. import org.sonar.api.server.ws.Response;
  28. import org.sonar.api.server.ws.WebService;
  29. import org.sonar.api.utils.DateUtils;
  30. import org.sonar.api.utils.text.JsonWriter;
  31. import org.sonar.api.web.UserRole;
  32. import org.sonar.db.DbClient;
  33. import org.sonar.db.DbSession;
  34. import org.sonar.db.component.ComponentDto;
  35. import org.sonar.db.protobuf.DbFileSources;
  36. import org.sonar.server.component.ComponentFinder;
  37. import org.sonar.server.source.SourceService;
  38. import org.sonar.server.user.UserSession;
  39. import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional;
  40. public class ScmAction implements SourcesWsAction {
  41. private final DbClient dbClient;
  42. private final SourceService sourceService;
  43. private final UserSession userSession;
  44. private final ComponentFinder componentFinder;
  45. public ScmAction(DbClient dbClient, SourceService sourceService, UserSession userSession, ComponentFinder componentFinder) {
  46. this.dbClient = dbClient;
  47. this.sourceService = sourceService;
  48. this.userSession = userSession;
  49. this.componentFinder = componentFinder;
  50. }
  51. @Override
  52. public void define(WebService.NewController controller) {
  53. WebService.NewAction action = controller.createAction("scm")
  54. .setDescription("Get SCM information of source files. Require See Source Code permission on file's project<br/>" +
  55. "Each element of the result array is composed of:" +
  56. "<ol>" +
  57. "<li>Line number</li>" +
  58. "<li>Author of the commit</li>" +
  59. "<li>Datetime of the commit (before 5.2 it was only the Date)</li>" +
  60. "<li>Revision of the commit (added in 5.2)</li>" +
  61. "</ol>")
  62. .setSince("4.4")
  63. .setResponseExample(Resources.getResource(getClass(), "example-scm.json"))
  64. .setHandler(this);
  65. action
  66. .createParam("key")
  67. .setRequired(true)
  68. .setDescription("File key")
  69. .setExampleValue("my_project:/src/foo/Bar.php");
  70. action
  71. .createParam("from")
  72. .setDescription("First line to return. Starts at 1")
  73. .setExampleValue("10")
  74. .setDefaultValue("1");
  75. action
  76. .createParam("to")
  77. .setDescription("Last line to return (inclusive)")
  78. .setExampleValue("20");
  79. action
  80. .createParam("commits_by_line")
  81. .setDescription("Group lines by SCM commit if value is false, else display commits for each line, even if two " +
  82. "consecutive lines relate to the same commit.")
  83. .setBooleanPossibleValues()
  84. .setDefaultValue("false");
  85. }
  86. @Override
  87. public void handle(Request request, Response response) {
  88. String fileKey = request.mandatoryParam("key");
  89. int from = Math.max(request.mandatoryParamAsInt("from"), 1);
  90. int to = ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE);
  91. boolean commitsByLine = request.mandatoryParamAsBoolean("commits_by_line");
  92. try (DbSession dbSession = dbClient.openSession(false)) {
  93. ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
  94. userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
  95. Iterable<DbFileSources.Line> sourceLines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "File '%s' has no sources", fileKey);
  96. try (JsonWriter json = response.newJsonWriter()) {
  97. json.beginObject();
  98. writeSource(sourceLines, commitsByLine, json);
  99. json.endObject().close();
  100. }
  101. }
  102. }
  103. private static void writeSource(Iterable<DbFileSources.Line> lines, boolean showCommitsByLine, JsonWriter json) {
  104. json.name("scm").beginArray();
  105. DbFileSources.Line previousLine = null;
  106. boolean started = false;
  107. for (DbFileSources.Line lineDoc : lines) {
  108. if (hasScm(lineDoc) && (!started || showCommitsByLine || !isSameCommit(previousLine, lineDoc))) {
  109. json.beginArray()
  110. .value(lineDoc.getLine())
  111. .value(lineDoc.getScmAuthor());
  112. json.value(lineDoc.hasScmDate() ? DateUtils.formatDateTime(new Date(lineDoc.getScmDate())) : null);
  113. json.value(lineDoc.getScmRevision());
  114. json.endArray();
  115. started = true;
  116. }
  117. previousLine = lineDoc;
  118. }
  119. json.endArray();
  120. }
  121. private static boolean isSameCommit(DbFileSources.Line previousLine, DbFileSources.Line currentLine) {
  122. return new EqualsBuilder()
  123. .append(previousLine.getScmAuthor(), currentLine.getScmAuthor())
  124. .append(previousLine.getScmDate(), currentLine.getScmDate())
  125. .append(previousLine.getScmRevision(), currentLine.getScmRevision())
  126. .isEquals();
  127. }
  128. private static boolean hasScm(DbFileSources.Line line) {
  129. return !Strings.isNullOrEmpty(line.getScmAuthor()) || line.hasScmDate() || !Strings.isNullOrEmpty(line.getScmRevision());
  130. }
  131. }