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

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