source: trunk/yat/utility/CommandLine.cc @ 1275

Last change on this file since 1275 was 1275, checked in by Jari Häkkinen, 15 years ago

Updating copyright statements.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 5.0 KB
Line 
1// $Id: CommandLine.cc 1275 2008-04-11 06:10:12Z jari $
2
3/*
4  Copyright (C) 2007 Jari Häkkinen, Peter Johansson, Markus Ringnér
5  Copyright (C) 2008 Peter Johansson
6
7  This file is part of the yat library, http://trac.thep.lu.se/yat
8
9  The yat library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU General Public License as
11  published by the Free Software Foundation; either version 2 of the
12  License, or (at your option) any later version.
13
14  The yat library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with this program; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
22  02111-1307, USA.
23*/
24
25#include "CommandLine.h"
26
27#include "ColumnStream.h"
28#include "Exception.h"
29#include "Option.h"
30#include "OptionSwitch.h"
31#include "utility.h"
32
33#include <algorithm>
34#include <functional>
35#include <fstream>
36#include <iostream>
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)
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      long_options_[option.long_name()] = &option;
60    if (option.short_name())
61      short_options_[option.short_name()] = &option;
62    if (option.long_name().size() || option.short_name())
63      options_.push_back(&option);
64    // allow `no-switch' for option `switch'
65    OptionSwitch* o = dynamic_cast<OptionSwitch*>(&option);
66    if (option.long_name().size() && o && 
67        !( o->long_name().size()>2 && o->long_name().substr(0,3)=="no-"))
68      long_options_[std::string("no-")+option.long_name()] = &option;
69  }
70
71
72  bool CommandLine::is_long_option(std::string str) const
73  {
74    return (str.size()>2 && str[0]=='-' && str[1]=='-');
75  }
76
77
78  bool CommandLine::is_short_option(std::string str) const
79  {
80    return (str.size()>=2 && str[0]=='-' && str[1]!='-');
81  }
82
83
84  void CommandLine::parse(int argc, char* argv[])
85  {   
86    using namespace std;
87    // just in case it is not pristine
88    for_each(options_.begin(), options_.end(),std::mem_fun(&Option::reset)); 
89
90    std::vector<std::string> arguments;
91    arguments.reserve(argc);
92    for (int i=0; i<argc; ++i)
93      arguments.push_back(argv[i]);
94    std::vector<std::string>::iterator arg(arguments.begin());   
95    stringstream ss(*arg++);
96    // keeping string after last /
97    while (getline(ss, program_name_,'/')) {}
98
99    try {
100      for (; arg!=arguments.end(); ++arg) {
101        if (is_long_option(*arg)) {
102          std::string key(arg->substr(2));
103          std::stringstream ss(key);
104          getline(ss, key, '=');
105          std::string value;
106          getline(ss, value, '\0');
107          if (!value.empty()){
108            *arg = value;
109            *(--arg) = std::string("--")+key;
110          }         
111          else
112            *arg = key;
113          std::map<std::string, Option*>::const_iterator
114            iter(long_options_.find(key));
115          if (iter==long_options_.end()) {
116            std::stringstream ss;
117            ss << ": unrecognized option `" << key << "'\n"
118               << try_help();
119            throw cmd_error(ss.str());
120          }
121          else 
122            iter->second->parse(arg, arguments.end());
123        }
124       
125        if (is_short_option(*arg)) {
126          for (size_t i=1; i<arg->size(); ++i){
127            std::map<char, Option*>::const_iterator
128              iter(short_options_.find((*arg)[i]));
129            if (iter==short_options_.end()) {
130              std::stringstream ss;
131              ss << ": invalid option -- " << (*arg)[i] << "\n"
132                 << try_help() << "\n";
133              throw cmd_error(ss.str());
134            }       
135            else 
136              iter->second->parse(arg, arguments.end());
137          }
138        }
139      }
140      for_each(options_.begin(),options_.end(),
141               std::mem_fun(&Option::validate)); 
142    }
143    catch (cmd_error& e){
144      std::stringstream ss;
145      ss << program_name_ << ": " << e.what();
146      throw cmd_error(ss.str());
147    }
148     
149  }
150
151
152  std::string CommandLine::program_name(void) const
153  {
154    return program_name_;
155  }
156
157
158  std::vector<std::string> CommandLine::split(std::string str, char del) const
159  {
160    std::vector<std::string> vec;
161    std::stringstream ss(str);
162    while (std::getline(ss, str, del)){
163      vec.push_back(str);
164    }
165    return vec;
166  }
167
168  std::string CommandLine::try_help(void) const
169  {
170    return std::string("Try `"+program_name()+" --help' for more information.");
171  }
172
173
174  std::ostream& operator<<(std::ostream& os, const CommandLine& cmd)
175  {
176    os << cmd.description_ << "\n";
177    ColumnStream cs2(os, 2);
178    std::string::size_type width = 0;
179    for (std::vector<Option*>::const_iterator i(cmd.options_.begin()); 
180         i!=cmd.options_.end();++i) {
181      std::stringstream ss((*i)->print());
182      std::string str;
183      getline(ss, str, '\t');
184      width = std::max(width, str.size()+3);       
185    }
186    cs2.width(0)=width;
187    cs2.width(1)=76-width;
188    cs2.margin(0)=2;
189
190    for (std::vector<Option*>::const_iterator i(cmd.options_.begin()); 
191         i!=cmd.options_.end();++i) 
192      cs2 << (*i)->print() << "\n";
193
194    return os;
195  }
196
197
198}}} // of namespace utility, yat, and theplu
Note: See TracBrowser for help on using the repository browser.