]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
redis-cli no longer aborts in repl-mode on error, and retries to reconncet with the...
[redis.git] / src / redis-cli.c
CommitLineData
ed9b544e 1/* Redis CLI (command line interface)
2 *
12d090d2 3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
23d4709d 31#include "fmacros.h"
185cabda 32#include "version.h"
23d4709d 33
ed9b544e 34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37#include <unistd.h>
a88a2af6 38#include <ctype.h>
c0b3d423 39#include <errno.h>
b4b62c34 40#include <sys/stat.h>
3ce014c7 41#include <sys/time.h>
41945ba6 42#include <assert.h>
ed9b544e 43
7fc4ce13 44#include "hiredis.h"
ed9b544e 45#include "sds.h"
ed9b544e 46#include "zmalloc.h"
cf87ebf2 47#include "linenoise.h"
5397f2b5 48#include "help.h"
ed9b544e 49
ed9b544e 50#define REDIS_NOTUSED(V) ((void) V)
51
7fc4ce13 52static redisContext *context;
ed9b544e 53static struct config {
54 char *hostip;
55 int hostport;
7e91f971 56 char *hostsocket;
5762b7f0 57 long repeat;
62e920df 58 int dbnum;
5d15b520 59 int interactive;
36e5db6d 60 int shutdown;
249c3a7d 61 int monitor_mode;
62 int pubsub_mode;
bc63407b 63 int stdinarg; /* get last arg from stdin. (-x option) */
288799e0 64 char *auth;
65add0a3
PN
65 int raw_output; /* output mode per command */
66 sds mb_delim;
3f4eef21 67 char prompt[32];
ed9b544e 68} config;
69
a9158272 70static void usage();
11fd0c42 71char *redisGitSHA1(void);
c392edf5 72char *redisGitDirty(void);
c937aa89 73
3ce014c7 74/*------------------------------------------------------------------------------
75 * Utility functions
76 *--------------------------------------------------------------------------- */
77
78static long long mstime(void) {
79 struct timeval tv;
80 long long mst;
81
82 gettimeofday(&tv, NULL);
83 mst = ((long)tv.tv_sec)*1000;
84 mst += tv.tv_usec/1000;
85 return mst;
86}
87
3f4eef21
PN
88static void cliRefreshPrompt(void) {
89 if (config.dbnum == 0)
a45f9a1a 90 snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d> ",
91 config.hostip, config.hostport);
3f4eef21 92 else
a45f9a1a 93 snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d[%d]> ",
94 config.hostip, config.hostport, config.dbnum);
3f4eef21
PN
95}
96
a2a69d58
PN
97/*------------------------------------------------------------------------------
98 * Help functions
99 *--------------------------------------------------------------------------- */
100
b2cc45bf
PN
101#define CLI_HELP_COMMAND 1
102#define CLI_HELP_GROUP 2
103
104typedef struct {
105 int type;
106 int argc;
107 sds *argv;
108 sds full;
109
110 /* Only used for help on commands */
111 struct commandHelp *org;
112} helpEntry;
113
114static helpEntry *helpEntries;
115static int helpEntriesLen;
116
c392edf5
PN
117static sds cliVersion() {
118 sds version;
119 version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
120
121 /* Add git commit and working tree status when available */
122 if (strtoll(redisGitSHA1(),NULL,16)) {
123 version = sdscatprintf(version, " (git:%s", redisGitSHA1());
124 if (strtoll(redisGitDirty(),NULL,10))
125 version = sdscatprintf(version, "-dirty");
126 version = sdscat(version, ")");
127 }
128 return version;
129}
130
b2cc45bf
PN
131static void cliInitHelp() {
132 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
133 int groupslen = sizeof(commandGroups)/sizeof(char*);
134 int i, len, pos = 0;
135 helpEntry tmp;
136
137 helpEntriesLen = len = commandslen+groupslen;
138 helpEntries = malloc(sizeof(helpEntry)*len);
139
140 for (i = 0; i < groupslen; i++) {
141 tmp.argc = 1;
142 tmp.argv = malloc(sizeof(sds));
143 tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
144 tmp.full = tmp.argv[0];
145 tmp.type = CLI_HELP_GROUP;
146 tmp.org = NULL;
147 helpEntries[pos++] = tmp;
148 }
149
150 for (i = 0; i < commandslen; i++) {
151 tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
152 tmp.full = sdsnew(commandHelp[i].name);
153 tmp.type = CLI_HELP_COMMAND;
154 tmp.org = &commandHelp[i];
155 helpEntries[pos++] = tmp;
156 }
157}
158
a2a69d58 159/* Output command help to stdout. */
41945ba6
PN
160static void cliOutputCommandHelp(struct commandHelp *help, int group) {
161 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
162 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
163 printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
164 if (group) {
165 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
166 }
a2a69d58
PN
167}
168
41945ba6
PN
169/* Print generic help. */
170static void cliOutputGenericHelp() {
c392edf5 171 sds version = cliVersion();
41945ba6
PN
172 printf(
173 "redis-cli %s\r\n"
174 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
175 " \"help <command>\" for help on <command>\r\n"
176 " \"help <tab>\" to get a list of possible help topics\r\n"
177 " \"quit\" to exit\r\n",
c392edf5 178 version
41945ba6 179 );
c392edf5 180 sdsfree(version);
a2a69d58
PN
181}
182
183/* Output all command help, filtering by group or command name. */
41945ba6 184static void cliOutputHelp(int argc, char **argv) {
b2cc45bf 185 int i, j, len;
41945ba6 186 int group = -1;
b2cc45bf
PN
187 helpEntry *entry;
188 struct commandHelp *help;
a2a69d58 189
41945ba6
PN
190 if (argc == 0) {
191 cliOutputGenericHelp();
a2a69d58 192 return;
41945ba6
PN
193 } else if (argc > 0 && argv[0][0] == '@') {
194 len = sizeof(commandGroups)/sizeof(char*);
195 for (i = 0; i < len; i++) {
196 if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
197 group = i;
198 break;
199 }
200 }
a2a69d58
PN
201 }
202
41945ba6 203 assert(argc > 0);
b2cc45bf
PN
204 for (i = 0; i < helpEntriesLen; i++) {
205 entry = &helpEntries[i];
206 if (entry->type != CLI_HELP_COMMAND) continue;
207
208 help = entry->org;
a2a69d58 209 if (group == -1) {
b2cc45bf
PN
210 /* Compare all arguments */
211 if (argc == entry->argc) {
212 for (j = 0; j < argc; j++) {
213 if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
214 }
215 if (j == argc) {
216 cliOutputCommandHelp(help,1);
217 }
a2a69d58
PN
218 }
219 } else {
220 if (group == help->group) {
41945ba6 221 cliOutputCommandHelp(help,0);
a2a69d58
PN
222 }
223 }
224 }
41945ba6
PN
225 printf("\r\n");
226}
227
41945ba6
PN
228static void completionCallback(const char *buf, linenoiseCompletions *lc) {
229 size_t startpos = 0;
230 int mask;
231 int i;
232 size_t matchlen;
b2cc45bf 233 sds tmp;
41945ba6
PN
234
235 if (strncasecmp(buf,"help ",5) == 0) {
236 startpos = 5;
237 while (isspace(buf[startpos])) startpos++;
b2cc45bf 238 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
41945ba6 239 } else {
b2cc45bf 240 mask = CLI_HELP_COMMAND;
41945ba6
PN
241 }
242
b2cc45bf
PN
243 for (i = 0; i < helpEntriesLen; i++) {
244 if (!(helpEntries[i].type & mask)) continue;
41945ba6
PN
245
246 matchlen = strlen(buf+startpos);
b2cc45bf
PN
247 if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
248 tmp = sdsnewlen(buf,startpos);
249 tmp = sdscat(tmp,helpEntries[i].full);
41945ba6 250 linenoiseAddCompletion(lc,tmp);
b2cc45bf 251 sdsfree(tmp);
41945ba6
PN
252 }
253 }
a2a69d58
PN
254}
255
3ce014c7 256/*------------------------------------------------------------------------------
257 * Networking / parsing
258 *--------------------------------------------------------------------------- */
259
7fc4ce13
PN
260/* Send AUTH command to the server */
261static int cliAuth() {
262 redisReply *reply;
263 if (config.auth == NULL) return REDIS_OK;
264
265 reply = redisCommand(context,"AUTH %s",config.auth);
266 if (reply != NULL) {
267 freeReplyObject(reply);
268 return REDIS_OK;
269 }
270 return REDIS_ERR;
271}
272
273/* Send SELECT dbnum to the server */
274static int cliSelect() {
275 redisReply *reply;
7fc4ce13
PN
276 if (config.dbnum == 0) return REDIS_OK;
277
96e34b3c 278 reply = redisCommand(context,"SELECT %d",config.dbnum);
7fc4ce13
PN
279 if (reply != NULL) {
280 freeReplyObject(reply);
281 return REDIS_OK;
282 }
283 return REDIS_ERR;
284}
285
c0b3d423 286/* Connect to the client. If force is not zero the connection is performed
287 * even if there is already a connected socket. */
288static int cliConnect(int force) {
7fc4ce13
PN
289 if (context == NULL || force) {
290 if (context != NULL)
291 redisFree(context);
ed9b544e 292
7e91f971 293 if (config.hostsocket == NULL) {
7fc4ce13 294 context = redisConnect(config.hostip,config.hostport);
7e91f971 295 } else {
7fc4ce13 296 context = redisConnectUnix(config.hostsocket);
7e91f971 297 }
7fc4ce13
PN
298
299 if (context->err) {
7e91f971
PN
300 fprintf(stderr,"Could not connect to Redis at ");
301 if (config.hostsocket == NULL)
7fc4ce13 302 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
7e91f971 303 else
7fc4ce13
PN
304 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
305 redisFree(context);
306 context = NULL;
307 return REDIS_ERR;
6fa24622 308 }
ed9b544e 309
7fc4ce13
PN
310 /* Do AUTH and select the right DB. */
311 if (cliAuth() != REDIS_OK)
312 return REDIS_ERR;
313 if (cliSelect() != REDIS_OK)
314 return REDIS_ERR;
ed9b544e 315 }
7fc4ce13 316 return REDIS_OK;
ed9b544e 317}
318
a45f9a1a 319static void cliPrintContextError() {
7fc4ce13
PN
320 if (context == NULL) return;
321 fprintf(stderr,"Error: %s\n",context->errstr);
ed9b544e 322}
323
65add0a3 324static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
7fc4ce13
PN
325 sds out = sdsempty();
326 switch (r->type) {
327 case REDIS_REPLY_ERROR:
65add0a3 328 out = sdscatprintf(out,"(error) %s\n", r->str);
7fc4ce13
PN
329 break;
330 case REDIS_REPLY_STATUS:
7fc4ce13
PN
331 out = sdscat(out,r->str);
332 out = sdscat(out,"\n");
333 break;
334 case REDIS_REPLY_INTEGER:
65add0a3 335 out = sdscatprintf(out,"(integer) %lld\n",r->integer);
7fc4ce13
PN
336 break;
337 case REDIS_REPLY_STRING:
65add0a3
PN
338 /* If you are producing output for the standard output we want
339 * a more interesting output with quoted characters and so forth */
340 out = sdscatrepr(out,r->str,r->len);
341 out = sdscat(out,"\n");
7fc4ce13
PN
342 break;
343 case REDIS_REPLY_NIL:
7fc4ce13
PN
344 out = sdscat(out,"(nil)\n");
345 break;
346 case REDIS_REPLY_ARRAY:
347 if (r->elements == 0) {
7fc4ce13 348 out = sdscat(out,"(empty list or set)\n");
c0b3d423 349 } else {
cfcd5d6d
PN
350 unsigned int i, idxlen = 0;
351 char _prefixlen[16];
352 char _prefixfmt[16];
353 sds _prefix;
7fc4ce13
PN
354 sds tmp;
355
cfcd5d6d
PN
356 /* Calculate chars needed to represent the largest index */
357 i = r->elements;
358 do {
359 idxlen++;
360 i /= 10;
361 } while(i);
362
363 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
364 memset(_prefixlen,' ',idxlen+2);
365 _prefixlen[idxlen+2] = '\0';
366 _prefix = sdscat(sdsnew(prefix),_prefixlen);
367
368 /* Setup prefix format for every entry */
369 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
370
7fc4ce13 371 for (i = 0; i < r->elements; i++) {
cfcd5d6d
PN
372 /* Don't use the prefix for the first element, as the parent
373 * caller already prepended the index number. */
374 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
375
376 /* Format the multi bulk entry */
65add0a3 377 tmp = cliFormatReplyTTY(r->element[i],_prefix);
7fc4ce13
PN
378 out = sdscatlen(out,tmp,sdslen(tmp));
379 sdsfree(tmp);
380 }
cfcd5d6d 381 sdsfree(_prefix);
c0b3d423 382 }
7fc4ce13 383 break;
c937aa89 384 default:
7fc4ce13
PN
385 fprintf(stderr,"Unknown reply type: %d\n", r->type);
386 exit(1);
c937aa89 387 }
7fc4ce13 388 return out;
c937aa89 389}
390
65add0a3
PN
391static sds cliFormatReplyRaw(redisReply *r) {
392 sds out = sdsempty(), tmp;
393 size_t i;
394
395 switch (r->type) {
396 case REDIS_REPLY_NIL:
397 /* Nothing... */
ecc91094 398 break;
65add0a3 399 case REDIS_REPLY_ERROR:
ecc91094 400 out = sdscatlen(out,r->str,r->len);
401 out = sdscatlen(out,"\n",1);
402 break;
65add0a3
PN
403 case REDIS_REPLY_STATUS:
404 case REDIS_REPLY_STRING:
405 out = sdscatlen(out,r->str,r->len);
ecc91094 406 break;
65add0a3
PN
407 case REDIS_REPLY_INTEGER:
408 out = sdscatprintf(out,"%lld",r->integer);
ecc91094 409 break;
65add0a3
PN
410 case REDIS_REPLY_ARRAY:
411 for (i = 0; i < r->elements; i++) {
412 if (i > 0) out = sdscat(out,config.mb_delim);
413 tmp = cliFormatReplyRaw(r->element[i]);
414 out = sdscatlen(out,tmp,sdslen(tmp));
415 sdsfree(tmp);
416 }
ecc91094 417 break;
65add0a3
PN
418 default:
419 fprintf(stderr,"Unknown reply type: %d\n", r->type);
420 exit(1);
421 }
422 return out;
423}
424
425static int cliReadReply(int output_raw_strings) {
8ce39260 426 void *_reply;
7fc4ce13
PN
427 redisReply *reply;
428 sds out;
429
8ce39260 430 if (redisGetReply(context,&_reply) != REDIS_OK) {
7fc4ce13
PN
431 if (config.shutdown)
432 return REDIS_OK;
433 if (config.interactive) {
434 /* Filter cases where we should reconnect */
435 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
436 return REDIS_ERR;
437 if (context->err == REDIS_ERR_EOF)
438 return REDIS_ERR;
439 }
a45f9a1a 440 cliPrintContextError();
441 exit(1);
7fc4ce13 442 return REDIS_ERR; /* avoid compiler warning */
62e920df 443 }
7fc4ce13 444
8ce39260 445 reply = (redisReply*)_reply;
65add0a3
PN
446 if (output_raw_strings) {
447 out = cliFormatReplyRaw(reply);
448 } else {
449 if (config.raw_output) {
450 out = cliFormatReplyRaw(reply);
451 out = sdscat(out,"\n");
452 } else {
453 out = cliFormatReplyTTY(reply,"");
454 }
455 }
7fc4ce13
PN
456 fwrite(out,sdslen(out),1,stdout);
457 sdsfree(out);
65add0a3 458 freeReplyObject(reply);
7fc4ce13 459 return REDIS_OK;
62e920df 460}
461
aab055ae 462static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 463 char *command = argv[0];
7fc4ce13 464 size_t *argvlen;
65add0a3 465 int j, output_raw;
ed9b544e 466
a45f9a1a 467 if (context == NULL) return REDIS_ERR;
efcf948c 468
ecc91094 469 output_raw = 0;
470 if (!strcasecmp(command,"info") ||
471 (argc == 2 && !strcasecmp(command,"cluster") &&
472 (!strcasecmp(argv[1],"nodes") ||
3cd12b56 473 !strcasecmp(argv[1],"info"))) ||
474 (argc == 2 && !strcasecmp(command,"client") &&
475 !strcasecmp(argv[1],"list")))
476
ecc91094 477 {
478 output_raw = 1;
479 }
480
41945ba6
PN
481 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
482 cliOutputHelp(--argc, ++argv);
7fc4ce13 483 return REDIS_OK;
8079656a 484 }
37dc9e5a
PN
485 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
486 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
487 if (!strcasecmp(command,"subscribe") ||
488 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
ed9b544e 489
7fc4ce13
PN
490 /* Setup argument length */
491 argvlen = malloc(argc*sizeof(size_t));
492 for (j = 0; j < argc; j++)
493 argvlen[j] = sdslen(argv[j]);
a2f4f871 494
aab055ae 495 while(repeat--) {
7fc4ce13 496 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
249c3a7d 497 while (config.monitor_mode) {
65add0a3 498 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
d9d8ccab 499 fflush(stdout);
621d5c19 500 }
501
249c3a7d 502 if (config.pubsub_mode) {
65add0a3
PN
503 if (!config.raw_output)
504 printf("Reading messages... (press Ctrl-C to quit)\n");
249c3a7d 505 while (1) {
65add0a3 506 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
249c3a7d 507 }
508 }
509
33753a73
PN
510 if (cliReadReply(output_raw) != REDIS_OK) {
511 free(argvlen);
7fc4ce13 512 return REDIS_ERR;
96e34b3c
PN
513 } else {
514 /* Store database number when SELECT was successfully executed. */
3f4eef21 515 if (!strcasecmp(command,"select") && argc == 2) {
96e34b3c 516 config.dbnum = atoi(argv[1]);
3f4eef21
PN
517 cliRefreshPrompt();
518 }
33753a73 519 }
ed9b544e 520 }
33753a73
PN
521
522 free(argvlen);
7fc4ce13 523 return REDIS_OK;
ed9b544e 524}
525
3ce014c7 526/*------------------------------------------------------------------------------
527 * User interface
528 *--------------------------------------------------------------------------- */
529
ed9b544e 530static int parseOptions(int argc, char **argv) {
531 int i;
532
533 for (i = 1; i < argc; i++) {
534 int lastarg = i==argc-1;
6cf5882c 535
ed9b544e 536 if (!strcmp(argv[i],"-h") && !lastarg) {
efcf948c 537 sdsfree(config.hostip);
538 config.hostip = sdsnew(argv[i+1]);
ed9b544e 539 i++;
a9158272 540 } else if (!strcmp(argv[i],"-h") && lastarg) {
541 usage();
f18e059e
PN
542 } else if (!strcmp(argv[i],"--help")) {
543 usage();
bc63407b 544 } else if (!strcmp(argv[i],"-x")) {
545 config.stdinarg = 1;
ed9b544e 546 } else if (!strcmp(argv[i],"-p") && !lastarg) {
547 config.hostport = atoi(argv[i+1]);
548 i++;
7e91f971
PN
549 } else if (!strcmp(argv[i],"-s") && !lastarg) {
550 config.hostsocket = argv[i+1];
551 i++;
5762b7f0 552 } else if (!strcmp(argv[i],"-r") && !lastarg) {
553 config.repeat = strtoll(argv[i+1],NULL,10);
554 i++;
62e920df 555 } else if (!strcmp(argv[i],"-n") && !lastarg) {
556 config.dbnum = atoi(argv[i+1]);
557 i++;
fdfdae0f 558 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 559 config.auth = argv[i+1];
fdfdae0f 560 i++;
65add0a3
PN
561 } else if (!strcmp(argv[i],"--raw")) {
562 config.raw_output = 1;
28c07c7b
PN
563 } else if (!strcmp(argv[i],"-d") && !lastarg) {
564 sdsfree(config.mb_delim);
565 config.mb_delim = sdsnew(argv[i+1]);
566 i++;
f18e059e
PN
567 } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
568 sds version = cliVersion();
569 printf("redis-cli %s\n", version);
570 sdsfree(version);
185cabda 571 exit(0);
ed9b544e 572 } else {
573 break;
574 }
575 }
576 return i;
577}
578
579static sds readArgFromStdin(void) {
580 char buf[1024];
581 sds arg = sdsempty();
582
583 while(1) {
584 int nread = read(fileno(stdin),buf,1024);
585
586 if (nread == 0) break;
587 else if (nread == -1) {
588 perror("Reading from standard input");
589 exit(1);
590 }
591 arg = sdscatlen(arg,buf,nread);
592 }
593 return arg;
594}
595
a9158272 596static void usage() {
f18e059e
PN
597 sds version = cliVersion();
598 fprintf(stderr,
599"redis-cli %s\n"
600"\n"
601"Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
602" -h <hostname> Server hostname (default: 127.0.0.1)\n"
603" -p <port> Server port (default: 6379)\n"
604" -s <socket> Server socket (overrides hostname and port)\n"
605" -a <password> Password to use when connecting to the server\n"
606" -r <repeat> Execute specified command N times\n"
607" -n <db> Database number\n"
608" -x Read last argument from STDIN\n"
28c07c7b 609" -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
65add0a3 610" --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
f18e059e
PN
611" --help Output this help and exit\n"
612" --version Output version and exit\n"
613"\n"
614"Examples:\n"
615" cat /etc/passwd | redis-cli -x set mypasswd\n"
616" redis-cli get mypasswd\n"
617" redis-cli -r 100 lpush mylist x\n"
618"\n"
619"When no command is given, redis-cli starts in interactive mode.\n"
620"Type \"help\" in interactive mode for information on available commands.\n"
621"\n",
622 version);
623 sdsfree(version);
a9158272 624 exit(1);
625}
626
6cf5882c
MMDJ
627/* Turn the plain C strings into Sds strings */
628static char **convertToSds(int count, char** args) {
629 int j;
37dc9e5a 630 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
631
632 for(j = 0; j < count; j++)
633 sds[j] = sdsnew(args[j]);
634
635 return sds;
636}
637
a88a2af6 638#define LINE_BUFLEN 4096
6cf5882c 639static void repl() {
ca36b4ab
PN
640 sds historyfile = NULL;
641 int history = 0;
cbce5171 642 char *line;
ca36b4ab 643 int argc;
cbce5171 644 sds *argv;
6cf5882c 645
5d15b520 646 config.interactive = 1;
41945ba6 647 linenoiseSetCompletionCallback(completionCallback);
ce260f73 648
ca36b4ab
PN
649 /* Only use history when stdin is a tty. */
650 if (isatty(fileno(stdin))) {
651 history = 1;
652
653 if (getenv("HOME") != NULL) {
654 historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
655 linenoiseHistoryLoad(historyfile);
656 }
657 }
658
3f4eef21
PN
659 cliRefreshPrompt();
660 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
cf87ebf2 661 if (line[0] != '\0') {
cbce5171 662 argv = sdssplitargs(line,&argc);
ca36b4ab
PN
663 if (history) linenoiseHistoryAdd(line);
664 if (historyfile) linenoiseHistorySave(historyfile);
665
0439d792
PN
666 if (argv == NULL) {
667 printf("Invalid argument(s)\n");
668 continue;
669 } else if (argc > 0) {
a88a2af6 670 if (strcasecmp(argv[0],"quit") == 0 ||
671 strcasecmp(argv[0],"exit") == 0)
c0b3d423 672 {
673 exit(0);
efcf948c 674 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
675 sdsfree(config.hostip);
676 config.hostip = sdsnew(argv[1]);
677 config.hostport = atoi(argv[2]);
678 cliConnect(1);
bbac56c2 679 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
680 linenoiseClearScreen();
c0b3d423 681 } else {
3ce014c7 682 long long start_time = mstime(), elapsed;
c0b3d423 683
7fc4ce13 684 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
efcf948c 685 cliConnect(1);
7fc4ce13
PN
686
687 /* If we still cannot send the command,
688 * print error and abort. */
689 if (cliSendCommand(argc,argv,1) != REDIS_OK)
a45f9a1a 690 cliPrintContextError();
c0b3d423 691 }
3ce014c7 692 elapsed = mstime()-start_time;
339b9dc2
PN
693 if (elapsed >= 500) {
694 printf("(%.2fs)\n",(double)elapsed/1000);
695 }
c0b3d423 696 }
a88a2af6 697 }
698 /* Free the argument vector */
ca36b4ab 699 while(argc--) sdsfree(argv[argc]);
8ff6a48b 700 zfree(argv);
6cf5882c 701 }
a88a2af6 702 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 703 free(line);
6cf5882c 704 }
6cf5882c
MMDJ
705 exit(0);
706}
707
b4b62c34
PN
708static int noninteractive(int argc, char **argv) {
709 int retval = 0;
bc63407b 710 if (config.stdinarg) {
b4b62c34
PN
711 argv = zrealloc(argv, (argc+1)*sizeof(char*));
712 argv[argc] = readArgFromStdin();
713 retval = cliSendCommand(argc+1, argv, config.repeat);
714 } else {
715 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
716 retval = cliSendCommand(argc, argv, config.repeat);
717 }
718 return retval;
719}
720
ed9b544e 721int main(int argc, char **argv) {
6cf5882c 722 int firstarg;
ed9b544e 723
efcf948c 724 config.hostip = sdsnew("127.0.0.1");
ed9b544e 725 config.hostport = 6379;
7e91f971 726 config.hostsocket = NULL;
5762b7f0 727 config.repeat = 1;
62e920df 728 config.dbnum = 0;
5d15b520 729 config.interactive = 0;
36e5db6d 730 config.shutdown = 0;
249c3a7d 731 config.monitor_mode = 0;
732 config.pubsub_mode = 0;
bc63407b 733 config.stdinarg = 0;
288799e0 734 config.auth = NULL;
65add0a3
PN
735 config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL);
736 config.mb_delim = sdsnew("\n");
41945ba6 737 cliInitHelp();
99628c1a 738
ed9b544e 739 firstarg = parseOptions(argc,argv);
740 argc -= firstarg;
741 argv += firstarg;
ed9b544e 742
abb731e5 743 /* Start interactive mode when no command is provided */
a45f9a1a 744 if (argc == 0) {
745 /* Note that in repl mode we don't abort on connection error.
746 * A new attempt will be performed for every command send. */
747 cliConnect(0);
748 repl();
749 }
750
b4b62c34 751 /* Otherwise, we have some arguments to execute */
a45f9a1a 752 if (cliConnect(0) != REDIS_OK) exit(1);
b4b62c34 753 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 754}