summaryrefslogtreecommitdiff
path: root/support/arara/source/src/main/java/com/github/cereda/arara/model/Parser.java
blob: 681c2f8fef3c7d194d440a2856eaf066e8610a77 (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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
 * Arara, the cool TeX automation tool
 * Copyright (c) 2012 -- 2019, Paulo Roberto Massa Cereda 
 * All rights reserved.
 *
 * Redistribution and  use in source  and binary forms, with  or without
 * modification, are  permitted provided  that the  following conditions
 * are met:
 *
 * 1. Redistributions  of source  code must  retain the  above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form  must reproduce the above copyright
 * notice, this list  of conditions and the following  disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * 3. Neither  the name  of the  project's author nor  the names  of its
 * contributors may be used to  endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS  PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS
 * "AS IS"  AND ANY  EXPRESS OR IMPLIED  WARRANTIES, INCLUDING,  BUT NOT
 * LIMITED  TO, THE  IMPLIED WARRANTIES  OF MERCHANTABILITY  AND FITNESS
 * FOR  A PARTICULAR  PURPOSE  ARE  DISCLAIMED. IN  NO  EVENT SHALL  THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE  LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY,  OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT  NOT LIMITED  TO, PROCUREMENT  OF SUBSTITUTE  GOODS OR  SERVICES;
 * LOSS  OF USE,  DATA, OR  PROFITS; OR  BUSINESS INTERRUPTION)  HOWEVER
 * CAUSED AND  ON ANY THEORY  OF LIABILITY, WHETHER IN  CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
 * WAY  OUT  OF  THE USE  OF  THIS  SOFTWARE,  EVEN  IF ADVISED  OF  THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package com.github.cereda.arara.model;

import com.github.cereda.arara.controller.ConfigurationController;
import com.github.cereda.arara.controller.LanguageController;
import com.github.cereda.arara.controller.LoggingController;
import com.github.cereda.arara.utils.CommonUtils;
import com.github.cereda.arara.utils.DisplayUtils;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * Implements the command line parser.
 * @author Paulo Roberto Massa Cereda
 * @version 4.0
 * @since 4.0
 */
public class Parser {

    // command line arguments to be
    // processed by this parser
    private final String[] arguments;

    // command line options, it will
    // group each option available
    // in arara
    private Options options;

    // each option available in
    // arara
    private Option version;
    private Option help;
    private Option log;
    private Option verbose;
    private Option silent;
    private Option dryrun;
    private Option timeout;
    private Option language;
    private Option loops;
    private Option preamble;
    private Option onlyheader;

    public Parser() {
        this.arguments = null;
    }

    // the application messages obtained from the
    // language controller
    private static final LanguageController messages =
            LanguageController.getInstance();

    /**
     * Constructor.
     * @param arguments Array of strings representing the command line
     * arguments.
     */
    public Parser(String[] arguments) {
        this.arguments = arguments;
    }

