File: CmdlineParser.cc

package info (click to toggle)
rdfind 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 648 kB
  • sloc: cpp: 1,670; sh: 1,622; makefile: 32
file content (99 lines) | stat: -rw-r--r-- 2,430 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
   copyright 2018 Paul Dreik (earlier Paul Sundvall)
   Distributed under GPL v 2.0 or later, at your option.
   See LICENSE for further details.
*/

#include "config.h"

// std
#include <cstdlib>
#include <cstring>
#include <iostream>

// project
#include "CmdlineParser.hh"

bool
Parser::try_parse_bool(const char* arg)
{
  if (m_index >= m_argc) {
    // out of bounds - programming error.
    std::cerr << "out of bounds: m_index=" << m_index << " m_argc=" << m_argc
              << '\n';
    std::exit(EXIT_FAILURE);
  }
  if (0 == std::strcmp(arg, m_argv[m_index])) {
    // yep - match!
    if (1 + m_index >= m_argc) {
      // out of bounds - user gave to few arguments.
      std::cerr << "expected true or false after " << arg
                << ", not end of argument list.\n";
      std::exit(EXIT_FAILURE);
    }
    auto value = m_argv[++m_index];
    if (0 == std::strcmp(value, "true")) {
      m_last_bool_result = true;
      return true;
    }
    if (0 == std::strcmp(value, "false")) {
      m_last_bool_result = false;
      return true;
    }
    std::cerr << "expected true or false after " << arg << ", not \"" << value
              << "\"\n";
    std::exit(EXIT_FAILURE);
  } else {
    // no match. keep searching.
    return false;
  }
}

bool
Parser::try_parse_string(const char* arg)
{
  if (m_index >= m_argc) {
    // out of bounds - programming error.
    std::cerr << "out of bounds: m_index=" << m_index << " m_argc=" << m_argc
              << '\n';
    std::exit(EXIT_FAILURE);
  }
  if (0 == std::strcmp(arg, m_argv[m_index])) {
    // yep - match!
    if (1 + m_index >= m_argc) {
      // out of bounds. user supplied to few arguments.
      std::cerr << "expected string after " << arg
                << ", not end of argument list.\n";
      std::exit(EXIT_FAILURE);
    }
    m_last_str_result = m_argv[++m_index];
    return true;
  } else {
    // no match. keep searching.
    return false;
  }
}

bool
Parser::parsed_string_is(const char* value) const
{
  return 0 == std::strcmp(m_last_str_result, value);
}

const char*
Parser::get_current_arg() const
{
  if (m_index >= m_argc) {
    // out of bounds.
    std::cerr << "out of bounds: m_index=" << m_index << " m_argc=" << m_argc
              << '\n';
    std::exit(EXIT_FAILURE);
  }
  return m_argv[m_index];
}

bool
Parser::current_arg_is(const char* what) const
{
  return 0 == std::strcmp(get_current_arg(), what);
}