bin: consolidate clients
[awesomized/libmemcached] / src / bin / memexist.cc
1 /*
2 +--------------------------------------------------------------------+
3 | libmemcached - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020 Michael Wallner <mike@php.net> |
13 +--------------------------------------------------------------------+
14 */
15
16 #include "mem_config.h"
17
18 #define PROGRAM_NAME "memexist"
19 #define PROGRAM_DESCRIPTION "Check for the existence of a key within a memcached cluster."
20 #define PROGRAM_VERSION "1.1"
21
22 #include "common/options.hpp"
23
24 int main(int argc, char *argv[]) {
25 client_options opt{PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_DESCRIPTION, "key [key ...]"};
26
27 for (const auto &def : opt.defaults) {
28 opt.add(def);
29 }
30
31 char **argp = nullptr;
32 if (!opt.parse(argc, argv, &argp)) {
33 exit(EXIT_FAILURE);
34 }
35
36 memcached_st memc;
37 if (!memcached_create(&memc)) {
38 if (!opt.isset("quiet")) {
39 std::cerr << "Failed to initialize memcached client.\n";
40 }
41 exit(EXIT_FAILURE);
42 }
43
44 if (!opt.apply(&memc)) {
45 memcached_free(&memc);
46 exit(EXIT_FAILURE);
47 }
48
49 if (!*argp) {
50 if (!opt.isset("quiet")) {
51 std::cerr << "No key(s) provided.\n";
52 }
53 memcached_free(&memc);
54 exit(EXIT_FAILURE);
55 }
56
57 auto exit_code = EXIT_SUCCESS;
58 for (auto arg = argp; *arg; ++arg) {
59 auto rc = memcached_exist(&memc, *arg, strlen(*arg));
60
61 if (MEMCACHED_SUCCESS == rc) {
62 if (opt.isset("verbose")) {
63 std::cerr << "Found key '" << *arg << "'.\n";
64 }
65 } else {
66 exit_code = EXIT_FAILURE;
67 if (opt.isset("verbose")) {
68 if (rc == MEMCACHED_NOTFOUND) {
69 std::cerr << "Could not find key '" << *arg << "'.\n";
70 } else {
71 std::cerr << "Fatal error for key '" << *arg << "': "
72 << memcached_last_error_message(&memc) << "\n";
73 }
74 }
75 }
76 }
77
78 memcached_free(&memc);
79 exit(exit_code);
80 }