summaryrefslogtreecommitdiff
path: root/org.genivi.commonapi.core.cli/src/org/genivi/commonapi/core/cli/CommandlineToolMain.java
blob: bc85c201d58f005790b579686c02da55496c4e35 (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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
 * Copyright (C) 2013 BMW Group Author: Manfred Bathelt (manfred.bathelt@bmw.de)
 * Author: Juergen Gehring (juergen.gehring@bmw.de) This Source Code Form is
 * subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the
 * MPL was not distributed with this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 */

package org.genivi.commonapi.core.cli;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.generator.IGenerator;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.validation.AbstractValidationMessageAcceptor;
import org.eclipse.xtext.validation.ValidationMessageAcceptor;
import org.franca.core.dsl.FrancaIDLRuntimeModule;
import org.franca.core.franca.FModel;
import org.franca.deploymodel.dsl.fDeploy.FDModel;
import org.genivi.commonapi.console.CommandlineTool;
import org.genivi.commonapi.console.ConsoleLogger;
import org.genivi.commonapi.core.generator.FrancaGenerator;
import org.genivi.commonapi.core.generator.FrancaGeneratorExtensions;
import org.genivi.commonapi.core.generator.GeneratorFileSystemAccess;
import org.genivi.commonapi.core.preferences.FPreferences;
import org.genivi.commonapi.core.preferences.PreferenceConstants;
import org.genivi.commonapi.core.verification.CommandlineValidator;
import org.genivi.commonapi.core.verification.ValidatorCore;

import com.google.inject.Guice;
import com.google.inject.Injector;

/**
 * Receive command line arguments and set them as preference values for the code
 * generation.
 */
public class CommandlineToolMain extends CommandlineTool {

	protected GeneratorFileSystemAccess fsa;
	private FPreferences pref;
	protected Injector injector;
	protected IGenerator francaGenerator;
	protected String scope = "Core validation: ";

	private ValidationMessageAcceptor cliMessageAcceptor = new AbstractValidationMessageAcceptor() {

		@Override
		public void acceptInfo(String message, EObject object,
				EStructuralFeature feature, int index, String code,
				String... issueData) {
			ConsoleLogger.printLog(scope + message);
		}

		@Override
		public void acceptWarning(String message, EObject object,
				EStructuralFeature feature, int index, String code,
				String... issueData) {
			ConsoleLogger.printLog("Warning: " + scope + message);
		}

		@Override
		public void acceptError(String message, EObject object,
				EStructuralFeature feature, int index, String code,
				String... issueData) {
			hasValidationError = true;
			ConsoleLogger.printErrorLog("Error: " + scope + message);
		}
	};

	/**
	 * The constructor registers the needed bindings to use the generator
	 */
	public CommandlineToolMain() {

		injector = Guice.createInjector(new FrancaIDLRuntimeModule());

		fsa = injector.getInstance(GeneratorFileSystemAccess.class);

		pref = FPreferences.getInstance();

	}

	public void generateCore(List<String> fileList) {
		francaGenerator = injector.getInstance(FrancaGenerator.class);

		doGenerate(fileList);
	}
	
	protected String normalize(String _path) {
		File itsFile = new File(_path);
		return itsFile.getAbsolutePath();
	}
	

	/**
	 * Call the franca generator for the specified list of files.
	 * 
	 * @param fileList
	 *            the list of files to generate code from
	 */
	protected void doGenerate(List<String> _fileList) {
		fsa.setOutputConfigurations(FPreferences.getInstance()
				.getOutputpathConfiguration());

		XtextResourceSet rsset = injector.getProvider(XtextResourceSet.class)
				.get();

		ConsoleLogger.printLog("Using Franca Version " + getFrancaVersion());
		ConsoleLogger.printLog("and CommonAPI Version "
				+ FrancaGeneratorExtensions.getCoreVersion());
		int error_state = NO_ERROR_STATE;
		
		// Create absolute paths
		List<String> fileList = new ArrayList<String>();
		for (String path : _fileList) {
			String absolutePath = normalize(path);
			fileList.add(absolutePath);
		}

		for (String file : fileList) {
			URI uri = URI.createFileURI(file);
			Resource resource = null;
			try {
				resource = rsset.createResource(uri);
			} catch (IllegalStateException ise) {
				ConsoleLogger.printErrorLog("Failed to create a resource from "
						+ file + "\n" + ise.getMessage());
				error_state = ERROR_STATE;
				continue;
			}
			hasValidationError = false;
			if (isValidation) {
				validateCore(resource);
			}
			if (hasValidationError) {
				ConsoleLogger.printErrorLog(file
						+ " contains validation errors !");
				error_state = ERROR_STATE;
			} else if (isCodeGeneration) {
				ConsoleLogger.printLog("Generating code for " + file);
				try {
					if (FPreferences.getInstance().getPreference(
							PreferenceConstants.P_OUTPUT_SUBDIRS, "false").equals("true")) {
						String subdir = (new File(file)).getName();
						subdir = subdir.replace(".fidl", "");
						subdir = subdir.replace(".fdepl", "");
						fsa.setOutputConfigurations(FPreferences.getInstance()
								.getOutputpathConfiguration(subdir));
					}
					francaGenerator.doGenerate(resource, fsa);
				} catch (Exception e) {
					System.err.println("Failed to generate code for " + file
							+ " due to " + e.getMessage());
					error_state = ERROR_STATE;
				}
			}
			if (resource != null) {
				// Clear each resource from the resource set in order to let
				// other fidl files import it.
				// Otherwise an IllegalStateException will be thrown for a
				// resource that was already created.
				resource.unload();
				rsset.getResources().clear();
			}
		}
		if (dumpGeneratedFiles) {
			fsa.dumpGeneratedFiles();
		}
		fsa.clearFileList();
		dumpGeneratedFiles = false;
		System.exit(error_state);
	}

	/**
	 * Validate the fidl/fdepl file resource
	 * 
	 * @param resource
	 */
	private void validateCore(Resource resource) {
		EObject model = null;
		CommandlineValidator cliValidator = new CommandlineValidator(
				cliMessageAcceptor);

		//ConsoleLogger.printLog("validating " + resource.getURI().lastSegment());

		model = cliValidator.loadResource(resource);

		if (model != null) {
			// check existence of imported fidl/fdepl files
			if (model instanceof FModel) {
				cliValidator.validateImports((FModel) model, resource.getURI());

				// validate against GENIVI rules
				ValidatorCore validator = new ValidatorCore();
				try {
					validator.validateModel((FModel) model, cliMessageAcceptor);
				} catch (Exception e) {
					ConsoleLogger.printErrorLog(e.getMessage());
					hasValidationError = true;
					return;
				}
			}
			if (model instanceof FDModel) {
				// don't validate fdepl files at the moment				
				return;
				// cliValidator.validateImports((FDModel) model, resource.getURI());
			}
			// XText validation
			cliValidator.validateResourceWithImports(resource);
		} else {
			// model is null, no resource factory was registered !
			hasValidationError = true;
		}
	}

	public void setNoCommonCode() {
		pref.setPreference(PreferenceConstants.P_GENERATE_COMMON, "false");
		ConsoleLogger.printLog("No common code will be generated");
	}
	
	public void setNoProxyCode() {
		pref.setPreference(PreferenceConstants.P_GENERATE_PROXY, "false");
		ConsoleLogger.printLog("No proxy code will be generated");
	}

	public void setNoStubCode() {
		pref.setPreference(PreferenceConstants.P_GENERATE_STUB, "false");
		ConsoleLogger.printLog("No stub code will be generated");
	}

	public void setDefaultDirectory(String optionValue) {
		ConsoleLogger.printLog("Default output directory: " + optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_DEFAULT, optionValue);
		// In the case where no other output directories are set,
		// this default directory will be used for them
		pref.setPreference(PreferenceConstants.P_OUTPUT_COMMON, optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_PROXIES, optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_STUBS, optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_SKELETON, optionValue);
	}

	public void setDestinationSubdirs() {
		ConsoleLogger.printLog("Using destination subdirs");
		pref.setPreference(PreferenceConstants.P_OUTPUT_SUBDIRS, "true");
	}

	public void setCommonDirectory(String optionValue) {
		ConsoleLogger.printLog("Common output directory: " + optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_COMMON, optionValue);
	}

	public void setProxyDirectory(String optionValue) {
		ConsoleLogger.printLog("Proxy output directory: " + optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_PROXIES, optionValue);
	}

	public void setStubDirectory(String optionValue) {
		ConsoleLogger.printLog("Stub output directory: " + optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_STUBS, optionValue);
	}

	public void setSkeletonDirectory(String optionValue) {
		ConsoleLogger.printLog("Skeleton output directory: " + optionValue);
		pref.setPreference(PreferenceConstants.P_OUTPUT_SKELETON, optionValue);
	}

	public void setLogLevel(String optionValue) {
		if (PreferenceConstants.LOGLEVEL_QUIET.equals(optionValue)) {
			pref.setPreference(PreferenceConstants.P_LOGOUTPUT, "false");
			ConsoleLogger.enableLogging(false);
			ConsoleLogger.enableErrorLogging(false);
		}
		if (PreferenceConstants.LOGLEVEL_VERBOSE.equals(optionValue)) {
			pref.setPreference(PreferenceConstants.P_LOGOUTPUT, "true");
			ConsoleLogger.enableErrorLogging(true);
			ConsoleLogger.enableLogging(true);
		}
	}

	public void setEnumPrefix(String optionValue) {
		pref.setPreference(PreferenceConstants.P_ENUMPREFIX, optionValue);
		ConsoleLogger.printLog("Enum prefix: " + optionValue);
	}

	public void setCreateSkeletonCode() {
		pref.setPreference(PreferenceConstants.P_GENERATE_SKELETON, "true");
		ConsoleLogger.printLog("Skeleton code will be created");
	}

	public void setSkeletonPostfix(String optionValue) {
		String postfix = (optionValue == null ? "Default" : optionValue);
		pref.setPreference(PreferenceConstants.P_SKELETONPOSTFIX, postfix);
		ConsoleLogger.printLog("Skeleton postfix: " + postfix);
	}

	public void disableValidation() {
		ConsoleLogger.printLog("Validation is off");
		isValidation = false;
	}

	/**
	 * Set the text from a file which will be inserted as a comment in each
	 * generated file (for example your license)
	 * 
	 * @param fileWithText
	 * @return
	 */
	public void setLicenseText(String fileWithText) {

		String licenseText = getLicenseText(fileWithText);

		if (licenseText != null && !licenseText.isEmpty()) {
			pref.setPreference(PreferenceConstants.P_LICENSE, licenseText);
		}
	}

	/**
	 * set a preference value to disable code generation
	 */
	public void disableCodeGeneration() {
		ConsoleLogger.printLog("Code generation is off");
		pref.setPreference(PreferenceConstants.P_GENERATE_CODE, "false");
	}

	/**
	 * Set a preference value to disable code generation for included types and
	 * interfaces
	 */
	public void noCodeforDependencies() {
		ConsoleLogger.printLog("Code generation for dependencies is switched off");
		pref.setPreference(PreferenceConstants.P_GENERATE_DEPENDENCIES, "false");
	}

	public void listGeneratedFiles() {
		dumpGeneratedFiles = true;
	}

	public void disableSyncCalls() {
		ConsoleLogger.printLog("Code generation for synchronous calls is off");
		pref.setPreference(PreferenceConstants.P_GENERATE_SYNC_CALLS, "false");
	}

}