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.

Conf.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * SonarQube Scanner
  3. * Copyright (C) 2011-2019 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.sonarsource.scanner.cli;
  21. import java.io.FileInputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.nio.file.Files;
  25. import java.nio.file.Path;
  26. import java.nio.file.Paths;
  27. import java.text.MessageFormat;
  28. import java.util.ArrayList;
  29. import java.util.List;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.Properties;
  33. import javax.annotation.Nullable;
  34. import org.sonarsource.scanner.api.Utils;
  35. class Conf {
  36. private static final String SCANNER_HOME = "scanner.home";
  37. private static final String SCANNER_SETTINGS = "scanner.settings";
  38. private static final String PROJECT_HOME = "project.home";
  39. private static final String PROJECT_SETTINGS = "project.settings";
  40. private static final String PROPERTY_MODULES = "sonar.modules";
  41. private static final String PROPERTY_PROJECT_BASEDIR = "sonar.projectBaseDir";
  42. private static final String PROPERTY_PROJECT_CONFIG_FILE = "sonar.projectConfigFile";
  43. private static final String SONAR_PROJECT_PROPERTIES_FILENAME = "sonar-project.properties";
  44. private static final String PROPERTY_SONAR_HOST_URL = "sonar.host.url";
  45. private final Cli cli;
  46. private final Logs logger;
  47. private final Map<String, String> env;
  48. Conf(Cli cli, Logs logger, Map<String, String> env) {
  49. this.cli = cli;
  50. this.logger = logger;
  51. this.env = env;
  52. }
  53. Properties properties() {
  54. Properties result = new Properties();
  55. result.putAll(loadGlobalProperties());
  56. result.putAll(loadProjectProperties());
  57. result.putAll(System.getProperties());
  58. result.putAll(loadEnvironmentProperties());
  59. result.putAll(cli.properties());
  60. result = resolve(result);
  61. // root project base directory must be present and be absolute
  62. result.setProperty(PROPERTY_PROJECT_BASEDIR, getRootProjectBaseDir(result).toString());
  63. result.remove(PROJECT_HOME);
  64. return result;
  65. }
  66. boolean isSonarCloud(@Nullable Properties testProperties) {
  67. String hostUrl = testProperties != null ? testProperties.getProperty(PROPERTY_SONAR_HOST_URL) : properties().getProperty(PROPERTY_SONAR_HOST_URL);
  68. if (hostUrl != null) {
  69. return hostUrl.toLowerCase(Locale.getDefault()).contains("sonarcloud");
  70. }
  71. return false;
  72. }
  73. private Properties resolve(Properties props) {
  74. PropertyResolver resolver = new PropertyResolver(props, env);
  75. return resolver.resolve();
  76. }
  77. private Properties loadEnvironmentProperties() {
  78. return Utils.loadEnvironmentProperties(env);
  79. }
  80. private Properties loadGlobalProperties() {
  81. Properties knownPropsAtThatPoint = new Properties();
  82. knownPropsAtThatPoint.putAll(System.getProperties());
  83. knownPropsAtThatPoint.putAll(loadEnvironmentProperties());
  84. knownPropsAtThatPoint.putAll(cli.properties());
  85. Path settingsFile = locatePropertiesFile(knownPropsAtThatPoint, SCANNER_HOME, "conf/sonar-scanner.properties",
  86. SCANNER_SETTINGS);
  87. if (settingsFile != null && Files.isRegularFile(settingsFile)) {
  88. logger.info("Scanner configuration file: " + settingsFile);
  89. return toProperties(settingsFile);
  90. }
  91. logger.info("Scanner configuration file: NONE");
  92. return new Properties();
  93. }
  94. private Properties loadProjectProperties() {
  95. Properties rootProps = new Properties();
  96. Properties knownPropsAtThatPoint = new Properties();
  97. knownPropsAtThatPoint.putAll(System.getProperties());
  98. knownPropsAtThatPoint.putAll(loadEnvironmentProperties());
  99. knownPropsAtThatPoint.putAll(cli.properties());
  100. Path defaultRootSettingsFile = getRootProjectBaseDir(knownPropsAtThatPoint).resolve(SONAR_PROJECT_PROPERTIES_FILENAME);
  101. Path rootSettingsFile = locatePropertiesFile(defaultRootSettingsFile, knownPropsAtThatPoint, PROJECT_SETTINGS);
  102. if (rootSettingsFile != null && Files.isRegularFile(rootSettingsFile)) {
  103. logger.info("Project root configuration file: " + rootSettingsFile);
  104. rootProps.putAll(toProperties(rootSettingsFile));
  105. } else {
  106. logger.info("Project root configuration file: NONE");
  107. }
  108. Properties projectProps = new Properties();
  109. // include already root base directory and eventually props loaded from
  110. // root config file
  111. projectProps.putAll(rootProps);
  112. rootProps.putAll(knownPropsAtThatPoint);
  113. rootProps.setProperty(PROPERTY_PROJECT_BASEDIR, getRootProjectBaseDir(rootProps).toString());
  114. // projectProps will be overridden by any properties found in child
  115. // project settings
  116. loadModulesProperties(rootProps, projectProps, "");
  117. return projectProps;
  118. }
  119. private static Path getRootProjectBaseDir(Properties cliProps) {
  120. Path absoluteProjectHome;
  121. if (cliProps.containsKey(PROJECT_HOME)) {
  122. absoluteProjectHome = Paths.get(cliProps.getProperty(PROJECT_HOME)).toAbsolutePath();
  123. } else {
  124. // this should always be avoided, as it will resolve symbolic links
  125. absoluteProjectHome = Paths.get("").toAbsolutePath();
  126. }
  127. if (!cliProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  128. return absoluteProjectHome;
  129. }
  130. return getAbsolutePath(cliProps.getProperty(PROPERTY_PROJECT_BASEDIR), absoluteProjectHome);
  131. }
  132. private void loadModulesProperties(Properties parentProps, Properties projectProps, String prefix) {
  133. Path parentBaseDir = Paths.get(parentProps.getProperty(PROPERTY_PROJECT_BASEDIR));
  134. if (parentProps.containsKey(PROPERTY_MODULES)) {
  135. for (String module : getListFromProperty(parentProps, PROPERTY_MODULES)) {
  136. Properties moduleProps = extractModuleProperties(module, parentProps);
  137. // higher priority to child configuration files
  138. loadModuleConfigFile(parentBaseDir, moduleProps, module);
  139. // the child project may have children as well
  140. loadModulesProperties(moduleProps, projectProps, prefix + module + ".");
  141. // and finally add this child properties to global props
  142. merge(projectProps, prefix, module, moduleProps);
  143. }
  144. }
  145. }
  146. private static void merge(Properties projectProps, String prefix, String module, Properties moduleProps) {
  147. for (Map.Entry<Object, Object> entry : moduleProps.entrySet()) {
  148. projectProps.put(prefix + module + "." + entry.getKey(), entry.getValue());
  149. }
  150. }
  151. private void loadModuleConfigFile(Path parentAbsBaseDir, Properties moduleProps, String moduleId) {
  152. final Path absoluteBaseDir;
  153. if (moduleProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  154. absoluteBaseDir = getAbsolutePath(moduleProps.getProperty(PROPERTY_PROJECT_BASEDIR), parentAbsBaseDir);
  155. setModuleBaseDir(absoluteBaseDir, moduleProps, moduleId);
  156. try {
  157. if (!Files.isSameFile(parentAbsBaseDir, absoluteBaseDir)) {
  158. tryToFindAndLoadPropsFile(absoluteBaseDir, moduleProps, moduleId);
  159. }
  160. } catch (IOException e) {
  161. throw new IllegalStateException("Error when resolving baseDir", e);
  162. }
  163. } else if (moduleProps.containsKey(PROPERTY_PROJECT_CONFIG_FILE)) {
  164. loadModulePropsFile(parentAbsBaseDir, moduleProps, moduleId);
  165. moduleProps.remove(PROPERTY_PROJECT_CONFIG_FILE);
  166. } else {
  167. absoluteBaseDir = parentAbsBaseDir.resolve(moduleId);
  168. setModuleBaseDir(absoluteBaseDir, moduleProps, moduleId);
  169. tryToFindAndLoadPropsFile(absoluteBaseDir, moduleProps, moduleId);
  170. }
  171. }
  172. private static void setModuleBaseDir(Path absoluteBaseDir, Properties childProps, String moduleId) {
  173. if (!Files.isDirectory(absoluteBaseDir)) {
  174. throw new IllegalStateException(MessageFormat
  175. .format("The base directory of the module ''{0}'' does not exist: {1}", moduleId, absoluteBaseDir));
  176. }
  177. childProps.put(PROPERTY_PROJECT_BASEDIR, absoluteBaseDir.toString());
  178. }
  179. protected static Properties extractModuleProperties(String module, Properties properties) {
  180. Properties moduleProps = new Properties();
  181. String propertyPrefix = module + ".";
  182. int prefixLength = propertyPrefix.length();
  183. for (Map.Entry<Object, Object> entry : properties.entrySet()) {
  184. String key = (String) entry.getKey();
  185. if (key.startsWith(propertyPrefix)) {
  186. moduleProps.put(key.substring(prefixLength), entry.getValue());
  187. }
  188. }
  189. return moduleProps;
  190. }
  191. private static Path locatePropertiesFile(Properties props, String homeKey, String relativePathFromHome, String settingsKey) {
  192. Path settingsFile = null;
  193. String scannerHome = props.getProperty(homeKey, "");
  194. if (!"".equals(scannerHome)) {
  195. settingsFile = Paths.get(scannerHome, relativePathFromHome);
  196. }
  197. return locatePropertiesFile(settingsFile, props, settingsKey);
  198. }
  199. private static Path locatePropertiesFile(@Nullable Path defaultPath, Properties props, String settingsKey) {
  200. Path settingsFile;
  201. String settingsPath = props.getProperty(settingsKey, "");
  202. if (!"".equals(settingsPath)) {
  203. settingsFile = Paths.get(settingsPath);
  204. } else {
  205. settingsFile = defaultPath;
  206. }
  207. if (settingsFile != null) {
  208. return settingsFile.toAbsolutePath();
  209. }
  210. return null;
  211. }
  212. private static Properties toProperties(Path file) {
  213. Properties properties = new Properties();
  214. try (InputStream in = new FileInputStream(file.toFile())) {
  215. properties.load(in);
  216. // Trim properties
  217. for (String propKey : properties.stringPropertyNames()) {
  218. properties.setProperty(propKey, properties.getProperty(propKey).trim());
  219. }
  220. return properties;
  221. } catch (Exception e) {
  222. throw new IllegalStateException("Fail to load file: " + file, e);
  223. }
  224. }
  225. protected void loadModulePropsFile(Path parentAbsoluteBaseDir, Properties moduleProps, String moduleId) {
  226. Path propertyFile = getAbsolutePath(moduleProps.getProperty(PROPERTY_PROJECT_CONFIG_FILE),
  227. parentAbsoluteBaseDir);
  228. if (Files.isRegularFile(propertyFile)) {
  229. moduleProps.putAll(toProperties(propertyFile));
  230. Path absoluteBaseDir;
  231. if (moduleProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  232. absoluteBaseDir = getAbsolutePath(moduleProps.getProperty(PROPERTY_PROJECT_BASEDIR),
  233. propertyFile.getParent());
  234. } else {
  235. absoluteBaseDir = propertyFile.getParent();
  236. }
  237. setModuleBaseDir(absoluteBaseDir, moduleProps, moduleId);
  238. } else {
  239. throw new IllegalStateException(
  240. "The properties file of the module '" + moduleId + "' does not exist: " + propertyFile);
  241. }
  242. }
  243. private static void tryToFindAndLoadPropsFile(Path absoluteBaseDir, Properties moduleProps, String moduleId) {
  244. Path propertyFile = absoluteBaseDir.resolve(SONAR_PROJECT_PROPERTIES_FILENAME);
  245. if (!Files.isRegularFile(propertyFile)) {
  246. return;
  247. }
  248. moduleProps.putAll(toProperties(propertyFile));
  249. if (moduleProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
  250. Path overwrittenBaseDir = getAbsolutePath(moduleProps.getProperty(PROPERTY_PROJECT_BASEDIR),
  251. propertyFile.getParent());
  252. setModuleBaseDir(overwrittenBaseDir, moduleProps, moduleId);
  253. }
  254. }
  255. /**
  256. * Returns the file denoted by the given path, may this path be relative to
  257. * "baseDir" or absolute.
  258. */
  259. protected static Path getAbsolutePath(String path, Path baseDir) {
  260. Path propertyFile = Paths.get(path.trim());
  261. if (!propertyFile.isAbsolute()) {
  262. propertyFile = baseDir.resolve(propertyFile);
  263. }
  264. return propertyFile.normalize();
  265. }
  266. /**
  267. * Transforms a comma-separated list String property in to a array of
  268. * trimmed strings.
  269. *
  270. * This works even if they are separated by whitespace characters (space
  271. * char, EOL, ...)
  272. *
  273. */
  274. static String[] getListFromProperty(Properties properties, String key) {
  275. String value = properties.getProperty(key, "").trim();
  276. if (value.isEmpty()) {
  277. return new String[0];
  278. }
  279. String[] values = value.split(",");
  280. List<String> trimmedValues = new ArrayList<>();
  281. for (int i = 0; i < values.length; i++) {
  282. String trimmedValue = values[i].trim();
  283. if (!trimmedValue.isEmpty()) {
  284. trimmedValues.add(trimmedValue);
  285. }
  286. }
  287. return trimmedValues.toArray(new String[trimmedValues.size()]);
  288. }
  289. }