2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.bin.argparser;
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.EnumSet;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Locale;
35 import jalview.bin.Console;
36 import jalview.bin.Jalview;
37 import jalview.bin.argparser.Arg.Opt;
38 import jalview.util.FileUtils;
40 public class ArgParser
42 protected static final String DOUBLEDASH = "--";
44 protected static final String NEGATESTRING = "no";
46 // the default linked id prefix used for no id (not even square braces)
47 protected static final String DEFAULTLINKEDIDPREFIX = "JALVIEW:";
49 // the counter added to the default linked id prefix
50 private int defaultLinkedIdCounter = 0;
52 // the linked id prefix used for --opennew files
53 protected static final String OPENNEWLINKEDIDPREFIX = "OPENNEW:";
55 // the counter added to the default linked id prefix
56 private int opennewLinkedIdCounter = 0;
58 // the linked id used to increment the idCounter (and use the incremented
60 private static final String INCREMENTAUTOCOUNTERLINKEDID = "{++n}";
62 // the linked id used to use the idCounter
63 private static final String AUTOCOUNTERLINKEDID = "{n}";
65 private int linkedIdAutoCounter = 0;
67 // flag to say whether {n} subtitutions in output filenames should be made.
68 // Turn on and off with --subs and --nosubs
69 private boolean substitutions = false;
71 protected static final Map<String, Arg> argMap;
73 protected Map<String, ArgValuesMap> linkedArgs = new HashMap<>();
75 protected List<String> linkedOrder = null;
77 protected List<Arg> argList;
81 argMap = new HashMap<>();
82 for (Arg a : EnumSet.allOf(Arg.class))
84 for (String argName : a.getNames())
86 if (argMap.containsKey(argName))
88 Console.warn("Trying to add argument name multiple times: '"
89 + argName + "'"); // RESTORE THIS WHEN MERGED
90 if (argMap.get(argName) != a)
93 "Trying to add argument name multiple times for different Args: '"
94 + argMap.get(argName).getName() + ":" + argName
95 + "' and '" + a.getName() + ":" + argName
100 argMap.put(argName, a);
105 public ArgParser(String[] args)
107 // Make a mutable new ArrayList so that shell globbing parser works.
108 // (When shell file globbing is used, there are a sequence of non-Arg
109 // arguments (which are the expanded globbed filenames) that need to be
110 // consumed by the --open/--argfile/etc Arg which is most easily done by
111 // removing these filenames from the list one at a time. This can't be done
112 // with an ArrayList made with only Arrays.asList(String[] args). )
113 this(new ArrayList<>(Arrays.asList(args)));
116 public ArgParser(List<String> args)
121 private void parse(List<String> args)
124 boolean openEachInitialFilenames = true;
125 for (int i = 0; i < args.size(); i++)
127 String arg = args.get(i);
129 // If the first arguments do not start with "--" or "-" or is "open" and
130 // is a filename that exists it is probably a file/list of files to open
131 // so we fake an Arg.OPEN argument and when adding files only add the
132 // single arg[i] and increment the defaultLinkedIdCounter so that each of
133 // these files is opened separately.
134 if (openEachInitialFilenames && !arg.startsWith(DOUBLEDASH)
135 && !arg.startsWith("-") && new File(arg).exists())
137 arg = DOUBLEDASH + Arg.OPENNEW.getName();
141 openEachInitialFilenames = false;
144 String argName = null;
146 List<String> globVals = null; // for Opt.GLOB only
147 SubVals globSubVals = null; // also for use by Opt.GLOB only
148 String linkedId = null;
149 if (arg.startsWith(DOUBLEDASH))
151 int equalPos = arg.indexOf('=');
154 argName = arg.substring(DOUBLEDASH.length(), equalPos);
155 val = arg.substring(equalPos + 1);
159 argName = arg.substring(DOUBLEDASH.length());
161 int idOpen = argName.indexOf('[');
162 int idClose = argName.indexOf(']');
164 if (idOpen > -1 && idClose == argName.length() - 1)
166 linkedId = argName.substring(idOpen + 1, idClose);
167 argName = argName.substring(0, idOpen);
170 Arg a = argMap.get(argName);
171 // check for boolean prepended by "no"
172 boolean negated = false;
173 if (a == null && argName.startsWith(NEGATESTRING) && argMap
174 .containsKey(argName.substring(NEGATESTRING.length())))
176 argName = argName.substring(NEGATESTRING.length());
177 a = argMap.get(argName);
181 // check for config errors
185 Console.error("Argument '" + arg + "' not recognised. Ignoring.");
188 if (!a.hasOption(Opt.BOOLEAN) && negated)
190 // used "no" with a non-boolean option
191 Console.error("Argument '--" + NEGATESTRING + argName
192 + "' not a boolean option. Ignoring.");
195 if (!a.hasOption(Opt.STRING) && equalPos > -1)
197 // set --argname=value when arg does not accept values
198 Console.error("Argument '--" + argName
199 + "' does not expect a value (given as '" + arg
203 if (!a.hasOption(Opt.LINKED) && linkedId != null)
205 // set --argname[linkedId] when arg does not use linkedIds
206 Console.error("Argument '--" + argName
207 + "' does not expect a linked id (given as '" + arg
213 if (a.hasOption(Opt.STRING))
217 if (a.hasOption(Opt.GLOB))
219 // strip off and save the SubVals to be added individually later
220 globSubVals = ArgParser.getSubVals(val);
222 .getFilenamesFromGlob(globSubVals.getContent());
226 // val is already set -- will be saved in the ArgValue later in
232 // There is no "=" so value is next arg or args (possibly shell
234 if (i + 1 >= args.size())
236 // no value to take for arg, which wants a value
237 Console.error("Argument '" + a.getName()
238 + "' requires a value, none given. Ignoring.");
241 // deal with bash globs here (--arg val* is expanded before reaching
242 // the JVM). Note that SubVals cannot be used in this case.
243 // If using the --arg=val then the glob is preserved and Java globs
244 // will be used later. SubVals can be used.
245 if (a.hasOption(Opt.GLOB))
247 // if this is the first argument with a file list at the start of
248 // the args we add filenames from index i instead of i+1
249 globVals = getShellGlobbedFilenameValues(a, args,
250 openEachInitialFilenames ? i : i + 1);
254 val = args.get(i + 1);
259 // make NOACTION adjustments
260 // default and auto counter increments
261 if (a == Arg.INCREMENT)
263 defaultLinkedIdCounter++;
265 else if (a == Arg.NPP)
267 linkedIdAutoCounter++;
269 else if (a == Arg.SUBSTITUTIONS)
271 substitutions = !negated;
274 String autoCounterString = null;
275 boolean usingAutoCounterLinkedId = false;
276 String defaultLinkedId = new StringBuilder(DEFAULTLINKEDIDPREFIX)
277 .append(Integer.toString(defaultLinkedIdCounter))
279 boolean usingDefaultLinkedId = false;
280 if (a.hasOption(Opt.LINKED))
282 if (linkedId == null)
284 if (a == Arg.OPENNEW)
286 // use the next default prefixed OPENNEWLINKEDID
287 linkedId = new StringBuilder(OPENNEWLINKEDIDPREFIX)
288 .append(Integer.toString(opennewLinkedIdCounter))
290 opennewLinkedIdCounter++;
294 // use default linkedId for linked arguments
295 linkedId = defaultLinkedId;
296 usingDefaultLinkedId = true;
297 Console.debug("Changing linkedId to '" + linkedId + "' from "
301 else if (linkedId.contains(AUTOCOUNTERLINKEDID))
303 // turn {n} to the autoCounter
304 autoCounterString = Integer.toString(linkedIdAutoCounter);
305 linkedId = linkedId.replace(AUTOCOUNTERLINKEDID,
307 usingAutoCounterLinkedId = true;
309 "Changing linkedId to '" + linkedId + "' from " + arg);
311 else if (linkedId.contains(INCREMENTAUTOCOUNTERLINKEDID))
313 // turn {++n} to the incremented autoCounter
314 autoCounterString = Integer.toString(++linkedIdAutoCounter);
315 linkedId = linkedId.replace(INCREMENTAUTOCOUNTERLINKEDID,
317 usingAutoCounterLinkedId = true;
319 "Changing linkedId to '" + linkedId + "' from " + arg);
323 if (!linkedArgs.containsKey(linkedId))
324 linkedArgs.put(linkedId, new ArgValuesMap());
326 // do not continue for NOACTION args
327 if (a.hasOption(Opt.NOACTION))
330 ArgValuesMap avm = linkedArgs.get(linkedId);
332 // not dealing with both NODUPLICATEVALUES and GLOB
333 if (a.hasOption(Opt.NODUPLICATEVALUES) && avm.hasValue(a, val))
335 Console.error("Argument '--" + argName
336 + "' cannot contain a duplicate value ('" + val
337 + "'). Ignoring this and subsequent occurrences.");
341 // check for unique id
342 SubVals idsv = ArgParser.getSubVals(val);
343 String id = idsv.get(ArgValues.ID);
344 if (id != null && avm.hasId(a, id))
346 Console.error("Argument '--" + argName + "' has a duplicate id ('"
347 + id + "'). Ignoring.");
351 boolean argIndexIncremented = false;
352 ArgValues avs = avm.getOrCreateArgValues(a);
354 // store appropriate String value(s)
355 if (a.hasOption(Opt.STRING))
357 if (a.hasOption(Opt.GLOB) && globVals != null
358 && globVals.size() > 0)
360 for (String v : globVals)
362 v = makeSubstitutions(v);
363 SubVals vsv = new SubVals(globSubVals, v);
364 avs.addValue(vsv, v, argIndex++);
365 argIndexIncremented = true;
370 avs.addValue(makeSubstitutions(val), argIndex);
373 else if (a.hasOption(Opt.BOOLEAN))
375 avs.setBoolean(!negated, argIndex);
376 avs.setNegated(negated);
378 else if (a.hasOption(Opt.UNARY))
380 avs.setBoolean(true, argIndex);
382 avs.incrementCount();
383 if (!argIndexIncremented)
386 // store in appropriate place
387 if (a.hasOption(Opt.LINKED))
389 // store the order of linkedIds
390 if (linkedOrder == null)
391 linkedOrder = new ArrayList<>();
392 if (!linkedOrder.contains(linkedId))
393 linkedOrder.add(linkedId);
396 // store arg in the list of args used
398 argList = new ArrayList<>();
399 if (!argList.contains(a))
406 private String makeSubstitutions(String val)
408 if (!this.substitutions)
413 if (val.indexOf('[') == 0 && val.indexOf(']') > 1)
415 int closeBracket = val.indexOf(']');
416 if (val.length() == closeBracket)
418 subvals = val.substring(0, closeBracket + 1);
419 rest = val.substring(closeBracket + 1);
426 if ((rest.contains(AUTOCOUNTERLINKEDID)))
427 rest = rest.replace(AUTOCOUNTERLINKEDID,
428 String.valueOf(linkedIdAutoCounter));
429 if ((rest.contains(INCREMENTAUTOCOUNTERLINKEDID)))
430 rest = rest.replace(INCREMENTAUTOCOUNTERLINKEDID,
431 String.valueOf(++linkedIdAutoCounter));
432 if ((rest.contains("{}")))
433 rest = rest.replace("{}", String.valueOf(defaultLinkedIdCounter));
435 return new StringBuilder(subvals).append(rest).toString();
439 * A helper method to take a list of String args where we're expecting
440 * {"--previousargs", "--arg", "file1", "file2", "file3", "--otheroptionsornot"}
441 * and the index of the globbed arg, here 1. It returns a
442 * List<String> {"file1", "file2", "file3"}
443 * *and remove these from the original list object* so that processing
444 * can continue from where it has left off, e.g. args has become
445 * {"--previousargs", "--arg", "--otheroptionsornot"}
446 * so the next increment carries on from the next --arg if available.
448 protected static List<String> getShellGlobbedFilenameValues(Arg a,
449 List<String> args, int i)
451 List<String> vals = new ArrayList<>();
452 while (i < args.size() && !args.get(i).startsWith(DOUBLEDASH))
454 vals.add(FileUtils.substituteHomeDir(args.remove(i)));
455 if (!a.hasOption(Opt.GLOB))
461 public boolean isSet(Arg a)
463 return a.hasOption(Opt.LINKED) ? isSet("", a) : isSet(null, a);
466 public boolean isSet(String linkedId, Arg a)
468 ArgValuesMap avm = linkedArgs.get(linkedId);
469 return avm == null ? false : avm.containsArg(a);
472 public boolean getBool(Arg a)
474 if (!a.hasOption(Opt.BOOLEAN) && !a.hasOption(Opt.UNARY))
476 Console.warn("Getting boolean from non boolean Arg '" + a.getName()
479 return a.hasOption(Opt.LINKED) ? getBool("", a) : getBool(null, a);
482 public boolean getBool(String linkedId, Arg a)
484 ArgValuesMap avm = linkedArgs.get(linkedId);
486 return a.getDefaultBoolValue();
487 ArgValues avs = avm.getArgValues(a);
488 return avs == null ? a.getDefaultBoolValue() : avs.getBoolean();
491 public List<String> linkedIds()
496 public ArgValuesMap linkedArgs(String id)
498 return linkedArgs.get(id);
502 public String toString()
504 StringBuilder sb = new StringBuilder();
505 sb.append("UNLINKED\n");
506 sb.append(argValuesMapToString(linkedArgs.get(null)));
507 if (linkedIds() != null)
509 sb.append("LINKED\n");
510 for (String id : linkedIds())
512 // already listed these as UNLINKED args
516 ArgValuesMap avm = linkedArgs(id);
517 sb.append("ID: '").append(id).append("'\n");
518 sb.append(argValuesMapToString(avm));
521 return sb.toString();
524 private static String argValuesMapToString(ArgValuesMap avm)
528 StringBuilder sb = new StringBuilder();
529 for (Arg a : avm.getArgKeys())
531 ArgValues v = avm.getArgValues(a);
532 sb.append(v.toString());
535 return sb.toString();
538 public static SubVals getSubVals(String item)
540 return new SubVals(item);
543 public static ArgParser parseArgFiles(List<String> argFilenameGlobs)
545 List<File> argFiles = new ArrayList<>();
547 for (String pattern : argFilenameGlobs)
549 // I don't think we want to dedup files, making life easier
550 argFiles.addAll(FileUtils.getFilesFromGlob(pattern));
553 return parseArgFileList(argFiles);
556 public static ArgParser parseArgFileList(List<File> argFiles)
558 List<String> argsList = new ArrayList<>();
559 for (File argFile : argFiles)
561 if (!argFile.exists())
563 String message = DOUBLEDASH
564 + Arg.ARGFILE.name().toLowerCase(Locale.ROOT) + "=\""
565 + argFile.getPath() + "\": File does not exist.";
566 Jalview.exit(message, 2);
570 argsList.addAll(Files.readAllLines(Paths.get(argFile.getPath())));
571 } catch (IOException e)
573 String message = DOUBLEDASH
574 + Arg.ARGFILE.name().toLowerCase(Locale.ROOT) + "=\""
575 + argFile.getPath() + "\": File could not be read.";
576 Jalview.exit(message, 3);
579 return new ArgParser(argsList);