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