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

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