aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/sonar/runner/Main.java
blob: 53213454d8952716941e4100f5be8318be1abd92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
 * Sonar Runner
 * Copyright (C) 2011 SonarSource
 * dev@sonar.codehaus.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
 */
package org.sonar.runner;

import com.google.common.annotations.VisibleForTesting;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

/**
 * Arguments :
 * <ul>
 * <li>runner.home: optional path to runner home (root directory with sub-directories bin, lib and conf)</li>
 * <li>runner.settings: optional path to runner global settings, usually ${runner.home}/conf/sonar-runner.properties.
 * This property is used only if ${runner.home} is not defined</li>
 * <li>project.home: path to project root directory. If not set, then it's supposed to be the directory where the runner is executed</li>
 * <li>project.settings: optional path to project settings. Default value is ${project.home}/sonar-project.properties.</li>
 * </ul>
 *
 * @since 1.0
 */
public final class Main {

  private static final String RUNNER_HOME = "runner.home";
  private static final String RUNNER_SETTINGS = "runner.settings";
  private static final String PROJECT_HOME = "project.home";
  private static final String PROJECT_SETTINGS = "project.settings";

  private boolean debugMode = false;
  private boolean displayVersionOnly = false;
  private String command;
  @VisibleForTesting
  Properties globalProperties;
  @VisibleForTesting
  Properties projectProperties;

  /**
   * Entry point of the program.
   */
  public static void main(String[] args) {
    new Main().execute(args);
  }

  @VisibleForTesting
  Main() {
  }

  private void execute(String[] args) {
    Stats stats = new Stats().start();
    try {
      loadProperties(args);
      Runner runner = Runner.create(command, globalProperties, projectProperties);
      Logs.info("Runner version: " + Version.getVersion());
      Logs.info("Java version: " + System.getProperty("java.version", "<unknown>")
        + ", vendor: " + System.getProperty("java.vendor", "<unknown>"));
      Logs.info("OS name: \"" + System.getProperty("os.name") + "\", version: \"" + System.getProperty("os.version") + "\", arch: \"" + System.getProperty("os.arch") + "\"");
      Logs.info("Default locale: \"" + Locale.getDefault() + "\", source code encoding: \"" + runner.getSourceCodeEncoding() + "\""
        + (runner.isEncodingPlatformDependant() ? " (analysis is platform dependent)" : ""));
      if (debugMode) {
        Logs.info("Other system properties:");
        Logs.info("  - sun.arch.data.model: \"" + System.getProperty("sun.arch.data.model") + "\"");
      }
      Logs.info("Server: " + runner.getSonarServerURL());
      try {
        Logs.info("Work directory: " + runner.getWorkDir().getCanonicalPath());
      } catch (IOException e) {
        throw new RunnerException(e);
      }
      if (displayVersionOnly) {
        return;
      }
      runner.execute();
    } finally {
      stats.stop();
    }
  }

  @VisibleForTesting
  void loadProperties(String[] args) {
    Properties argsProperties = parseArguments(args);
    globalProperties = loadGlobalProperties(argsProperties);
    projectProperties = loadProjectProperties(argsProperties);
  }

  @VisibleForTesting
  Properties loadGlobalProperties(Properties argsProperties) {
    Properties commandLineProps = new Properties();
    commandLineProps.putAll(System.getProperties());
    commandLineProps.putAll(argsProperties);

    Properties result = new Properties();
    result.putAll(loadRunnerConfiguration(commandLineProps));
    result.putAll(commandLineProps);

    return result;
  }

  @VisibleForTesting
  Properties loadProjectProperties(Properties argsProperties) {
    Properties commandLineProps = new Properties();
    commandLineProps.putAll(System.getProperties());
    commandLineProps.putAll(argsProperties);

    Properties result = new Properties();
    result.putAll(loadProjectConfiguration(commandLineProps));
    result.putAll(commandLineProps);

    if (result.containsKey(PROJECT_HOME)) {
      // the real property of the Sonar Runner is "sonar.projectDir"
      String baseDir = result.getProperty(PROJECT_HOME);
      result.remove(PROJECT_HOME);
      result.put(Runner.PROPERTY_SONAR_PROJECT_BASEDIR, baseDir);
    }

    return result;
  }

