]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
1 /* Redis CLI (command line interface)
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
47 #include "linenoise.h"
50 #define REDIS_NOTUSED(V) ((void) V)
52 static redisContext
*context
;
53 static struct config
{
63 int stdinarg
; /* get last arg from stdin. (-x option) */
66 int raw_output
; /* output mode per command */
71 char *redisGitSHA1(void);
72 char *redisGitDirty(void);
74 /*------------------------------------------------------------------------------
76 *--------------------------------------------------------------------------- */
78 static long long mstime(void) {
82 gettimeofday(&tv
, NULL
);
83 mst
= ((long)tv
.tv_sec
)*1000;
84 mst
+= tv
.tv_usec
/1000;
88 /*------------------------------------------------------------------------------
90 *--------------------------------------------------------------------------- */
92 #define CLI_HELP_COMMAND 1
93 #define CLI_HELP_GROUP 2
101 /* Only used for help on commands */
102 struct commandHelp
*org
;
105 static helpEntry
*helpEntries
;
106 static int helpEntriesLen
;
108 static sds
cliVersion() {
110 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
112 /* Add git commit and working tree status when available */
113 if (strtoll(redisGitSHA1(),NULL
,16)) {
114 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
115 if (strtoll(redisGitDirty(),NULL
,10))
116 version
= sdscatprintf(version
, "-dirty");
117 version
= sdscat(version
, ")");
122 static void cliInitHelp() {
123 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
124 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
128 helpEntriesLen
= len
= commandslen
+groupslen
;
129 helpEntries
= malloc(sizeof(helpEntry
)*len
);
131 for (i
= 0; i
< groupslen
; i
++) {
133 tmp
.argv
= malloc(sizeof(sds
));
134 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
135 tmp
.full
= tmp
.argv
[0];
136 tmp
.type
= CLI_HELP_GROUP
;
138 helpEntries
[pos
++] = tmp
;
141 for (i
= 0; i
< commandslen
; i
++) {
142 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
143 tmp
.full
= sdsnew(commandHelp
[i
].name
);
144 tmp
.type
= CLI_HELP_COMMAND
;
145 tmp
.org
= &commandHelp
[i
];
146 helpEntries
[pos
++] = tmp
;
150 /* Output command help to stdout. */
151 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
152 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
153 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
154 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
156 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
160 /* Print generic help. */
161 static void cliOutputGenericHelp() {
162 sds version
= cliVersion();
165 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
166 " \"help <command>\" for help on <command>\r\n"
167 " \"help <tab>\" to get a list of possible help topics\r\n"
168 " \"quit\" to exit\r\n",
174 /* Output all command help, filtering by group or command name. */
175 static void cliOutputHelp(int argc
, char **argv
) {
179 struct commandHelp
*help
;
182 cliOutputGenericHelp();
184 } else if (argc
> 0 && argv
[0][0] == '@') {
185 len
= sizeof(commandGroups
)/sizeof(char*);
186 for (i
= 0; i
< len
; i
++) {
187 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
195 for (i
= 0; i
< helpEntriesLen
; i
++) {
196 entry
= &helpEntries
[i
];
197 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
201 /* Compare all arguments */
202 if (argc
== entry
->argc
) {
203 for (j
= 0; j
< argc
; j
++) {
204 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
207 cliOutputCommandHelp(help
,1);
211 if (group
== help
->group
) {
212 cliOutputCommandHelp(help
,0);
219 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
226 if (strncasecmp(buf
,"help ",5) == 0) {
228 while (isspace(buf
[startpos
])) startpos
++;
229 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
231 mask
= CLI_HELP_COMMAND
;
234 for (i
= 0; i
< helpEntriesLen
; i
++) {
235 if (!(helpEntries
[i
].type
& mask
)) continue;
237 matchlen
= strlen(buf
+startpos
);
238 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
239 tmp
= sdsnewlen(buf
,startpos
);
240 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
241 linenoiseAddCompletion(lc
,tmp
);
247 /*------------------------------------------------------------------------------
248 * Networking / parsing
249 *--------------------------------------------------------------------------- */
251 /* Send AUTH command to the server */
252 static int cliAuth() {
254 if (config
.auth
== NULL
) return REDIS_OK
;
256 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
258 freeReplyObject(reply
);
264 /* Send SELECT dbnum to the server */
265 static int cliSelect() {
268 if (config
.dbnum
== 0) return REDIS_OK
;
270 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
271 reply
= redisCommand(context
,"SELECT %s",dbnum
);
273 freeReplyObject(reply
);
279 /* Connect to the client. If force is not zero the connection is performed
280 * even if there is already a connected socket. */
281 static int cliConnect(int force
) {
282 if (context
== NULL
|| force
) {
286 if (config
.hostsocket
== NULL
) {
287 context
= redisConnect(config
.hostip
,config
.hostport
);
289 context
= redisConnectUnix(config
.hostsocket
);
293 fprintf(stderr
,"Could not connect to Redis at ");
294 if (config
.hostsocket
== NULL
)
295 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
297 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
303 /* Do AUTH and select the right DB. */
304 if (cliAuth() != REDIS_OK
)
306 if (cliSelect() != REDIS_OK
)
312 static void cliPrintContextErrorAndExit() {
313 if (context
== NULL
) return;
314 fprintf(stderr
,"Error: %s\n",context
->errstr
);
318 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
319 sds out
= sdsempty();
321 case REDIS_REPLY_ERROR
:
322 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
324 case REDIS_REPLY_STATUS
:
325 out
= sdscat(out
,r
->str
);
326 out
= sdscat(out
,"\n");
328 case REDIS_REPLY_INTEGER
:
329 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
331 case REDIS_REPLY_STRING
:
332 /* If you are producing output for the standard output we want
333 * a more interesting output with quoted characters and so forth */
334 out
= sdscatrepr(out
,r
->str
,r
->len
);
335 out
= sdscat(out
,"\n");
337 case REDIS_REPLY_NIL
:
338 out
= sdscat(out
,"(nil)\n");
340 case REDIS_REPLY_ARRAY
:
341 if (r
->elements
== 0) {
342 out
= sdscat(out
,"(empty list or set)\n");
344 unsigned int i
, idxlen
= 0;
350 /* Calculate chars needed to represent the largest index */
357 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
358 memset(_prefixlen
,' ',idxlen
+2);
359 _prefixlen
[idxlen
+2] = '\0';
360 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
362 /* Setup prefix format for every entry */
363 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
365 for (i
= 0; i
< r
->elements
; i
++) {
366 /* Don't use the prefix for the first element, as the parent
367 * caller already prepended the index number. */
368 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
370 /* Format the multi bulk entry */
371 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
372 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
379 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
385 static sds
cliFormatReplyRaw(redisReply
*r
) {
386 sds out
= sdsempty(), tmp
;
390 case REDIS_REPLY_NIL
:
393 case REDIS_REPLY_ERROR
:
394 case REDIS_REPLY_STATUS
:
395 case REDIS_REPLY_STRING
:
396 out
= sdscatlen(out
,r
->str
,r
->len
);
398 case REDIS_REPLY_INTEGER
:
399 out
= sdscatprintf(out
,"%lld",r
->integer
);
401 case REDIS_REPLY_ARRAY
:
402 for (i
= 0; i
< r
->elements
; i
++) {
403 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
404 tmp
= cliFormatReplyRaw(r
->element
[i
]);
405 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
410 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
416 static int cliReadReply(int output_raw_strings
) {
421 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
424 if (config
.interactive
) {
425 /* Filter cases where we should reconnect */
426 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
428 if (context
->err
== REDIS_ERR_EOF
)
431 cliPrintContextErrorAndExit();
432 return REDIS_ERR
; /* avoid compiler warning */
435 reply
= (redisReply
*)_reply
;
436 if (output_raw_strings
) {
437 out
= cliFormatReplyRaw(reply
);
439 if (config
.raw_output
) {
440 out
= cliFormatReplyRaw(reply
);
441 out
= sdscat(out
,"\n");
443 out
= cliFormatReplyTTY(reply
,"");
446 fwrite(out
,sdslen(out
),1,stdout
);
448 freeReplyObject(reply
);
452 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
453 char *command
= argv
[0];
457 if (context
== NULL
) {
458 printf("Not connected, please use: connect <host> <port>\n");
462 output_raw
= !strcasecmp(command
,"info");
463 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
464 cliOutputHelp(--argc
, ++argv
);
467 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
468 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
469 if (!strcasecmp(command
,"subscribe") ||
470 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
472 /* Setup argument length */
473 argvlen
= malloc(argc
*sizeof(size_t));
474 for (j
= 0; j
< argc
; j
++)
475 argvlen
[j
] = sdslen(argv
[j
]);
478 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
479 while (config
.monitor_mode
) {
480 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
484 if (config
.pubsub_mode
) {
485 if (!config
.raw_output
)
486 printf("Reading messages... (press Ctrl-C to quit)\n");
488 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
492 if (cliReadReply(output_raw
) != REDIS_OK
)
498 /*------------------------------------------------------------------------------
500 *--------------------------------------------------------------------------- */
502 static int parseOptions(int argc
, char **argv
) {
505 for (i
= 1; i
< argc
; i
++) {
506 int lastarg
= i
==argc
-1;
508 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
509 sdsfree(config
.hostip
);
510 config
.hostip
= sdsnew(argv
[i
+1]);
512 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
514 } else if (!strcmp(argv
[i
],"--help")) {
516 } else if (!strcmp(argv
[i
],"-x")) {
518 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
519 config
.hostport
= atoi(argv
[i
+1]);
521 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
522 config
.hostsocket
= argv
[i
+1];
524 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
525 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
527 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
528 config
.dbnum
= atoi(argv
[i
+1]);
530 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
531 config
.auth
= argv
[i
+1];
533 } else if (!strcmp(argv
[i
],"--raw")) {
534 config
.raw_output
= 1;
535 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
536 sdsfree(config
.mb_delim
);
537 config
.mb_delim
= sdsnew(argv
[i
+1]);
539 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
540 sds version
= cliVersion();
541 printf("redis-cli %s\n", version
);
551 static sds
readArgFromStdin(void) {
553 sds arg
= sdsempty();
556 int nread
= read(fileno(stdin
),buf
,1024);
558 if (nread
== 0) break;
559 else if (nread
== -1) {
560 perror("Reading from standard input");
563 arg
= sdscatlen(arg
,buf
,nread
);
568 static void usage() {
569 sds version
= cliVersion();
573 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
574 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
575 " -p <port> Server port (default: 6379)\n"
576 " -s <socket> Server socket (overrides hostname and port)\n"
577 " -a <password> Password to use when connecting to the server\n"
578 " -r <repeat> Execute specified command N times\n"
579 " -n <db> Database number\n"
580 " -x Read last argument from STDIN\n"
581 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
582 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
583 " --help Output this help and exit\n"
584 " --version Output version and exit\n"
587 " cat /etc/passwd | redis-cli -x set mypasswd\n"
588 " redis-cli get mypasswd\n"
589 " redis-cli -r 100 lpush mylist x\n"
591 "When no command is given, redis-cli starts in interactive mode.\n"
592 "Type \"help\" in interactive mode for information on available commands.\n"
599 /* Turn the plain C strings into Sds strings */
600 static char **convertToSds(int count
, char** args
) {
602 char **sds
= zmalloc(sizeof(char*)*count
);
604 for(j
= 0; j
< count
; j
++)
605 sds
[j
] = sdsnew(args
[j
]);
610 #define LINE_BUFLEN 4096
616 config
.interactive
= 1;
617 linenoiseSetCompletionCallback(completionCallback
);
619 while((line
= linenoise(context
? "redis> " : "not connected> ")) != NULL
) {
620 if (line
[0] != '\0') {
621 argv
= sdssplitargs(line
,&argc
);
622 linenoiseHistoryAdd(line
);
623 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
625 printf("Invalid argument(s)\n");
627 } else if (argc
> 0) {
628 if (strcasecmp(argv
[0],"quit") == 0 ||
629 strcasecmp(argv
[0],"exit") == 0)
632 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
633 sdsfree(config
.hostip
);
634 config
.hostip
= sdsnew(argv
[1]);
635 config
.hostport
= atoi(argv
[2]);
637 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
638 linenoiseClearScreen();
640 long long start_time
= mstime(), elapsed
;
642 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
645 /* If we still cannot send the command,
646 * print error and abort. */
647 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
648 cliPrintContextErrorAndExit();
650 elapsed
= mstime()-start_time
;
651 if (elapsed
>= 500) {
652 printf("(%.2fs)\n",(double)elapsed
/1000);
656 /* Free the argument vector */
657 for (j
= 0; j
< argc
; j
++)
661 /* linenoise() returns malloc-ed lines like readline() */
667 static int noninteractive(int argc
, char **argv
) {
669 if (config
.stdinarg
) {
670 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
671 argv
[argc
] = readArgFromStdin();
672 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
674 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
675 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
680 int main(int argc
, char **argv
) {
683 config
.hostip
= sdsnew("127.0.0.1");
684 config
.hostport
= 6379;
685 config
.hostsocket
= NULL
;
688 config
.interactive
= 0;
690 config
.monitor_mode
= 0;
691 config
.pubsub_mode
= 0;
694 config
.historyfile
= NULL
;
695 config
.raw_output
= !isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
);
696 config
.mb_delim
= sdsnew("\n");
699 if (getenv("HOME") != NULL
) {
700 config
.historyfile
= malloc(256);
701 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
702 linenoiseHistoryLoad(config
.historyfile
);
705 firstarg
= parseOptions(argc
,argv
);
710 if (cliConnect(0) != REDIS_OK
) exit(1);
712 /* Start interactive mode when no command is provided */
713 if (argc
== 0) repl();
714 /* Otherwise, we have some arguments to execute */
715 return noninteractive(argc
,convertToSds(argc
,argv
));