]>
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
) {
420 if (redisGetReply(context
,(void**)&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 if (output_raw_strings
) {
435 out
= cliFormatReplyRaw(reply
);
437 if (config
.raw_output
) {
438 out
= cliFormatReplyRaw(reply
);
439 out
= sdscat(out
,"\n");
441 out
= cliFormatReplyTTY(reply
,"");
444 fwrite(out
,sdslen(out
),1,stdout
);
446 freeReplyObject(reply
);
450 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
451 char *command
= argv
[0];
455 if (context
== NULL
) {
456 printf("Not connected, please use: connect <host> <port>\n");
460 output_raw
= !strcasecmp(command
,"info");
461 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
462 cliOutputHelp(--argc
, ++argv
);
465 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
466 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
467 if (!strcasecmp(command
,"subscribe") ||
468 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
470 /* Setup argument length */
471 argvlen
= malloc(argc
*sizeof(size_t));
472 for (j
= 0; j
< argc
; j
++)
473 argvlen
[j
] = sdslen(argv
[j
]);
476 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
477 while (config
.monitor_mode
) {
478 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
482 if (config
.pubsub_mode
) {
483 if (!config
.raw_output
)
484 printf("Reading messages... (press Ctrl-C to quit)\n");
486 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
490 if (cliReadReply(output_raw
) != REDIS_OK
)
496 /*------------------------------------------------------------------------------
498 *--------------------------------------------------------------------------- */
500 static int parseOptions(int argc
, char **argv
) {
503 for (i
= 1; i
< argc
; i
++) {
504 int lastarg
= i
==argc
-1;
506 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
507 sdsfree(config
.hostip
);
508 config
.hostip
= sdsnew(argv
[i
+1]);
510 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
512 } else if (!strcmp(argv
[i
],"--help")) {
514 } else if (!strcmp(argv
[i
],"-x")) {
516 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
517 config
.hostport
= atoi(argv
[i
+1]);
519 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
520 config
.hostsocket
= argv
[i
+1];
522 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
523 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
525 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
526 config
.dbnum
= atoi(argv
[i
+1]);
528 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
529 config
.auth
= argv
[i
+1];
531 } else if (!strcmp(argv
[i
],"--raw")) {
532 config
.raw_output
= 1;
533 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
534 sdsfree(config
.mb_delim
);
535 config
.mb_delim
= sdsnew(argv
[i
+1]);
537 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
538 sds version
= cliVersion();
539 printf("redis-cli %s\n", version
);
549 static sds
readArgFromStdin(void) {
551 sds arg
= sdsempty();
554 int nread
= read(fileno(stdin
),buf
,1024);
556 if (nread
== 0) break;
557 else if (nread
== -1) {
558 perror("Reading from standard input");
561 arg
= sdscatlen(arg
,buf
,nread
);
566 static void usage() {
567 sds version
= cliVersion();
571 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
572 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
573 " -p <port> Server port (default: 6379)\n"
574 " -s <socket> Server socket (overrides hostname and port)\n"
575 " -a <password> Password to use when connecting to the server\n"
576 " -r <repeat> Execute specified command N times\n"
577 " -n <db> Database number\n"
578 " -x Read last argument from STDIN\n"
579 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
580 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
581 " --help Output this help and exit\n"
582 " --version Output version and exit\n"
585 " cat /etc/passwd | redis-cli -x set mypasswd\n"
586 " redis-cli get mypasswd\n"
587 " redis-cli -r 100 lpush mylist x\n"
589 "When no command is given, redis-cli starts in interactive mode.\n"
590 "Type \"help\" in interactive mode for information on available commands.\n"
597 /* Turn the plain C strings into Sds strings */
598 static char **convertToSds(int count
, char** args
) {
600 char **sds
= zmalloc(sizeof(char*)*count
);
602 for(j
= 0; j
< count
; j
++)
603 sds
[j
] = sdsnew(args
[j
]);
608 #define LINE_BUFLEN 4096
614 config
.interactive
= 1;
615 linenoiseSetCompletionCallback(completionCallback
);
617 while((line
= linenoise(context
? "redis> " : "not connected> ")) != NULL
) {
618 if (line
[0] != '\0') {
619 argv
= sdssplitargs(line
,&argc
);
620 linenoiseHistoryAdd(line
);
621 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
623 printf("Invalid argument(s)\n");
625 } else if (argc
> 0) {
626 if (strcasecmp(argv
[0],"quit") == 0 ||
627 strcasecmp(argv
[0],"exit") == 0)
630 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
631 sdsfree(config
.hostip
);
632 config
.hostip
= sdsnew(argv
[1]);
633 config
.hostport
= atoi(argv
[2]);
635 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
636 linenoiseClearScreen();
638 long long start_time
= mstime(), elapsed
;
640 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
643 /* If we still cannot send the command,
644 * print error and abort. */
645 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
646 cliPrintContextErrorAndExit();
648 elapsed
= mstime()-start_time
;
649 if (elapsed
>= 500) {
650 printf("(%.2fs)\n",(double)elapsed
/1000);
654 /* Free the argument vector */
655 for (j
= 0; j
< argc
; j
++)
659 /* linenoise() returns malloc-ed lines like readline() */
665 static int noninteractive(int argc
, char **argv
) {
667 if (config
.stdinarg
) {
668 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
669 argv
[argc
] = readArgFromStdin();
670 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
672 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
673 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
678 int main(int argc
, char **argv
) {
681 config
.hostip
= sdsnew("127.0.0.1");
682 config
.hostport
= 6379;
683 config
.hostsocket
= NULL
;
686 config
.interactive
= 0;
688 config
.monitor_mode
= 0;
689 config
.pubsub_mode
= 0;
692 config
.historyfile
= NULL
;
693 config
.raw_output
= !isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
);
694 config
.mb_delim
= sdsnew("\n");
697 if (getenv("HOME") != NULL
) {
698 config
.historyfile
= malloc(256);
699 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
700 linenoiseHistoryLoad(config
.historyfile
);
703 firstarg
= parseOptions(argc
,argv
);
708 if (cliConnect(0) != REDIS_OK
) exit(1);
710 /* Start interactive mode when no command is provided */
711 if (argc
== 0) repl();
712 /* Otherwise, we have some arguments to execute */
713 return noninteractive(argc
,convertToSds(argc
,argv
));