001    /*
002     * Copyright (C) 2012 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    package org.crsh.cli.impl.invocation;
020    
021    import org.crsh.cli.impl.tokenizer.Token;
022    
023    import java.util.ArrayList;
024    import java.util.Iterator;
025    import java.util.List;
026    
027    /**
028     * @author Julien Viet
029     */
030    class TokenList implements Iterable<Token> {
031    
032      /** . */
033      final ArrayList<Token> list = new ArrayList<Token>();
034    
035      TokenList() {
036      }
037    
038      TokenList(Iterable<Token> tokens) {
039        for (Token token : tokens) {
040          list.add(token);
041        }
042      }
043    
044      int last() {
045        return list.size() > 0 ? list.get(list.size() - 1).getTo() : 0;
046      }
047    
048      public void add(Token token) {
049        if (list.size() > 0) {
050          list.add(new Token.Whitespace(last(), " "));
051        }
052        list.add(token);
053      }
054    
055      public void addOption(String name) {
056        if (name.length() == 1) {
057          add(new Token.Literal.Option.Short(last(), "-" + name));
058        } else {
059          add(new Token.Literal.Option.Long(last(), "--" + name));
060        }
061      }
062    
063      public void addOption(String name, List<?> value) {
064        if (value.size() > 0) {
065          Object first = value.get(0);
066          if (first instanceof Boolean) {
067            for (Object o : value) {
068              if ((Boolean)o) {
069                addOption(name);
070              }
071            }
072          } else {
073            for (Object o : value) {
074              addOption(name);
075              add(new Token.Literal.Word(last(), o.toString()));
076            }
077          }
078        }
079      }
080    
081      @Override
082      public Iterator<Token> iterator() {
083        return list.iterator();
084      }
085    }