Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

SonarProjectBuilder.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Sonar Standalone Runner
  3. * Copyright (C) 2011 SonarSource
  4. * dev@sonar.codehaus.org
  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
  17. * License along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
  19. */
  20. package org.sonar.runner.internal.batch;
  21. import com.google.common.annotations.VisibleForTesting;
  22. import com.google.common.collect.Lists;
  23. import org.apache.commons.io.IOUtils;
  24. import org.apache.commons.io.filefilter.AndFileFilter;
  25. import org.apache.commons.io.filefilter.FileFileFilter;
  26. import org.apache.commons.io.filefilter.WildcardFileFilter;
  27. import org.apache.commons.lang.StringUtils;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import org.sonar.api.batch.bootstrap.ProjectDefinition;
  31. import org.sonar.runner.RunnerException;
  32. import org.sonar.runner.utils.SonarRunnerUtils;
  33. import java.io.File;
  34. import java.io.FileFilter;
  35. import java.io.FileInputStream;
  36. import java.io.IOException;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. import java.util.Map.Entry;
  41. import java.util.Properties;
  42. /**
  43. * Class that creates a Sonar project definition based on a set of properties.
  44. *
  45. * @since 1.5
  46. */
  47. public final class SonarProjectBuilder {
  48. private static final Logger LOG = LoggerFactory.getLogger(SonarProjectBuilder.class);
  49. private static final String PROPERTY_PROJECT_BASEDIR = "sonar.projectBaseDir";
  50. private static final String PROPERTY_PROJECT_CONFIG_FILE = "sonar.projectConfigFile";
  51. private static final String PROPERTY_PROJECT_KEY = "sonar.projectKey";
  52. private static final String PROPERTY_PROJECT_NAME = "sonar.projectName";
  53. private static final String PROPERTY_PROJECT_DESCRIPTION = "sonar.projectDescription";
  54. private static final String PROPERTY_PROJECT_VERSION = "sonar.projectVersion";
  55. private static final String PROPERTY_MODULES = "sonar.modules";
  56. /**
  57. * New properties, to be consistent with Sonar naming conventions
  58. * @since 1.5
  59. */
  60. private static final String PROPERTY_SOURCES = "sonar.sources";
  61. private static final String PROPERTY_TESTS = "sonar.tests";
  62. private static final String PROPERTY_BINARIES = "sonar.binaries";
  63. private static final String PROPERTY_LIBRARIES = "sonar.libraries";
  64. /**
  65. * Old deprecated properties, replaced by the same ones preceded by "sonar."
  66. */
  67. private static final String PROPERTY_OLD_SOURCES = "sources";
  68. private static final String PROPERTY_OLD_TESTS = "tests";
  69. private static final String PROPERTY_OLD_BINARIES = "binaries";
  70. private static final String PROPERTY_OLD_LIBRARIES = "libraries";
  71. private static final Map<String, String> DEPRECATED_PROPS_TO_NEW_PROPS = new HashMap<String, String>() {
  72. {
  73. put(PROPERTY_OLD_SOURCES, PROPERTY_SOURCES);
  74. put(PROPERTY_OLD_TESTS, PROPERTY_TESTS);
  75. put(PROPERTY_OLD_BINARIES, PROPERTY_BINARIES);
  76. put(PROPERTY_OLD_LIBRARIES, PROPERTY_LIBRARIES);
  77. }
  78. };
  79. /**
  80. * @since 1.4
  81. */
  82. private static final String PROPERTY_WORK_DIRECTORY = "sonar.working.directory";
  83. private static final String DEF_VALUE_WORK_DIRECTORY = ".sonar";
  84. /**
  85. * Array of all mandatory properties required for a project.
  86. */
  87. private static final String[] MANDATORY_PROPERTIES_FOR_PROJECT = {PROPERTY_PROJECT_BASEDIR, PROPERTY_PROJECT_KEY, PROPERTY_PROJECT_NAME, PROPERTY_PROJECT_VERSION,
  88. PROPERTY_SOURCES};
  89. /**
  90. * Array of all mandatory properties required for a child project before its properties get merged with its parent ones.
  91. */
  92. private static final String[] MANDATORY_PROPERTIES_FOR_CHILD = {PROPERTY_PROJECT_KEY, PROPERTY_PROJECT_NAME};
  93. /**
  94. * Properties that must not be passed from the parent project to its children.
  95. */
  96. private static final List<String> NON_HERITED_PROPERTIES_FOR_CHILD = Lists.newArrayList(PROPERTY_PROJECT_BASEDIR, PROPERTY_MODULES, PROPERTY_PROJECT_DESCRIPTION);
  97. private Properties properties;
  98. private SonarProjectBuilder(Properties properties) {
  99. this.properties = properties;
  100. }
  101. public static SonarProjectBuilder create(Properties properties) {
  102. return new SonarProjectBuilder(properties);
  103. }
  104. public ProjectDefinition generateProjectDefinition() {
  105. ProjectDefinition rootProject = defineProject(properties);
  106. defineChildren(rootProject);
  107. cleanAndCheckProjectDefinitions(rootProject);
  108. return rootProject;
  109. }
  110. private ProjectDefinition defineProject(Properties properties) {
  111. checkMandatoryProperties("root project", properties, MANDATORY_PROPERTIES_FOR_PROJECT);
  112. File baseDir = new File(properties.getProperty(PROPERTY_PROJECT_BASEDIR));
  113. ProjectDefinition definition = ProjectDefinition.create((Properties) properties.clone())
  114. .setBaseDir(baseDir)
  115. .setWorkDir(initWorkDir(baseDir));
  116. return definition;
  117. }
  118. @VisibleForTesting
  119. protected File initWorkDir(File baseDir) {
  120. String workDir = properties.getProperty(PROPERTY_WORK_DIRECTORY);
  121. if (StringUtils.isBlank(workDir)) {
  122. return new File(baseDir, DEF_VALUE_WORK_DIRECTORY);
  123. }
  124. File customWorkDir = new File(workDir);
  125. if (customWorkDir.isAbsolute()) {
  126. return customWorkDir;
  127. }
  128. return new File(baseDir, customWorkDir.getPath());
  129. }
  130. private void defineChildren(ProjectDefinition parentProject) {
  131. Properties parentProps = parentProject.getProperties();
  132. if (parentProps.containsKey(PROPERTY_MODULES)) {
  133. for (String module : SonarRunnerUtils.getListFromProperty(parentProps, PROPERTY_MODULES)) {
  134. Properties moduleProps = extractModuleProperties(module, parentProps);
  135. ProjectDefinition childProject = null;
  136. if (moduleProps.containsKey(PROPERTY_PROJECT_CONFIG_FILE)) {
  137. childProject = loadChildProjectFromPropertyFile(parentProject, moduleProps, module);
  138. } else {
  139. childProject = loadChildProjectFromProperties(parentProject, moduleProps, module);
  140. }
  141. // the child project may have children as well
  142. defineChildren(childProject);
  143. // and finally add this child project to its parent
  144. parentProject.addSubProject(childProject);
  145. }
  146. }
  147. }
  148. private ProjectDefinition loadChildProjectFromProperties(ProjectDefinition parentProject, Properties childProps, String moduleId) {
  149. checkMandatoryProperties(moduleId, childProps, MANDATORY_PROPERTIES_FOR_CHILD);
  150. mergeParentProperties(childProps, parentProject.getProperties());
  151. File baseDir = null;
  152. if (childProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  153. baseDir = getFileFromPath(childProps.getProperty(PROPERTY_PROJECT_BASEDIR), parentProject.getBaseDir());
  154. } else {
  155. baseDir = new File(parentProject.getBaseDir(), moduleId);
  156. }
  157. setProjectBaseDirOnProperties(childProps, moduleId, baseDir);
  158. prefixProjectKeyWithParentKey(childProps, parentProject.getKey());
  159. return defineProject(childProps);
  160. }
  161. private ProjectDefinition loadChildProjectFromPropertyFile(ProjectDefinition parentProject, Properties moduleProps, String moduleId) {
  162. File propertyFile = getFileFromPath(moduleProps.getProperty(PROPERTY_PROJECT_CONFIG_FILE), parentProject.getBaseDir());
  163. if (!propertyFile.isFile()) {
  164. throw new RunnerException("The properties file of the module '" + moduleId + "' does not exist: " + propertyFile.getAbsolutePath());
  165. }
  166. Properties childProps = new Properties();
  167. FileInputStream fileInputStream = null;
  168. try {
  169. fileInputStream = new FileInputStream(propertyFile);
  170. childProps.load(fileInputStream);
  171. } catch (IOException e) {
  172. throw new RunnerException("Impossible to read the property file: " + propertyFile.getAbsolutePath(), e);
  173. } finally {
  174. IOUtils.closeQuietly(fileInputStream);
  175. }
  176. checkMandatoryProperties(moduleId, childProps, MANDATORY_PROPERTIES_FOR_CHILD);
  177. mergeParentProperties(childProps, parentProject.getProperties());
  178. File baseDir = null;
  179. if (childProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  180. baseDir = getFileFromPath(childProps.getProperty(PROPERTY_PROJECT_BASEDIR), propertyFile.getParentFile());
  181. } else {
  182. baseDir = propertyFile.getParentFile();
  183. }
  184. setProjectBaseDirOnProperties(childProps, moduleId, baseDir);
  185. prefixProjectKeyWithParentKey(childProps, parentProject.getKey());
  186. return defineProject(childProps);
  187. }
  188. @VisibleForTesting
  189. protected static void prefixProjectKeyWithParentKey(Properties childProps, String parentKey) {
  190. String childKey = childProps.getProperty(PROPERTY_PROJECT_KEY);
  191. childProps.put(PROPERTY_PROJECT_KEY, parentKey + ":" + childKey);
  192. }
  193. private static void setProjectBaseDirOnProperties(Properties childProps, String moduleId, File baseDir) {
  194. if (!baseDir.isDirectory()) {
  195. throw new RunnerException("The base directory of the module '" + moduleId + "' does not exist: " + baseDir.getAbsolutePath());
  196. }
  197. childProps.put(PROPERTY_PROJECT_BASEDIR, baseDir.getAbsolutePath());
  198. }
  199. @VisibleForTesting
  200. protected static void checkMandatoryProperties(String moduleId, Properties props, String[] mandatoryProps) {
  201. replaceDeprecatedProperties(props);
  202. StringBuilder missing = new StringBuilder();
  203. for (String mandatoryProperty : mandatoryProps) {
  204. if (!props.containsKey(mandatoryProperty)) {
  205. if (missing.length() > 0) {
  206. missing.append(", ");
  207. }
  208. missing.append(mandatoryProperty);
  209. }
  210. }
  211. if (missing.length() != 0) {
  212. throw new RunnerException("You must define the following mandatory properties for '" + moduleId + "': " + missing);
  213. }
  214. }
  215. @VisibleForTesting
  216. protected static void cleanAndCheckProjectDefinitions(ProjectDefinition project) {
  217. if (project.getSubProjects().isEmpty()) {
  218. cleanAndCheckModuleProperties(project);
  219. } else {
  220. cleanAggregatorProjectProperties(project);
  221. // clean modules properties as well
  222. for (ProjectDefinition module : project.getSubProjects()) {
  223. cleanAndCheckProjectDefinitions(module);
  224. }
  225. }
  226. }
  227. @VisibleForTesting
  228. protected static void cleanAndCheckModuleProperties(ProjectDefinition project) {
  229. Properties properties = project.getProperties();
  230. // We need to check the existence of source directories
  231. String[] sourceDirs = SonarRunnerUtils.getListFromProperty(properties, PROPERTY_SOURCES);
  232. checkExistenceOfDirectories(project.getKey(), project.getBaseDir(), sourceDirs);
  233. // And we need to resolve patterns that may have been used in "sonar.libraries"
  234. List<String> libPaths = Lists.newArrayList();
  235. for (String pattern : SonarRunnerUtils.getListFromProperty(properties, PROPERTY_LIBRARIES)) {
  236. for (File file : getLibraries(project.getBaseDir(), pattern)) {
  237. libPaths.add(file.getAbsolutePath());
  238. }
  239. }
  240. properties.remove(PROPERTY_LIBRARIES);
  241. properties.put(PROPERTY_LIBRARIES, StringUtils.join(libPaths, ","));
  242. }
  243. @VisibleForTesting
  244. protected static void cleanAggregatorProjectProperties(ProjectDefinition project) {
  245. Properties properties = project.getProperties();
  246. // "aggregator" project must not have the following properties:
  247. properties.remove(PROPERTY_SOURCES);
  248. properties.remove(PROPERTY_TESTS);
  249. properties.remove(PROPERTY_BINARIES);
  250. properties.remove(PROPERTY_LIBRARIES);
  251. // and they don't need properties related to their modules either
  252. Properties clone = (Properties) properties.clone();
  253. List<String> moduleIds = Lists.newArrayList(SonarRunnerUtils.getListFromProperty(properties, PROPERTY_MODULES));
  254. for (Entry<Object, Object> entry : clone.entrySet()) {
  255. String key = (String) entry.getKey();
  256. if (isKeyPrefixedByModuleId(key, moduleIds)) {
  257. properties.remove(key);
  258. }
  259. }
  260. }
  261. /**
  262. * Replaces the deprecated properties by the new ones, and logs a message to warn the users.
  263. */
  264. @VisibleForTesting
  265. protected static void replaceDeprecatedProperties(Properties props) {
  266. for (Entry<String, String> entry : DEPRECATED_PROPS_TO_NEW_PROPS.entrySet()) {
  267. String key = entry.getKey();
  268. if (props.containsKey(key)) {
  269. String newKey = entry.getValue();
  270. LOG.warn("/!\\ The '{}' property is deprecated and is replaced by '{}'. Don't forget to update your files.", key, newKey);
  271. String value = props.getProperty(key);
  272. props.remove(key);
  273. props.put(newKey, value);
  274. }
  275. }
  276. }
  277. @VisibleForTesting
  278. protected static void mergeParentProperties(Properties childProps, Properties parentProps) {
  279. List<String> moduleIds = Lists.newArrayList(SonarRunnerUtils.getListFromProperty(parentProps, PROPERTY_MODULES));
  280. for (Map.Entry<Object, Object> entry : parentProps.entrySet()) {
  281. String key = (String) entry.getKey();
  282. if (!childProps.containsKey(key)
  283. && !NON_HERITED_PROPERTIES_FOR_CHILD.contains(key)
  284. && !isKeyPrefixedByModuleId(key, moduleIds)) {
  285. childProps.put(entry.getKey(), entry.getValue());
  286. }
  287. }
  288. }
  289. private static boolean isKeyPrefixedByModuleId(String key, List<String> moduleIds) {
  290. for (String moduleId : moduleIds) {
  291. if (key.startsWith(moduleId + ".")) {
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. @VisibleForTesting
  298. protected static Properties extractModuleProperties(String module, Properties properties) {
  299. Properties moduleProps = new Properties();
  300. String propertyPrefix = module + ".";
  301. int prefixLength = propertyPrefix.length();
  302. for (Map.Entry<Object, Object> entry : properties.entrySet()) {
  303. String key = (String) entry.getKey();
  304. if (key.startsWith(propertyPrefix)) {
  305. moduleProps.put(key.substring(prefixLength), entry.getValue());
  306. }
  307. }
  308. return moduleProps;
  309. }
  310. @VisibleForTesting
  311. protected static void checkExistenceOfDirectories(String projectKey, File baseDir, String[] sourceDirs) {
  312. for (String path : sourceDirs) {
  313. File sourceFolder = getFileFromPath(path, baseDir);
  314. if (!sourceFolder.isDirectory()) {
  315. throw new RunnerException("The source folder '" + path + "' does not exist for '" + projectKey +
  316. "' project/module (base directory = " + baseDir.getAbsolutePath() + ")");
  317. }
  318. }
  319. }
  320. /**
  321. * Returns files matching specified pattern.
  322. */
  323. @VisibleForTesting
  324. protected static File[] getLibraries(File baseDir, String pattern) {
  325. final int i = Math.max(pattern.lastIndexOf('/'), pattern.lastIndexOf('\\'));
  326. final String dirPath, filePattern;
  327. if (i == -1) {
  328. dirPath = ".";
  329. filePattern = pattern;
  330. } else {
  331. dirPath = pattern.substring(0, i);
  332. filePattern = pattern.substring(i + 1);
  333. }
  334. FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE, new WildcardFileFilter(filePattern));
  335. File dir = resolvePath(baseDir, dirPath);
  336. File[] files = dir.listFiles(fileFilter);
  337. if (files == null || files.length == 0) {
  338. throw new RunnerException("No files matching pattern \"" + filePattern + "\" in directory \"" + dir + "\"");
  339. }
  340. return files;
  341. }
  342. private static File resolvePath(File baseDir, String path) {
  343. File file = new File(path);
  344. if (!file.isAbsolute()) {
  345. try {
  346. file = new File(baseDir, path).getCanonicalFile();
  347. } catch (IOException e) {
  348. throw new RunnerException("Unable to resolve path \"" + path + "\"", e);
  349. }
  350. }
  351. return file;
  352. }
  353. /**
  354. * Returns the file denoted by the given path, may this path be relative to "baseDir" or absolute.
  355. */
  356. @VisibleForTesting
  357. protected static File getFileFromPath(String path, File baseDir) {
  358. File propertyFile = new File(path.trim());
  359. if (!propertyFile.isAbsolute()) {
  360. propertyFile = new File(baseDir, propertyFile.getPath());
  361. }
  362. return propertyFile;
  363. }
  364. }