ALib C++ Framework
by
Library Version: 2605 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
App/sample.cpp
Go to the documentation of this file.
1// #################################################################################################
2// ALib C++ Framework
3// App Sample
4//
5// Copyright 2025 A-Worx GmbH, Germany
6// Published under Boost Software License (a free software license, see LICENSE.txt)
7// #################################################################################################
8/// \file
9#include "ALib.Lang.H"
10#if !DOXYGEN // otherwise this sample would be seen in the ALib dox
11
12#include "sample.hpp"
13
14// Include necessary ALib headers
15#include "ALib.Strings.StdIOStream.H" // Support to write ALib strings and boxes to cout
16#include "ALib.Strings.Calendar.H" // Module ALib Strings, calendar formatting
17#include "ALib.Variables.Plugins.H" // Module ALib Variables, environment and cli-plugins
18#include "ALib.Bootstrap.H" // Bootstrapping ALib.
19#include "ALib.Camp.ResourceCompiler.H" // The resource compiler
20
21#include <filesystem> // C++ filesystem
22#include <chrono> // C++ chrono
23
24// namespaces to use locally
25using namespace alib;
26
27void Sample::onBsCLIDefine() {
28 App::onBsCLIDefine();
29
30 cli.DefineExitCodes <DateExitCodes >();
31 cli.DefineParameters<DateParameters>();
32 cli.DefineCommands <DateCommands >();
33 cli.DefineOptions <DateOptions >();
34}
35
36// DOX_MARKER([DOX_ALIB_SAMPLE_RESOURCE_COMPILER])
37void Sample::onBsPrepareConfig() {
38 // call parent's implementation. This bulk-loads the resources into the camps.
39 App::onBsPrepareConfig();
40
41 // now, we just add the resources that parent App did not define for us.
43 if(!rc.Do( "sample.alibrc", __FILE__, APP, APP.ResourceCategory, true,
44 // __FILE__ )
45 nullptr )
46 )
47 bulkloadResources();
48
53
54 // Read copyright string from resources and format to current version and year
55 Paragraphs buffer;
56 buffer.LineWidth= 70;
58 buffer.AddMarked( APP.GetResource( "AppInfo" ),
61 CalendarDateTime(DateTime()).Year );
62 }
63 cli.AppInfo.Allocate(cli.GetAllocator(), buffer.Buffer);
64}
65// DOX_MARKER([DOX_ALIB_SAMPLE_RESOURCE_COMPILER])
66
67bool Sample::processCLICmd(alib::app::Command* cmd ) {
68 if ( App::processCLICmd(cmd) )
69 return true;
70
71 if ( cmd == nullptr ) {
72 String128 dateWritten;
73 CalendarDateTime(DateTime()).Format( format, dateWritten );
74 cOut->Add(dateWritten);
75 return true;
76 }
77
78 // Note: Alternatively, we could do:
79 // auto actCmdCode= cmd->Declaration->Element();
80 //
81 // if ( actCmdCode == DateCommands::Now ) {
82 // ...
83 // }
84 //
85 // else if ( actCmdCode == DateCommands::File ) {
86 // {
87 // ...
88 //
89 // But the following version lets the compiler assure us that
90 // all custom commands are handled:
91
93 if ( cmd->Declaration->Element().IsEnumType<DateCommands>()) {
94 switch (cmd->Declaration->Element().Get<DateCommands>()) {
95 case DateCommands::Now: {
96 String128 dateWritten;
97 CalendarDateTime(DateTime()).Format( format, dateWritten);
98 cOut->Add(dateWritten);
99 return true;
100 }
101 case DateCommands::File: {
102 // check if filename was given as parameter
103 if(cmd->ParametersMandatory.size() < 1)
104 {
105 cErr->Add(APP.GetResource("MSNGFNAME"));
107 CLIUtil::GetHelp( cli, cmd->Declaration->Identifier(), *cOut )
108 ,true)
109 machine.SetExitCode(DateExitCodes::ErrMissingFilename);
110 return true;
111 }
112
113 // get file (or directory) modification date
114 String4K name( cmd->ParametersMandatory.front()->Args.front() );
115 std::filesystem::path stdpath( name.Terminate() );
116 DateTime dt;
117
118 // While class App catches exceptions and provides explicit virtual method
119 // App::exceptionToExitCode() to be overridden, we use the non-throwing version
120 // of std::filesystem::last_write_time. Here is why:
121 // - We have the filename here at hand. No need to pass it over
122 // - while exceptionToExitCode is nice in respect to having all exceptions in
123 // one place, it is also nice to handle an error where it occurs.
124 // So, maybe a matter of taste. And finally we mix it: if we do not handle the
125 // error code here, we then throw!
126 std::error_code errorCode;
127 auto timeValue= std::filesystem::last_write_time( stdpath, errorCode );
128 if ( errorCode.value() != 0 ) {
129 // not found
130 if ( errorCode.value() == int(std::errc::no_such_file_or_directory) ) {
131 cErr->Add( APP.GetResource("FNOTFND"), name);
132 machine.SetExitCode( DateExitCodes::ErrFileNotFound );
133 return true;
134 }
135
136 // permission denied
137 if ( errorCode.value() == int(std::errc::permission_denied) ) {
138 cErr->Add( APP.GetResource("FNOACC"), name);
139 machine.SetExitCode( DateExitCodes::ErrPermissionDenied );
140 return true;
141 }
142
143 // other errors
145 }
146 dt.Import( std::chrono::clock_cast<std::chrono::system_clock>(timeValue) );
147 String128 dateWritten;
148 CalendarDateTime(dt).Format( format, dateWritten );
149 cOut->Add(dateWritten);
150
151 return true;
152 }
153 }
154 }
155
157
158 return false;
159}
160
161void Sample::bulkloadResources() {
162
163 APP.GetResourcePool().BootstrapBulk( APP.ResourceCategory,
164
165 // ALIB-RESOURCE-COMPILER-REPLACEMENT-START
166 "HlpCLIAppName" , A_CHAR("sample"),
167 "HlpUsage" , A_CHAR("sample [format=\"FORMATSPEC\" [now]|[file FILENAME]"),
168 "AppInfo" , A_CHAR("@HL-ALib Resource Compiler V. {}.{}\n")
169 A_CHAR("(c) 2023-{} AWorx GmbH. Published under MIT License (Open Source).\n")
170 A_CHAR("For more information, see: https://alib.dev/alib_mod_resources.html\n")
171 A_CHAR("@HL-"),
172 "HlpGeneral" , A_CHAR("\nABOUT sample\n")
173 A_CHAR("@>> This is a sample application provided with C++ library 'ALib' to demonstrate the use of its module \"ALib App\".\" \n")
174 A_CHAR("@<<"),
175 "DateC<" , A_CHAR("datesample::Commands::"),
176 "DateC" , A_CHAR("1,now,1,,2,file,1,filename"),
177 "THlpCmdSht_now" , A_CHAR("Reports the actual date/time"),
178 "THlpCmdLng_now" , A_CHAR(""),
179 "Reports" , A_CHAR("the actual date/time. May be omitted, as this is the default if no command is given."),
180 "THlpCmdSht_file" , A_CHAR("Returns the date/time of a file."),
181 "THlpCmdLng_file" , A_CHAR("Returns the last modification date/time of a file."),
182 "DateO<" , A_CHAR("datesample::Options::"),
183 "DateO" , A_CHAR("0,format,1,f,=,1,"),
184 "TOptUsg_format" , A_CHAR("--format[=]\"placeholders\""),
185 "TOptHlp_format" , A_CHAR("Sets the output format. The format specification is given with the documentation of the ALib method CalendarDateTime::Format, found here:\n")
186 A_CHAR("https://alib.dev/classalib_1_1strings_1_1util_1_1CalendarDateTime.html"),
187 "DateP<" , A_CHAR("datesample::Parameters::"),
188 "DateP" , A_CHAR("0,FILENAME,1,,=,,-1,0"),
189 "THlpParSht_FILENAME", A_CHAR("Mandatory parameter of command \"file\"."),
190 "THlpParLng_FILENAME", A_CHAR("Denotes the file that is used for retrieving the modification date. This parameter is mandatory to be given with command 'file' and has to be appended to this command, separated by '='\""),
191 "DateE<" , A_CHAR("datesample::"),
192 "DateE" , A_CHAR("101,ErrMissingFilename,-1,102,ErrFileNotFound,-1,103,ErrPermissionDenied,-1"),
193 "TExit101" , A_CHAR("Command 'file' given without a filename argument."),
194 "TExit102" , A_CHAR("File not found."),
195 "TExit103" , A_CHAR("Permission denied."),
196 "FNOTFND" , A_CHAR("The file {!Q} specified with command 'file' was not found."),
197 "FNOACC" , A_CHAR("Access denied to file {!Q} specified with command 'file'."),
198 "MSNGFNAME" , A_CHAR("Error: no filename given with command 'file'."),
199 // ALIB-RESOURCE-COMPILER-REPLACEMENT-END
200
201 // end of BootstrapBulk()
202 nullptr );
203
204}
205
206
207#endif // !DOXYGEN
#define ALIB_ASSERT_RESULT_EQUALS( func, value)
#define ALIB_CALLER_NULLED
#define A_CHAR(STR)
#define ALIB_ALLOW_SWITCH_WITHOUT_DEFAULT
#define ALIB_LOCK_RECURSIVE_WITH(lock)
#define ALIB_POP_ALLOWANCE
static bool GetHelp(CommandLine &cmdLine, const String &topics, Paragraphs &text)
Definition cliutil.cpp:87
const Enum & Element() const
const String & Identifier()
bool Do(const NString &alibrcFileName, const NString &callingFile, Camp &campInstance, const NString &resourceCategory, bool allowReplacements, const NString &cppFileName)
static threads::RecursiveLock DEFAULT_LOCK
void AddMarked(boxing::TBoxes< TAllocatorArgs > &args)
integer LineWidth
Used as parameter lineWidth of static method invocations.
void Import(TTimePoint timePoint)
void Bootstrap(camp::Camp &camp, const NString &name, character innerDelim=',', character outerDelim=',')
Definition camp.hpp:263
Exception CreateExceptionFromSystemError(const CallerInfo &ci, std::error_code errorCode)
Definition alox.cpp:14
LocalString< 4096 > String4K
Type alias name for #"TLocalString;TLocalString<character,4096>".
int VERSION
Definition bootstrap.cpp:8
strings::util::CalendarDateTime CalendarDateTime
Type alias in namespace #"%alib".
Definition calendar.hpp:509
LocalString< 128 > String128
Type alias name for #"TLocalString;TLocalString<character,128>".
app::AppCamp APP
The singleton instance of the camp class used by class #"App".
Definition appcamp.cpp:1
format::Paragraphs Paragraphs
Type alias in namespace #"%alib".
time::DateTime DateTime
Type alias in namespace #"%alib".
Definition datetime.hpp:188
unsigned char REVISION
Definition bootstrap.cpp:9
A command argument of the command-line.
CommandDecl * Declaration
The underlying declaration.
ListMA< Parameter *, Recycling::Shared > ParametersMandatory
Mandatory parameters parsed.
bool IsEnumType() const
Definition enum.hpp:141
TEnum Get() const
Definition enum.hpp:74