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.

SonarProjectBuilder.java 18KB

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