    /**
     * Parses the command line arguments.
     * @return A boolean value indicating if the parsing should allow the
     * application to look for directives in the provided main file.
     * @throws AraraException Something wrong happened, to be caught in the
     * higher levels.
     */
    public boolean parse() throws AraraException {

        // create new instances of the
        // command line options, including
        // the ones that require arguments
        version = new Option("V", "version", false, "");
        help = new Option("h", "help", false, "");
        log = new Option("l", "log", false, "");
        verbose = new Option("v", "verbose", false, "");
        silent = new Option("s", "silent", false, "");
        dryrun = new Option("n", "dry-run", false, "");
        timeout = new Option("t", "timeout", true, "");
        timeout.setArgName("number");
        language = new Option("L", "language", true, "");
        language.setArgName("code");
        loops = new Option("m", "max-loops", true, "");
        loops.setArgName("number");
        preamble = new Option("p", "preamble", true, "");
        preamble.setArgName("name");
        onlyheader = new Option("H", "header", false, "");

        // add all options to the options
        // group, so they are recognized
        // by the command line parser
        options = new Options();
        options.addOption(version);
        options.addOption(help);
        options.addOption(log);
        options.addOption(verbose);
        options.addOption(silent);
        options.addOption(dryrun);
        options.addOption(timeout);
        options.addOption(language);
        options.addOption(loops);
        options.addOption(preamble);
        options.addOption(onlyheader);

        // update all descriptions based
        // on the localized messages
        updateDescriptions();

        // a new default command line
        // parser is created and the
        // arguments are parsed
        CommandLineParser parser = new DefaultParser();

        try {

            CommandLine line = parser.parse(options, arguments);

            String reference;
            if (line.hasOption("language")) {
                ConfigurationController.getInstance().
                        put("execution.language",
                                new Language(line.getOptionValue("language"))
                        );
                Locale locale = ((Language) ConfigurationController.
                        getInstance().get("execution.language")).getLocale();
                messages.setLocale(locale);
                updateDescriptions();
            }

            if (line.hasOption("help")) {
                printVersion();
                printUsage();
                return false;
            }

            if (line.hasOption("version")) {
                printVersion();
                printNotes();
                return false;
            }

            if (line.getArgs().length != 1) {
                printVersion();
                printUsage();
                return false;
            } else {
                reference = line.getArgs()[0];
            }

            if (line.hasOption("timeout")) {
                try {
                    long value = Long.parseLong(line.getOptionValue("timeout"));
                    if (value <= 0) {
                        throw new AraraException(
                                messages.getMessage(
                                        Messages.ERROR_PARSER_TIMEOUT_INVALID_RANGE
                                )
                        );
                    } else {
                        ConfigurationController.getInstance().
                                put("execution.timeout", true);
                        ConfigurationController.getInstance().
                                put("execution.timeout.value", value);
                    }
                } catch (NumberFormatException nfexception) {
                    throw new AraraException(
                            messages.getMessage(
                                    Messages.ERROR_PARSER_TIMEOUT_NAN
                            )
                    );
                }
            }

            if (line.hasOption("max-loops")) {
                try {
                    long value = Long.parseLong(
                            line.getOptionValue("max-loops")
                    );
                    if (value <= 0) {
                        throw new AraraException(
                                messages.getMessage(
                                        Messages.ERROR_PARSER_LOOPS_INVALID_RANGE
                                )
                        );
                    } else {
                        ConfigurationController.getInstance().
                                put("execution.loops", value);
                    }
                } catch (NumberFormatException nfexception) {
                    throw new AraraException(
                            messages.getMessage(
                                    Messages.ERROR_PARSER_LOOPS_NAN
                            )
                    );
                }
            }

            if (line.hasOption("verbose")) {
                ConfigurationController.getInstance().
                        put("execution.verbose", true);
            }
            
            if (line.hasOption("silent")) {
                ConfigurationController.getInstance().
                        put("execution.verbose", false);
            }

            if (line.hasOption("dry-run")) {
                ConfigurationController.getInstance().
                        put("execution.dryrun", true);
                ConfigurationController.getInstance().
                        put("execution.errors.halt", false);
            }

            if (line.hasOption("log")) {
                ConfigurationController.getInstance().
                        put("execution.logging", true);
            }
            
            if (line.hasOption("preamble")) {
                @SuppressWarnings("unchecked")
                Map<String, String> preambles = (Map<String, String>) 
                        ConfigurationController.getInstance().
                        get("execution.preambles");
                if (preambles.containsKey(line.getOptionValue("preamble"))) {
                    ConfigurationController.getInstance().
                        put("execution.preamble.active", true);
                    ConfigurationController.getInstance().
                        put("execution.preamble.content",
                                preambles.get(line.getOptionValue("preamble"))
                        );
                }
                else {
                    throw new AraraException(
                            messages.getMessage(
                                    Messages.ERROR_PARSER_INVALID_PREAMBLE,
                                    line.getOptionValue("preamble")
                            )
                    );
                }
            }
            
            if (line.hasOption("header")) {
                ConfigurationController.getInstance().
                        put("execution.header", true);
            }

            CommonUtils.discoverFile(reference);
            LoggingController.enableLogging((Boolean) ConfigurationController.
                    getInstance().get("execution.logging"));
            ConfigurationController.getInstance().put("display.time", true);

            return true;

        } catch (ParseException pexception) {
            printVersion();
            printUsage();
            return false;
        }
    }

    /**
     * Prints the application usage.
     */
    private void printUsage() {
        HelpFormatter formatter = new HelpFormatter();
        StringBuilder builder = new StringBuilder();
        builder.append("arara [file [--dry-run] [--log] ");
        builder.append("[--verbose | --silent] [--timeout N] ");
        builder.append("[--max-loops N] [--language L] ");
        builder.append("[ --preamble P ] [--header] | --help | --version]");
        formatter.printHelp(builder.toString(), options);
    }

    /**
     * Prints the application version.
     */
    private void printVersion() {
        String year = (String) ConfigurationController.getInstance().
                get("application.copyright.year");
        String number = (String) ConfigurationController.getInstance().
                get("application.version");
        String revision = (String) ConfigurationController.getInstance().
                get("application.revision");
        StringBuilder builder = new StringBuilder();
        builder.append("arara ");
        builder.append(number);
        builder.append(" (revision ");
        builder.append(revision);
        builder.append(")");
        builder.append("\n");
        builder.append("Copyright (c) ").append(year).append(", ");
        builder.append("Paulo Roberto Massa Cereda");
        builder.append("\n");
        builder.append(messages.getMessage(
                Messages.INFO_PARSER_ALL_RIGHTS_RESERVED)
        );
        builder.append("\n");
        System.out.println(builder.toString());
    }

    /**
     * Print the application notes.
     */
    private void printNotes() {
        DisplayUtils.wrapText(messages.getMessage(Messages.INFO_PARSER_NOTES));
    }

    /**
     * Updates all the descriptions in order to make them reflect the current
     * language setting.
     */
    private void updateDescriptions() {
        version.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_VERSION_DESCRIPTION
                )
        );
        help.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_HELP_DESCRIPTION
                )
        );
        log.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_LOG_DESCRIPTION
                )
        );
        verbose.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_VERBOSE_MODE_DESCRIPTION
                )
        );
        silent.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_SILENT_MODE_DESCRIPTION
                )
        );
        dryrun.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_DRYRUN_MODE_DESCRIPTION
                )
        );
        timeout.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_TIMEOUT_DESCRIPTION
                )
        );
        language.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_LANGUAGE_DESCRIPTION
                )
        );
        loops.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_LOOPS_DESCRIPTION
                )
        );
        preamble.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_PREAMBLE_DESCRIPTION
                )
        );
        onlyheader.setDescription(
                messages.getMessage(
                        Messages.INFO_PARSER_ONLY_HEADER
                )
        );
    }

}