source: trunk/yat/CommandLine.cc @ 1336

Last change on this file since 1336 was 1336, checked in by Peter Johansson, 12 years ago

latest yat

  • Property svn:eol-style set to native
File size: 6.3 KB
Line 
1// $Id: CommandLine.cc 2384 2010-12-22 14:03:36Z peter $
2
3/*
4  Copyright (C) 2007 Jari Häkkinen, Peter Johansson, Markus Ringnér
5  Copyright (C) 2008 Jari Häkkinen, Peter Johansson
6  Copyright (C) 2009, 2010 Peter Johansson
7
8  This file is part of the yat library, http://dev.thep.lu.se/yat
9
10  The yat library is free software; you can redistribute it and/or
11  modify it under the terms of the GNU General Public License as
12  published by the Free Software Foundation; either version 3 of the
13  License, or (at your option) any later version.
14
15  The yat library is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  General Public License for more details.
19
20  You should have received a copy of the GNU General Public License
21  along with yat. If not, see <http://www.gnu.org/licenses/>.
22*/
23
24#include "CommandLine.h"
25
26#include "ColumnStream.h"
27#include "Exception.h"
28#include "Option.h"
29#include "OptionSwitch.h"
30#include "utility.h"
31
32#include <algorithm>
33#include <cassert>
34#include <functional>
35#include <fstream>
36#include <ostream>
37#include <sstream>
38#include <stdexcept>
39#include <string>
40#include <vector>
41
42namespace theplu {
43namespace yat {
44namespace utility {
45
46  CommandLine::CommandLine(std::string str)
47    : description_(str), free_arg_max_(0), parsed_(false)
48  {}
49
50
51  CommandLine::~CommandLine(void)
52  {
53  }
54
55
56  void CommandLine::add(Option& option)
57  {
58    if (option.long_name().size()) {
59      if (long_options_.find(option.long_name())!=long_options_.end()) {
60        std::stringstream ss;
61        ss << "yat::utility::Commandline: two options with long_name: "
62           << option.long_name();
63        throw runtime_error(ss.str());
64      }
65      long_options_[option.long_name()] = &option;
66    }
67    if (option.short_name()) {
68      if (short_options_.find(option.short_name())!=short_options_.end()) {
69        std::stringstream ss;
70        ss << "yat::utility::Commandline: two options with short_name: "
71           << option.short_name();
72        throw runtime_error(ss.str());
73      }
74      short_options_[option.short_name()] = &option;
75    }
76    if (option.long_name().size() || option.short_name())
77      options_.push_back(&option);
78  }
79
80
81  void CommandLine::allow_free_args(size_t n)
82  {
83    free_arg_max_ = n;
84  }
85
86
87  const std::vector<std::string>& CommandLine::free_args(void) const
88  {
89    return free_arg_;
90  }
91
92
93  bool CommandLine::is_long_option(std::string str) const
94  {
95    return (str.size()>2 && str[0]=='-' && str[1]=='-');
96  }
97
98
99  bool CommandLine::is_short_option(std::string str) const
100  {
101    return (str.size()>=2 && str[0]=='-' && str[1]!='-');
102  }
103
104
105  void CommandLine::parse(int argc, char* argv[])
106  {   
107    parsed_=true;
108    using namespace std;
109    // just in case it is not pristine
110    for_each(options_.begin(), options_.end(),std::mem_fun(&Option::reset)); 
111
112    std::vector<std::string> arguments;
113    arguments.reserve(argc);
114    for (int i=0; i<argc; ++i)
115      arguments.push_back(argv[i]);
116    std::vector<std::string>::iterator arg(arguments.begin());   
117    stringstream ss(*arg++);
118    // keeping string after last /
119    while (getline(ss, program_name_,'/')) {}
120
121    try {
122      for (; arg!=arguments.end(); ++arg) {
123        if (is_long_option(*arg)) {
124          std::string key(arg->substr(2));
125          std::stringstream ss2(key);
126          getline(ss2, key, '=');
127          std::string value;
128          getline(ss2, value, '\0');
129          if (!value.empty()){
130            *arg = value;
131            *(--arg) = std::string("--")+key;
132          }         
133          else
134            *arg = key;
135          std::map<std::string, Option*>::const_iterator
136            iter(long_options_.find(key));
137          if (iter!=long_options_.end())
138            iter->second->parse(arg, arguments.end());
139          else if (key.size()>3 && key.substr(0,3)=="no-") { 
140            iter = long_options_.find(key.substr(3));
141            if (iter!=long_options_.end())
142              iter->second->parse(arg, arguments.end());
143          }           
144          else if (iter==long_options_.end()) {
145            std::stringstream ss3;
146            ss3 << "unrecognized option `" << key << "'\n" << try_help();
147            throw cmd_error(ss3.str());
148          }
149        }
150        else if (is_short_option(*arg)) {
151          size_t size=arg->size();
152          for (size_t i=1; i<size; ++i){
153            std::map<char, Option*>::const_iterator
154              iter(short_options_.find((*arg)[i]));
155            if (iter==short_options_.end()) {
156              std::stringstream ss2;
157              ss2 << ": invalid option -- " << (*arg)[i] << "\n"
158                  << try_help() << "\n";
159              throw cmd_error(ss2.str());
160            }       
161            else 
162              iter->second->parse(arg, arguments.end());
163          }
164        }
165        else {
166          free_arg_.push_back(*arg);
167          if (free_arg_.size()>free_arg_max_) {
168            std::stringstream ss2;
169            ss2 << ": invalid option -- " << *arg << "\n"
170                << try_help() << "\n";
171            throw cmd_error(ss2.str());
172          }
173        }
174      }
175      for_each(options_.begin(),options_.end(),
176               std::mem_fun(&Option::validate)); 
177    }
178    catch (cmd_error& e){
179      std::stringstream ss2;
180      ss2 << program_name_ << ": " << e.what();
181      throw cmd_error(ss2.str());
182    }
183     
184  }
185
186
187  bool CommandLine::parsed(void) const
188  {
189    return parsed_;
190  }
191
192
193  std::string CommandLine::program_name(void) const
194  {
195    return program_name_;
196  }
197
198
199  void CommandLine::sort(void)
200  {
201    sort(OptionCompare());
202  }
203
204
205  std::string CommandLine::try_help(void) const
206  {
207    return std::string("Try `"+program_name()+" --help' for more information.");
208  }
209
210
211  std::ostream& operator<<(std::ostream& os, const CommandLine& cmd)
212  {
213    os << cmd.description_ << "\n";
214    ColumnStream cs2(os, 2);
215    std::string::size_type width = 0;
216    for (std::vector<Option*>::const_iterator i(cmd.options_.begin()); 
217         i!=cmd.options_.end();++i) {
218      std::stringstream ss((*i)->print());
219      std::string str;
220      getline(ss, str, '\t');
221      width = std::max(width, str.size()+3);       
222    }
223    cs2.width(0)=width;
224    cs2.width(1)=76-width;
225    cs2.margin(0)=2;
226
227    for (std::vector<Option*>::const_iterator i(cmd.options_.begin()); 
228         i!=cmd.options_.end();++i) 
229      cs2 << (*i)->print() << "\n";
230
231    return os;
232  }
233
234
235  bool CommandLine::OptionCompare::operator()(const Option* lhs, 
236                                              const Option* rhs) const
237  {
238    assert(lhs);
239    assert(rhs);
240    std::string lhs_str = lhs->long_name();
241    if (lhs_str.empty())
242      lhs_str = lhs->short_name();
243    std::string rhs_str = rhs->long_name();
244    if (rhs_str.empty())
245      rhs_str = rhs->short_name();
246    return lhs_str < rhs_str;
247  }
248
249
250}}} // of namespace utility, yat, and theplu
Note: See TracBrowser for help on using the repository browser.