  @VisibleForTesting
  Properties loadRunnerConfiguration(Properties props) {
    File settingsFile = locatePropertiesFile(props, RUNNER_HOME, "conf/sonar-runner.properties", RUNNER_SETTINGS);
    if (settingsFile != null && settingsFile.isFile() && settingsFile.exists()) {
      Logs.info("Runner configuration file: " + settingsFile.getAbsolutePath());
      return toProperties(settingsFile);
    }
    Logs.info("Runner configuration file: NONE");
    return new Properties();
  }

  private Properties loadProjectConfiguration(Properties props) {
    File settingsFile = locatePropertiesFile(props, PROJECT_HOME, "sonar-project.properties", PROJECT_SETTINGS);
    if (settingsFile != null && settingsFile.isFile() && settingsFile.exists()) {
      Logs.info("Project configuration file: " + settingsFile.getAbsolutePath());
      return toProperties(settingsFile);
    }
    Logs.info("Project configuration file: NONE");
    return new Properties();
  }

  private File locatePropertiesFile(Properties props, String homeKey, String relativePathFromHome, String settingsKey) {
    File settingsFile = null;
    String runnerHome = props.getProperty(homeKey);
    if (runnerHome != null && !"".equals(runnerHome)) {
      settingsFile = new File(runnerHome, relativePathFromHome);
    }

    if (settingsFile == null || !settingsFile.exists()) {
      String settingsPath = props.getProperty(settingsKey);
      if (settingsPath != null && !"".equals(settingsPath)) {
        settingsFile = new File(settingsPath);
      }
    }
    return settingsFile;
  }

  private Properties toProperties(File file) {
    InputStream in = null;
    Properties properties = new Properties();
    try {
      in = new FileInputStream(file);
      properties.load(in);
      return properties;

    } catch (Exception e) {
      throw new IllegalStateException("Fail to load file: " + file.getAbsolutePath(), e);

    } finally {
      IOUtils.closeQuietly(in);
    }
  }

  @VisibleForTesting
  Properties parseArguments(String[] args) {
    int i = 0;
    if (args.length > 0 && !args[0].startsWith("-")) {
      command = args[0];
      i++;
    }
    else {
      command = null;
    }
    Properties props = new Properties();
    for (; i < args.length; i++) {
      String arg = args[i];
      if ("-h".equals(arg) || "--help".equals(arg)) {
        printUsage();
      }
      else if ("-v".equals(arg) || "--version".equals(arg)) {
        displayVersionOnly = true;
      }
      else if ("-X".equals(arg) || "--debug".equals(arg)) {
        props.setProperty(Runner.PROPERTY_VERBOSE, "true");
        debugMode = true;
      }
      else if ("-D".equals(arg) || "--define".equals(arg)) {
        i++;
        if (i >= args.length) {
          printError("Missing argument for option --define");
        }
        arg = args[i];
        appendPropertyTo(arg, props);

      }
      else if (arg.startsWith("-D")) {
        arg = arg.substring(2);
        appendPropertyTo(arg, props);

      }
      else {
        printError("Unrecognized option: " + arg);
      }
    }
    return props;
  }

  private void appendPropertyTo(String arg, Properties props) {
    final String key, value;
    int j = arg.indexOf('=');
    if (j == -1) {
      key = arg;
      value = "true";
    } else {
      key = arg.substring(0, j);
      value = arg.substring(j + 1);
    }
    props.setProperty(key, value);
  }

  private void printError(String message) {
    Logs.info("");
    Logs.info(message);
    printUsage();
  }

  private void printUsage() {
    Logs.info("");
    Logs.info("usage: sonar-runner [command] [options]");
    Logs.info("");
    Logs.info("Command:");
    Logs.info(" analyse-project       Run Sonar analysis task on the current project (default)");
    Logs.info(" list-tasks            Display all tasks available");
    Logs.info("Options:");
    Logs.info(" -h,--help             Display help information");
    Logs.info(" -v,--version          Display version information");
    Logs.info(" -X,--debug            Produce execution debug output");
    Logs.info(" -D,--define <arg>     Define property");
    System.exit(0);
  }
}