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 12KB

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