]>
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) */
65 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 static void cliRefreshPrompt(void) {
89 if (config
.dbnum
== 0)
90 snprintf(config
.prompt
,sizeof(config
.prompt
),"redis> ");
92 snprintf(config
.prompt
,sizeof(config
.prompt
),"redis:%d> ",config
.dbnum
);
95 /*------------------------------------------------------------------------------
97 *--------------------------------------------------------------------------- */
99 #define CLI_HELP_COMMAND 1
100 #define CLI_HELP_GROUP 2
108 /* Only used for help on commands */
109 struct commandHelp
*org
;
112 static helpEntry
*helpEntries
;
113 static int helpEntriesLen
;
115 static sds
cliVersion() {
117 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
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
, ")");
129 static void cliInitHelp() {
130 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
131 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
135 helpEntriesLen
= len
= commandslen
+groupslen
;
136 helpEntries
= malloc(sizeof(helpEntry
)*len
);
138 for (i
= 0; i
< groupslen
; i
++) {
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
;
145 helpEntries
[pos
++] = tmp
;
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
;
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
);
163 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
167 /* Print generic help. */
168 static void cliOutputGenericHelp() {
169 sds version
= cliVersion();
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",
181 /* Output all command help, filtering by group or command name. */
182 static void cliOutputHelp(int argc
, char **argv
) {
186 struct commandHelp
*help
;
189 cliOutputGenericHelp();
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) {
202 for (i
= 0; i
< helpEntriesLen
; i
++) {
203 entry
= &helpEntries
[i
];
204 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
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;
214 cliOutputCommandHelp(help
,1);
218 if (group
== help
->group
) {
219 cliOutputCommandHelp(help
,0);
226 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
233 if (strncasecmp(buf
,"help ",5) == 0) {
235 while (isspace(buf
[startpos
])) startpos
++;
236 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
238 mask
= CLI_HELP_COMMAND
;
241 for (i
= 0; i
< helpEntriesLen
; i
++) {
242 if (!(helpEntries
[i
].type
& mask
)) continue;
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
);
254 /*------------------------------------------------------------------------------
255 * Networking / parsing
256 *--------------------------------------------------------------------------- */
258 /* Send AUTH command to the server */
259 static int cliAuth() {
261 if (config
.auth
== NULL
) return REDIS_OK
;
263 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
265 freeReplyObject(reply
);
271 /* Send SELECT dbnum to the server */
272 static int cliSelect() {
274 if (config
.dbnum
== 0) return REDIS_OK
;
276 reply
= redisCommand(context
,"SELECT %d",config
.dbnum
);
278 freeReplyObject(reply
);
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
) {
291 if (config
.hostsocket
== NULL
) {
292 context
= redisConnect(config
.hostip
,config
.hostport
);
294 context
= redisConnectUnix(config
.hostsocket
);
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
);
302 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
308 /* Do AUTH and select the right DB. */
309 if (cliAuth() != REDIS_OK
)
311 if (cliSelect() != REDIS_OK
)
317 static void cliPrintContextErrorAndExit() {
318 if (context
== NULL
) return;
319 fprintf(stderr
,"Error: %s\n",context
->errstr
);
323 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
324 sds out
= sdsempty();
326 case REDIS_REPLY_ERROR
:
327 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
329 case REDIS_REPLY_STATUS
:
330 out
= sdscat(out
,r
->str
);
331 out
= sdscat(out
,"\n");
333 case REDIS_REPLY_INTEGER
:
334 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
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");
342 case REDIS_REPLY_NIL
:
343 out
= sdscat(out
,"(nil)\n");
345 case REDIS_REPLY_ARRAY
:
346 if (r
->elements
== 0) {
347 out
= sdscat(out
,"(empty list or set)\n");
349 unsigned int i
, idxlen
= 0;
355 /* Calculate chars needed to represent the largest index */
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
);
367 /* Setup prefix format for every entry */
368 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
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);
375 /* Format the multi bulk entry */
376 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
377 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
384 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
390 static sds
cliFormatReplyRaw(redisReply
*r
) {
391 sds out
= sdsempty(), tmp
;
395 case REDIS_REPLY_NIL
:
398 case REDIS_REPLY_ERROR
:
399 out
= sdscatlen(out
,r
->str
,r
->len
);
400 out
= sdscatlen(out
,"\n",1);
402 case REDIS_REPLY_STATUS
:
403 case REDIS_REPLY_STRING
:
404 out
= sdscatlen(out
,r
->str
,r
->len
);
406 case REDIS_REPLY_INTEGER
:
407 out
= sdscatprintf(out
,"%lld",r
->integer
);
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
));
418 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
424 static int cliReadReply(int output_raw_strings
) {
429 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
432 if (config
.interactive
) {
433 /* Filter cases where we should reconnect */
434 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
436 if (context
->err
== REDIS_ERR_EOF
)
439 cliPrintContextErrorAndExit();
440 return REDIS_ERR
; /* avoid compiler warning */
443 reply
= (redisReply
*)_reply
;
444 if (output_raw_strings
) {
445 out
= cliFormatReplyRaw(reply
);
447 if (config
.raw_output
) {
448 out
= cliFormatReplyRaw(reply
);
449 out
= sdscat(out
,"\n");
451 out
= cliFormatReplyTTY(reply
,"");
454 fwrite(out
,sdslen(out
),1,stdout
);
456 freeReplyObject(reply
);
460 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
461 char *command
= argv
[0];
465 if (context
== NULL
) {
466 printf("Not connected, please use: connect <host> <port>\n");
471 if (!strcasecmp(command
,"info") ||
472 (argc
== 2 && !strcasecmp(command
,"cluster") &&
473 (!strcasecmp(argv
[1],"nodes") ||
474 !strcasecmp(argv
[1],"info"))))
479 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
480 cliOutputHelp(--argc
, ++argv
);
483 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
484 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
485 if (!strcasecmp(command
,"subscribe") ||
486 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
488 /* Setup argument length */
489 argvlen
= malloc(argc
*sizeof(size_t));
490 for (j
= 0; j
< argc
; j
++)
491 argvlen
[j
] = sdslen(argv
[j
]);
494 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
495 while (config
.monitor_mode
) {
496 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
500 if (config
.pubsub_mode
) {
501 if (!config
.raw_output
)
502 printf("Reading messages... (press Ctrl-C to quit)\n");
504 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
508 if (cliReadReply(output_raw
) != REDIS_OK
) {
512 /* Store database number when SELECT was successfully executed. */
513 if (!strcasecmp(command
,"select") && argc
== 2) {
514 config
.dbnum
= atoi(argv
[1]);
524 /*------------------------------------------------------------------------------
526 *--------------------------------------------------------------------------- */
528 static int parseOptions(int argc
, char **argv
) {
531 for (i
= 1; i
< argc
; i
++) {
532 int lastarg
= i
==argc
-1;
534 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
535 sdsfree(config
.hostip
);
536 config
.hostip
= sdsnew(argv
[i
+1]);
538 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
540 } else if (!strcmp(argv
[i
],"--help")) {
542 } else if (!strcmp(argv
[i
],"-x")) {
544 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
545 config
.hostport
= atoi(argv
[i
+1]);
547 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
548 config
.hostsocket
= argv
[i
+1];
550 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
551 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
553 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
554 config
.dbnum
= atoi(argv
[i
+1]);
556 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
557 config
.auth
= argv
[i
+1];
559 } else if (!strcmp(argv
[i
],"--raw")) {
560 config
.raw_output
= 1;
561 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
562 sdsfree(config
.mb_delim
);
563 config
.mb_delim
= sdsnew(argv
[i
+1]);
565 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
566 sds version
= cliVersion();
567 printf("redis-cli %s\n", version
);
577 static sds
readArgFromStdin(void) {
579 sds arg
= sdsempty();
582 int nread
= read(fileno(stdin
),buf
,1024);
584 if (nread
== 0) break;
585 else if (nread
== -1) {
586 perror("Reading from standard input");
589 arg
= sdscatlen(arg
,buf
,nread
);
594 static void usage() {
595 sds version
= cliVersion();
599 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
600 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
601 " -p <port> Server port (default: 6379)\n"
602 " -s <socket> Server socket (overrides hostname and port)\n"
603 " -a <password> Password to use when connecting to the server\n"
604 " -r <repeat> Execute specified command N times\n"
605 " -n <db> Database number\n"
606 " -x Read last argument from STDIN\n"
607 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
608 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
609 " --help Output this help and exit\n"
610 " --version Output version and exit\n"
613 " cat /etc/passwd | redis-cli -x set mypasswd\n"
614 " redis-cli get mypasswd\n"
615 " redis-cli -r 100 lpush mylist x\n"
617 "When no command is given, redis-cli starts in interactive mode.\n"
618 "Type \"help\" in interactive mode for information on available commands.\n"
625 /* Turn the plain C strings into Sds strings */
626 static char **convertToSds(int count
, char** args
) {
628 char **sds
= zmalloc(sizeof(char*)*count
);
630 for(j
= 0; j
< count
; j
++)
631 sds
[j
] = sdsnew(args
[j
]);
636 #define LINE_BUFLEN 4096
638 sds historyfile
= NULL
;
644 config
.interactive
= 1;
645 linenoiseSetCompletionCallback(completionCallback
);
647 /* Only use history when stdin is a tty. */
648 if (isatty(fileno(stdin
))) {
651 if (getenv("HOME") != NULL
) {
652 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
653 linenoiseHistoryLoad(historyfile
);
658 while((line
= linenoise(context
? config
.prompt
: "not connected> ")) != NULL
) {
659 if (line
[0] != '\0') {
660 argv
= sdssplitargs(line
,&argc
);
661 if (history
) linenoiseHistoryAdd(line
);
662 if (historyfile
) linenoiseHistorySave(historyfile
);
665 printf("Invalid argument(s)\n");
667 } else if (argc
> 0) {
668 if (strcasecmp(argv
[0],"quit") == 0 ||
669 strcasecmp(argv
[0],"exit") == 0)
672 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
673 sdsfree(config
.hostip
);
674 config
.hostip
= sdsnew(argv
[1]);
675 config
.hostport
= atoi(argv
[2]);
677 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
678 linenoiseClearScreen();
680 long long start_time
= mstime(), elapsed
;
682 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
685 /* If we still cannot send the command,
686 * print error and abort. */
687 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
688 cliPrintContextErrorAndExit();
690 elapsed
= mstime()-start_time
;
691 if (elapsed
>= 500) {
692 printf("(%.2fs)\n",(double)elapsed
/1000);
696 /* Free the argument vector */
697 while(argc
--) sdsfree(argv
[argc
]);
700 /* linenoise() returns malloc-ed lines like readline() */
706 static int noninteractive(int argc
, char **argv
) {
708 if (config
.stdinarg
) {
709 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
710 argv
[argc
] = readArgFromStdin();
711 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
713 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
714 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
719 int main(int argc
, char **argv
) {
722 config
.hostip
= sdsnew("127.0.0.1");
723 config
.hostport
= 6379;
724 config
.hostsocket
= NULL
;
727 config
.interactive
= 0;
729 config
.monitor_mode
= 0;
730 config
.pubsub_mode
= 0;
733 config
.raw_output
= !isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
);
734 config
.mb_delim
= sdsnew("\n");
737 firstarg
= parseOptions(argc
,argv
);
742 if (cliConnect(0) != REDIS_OK
) exit(1);
744 /* Start interactive mode when no command is provided */
745 if (argc
== 0) repl();
746 /* Otherwise, we have some arguments to execute */
747 return noninteractive(argc
,convertToSds(argc
,argv
));