]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
4d698158391b1858c9f0539822169714cfff6d68
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 raw_output
; /* output mode per command */
64 int tty
; /* flag for default output format */
65 int stdinarg
; /* get last arg from stdin. (-x option) */
72 char *redisGitSHA1(void);
73 char *redisGitDirty(void);
75 /*------------------------------------------------------------------------------
77 *--------------------------------------------------------------------------- */
79 static long long mstime(void) {
83 gettimeofday(&tv
, NULL
);
84 mst
= ((long)tv
.tv_sec
)*1000;
85 mst
+= tv
.tv_usec
/1000;
89 /*------------------------------------------------------------------------------
91 *--------------------------------------------------------------------------- */
93 #define CLI_HELP_COMMAND 1
94 #define CLI_HELP_GROUP 2
102 /* Only used for help on commands */
103 struct commandHelp
*org
;
106 static helpEntry
*helpEntries
;
107 static int helpEntriesLen
;
109 static sds
cliVersion() {
111 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
113 /* Add git commit and working tree status when available */
114 if (strtoll(redisGitSHA1(),NULL
,16)) {
115 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
116 if (strtoll(redisGitDirty(),NULL
,10))
117 version
= sdscatprintf(version
, "-dirty");
118 version
= sdscat(version
, ")");
123 static void cliInitHelp() {
124 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
125 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
129 helpEntriesLen
= len
= commandslen
+groupslen
;
130 helpEntries
= malloc(sizeof(helpEntry
)*len
);
132 for (i
= 0; i
< groupslen
; i
++) {
134 tmp
.argv
= malloc(sizeof(sds
));
135 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
136 tmp
.full
= tmp
.argv
[0];
137 tmp
.type
= CLI_HELP_GROUP
;
139 helpEntries
[pos
++] = tmp
;
142 for (i
= 0; i
< commandslen
; i
++) {
143 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
144 tmp
.full
= sdsnew(commandHelp
[i
].name
);
145 tmp
.type
= CLI_HELP_COMMAND
;
146 tmp
.org
= &commandHelp
[i
];
147 helpEntries
[pos
++] = tmp
;
151 /* Output command help to stdout. */
152 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
153 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
154 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
155 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
157 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
161 /* Print generic help. */
162 static void cliOutputGenericHelp() {
163 sds version
= cliVersion();
166 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
167 " \"help <command>\" for help on <command>\r\n"
168 " \"help <tab>\" to get a list of possible help topics\r\n"
169 " \"quit\" to exit\r\n",
175 /* Output all command help, filtering by group or command name. */
176 static void cliOutputHelp(int argc
, char **argv
) {
180 struct commandHelp
*help
;
183 cliOutputGenericHelp();
185 } else if (argc
> 0 && argv
[0][0] == '@') {
186 len
= sizeof(commandGroups
)/sizeof(char*);
187 for (i
= 0; i
< len
; i
++) {
188 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
196 for (i
= 0; i
< helpEntriesLen
; i
++) {
197 entry
= &helpEntries
[i
];
198 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
202 /* Compare all arguments */
203 if (argc
== entry
->argc
) {
204 for (j
= 0; j
< argc
; j
++) {
205 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
208 cliOutputCommandHelp(help
,1);
212 if (group
== help
->group
) {
213 cliOutputCommandHelp(help
,0);
220 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
227 if (strncasecmp(buf
,"help ",5) == 0) {
229 while (isspace(buf
[startpos
])) startpos
++;
230 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
232 mask
= CLI_HELP_COMMAND
;
235 for (i
= 0; i
< helpEntriesLen
; i
++) {
236 if (!(helpEntries
[i
].type
& mask
)) continue;
238 matchlen
= strlen(buf
+startpos
);
239 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
240 tmp
= sdsnewlen(buf
,startpos
);
241 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
242 linenoiseAddCompletion(lc
,tmp
);
248 /*------------------------------------------------------------------------------
249 * Networking / parsing
250 *--------------------------------------------------------------------------- */
252 /* Send AUTH command to the server */
253 static int cliAuth() {
255 if (config
.auth
== NULL
) return REDIS_OK
;
257 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
259 freeReplyObject(reply
);
265 /* Send SELECT dbnum to the server */
266 static int cliSelect() {
269 if (config
.dbnum
== 0) return REDIS_OK
;
271 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
272 reply
= redisCommand(context
,"SELECT %s",dbnum
);
274 freeReplyObject(reply
);
280 /* Connect to the client. If force is not zero the connection is performed
281 * even if there is already a connected socket. */
282 static int cliConnect(int force
) {
283 if (context
== NULL
|| force
) {
287 if (config
.hostsocket
== NULL
) {
288 context
= redisConnect(config
.hostip
,config
.hostport
);
290 context
= redisConnectUnix(config
.hostsocket
);
294 fprintf(stderr
,"Could not connect to Redis at ");
295 if (config
.hostsocket
== NULL
)
296 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
298 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
304 /* Do AUTH and select the right DB. */
305 if (cliAuth() != REDIS_OK
)
307 if (cliSelect() != REDIS_OK
)
313 static void cliPrintContextErrorAndExit() {
314 if (context
== NULL
) return;
315 fprintf(stderr
,"Error: %s\n",context
->errstr
);
319 static sds
cliFormatReply(redisReply
*r
, char *prefix
) {
320 sds out
= sdsempty();
322 case REDIS_REPLY_ERROR
:
323 if (config
.tty
) out
= sdscat(out
,"(error) ");
324 out
= sdscatprintf(out
,"%s\n", r
->str
);
326 case REDIS_REPLY_STATUS
:
327 out
= sdscat(out
,r
->str
);
328 out
= sdscat(out
,"\n");
330 case REDIS_REPLY_INTEGER
:
331 if (config
.tty
) out
= sdscat(out
,"(integer) ");
332 out
= sdscatprintf(out
,"%lld\n",r
->integer
);
334 case REDIS_REPLY_STRING
:
335 if (config
.raw_output
|| !config
.tty
) {
336 out
= sdscatlen(out
,r
->str
,r
->len
);
338 /* If you are producing output for the standard output we want
339 * a more interesting output with quoted characters and so forth */
340 out
= sdscatrepr(out
,r
->str
,r
->len
);
341 out
= sdscat(out
,"\n");
344 case REDIS_REPLY_NIL
:
345 out
= sdscat(out
,"(nil)\n");
347 case REDIS_REPLY_ARRAY
:
348 if (r
->elements
== 0) {
349 out
= sdscat(out
,"(empty list or set)\n");
351 unsigned int i
, idxlen
= 0;
357 /* Calculate chars needed to represent the largest index */
364 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
365 memset(_prefixlen
,' ',idxlen
+2);
366 _prefixlen
[idxlen
+2] = '\0';
367 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
369 /* Setup prefix format for every entry */
370 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
372 for (i
= 0; i
< r
->elements
; i
++) {
373 /* Don't use the prefix for the first element, as the parent
374 * caller already prepended the index number. */
375 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
377 /* Format the multi bulk entry */
378 tmp
= cliFormatReply(r
->element
[i
],_prefix
);
379 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
386 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
392 static int cliReadReply() {
396 if (redisGetReply(context
,(void**)&reply
) != REDIS_OK
) {
399 if (config
.interactive
) {
400 /* Filter cases where we should reconnect */
401 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
403 if (context
->err
== REDIS_ERR_EOF
)
406 cliPrintContextErrorAndExit();
407 return REDIS_ERR
; /* avoid compiler warning */
410 out
= cliFormatReply(reply
,"");
411 freeReplyObject(reply
);
412 fwrite(out
,sdslen(out
),1,stdout
);
417 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
418 char *command
= argv
[0];
422 if (context
== NULL
) {
423 printf("Not connected, please use: connect <host> <port>\n");
427 config
.raw_output
= !strcasecmp(command
,"info");
428 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
429 cliOutputHelp(--argc
, ++argv
);
432 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
433 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
434 if (!strcasecmp(command
,"subscribe") ||
435 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
437 /* Setup argument length */
438 argvlen
= malloc(argc
*sizeof(size_t));
439 for (j
= 0; j
< argc
; j
++)
440 argvlen
[j
] = sdslen(argv
[j
]);
443 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
444 while (config
.monitor_mode
) {
445 if (cliReadReply() != REDIS_OK
) exit(1);
449 if (config
.pubsub_mode
) {
450 printf("Reading messages... (press Ctrl-C to quit)\n");
452 if (cliReadReply() != REDIS_OK
) exit(1);
456 if (cliReadReply() != REDIS_OK
)
462 /*------------------------------------------------------------------------------
464 *--------------------------------------------------------------------------- */
466 static int parseOptions(int argc
, char **argv
) {
469 for (i
= 1; i
< argc
; i
++) {
470 int lastarg
= i
==argc
-1;
472 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
473 sdsfree(config
.hostip
);
474 config
.hostip
= sdsnew(argv
[i
+1]);
476 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
478 } else if (!strcmp(argv
[i
],"--help")) {
480 } else if (!strcmp(argv
[i
],"-x")) {
482 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
483 config
.hostport
= atoi(argv
[i
+1]);
485 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
486 config
.hostsocket
= argv
[i
+1];
488 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
489 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
491 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
492 config
.dbnum
= atoi(argv
[i
+1]);
494 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
495 config
.auth
= argv
[i
+1];
497 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
498 sds version
= cliVersion();
499 printf("redis-cli %s\n", version
);
509 static sds
readArgFromStdin(void) {
511 sds arg
= sdsempty();
514 int nread
= read(fileno(stdin
),buf
,1024);
516 if (nread
== 0) break;
517 else if (nread
== -1) {
518 perror("Reading from standard input");
521 arg
= sdscatlen(arg
,buf
,nread
);
526 static void usage() {
527 sds version
= cliVersion();
531 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
532 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
533 " -p <port> Server port (default: 6379)\n"
534 " -s <socket> Server socket (overrides hostname and port)\n"
535 " -a <password> Password to use when connecting to the server\n"
536 " -r <repeat> Execute specified command N times\n"
537 " -n <db> Database number\n"
538 " -x Read last argument from STDIN\n"
539 " --help Output this help and exit\n"
540 " --version Output version and exit\n"
543 " cat /etc/passwd | redis-cli -x set mypasswd\n"
544 " redis-cli get mypasswd\n"
545 " redis-cli -r 100 lpush mylist x\n"
547 "When no command is given, redis-cli starts in interactive mode.\n"
548 "Type \"help\" in interactive mode for information on available commands.\n"
555 /* Turn the plain C strings into Sds strings */
556 static char **convertToSds(int count
, char** args
) {
558 char **sds
= zmalloc(sizeof(char*)*count
);
560 for(j
= 0; j
< count
; j
++)
561 sds
[j
] = sdsnew(args
[j
]);
566 #define LINE_BUFLEN 4096
572 config
.interactive
= 1;
573 linenoiseSetCompletionCallback(completionCallback
);
575 while((line
= linenoise(context
? "redis> " : "not connected> ")) != NULL
) {
576 if (line
[0] != '\0') {
577 argv
= sdssplitargs(line
,&argc
);
578 linenoiseHistoryAdd(line
);
579 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
581 printf("Invalid argument(s)\n");
583 } else if (argc
> 0) {
584 if (strcasecmp(argv
[0],"quit") == 0 ||
585 strcasecmp(argv
[0],"exit") == 0)
588 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
589 sdsfree(config
.hostip
);
590 config
.hostip
= sdsnew(argv
[1]);
591 config
.hostport
= atoi(argv
[2]);
593 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
594 linenoiseClearScreen();
596 long long start_time
= mstime(), elapsed
;
598 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
601 /* If we still cannot send the command,
602 * print error and abort. */
603 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
604 cliPrintContextErrorAndExit();
606 elapsed
= mstime()-start_time
;
607 if (elapsed
>= 500) {
608 printf("(%.2fs)\n",(double)elapsed
/1000);
612 /* Free the argument vector */
613 for (j
= 0; j
< argc
; j
++)
617 /* linenoise() returns malloc-ed lines like readline() */
623 static int noninteractive(int argc
, char **argv
) {
625 if (config
.stdinarg
) {
626 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
627 argv
[argc
] = readArgFromStdin();
628 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
630 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
631 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
636 int main(int argc
, char **argv
) {
639 config
.hostip
= sdsnew("127.0.0.1");
640 config
.hostport
= 6379;
641 config
.hostsocket
= NULL
;
644 config
.interactive
= 0;
646 config
.monitor_mode
= 0;
647 config
.pubsub_mode
= 0;
648 config
.raw_output
= 0;
651 config
.historyfile
= NULL
;
652 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
653 config
.mb_sep
= '\n';
656 if (getenv("HOME") != NULL
) {
657 config
.historyfile
= malloc(256);
658 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
659 linenoiseHistoryLoad(config
.historyfile
);
662 firstarg
= parseOptions(argc
,argv
);
667 if (cliConnect(0) != REDIS_OK
) exit(1);
669 /* Start interactive mode when no command is provided */
670 if (argc
== 0) repl();
671 /* Otherwise, we have some arguments to execute */
672 return noninteractive(argc
,convertToSds(argc
,argv
));