2c34fd4bf127b618333853354f2bb050c7adc71d
[ric-plt/sdl.git] / src / cli / getcommand.cpp
1 #include <ostream>
2 #include <cstdlib>
3 #include "private/cli/commandmap.hpp"
4 #include "private/cli/common.hpp"
5 #include <sdl/syncstorage.hpp>
6
7 using namespace shareddatalayer;
8 using namespace shareddatalayer::cli;
9
10 namespace
11 {
12     std::shared_ptr<shareddatalayer::SyncStorage> createSyncStorage(const SyncStorage::Namespace& ns,
13                                                                     std::ostream& out)
14     {
15         try
16         {
17             auto sdl(shareddatalayer::SyncStorage::create());
18             sdl->waitReady(ns, std::chrono::minutes(1));
19             return sdl;
20         }
21         catch (const shareddatalayer::Exception& error)
22         {
23             out << "SyncStorage create failed: " << error.what() << std::endl;
24         }
25
26         return nullptr;
27     }
28
29     void get(shareddatalayer::SyncStorage& sdl,
30              const SyncStorage::Namespace& ns,
31              const SyncStorage::Key& key,
32              std::ostream& out)
33     {
34         try
35         {
36             auto data(sdl.get(ns, {key}));
37             out << data << std::endl;
38         }
39         catch (const shareddatalayer::Exception& error)
40         {
41             out << "get(" << ns << ", " << key << ") failed: "
42                 << error.what() << std::endl;
43         }
44     }
45
46     int getCommand(std::ostream& out, const boost::program_options::variables_map& map)
47     {
48         auto ns(map["ns"].as<std::string>());
49         auto key(map["key"].as<std::string>());
50
51         auto sdl(createSyncStorage(ns, out));
52         if (nullptr == sdl)
53             return EXIT_FAILURE;
54         sdl->setOperationTimeout(std::chrono::seconds(5));
55
56         get(std::ref(*sdl), ns, key, out);
57
58         return EXIT_SUCCESS;
59     }
60 }
61
62 const char *longHelpGetCmd =
63         "Use get SDL API to read data from storage under the namespace.\n\n"
64         "Example: sdltool get --ns 'sdltool' --key 'key1'";
65
66 AUTO_REGISTER_COMMAND(std::bind(getCommand, std::placeholders::_1, std::placeholders::_3),
67                       "get",
68                       "get data with SDL API under the namespace",
69                       longHelpGetCmd,
70                       CommandMap::Category::UTIL,
71                       30050,
72                       ("ns,n", boost::program_options::value<std::string>()->default_value("sdltoolns"), "namespace to use")
73                       ("key,k", boost::program_options::value<std::string>()->default_value("key1"), "key value")
74                      );
75