NCBI C++ ToolKit
basic_sample.cpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /* $Id: basic_sample.cpp 90001 2020-05-04 12:53:02Z ivanov $
2  * ===========================================================================
3  *
4  * PUBLIC DOMAIN NOTICE
5  * National Center for Biotechnology Information
6  *
7  * This software/database is a "United States Government Work" under the
8  * terms of the United States Copyright Act. It was written as part of
9  * the author's official duties as a United States Government employee and
10  * thus cannot be copyrighted. This software/database is freely available
11  * to the public for use. The National Library of Medicine and the U.S.
12  * Government have not placed any restriction on its use or reproduction.
13  *
14  * Although all reasonable efforts have been taken to ensure the accuracy
15  * and reliability of the software and data, the NLM and the U.S.
16  * Government do not and cannot warrant the performance or results that
17  * may be obtained by using this software or data. The NLM and the U.S.
18  * Government disclaim all warranties, express or implied, including
19  * warranties of performance, merchantability or fitness for any particular
20  * purpose.
21  *
22  * Please cite the author in any work or product based on this material.
23  *
24  * ===========================================================================
25  *
26  * Authors: Denis Vakatov, Vladimir Ivanov
27  *
28  * File Description:
29  * Minimalistic application, with command-line arguments' processing
30  *
31  */
32 
33 #include <ncbi_pch.hpp>
34 #include <corelib/ncbiapp.hpp>
35 #include <corelib/ncbienv.hpp>
36 #include <corelib/ncbiargs.hpp>
37 
39 
40 
41 /////////////////////////////////////////////////////////////////////////////
42 // CSampleBasicApplication::
43 
45 {
46 private:
47  virtual void Init(void);
48  virtual int Run(void);
49  virtual void Exit(void);
50 };
51 
52 
53 /////////////////////////////////////////////////////////////////////////////
54 // Init test for all different types of arguments
55 
57 {
58  // // Set error posting and tracing on maximum
59  // SetDiagTrace(eDT_Enable);
60  // SetDiagPostFlag(eDPF_All);
61  // SetDiagPostLevel(eDiag_Info);
62 
63  // Create command-line argument descriptions class
64  unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
65 
66  // Specify USAGE context
67  arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
68  "CArgDescriptions demo program");
69 
70  // Describe the expected command-line arguments
71  arg_desc->AddOptionalPositional
72  ("logfile",
73  "This is an optional named positional argument without default value",
76 
77  arg_desc->AddFlag
78  ("f1",
79  "This is a flag argument: TRUE if set, FALSE if not set");
80 
81  arg_desc->AddPositional
82  ("barfooetc",
83  "This is a mandatory plain (named positional) argument",
85  arg_desc->SetConstraint
86  ("barfooetc",
87  &(*new CArgAllow_Strings, "foo", "bar", "etc"),
89 
90  arg_desc->AddDefaultKey
91  ("kd", "DefaultKey",
92  "This is an optional integer key argument, with default value",
94  arg_desc->SetConstraint
95  ("kd", new CArgAllow_Integers(0, 200));
96 
97  arg_desc->AddExtra
98  (0, // no mandatory extra args
99  3, // up to 3 optional extra args
100  "These are the optional extra (unnamed positional) arguments. "
101  "They will be printed out to the file specified by the "
102  "2nd positional argument,\n\"logfile\"",
104 
105  arg_desc->AddKey
106  ("k", "MandatoryKey",
107  "This is a mandatory alpha-num key argument",
109  arg_desc->SetConstraint
111 
112  arg_desc->AddOptionalKey
113  ("ko", "OptionalKey",
114  "This is another optional key argument, without default value",
117 
118  arg_desc->AddFlag
119  ("f2",
120  "This is another flag argument: FALSE if set, TRUE if not set",
121  false);
122 
123  arg_desc->AddDefaultPositional
124  ("one_symbol",
125  "This is an optional named positional argument with default value",
127  arg_desc->SetConstraint
128  ("one_symbol", new CArgAllow_Symbols(" aB\tCd"));
129 
130  // Setup arg.descriptions for this application
131  SetupArgDescriptions(arg_desc.release());
132 }
133 
134 
135 /////////////////////////////////////////////////////////////////////////////
136 // Run test (printout arguments obtained from command-line)
137 
139 {
140  // Get arguments
141  const CArgs& args = GetArgs();
142 
143  // Do run
144  cout << string(72, '=') << endl;
145 
146  // Self test
147  _ASSERT(args.Exist("f1"));
148  _ASSERT(args.Exist("logfile"));
149  _ASSERT(args["barfooetc"]);
150 
151  // Stream to result output
152  // (NOTE: "x_lg" is just a workaround for bug in SUN WorkShop 5.1 compiler)
153  ostream* x_lg = args["logfile"] ? &args["logfile"].AsOutputFile() : &cout;
154  ostream& lg = *x_lg;
155 
156  if ( args["logfile"] )
157  cout << "Printing arguments to file `"
158  << args["logfile"].AsString() << "'..." << endl;
159 
160  // Printout argument values
161  lg << "k: " << args["k"].AsString() << endl;
162  lg << "barfooetc: " << args["barfooetc"].AsString() << endl;
163  if ( args["logfile"] )
164  lg << "logfile: " << args["logfile"].AsString() << endl;
165 
166  if ( args["ko"] ) {
167  lg << "ko: " << NStr::BoolToString(args["ko"].AsBoolean()) << endl;
168 
169  const CArgValue::TStringArray& ko_values = args["ko"].GetStringList();
170  if (!ko_values.empty()) {
171  lg << "ko list:";
172  for (const auto& v: ko_values) {
173  lg << v << ", ";
174  }
175  lg << endl;
176  }
177 
178  } else {
179  lg << "ko: not provided" << endl;
180  string message;
181  try {
182  (void) args["ko"].AsString();
183  } catch (CArgException& e) {
184  NCBI_REPORT_EXCEPTION("CArgException is thrown: ", e);
185  message = e.what();
186  }
187  _ASSERT( !message.empty() );
188  }
189 
190  if ( args["f1"] ) {
191  _ASSERT(args["f1"].AsBoolean());
192  }
193  if ( args["f2"] ) {
194  _ASSERT(args["f2"].AsBoolean());
195  }
196 
197  // Extra (unnamed positional) arguments
198  if ( args.GetNExtra() ) {
199  for (size_t extra = 1; extra <= args.GetNExtra(); extra++) {
200  lg << "#" << extra << ": "
201  << NStr::BoolToString(args[extra].AsBoolean())
202  << " (passed as `" << args[extra].AsString() << "')"
203  << endl;
204  }
205  } else {
206  lg << "(no unnamed positional arguments passed in the cmd-line)" << endl;
207  }
208 
209  // Separator
210  lg << string(44, '-') << endl;
211 
212  // Printout obtained argument values
213  string str;
214  cout << args.Print(str) << endl;
215 
216  return 0;
217 }
218 
219 
220 /////////////////////////////////////////////////////////////////////////////
221 // Cleanup
222 
224 {
225  // Do your after-Run() cleanup here
226 }
227 
228 
229 /////////////////////////////////////////////////////////////////////////////
230 // MAIN
231 
232 int NcbiSys_main(int argc, ncbi::TXChar* argv[])
233 {
234  // Execute main application function; change argument list to
235  // (argc, argv, 0, eDS_Default, 0) if there's no point in trying
236  // to look for an application-specific configuration file.
237  return CSampleBasicApplication().AppMain(argc, argv);
238 }
int NcbiSys_main(int argc, ncbi::TXChar *argv[])
USING_NCBI_SCOPE
CArgAllow_Integers –.
Definition: ncbiargs.hpp:1751
CArgAllow_String –.
Definition: ncbiargs.hpp:1600
CArgAllow_Strings –.
Definition: ncbiargs.hpp:1641
CArgAllow_Symbols –.
Definition: ncbiargs.hpp:1535
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgException –.
Definition: ncbiargs.hpp:120
CArgs –.
Definition: ncbiargs.hpp:379
virtual int Run(void)
Run the application.
virtual void Init(void)
Initialize the application.
virtual void Exit(void)
Cleanup on application exit.
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments.
Definition: ncbiapp.cpp:285
int AppMain(int argc, const char *const *argv, const char *const *envp=0, EAppDiagStream diag=eDS_Default, const char *conf=NcbiEmptyCStr, const string &name=NcbiEmptyString)
Main function (entry point) for the NCBI application.
Definition: ncbiapp.cpp:799
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: ncbiapp.cpp:1175
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
string & Print(string &str) const
Print (append) all arguments to the string "str" and return "str".
Definition: ncbiargs.cpp:1876
bool Exist(const string &name) const
Check existence of argument description.
Definition: ncbiargs.cpp:1813
vector< string > TStringArray
Some values types can contain several value lists.
Definition: ncbiargs.hpp:293
size_t GetNExtra(void) const
Get the number of unnamed positional (a.k.a. extra) args.
Definition: ncbiargs.hpp:422
@ fAllowMultiple
Repeated key arguments are legal (use with AddKey)
Definition: ncbiargs.hpp:635
@ fBinary
Open as binary file; for eInputFile, eOutputFile, eIOFile.
Definition: ncbiargs.hpp:620
@ fPreOpen
Open file right away; for eInputFile, eOutputFile, eIOFile.
Definition: ncbiargs.hpp:618
@ eBoolean
{'true', 't', 'false', 'f'}, case-insensitive
Definition: ncbiargs.hpp:590
@ eString
An arbitrary string.
Definition: ncbiargs.hpp:589
@ eOutputFile
Name of file (must be writable)
Definition: ncbiargs.hpp:596
@ eInteger
Convertible into an integer number (int or Int8)
Definition: ncbiargs.hpp:592
@ eAlnum
Alphanumeric characters.
Definition: ncbiargs.hpp:1542
@ eConstraint
Constraint is not inverted (taken as is)
Definition: ncbiargs.hpp:924
string
Definition: cgiapp.hpp:687
#define NCBI_REPORT_EXCEPTION(title, ex)
Generate a report on the exception.
Definition: ncbiexpt.hpp:755
virtual const char * what(void) const noexcept
Standard report (includes full backlog).
Definition: ncbiexpt.cpp:342
char TXChar
Definition: ncbistr.hpp:172
static const string BoolToString(bool value)
Convert bool to string.
Definition: ncbistr.cpp:2813
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Defines command line argument related classes.
Defines unified interface to application:
static const char * str(char *buf, int n)
Definition: stats.c:84
#define _ASSERT
Modified on Fri Dec 08 08:21:45 2023 by modify_doxy.py rev. 669887