]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
563c75300798e3af6879c7983b7c09215cf319bb
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 */
70 char *redisGitSHA1(void);
71 char *redisGitDirty(void);
73 /*------------------------------------------------------------------------------
75 *--------------------------------------------------------------------------- */
77 static long long mstime(void) {
81 gettimeofday(&tv
, NULL
);
82 mst
= ((long)tv
.tv_sec
)*1000;
83 mst
+= tv
.tv_usec
/1000;
87 /*------------------------------------------------------------------------------
89 *--------------------------------------------------------------------------- */
91 #define CLI_HELP_COMMAND 1
92 #define CLI_HELP_GROUP 2
100 /* Only used for help on commands */
101 struct commandHelp
*org
;
104 static helpEntry
*helpEntries
;
105 static int helpEntriesLen
;
107 static sds
cliVersion() {
109 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
111 /* Add git commit and working tree status when available */
112 if (strtoll(redisGitSHA1(),NULL
,16)) {
113 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
114 if (strtoll(redisGitDirty(),NULL
,10))
115 version
= sdscatprintf(version
, "-dirty");
116 version
= sdscat(version
, ")");
121 static void cliInitHelp() {
122 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
123 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
127 helpEntriesLen
= len
= commandslen
+groupslen
;
128 helpEntries
= malloc(sizeof(helpEntry
)*len
);
130 for (i
= 0; i
< groupslen
; i
++) {
132 tmp
.argv
= malloc(sizeof(sds
));
133 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
134 tmp
.full
= tmp
.argv
[0];
135 tmp
.type
= CLI_HELP_GROUP
;
137 helpEntries
[pos
++] = tmp
;
140 for (i
= 0; i
< commandslen
; i
++) {
141 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
142 tmp
.full
= sdsnew(commandHelp
[i
].name
);
143 tmp
.type
= CLI_HELP_COMMAND
;
144 tmp
.org
= &commandHelp
[i
];
145 helpEntries
[pos
++] = tmp
;
149 /* Output command help to stdout. */
150 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
151 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
152 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
153 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
155 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
159 /* Print generic help. */
160 static void cliOutputGenericHelp() {
161 sds version
= cliVersion();
164 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
165 " \"help <command>\" for help on <command>\r\n"
166 " \"help <tab>\" to get a list of possible help topics\r\n"
167 " \"quit\" to exit\r\n",
173 /* Output all command help, filtering by group or command name. */
174 static void cliOutputHelp(int argc
, char **argv
) {
178 struct commandHelp
*help
;
181 cliOutputGenericHelp();
183 } else if (argc
> 0 && argv
[0][0] == '@') {
184 len
= sizeof(commandGroups
)/sizeof(char*);
185 for (i
= 0; i
< len
; i
++) {
186 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
194 for (i
= 0; i
< helpEntriesLen
; i
++) {
195 entry
= &helpEntries
[i
];
196 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
200 /* Compare all arguments */
201 if (argc
== entry
->argc
) {
202 for (j
= 0; j
< argc
; j
++) {
203 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
206 cliOutputCommandHelp(help
,1);
210 if (group
== help
->group
) {
211 cliOutputCommandHelp(help
,0);
218 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
225 if (strncasecmp(buf
,"help ",5) == 0) {
227 while (isspace(buf
[startpos
])) startpos
++;
228 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
230 mask
= CLI_HELP_COMMAND
;
233 for (i
= 0; i
< helpEntriesLen
; i
++) {
234 if (!(helpEntries
[i
].type
& mask
)) continue;
236 matchlen
= strlen(buf
+startpos
);
237 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
238 tmp
= sdsnewlen(buf
,startpos
);
239 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
240 linenoiseAddCompletion(lc
,tmp
);
246 /*------------------------------------------------------------------------------
247 * Networking / parsing
248 *--------------------------------------------------------------------------- */
250 /* Send AUTH command to the server */
251 static int cliAuth() {
253 if (config
.auth
== NULL
) return REDIS_OK
;
255 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
257 freeReplyObject(reply
);
263 /* Send SELECT dbnum to the server */
264 static int cliSelect() {
267 if (config
.dbnum
== 0) return REDIS_OK
;
269 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
270 reply
= redisCommand(context
,"SELECT %s",dbnum
);
272 freeReplyObject(reply
);
278 /* Connect to the client. If force is not zero the connection is performed
279 * even if there is already a connected socket. */
280 static int cliConnect(int force
) {
281 if (context
== NULL
|| force
) {
285 if (config
.hostsocket
== NULL
) {
286 context
= redisConnect(config
.hostip
,config
.hostport
);
288 context
= redisConnectUnix(config
.hostsocket
);
292 fprintf(stderr
,"Could not connect to Redis at ");
293 if (config
.hostsocket
== NULL
)
294 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
296 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
302 /* Do AUTH and select the right DB. */
303 if (cliAuth() != REDIS_OK
)
305 if (cliSelect() != REDIS_OK
)
311 static void cliPrintContextErrorAndExit() {
312 if (context
== NULL
) return;
313 fprintf(stderr
,"Error: %s\n",context
->errstr
);
317 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
318 sds out
= sdsempty();
320 case REDIS_REPLY_ERROR
:
321 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
323 case REDIS_REPLY_STATUS
:
324 out
= sdscat(out
,r
->str
);
325 out
= sdscat(out
,"\n");
327 case REDIS_REPLY_INTEGER
:
328 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
330 case REDIS_REPLY_STRING
:
331 /* If you are producing output for the standard output we want
332 * a more interesting output with quoted characters and so forth */
333 out
= sdscatrepr(out
,r
->str
,r
->len
);
334 out
= sdscat(out
,"\n");
336 case REDIS_REPLY_NIL
:
337 out
= sdscat(out
,"(nil)\n");
339 case REDIS_REPLY_ARRAY
:
340 if (r
->elements
== 0) {
341 out
= sdscat(out
,"(empty list or set)\n");
343 unsigned int i
, idxlen
= 0;
349 /* Calculate chars needed to represent the largest index */
356 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
357 memset(_prefixlen
,' ',idxlen
+2);
358 _prefixlen
[idxlen
+2] = '\0';
359 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
361 /* Setup prefix format for every entry */
362 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
364 for (i
= 0; i
< r
->elements
; i
++) {
365 /* Don't use the prefix for the first element, as the parent
366 * caller already prepended the index number. */
367 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
369 /* Format the multi bulk entry */
370 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
371 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
378 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
384 static sds
cliFormatReplyRaw(redisReply
*r
) {
385 sds out
= sdsempty(), tmp
;
389 case REDIS_REPLY_NIL
:
392 case REDIS_REPLY_ERROR
:
393 case REDIS_REPLY_STATUS
:
394 case REDIS_REPLY_STRING
:
395 out
= sdscatlen(out
,r
->str
,r
->len
);
397 case REDIS_REPLY_INTEGER
:
398 out
= sdscatprintf(out
,"%lld",r
->integer
);
400 case REDIS_REPLY_ARRAY
:
401 for (i
= 0; i
< r
->elements
; i
++) {
402 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
403 tmp
= cliFormatReplyRaw(r
->element
[i
]);
404 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
409 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
415 static int cliReadReply(int output_raw_strings
) {
420 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
423 if (config
.interactive
) {
424 /* Filter cases where we should reconnect */
425 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
427 if (context
->err
== REDIS_ERR_EOF
)
430 cliPrintContextErrorAndExit();
431 return REDIS_ERR
; /* avoid compiler warning */
434 reply
= (redisReply
*)_reply
;
435 if (output_raw_strings
) {
436 out
= cliFormatReplyRaw(reply
);
438 if (config
.raw_output
) {
439 out
= cliFormatReplyRaw(reply
);
440 out
= sdscat(out
,"\n");
442 out
= cliFormatReplyTTY(reply
,"");
445 fwrite(out
,sdslen(out
),1,stdout
);
447 freeReplyObject(reply
);
451 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
452 char *command
= argv
[0];
456 if (context
== NULL
) {
457 printf("Not connected, please use: connect <host> <port>\n");
461 output_raw
= !strcasecmp(command
,"info");
462 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
463 cliOutputHelp(--argc
, ++argv
);
466 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
467 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
468 if (!strcasecmp(command
,"subscribe") ||
469 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
471 /* Setup argument length */
472 argvlen
= malloc(argc
*sizeof(size_t));
473 for (j
= 0; j
< argc
; j
++)
474 argvlen
[j
] = sdslen(argv
[j
]);
477 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
478 while (config
.monitor_mode
) {
479 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
483 if (config
.pubsub_mode
) {
484 if (!config
.raw_output
)
485 printf("Reading messages... (press Ctrl-C to quit)\n");
487 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
491 if (cliReadReply(output_raw
) != REDIS_OK
)
497 /*------------------------------------------------------------------------------
499 *--------------------------------------------------------------------------- */
501 static int parseOptions(int argc
, char **argv
) {
504 for (i
= 1; i
< argc
; i
++) {
505 int lastarg
= i
==argc
-1;
507 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
508 sdsfree(config
.hostip
);
509 config
.hostip
= sdsnew(argv
[i
+1]);
511 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
513 } else if (!strcmp(argv
[i
],"--help")) {
515 } else if (!strcmp(argv
[i
],"-x")) {
517 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
518 config
.hostport
= atoi(argv
[i
+1]);
520 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
521 config
.hostsocket
= argv
[i
+1];
523 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
524 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
526 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
527 config
.dbnum
= atoi(argv
[i
+1]);
529 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
530 config
.auth
= argv
[i
+1];
532 } else if (!strcmp(argv
[i
],"--raw")) {
533 config
.raw_output
= 1;
534 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
535 sdsfree(config
.mb_delim
);
536 config
.mb_delim
= sdsnew(argv
[i
+1]);
538 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
539 sds version
= cliVersion();
540 printf("redis-cli %s\n", version
);
550 static sds
readArgFromStdin(void) {
552 sds arg
= sdsempty();
555 int nread
= read(fileno(stdin
),buf
,1024);
557 if (nread
== 0) break;
558 else if (nread
== -1) {
559 perror("Reading from standard input");
562 arg
= sdscatlen(arg
,buf
,nread
);
567 static void usage() {
568 sds version
= cliVersion();
572 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
573 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
574 " -p <port> Server port (default: 6379)\n"
575 " -s <socket> Server socket (overrides hostname and port)\n"
576 " -a <password> Password to use when connecting to the server\n"
577 " -r <repeat> Execute specified command N times\n"
578 " -n <db> Database number\n"
579 " -x Read last argument from STDIN\n"
580 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
581 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
582 " --help Output this help and exit\n"
583 " --version Output version and exit\n"
586 " cat /etc/passwd | redis-cli -x set mypasswd\n"
587 " redis-cli get mypasswd\n"
588 " redis-cli -r 100 lpush mylist x\n"
590 "When no command is given, redis-cli starts in interactive mode.\n"
591 "Type \"help\" in interactive mode for information on available commands.\n"
598 /* Turn the plain C strings into Sds strings */
599 static char **convertToSds(int count
, char** args
) {
601 char **sds
= zmalloc(sizeof(char*)*count
);
603 for(j
= 0; j
< count
; j
++)
604 sds
[j
] = sdsnew(args
[j
]);
609 #define LINE_BUFLEN 4096
611 sds historyfile
= NULL
;
617 config
.interactive
= 1;
618 linenoiseSetCompletionCallback(completionCallback
);
620 /* Only use history when stdin is a tty. */
621 if (isatty(fileno(stdin
))) {
624 if (getenv("HOME") != NULL
) {
625 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
626 linenoiseHistoryLoad(historyfile
);
630 while((line
= linenoise(context
? "redis> " : "not connected> ")) != NULL
) {
631 if (line
[0] != '\0') {
632 argv
= sdssplitargs(line
,&argc
);
633 if (history
) linenoiseHistoryAdd(line
);
634 if (historyfile
) linenoiseHistorySave(historyfile
);
637 printf("Invalid argument(s)\n");
639 } else if (argc
> 0) {
640 if (strcasecmp(argv
[0],"quit") == 0 ||
641 strcasecmp(argv
[0],"exit") == 0)
644 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
645 sdsfree(config
.hostip
);
646 config
.hostip
= sdsnew(argv
[1]);
647 config
.hostport
= atoi(argv
[2]);
649 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
650 linenoiseClearScreen();
652 long long start_time
= mstime(), elapsed
;
654 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
657 /* If we still cannot send the command,
658 * print error and abort. */
659 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
660 cliPrintContextErrorAndExit();
662 elapsed
= mstime()-start_time
;
663 if (elapsed
>= 500) {
664 printf("(%.2fs)\n",(double)elapsed
/1000);
668 /* Free the argument vector */
669 while(argc
--) sdsfree(argv
[argc
]);
672 /* linenoise() returns malloc-ed lines like readline() */
678 static int noninteractive(int argc
, char **argv
) {
680 if (config
.stdinarg
) {
681 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
682 argv
[argc
] = readArgFromStdin();
683 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
685 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
686 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
691 int main(int argc
, char **argv
) {
694 config
.hostip
= sdsnew("127.0.0.1");
695 config
.hostport
= 6379;
696 config
.hostsocket
= NULL
;
699 config
.interactive
= 0;
701 config
.monitor_mode
= 0;
702 config
.pubsub_mode
= 0;
705 config
.raw_output
= !isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
);
706 config
.mb_delim
= sdsnew("\n");
709 firstarg
= parseOptions(argc
,argv
);
714 if (cliConnect(0) != REDIS_OK
) exit(1);
716 /* Start interactive mode when no command is provided */
717 if (argc
== 0) repl();
718 /* Otherwise, we have some arguments to execute */
719 return noninteractive(argc
,convertToSds(argc
,argv
));