Interactive CLI 2.3
A cross-platform C++14 library for interactive command-line interfaces
Loading...
Searching...
No Matches
clisession.h
Go to the documentation of this file.
1/*******************************************************************************
2 * CLI - A simple command line interface.
3 * Copyright (C) 2016-2026 Daniele Pallastrelli
4 *
5 * Boost Software License - Version 1.0 - August 17th, 2003
6 *
7 * Permission is hereby granted, free of charge, to any person or organization
8 * obtaining a copy of the software and accompanying documentation covered by
9 * this license (the "Software") to use, reproduce, display, distribute,
10 * execute, and transmit the Software, and to prepare derivative works of the
11 * Software, and to permit third-parties to whom the Software is furnished to
12 * do so, all subject to the following:
13 *
14 * The copyright notices in the Software and this entire statement, including
15 * the above license grant, this restriction and the following disclaimer,
16 * must be included in all copies of the Software, in whole or in part, and
17 * all derivative works of the Software, unless such copies or derivative
18 * works are solely in the form of machine-executable object code generated by
19 * a source language processor.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
24 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
25 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
26 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 * DEALINGS IN THE SOFTWARE.
28 ******************************************************************************/
29
30#ifndef CLI_CLISESSION_H_
31#define CLI_CLISESSION_H_
32
33#include <algorithm>
34#include <cctype>
35#include <functional>
36#include <memory>
37#include <ostream>
38#include <string>
39#include <vector>
40
41#include "colorprofile.h"
42#include "detail/history.h"
43#include "detail/split.h"
44#include "historystorage.h"
45#include "menu.h"
47
48namespace cli
49{
51 {
52 public:
53 CliSession(Cli& _cli, std::ostream& _out, std::size_t historySize = 100);
54 virtual ~CliSession() noexcept;
55
56 CliSession(const CliSession&) = delete;
57 CliSession& operator=(const CliSession&) = delete;
60
61 void Feed(const std::string& cmd);
62 void Prompt();
63 void Current(Menu* menu);
64 std::ostream& OutStream() { return out; }
65 void Help() const;
66 void Help(const std::string& commandName) const;
67
68 void Enter()
69 {
70 cli.EnterAction(out);
71 if (enterAction)
72 enterAction(out);
73 }
74
75 void Exit()
76 {
77 exitAction(out);
78 cli.ExitAction(out);
79
80 auto cmds = history.GetCommands();
81 cli.StoreCommands(cmds);
82
83 exit = true;
84 }
85
86 void EnterAction(const std::function<void(std::ostream&)>& action)
87 {
88 enterAction = action;
89 }
90
91 void ExitAction(const std::function<void(std::ostream&)>& action)
92 {
93 exitAction = action;
94 }
95
96 void ShowHistory() const { history.Show(out); }
97
98 void ExecFromHistory(unsigned index)
99 {
100 history.ForgetLatest();
101 const auto cmd = history.At(index);
102 Feed(cmd);
103 }
104
105 std::string PreviousCmd(const std::string& line)
106 {
107 return history.Previous(line);
108 }
109
110 std::string NextCmd()
111 {
112 return history.Next();
113 }
114
115 std::vector<std::string> GetCompletions(std::string currentLine) const;
116
117 protected:
118 virtual std::size_t TerminalWidth() const { return 80; }
119
120 private:
121 Cli& cli;
122 std::shared_ptr<cli::OutStream> coutPtr;
123 Menu* current;
124 std::unique_ptr<Menu> globalScopeMenu;
125 std::ostream& out;
126 std::function<void(std::ostream&)> enterAction = [](std::ostream&) noexcept {};
127 std::function<void(std::ostream&)> exitAction = [](std::ostream&) noexcept {};
128 detail::History history;
129 bool exit{false};
130 };
131
132 inline CliSession::CliSession(Cli& _cli, std::ostream& _out, std::size_t historySize) :
133 cli(_cli),
134 coutPtr(Cli::CoutPtr()),
135 current(cli.RootMenu()),
136 globalScopeMenu(std::make_unique<Menu>()),
137 out(_out),
138 history(historySize)
139 {
140 history.LoadCommands(cli.GetCommands());
141
142 coutPtr->Register(out);
143 globalScopeMenu->Insert(
144 cli.GetMessages().helpName,
145 {cli.GetMessages().helpArgName},
146 [this](std::ostream&, const std::vector<std::string>& args)
147 {
148 if (args.empty())
149 Help();
150 else if (args.size() == 1)
151 Help(args.front());
152 else
153 out << cli.GetMessages().helpUsage << '\n';
154 },
155 cli.GetMessages().helpCommand
156 );
157 globalScopeMenu->Insert(
158 cli.GetMessages().exitName,
159 [this](std::ostream&) { Exit(); },
160 cli.GetMessages().exitCommand
161 );
162 globalScopeMenu->Insert(
163 cli.GetMessages().historyName,
164 [this](std::ostream&) { ShowHistory(); },
165 cli.GetMessages().historyCommand
166 );
167 globalScopeMenu->Insert(
168 "!",
169 {cli.GetMessages().historyIndexArg},
170 [this](std::ostream&, unsigned cmdIndex) { ExecFromHistory(cmdIndex); },
171 cli.GetMessages().historyExecCommand
172 );
173 }
174
175 inline void CliSession::Feed(const std::string& cmd)
176 {
177 std::vector<std::string> strs;
178 detail::split(strs, cmd);
179 if (strs.empty()) return;
180
181 history.NewCommand(cmd);
182
183 try
184 {
185 bool found = globalScopeMenu->ScanCmds(strs, *this);
186 if (!found) found = current->ScanCmds(strs, *this);
187 if (!found)
188 cli.WrongCommandHandler(out, cmd);
189 }
190 catch (const std::exception& e)
191 {
192 cli.StdExceptionHandler(out, cmd, e);
193 }
194 catch (...)
195 {
196 out << cli.GetMessages().unknownException << cmd << "\"\n";
197 }
198 }
199
200 inline void CliSession::Prompt()
201 {
202 if (exit) return;
203 out << beforePrompt
204 << current->Prompt()
205 << afterPrompt
206 << "> "
207 << std::flush;
208 }
209
210 inline void CliSession::Help() const
211 {
212 detail::HelpGroup global, local;
213 globalScopeMenu->MainHelp(global);
214 current->MainHelp(local);
215
216 // GCC 15 emits a false-positive -Wstrict-overflow warning inside <bits/stl_tempbuf.h>
217 // during std::stable_sort's temporary buffer creation. Since -Werror is enabled,
218 // we suppress the warning locally for this call.
219 #ifdef __GNUC__
220 #pragma GCC diagnostic push
221 #pragma GCC diagnostic ignored "-Wstrict-overflow"
222 #endif
223
224 std::stable_sort(local.begin(), local.end(),
225 [](const detail::HelpEntry& a, const detail::HelpEntry& b) { return a.name < b.name; });
226
227 #ifdef __GNUC__
228 #pragma GCC diagnostic pop
229 #endif
230
231 detail::HelpGroup commands, menus;
232 for (auto& e : local)
233 (e.isMenu ? menus : commands).push_back(std::move(e));
234
235 out << cli.GetMessages().helpHeader;
236 detail::PrintHelp(out, {global, commands, menus}, TerminalWidth());
237 }
238
239 inline void CliSession::Help(const std::string& commandName) const
240 {
241 detail::HelpGroup matches;
242 auto appendMatches = [&](const detail::HelpGroup& entries)
243 {
244 for (const auto& entry : entries)
245 if (entry.name == commandName)
246 matches.push_back(entry);
247 };
248
249 detail::HelpGroup global, local;
250 globalScopeMenu->MainHelp(global);
251 current->MainHelp(local);
252 appendMatches(global);
253 appendMatches(local);
254
255 if (matches.empty())
256 {
257 out << cli.GetMessages().commandNotFound << commandName << '\n';
258 return;
259 }
260
261 detail::PrintHelp(out, {matches}, TerminalWidth());
262 }
263
264 inline std::vector<std::string> CliSession::GetCompletions(std::string currentLine) const
265 {
266 currentLine.erase(currentLine.begin(), std::find_if(currentLine.begin(), currentLine.end(), [](int ch) { return !std::isspace(ch); }));
267 auto v1 = globalScopeMenu->GetCompletions(currentLine);
268 auto v3 = current->GetCompletions(currentLine);
269 v1.insert(v1.end(), std::make_move_iterator(v3.begin()), std::make_move_iterator(v3.end()));
270
271 std::sort(v1.begin(), v1.end());
272 auto ip = std::unique(v1.begin(), v1.end());
273 v1.resize(static_cast<std::size_t>(std::distance(v1.begin(), ip)));
274
275 return v1;
276 }
277
278 template <typename F, typename ... Args>
279 inline bool VariadicFunctionCommand<F, Args...>::Exec(const std::vector<std::string>& cmdLine, CliSession& session)
280 {
281 if (!IsEnabled()) return false;
282 const std::size_t paramSize = sizeof...(Args);
283 if (cmdLine.size() != paramSize + 1) return false;
284 if (Name() == cmdLine[0])
285 {
286 try
287 {
288 auto g = [&](auto ... pars) { func(session.OutStream(), pars...); };
289 Select<Args...>::Exec(g, std::next(cmdLine.begin()), cmdLine.end());
290 }
291 catch (std::bad_cast&)
292 {
293 return false;
294 }
295 return true;
296 }
297 return false;
298 }
299
300 template <typename F, typename ... Args>
301 inline void VariadicFunctionCommand<F, Args...>::Help(detail::HelpGroup& entries) const
302 {
303 if (!IsEnabled()) return;
304 detail::HelpEntry e;
305 e.name = Name();
306 e.params = parameterDesc;
307 if (e.params.empty())
309 e.description = description;
310 entries.push_back(std::move(e));
311 }
312
313 template <typename F>
314 inline bool FreeformCommand<F>::Exec(const std::vector<std::string>& cmdLine, CliSession& session)
315 {
316 if (!IsEnabled()) return false;
317 assert(!cmdLine.empty());
318 if (Name() == cmdLine[0])
319 {
320 func(session.OutStream(), std::vector<std::string>(std::next(cmdLine.begin()), cmdLine.end()));
321 return true;
322 }
323 return false;
324 }
325
326 template <typename F>
327 inline void FreeformCommand<F>::Help(detail::HelpGroup& entries) const
328 {
329 if (!IsEnabled()) return;
330 detail::HelpEntry e;
331 e.name = Name();
332 e.params = parameterDesc;
333 if (e.params.empty())
334 ParamNames<std::vector<std::string>>::Collect(e.params);
335 e.description = description;
336 entries.push_back(std::move(e));
337 }
338
339 inline bool Menu::HandleCommand(const std::vector<std::string>& cmdNames, const std::vector<std::string>& cmdLine, CliSession& session)
340 {
341 if (!IsEnabled())
342 return false;
343
344 assert(!cmdLine.empty());
345
346 if (std::find(cmdNames.begin(), cmdNames.end(), cmdLine[0]) != cmdNames.end())
347 {
348 if (cmdLine.size() == 1)
349 {
350 session.Current(this);
351 return true;
352 }
353 else
354 {
355 std::vector<std::string> subCmdLine(cmdLine.begin() + 1, cmdLine.end());
356 for (auto& cmd : *cmds)
357 if (cmd->Exec(subCmdLine, session)) return true;
358 return (parent && parent->ExecParent(subCmdLine, session));
359 }
360 }
361 return false;
362 }
363
364 inline void CliSession::Current(Menu* menu)
365 {
366 current = menu;
367 if (current)
368 current->OnEnter(out);
369 }
370
371 inline CliSession::~CliSession() noexcept
372 {
373 coutPtr->UnRegister(out);
374 }
375}
376
377#endif // CLI_CLISESSION_H_
CliSession(Cli &_cli, std::ostream &_out, std::size_t historySize=100)
Definition clisession.h:132
CliSession & operator=(const CliSession &)=delete
std::ostream & OutStream()
Definition clisession.h:64
virtual std::size_t TerminalWidth() const
Definition clisession.h:118
CliSession(CliSession &&)=delete
void ShowHistory() const
Definition clisession.h:96
CliSession & operator=(CliSession &&)=delete
void Help() const
Definition clisession.h:210
void ExecFromHistory(unsigned index)
Definition clisession.h:98
void EnterAction(const std::function< void(std::ostream &)> &action)
Definition clisession.h:86
void Feed(const std::string &cmd)
Definition clisession.h:175
std::string NextCmd()
Definition clisession.h:110
std::string PreviousCmd(const std::string &line)
Definition clisession.h:105
std::vector< std::string > GetCompletions(std::string currentLine) const
Definition clisession.h:264
virtual ~CliSession() noexcept
Definition clisession.h:371
void ExitAction(const std::function< void(std::ostream &)> &action)
Definition clisession.h:91
CliSession(const CliSession &)=delete
void Current(Menu *menu)
Definition clisession.h:364
Definition cli.h:57
bool IsEnabled() const
Definition command.h:69
const std::string & Name() const
Definition command.h:68
bool Exec(const std::vector< std::string > &cmdLine, CliSession &session) override
Definition clisession.h:314
void Help(detail::HelpGroup &entries) const override
Definition clisession.h:327
bool ExecParent(const std::vector< std::string > &cmdLine, CliSession &session)
Definition menu.h:108
void OnEnter(std::ostream &out) const
Definition menu.h:134
bool Exec(const std::vector< std::string > &cmdLine, CliSession &session) override
Definition clisession.h:279
void Help(detail::HelpGroup &entries) const override
Definition clisession.h:301
@ afterPrompt
@ beforePrompt