+static void usage() {
+ fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
+ fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-a authpw] [-p port] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
+ fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
+ fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
+ fprintf(stderr, "example: redis-cli get my_passwd\n");
+ fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
+ fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
+ exit(1);
+}
+
+/* Turn the plain C strings into Sds strings */
+static char **convertToSds(int count, char** args) {
+ int j;
+ char **sds = zmalloc(sizeof(char*)*count+1);
+
+ for(j = 0; j < count; j++)
+ sds[j] = sdsnew(args[j]);
+
+ return sds;
+}
+
+static char **splitArguments(char *line, int *argc) {
+ char *p = line;
+ char *current = NULL;
+ char **vector = NULL;
+
+ *argc = 0;
+ while(1) {
+ /* skip blanks */
+ while(*p && isspace(*p)) p++;
+ if (*p) {
+ /* get a token */
+ int inq=0; /* set to 1 if we are in "quotes" */
+ int done = 0;
+
+ if (current == NULL) current = sdsempty();
+ while(!done) {
+ if (inq) {
+ if (*p == '\\' && *(p+1)) {
+ char c;
+
+ p++;
+ switch(*p) {
+ case 'n': c = '\n'; break;
+ case 'r': c = '\r'; break;
+ case 't': c = '\t'; break;
+ case 'b': c = '\b'; break;
+ case 'a': c = '\a'; break;
+ default: c = *p; break;
+ }
+ current = sdscatlen(current,&c,1);
+ } else if (*p == '"') {
+ done = 1;
+ } else {
+ current = sdscatlen(current,p,1);
+ }
+ } else {
+ switch(*p) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ case '\0':
+ done=1;
+ break;
+ case '"':
+ inq=1;
+ break;
+ default:
+ current = sdscatlen(current,p,1);
+ break;
+ }
+ }
+ if (*p) p++;
+ }
+ /* add the token to the vector */
+ vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
+ vector[*argc] = current;
+ (*argc)++;
+ current = NULL;
+ } else {
+ return vector;
+ }
+ }
+}
+
+#define LINE_BUFLEN 4096
+static void repl() {
+ int argc, j;
+ char *line, **argv;
+
+ while((line = linenoise("redis> ")) != NULL) {
+ if (line[0] != '\0') {
+ argv = splitArguments(line,&argc);
+ linenoiseHistoryAdd(line);
+ if (argc > 0) {
+ if (strcasecmp(argv[0],"quit") == 0 ||
+ strcasecmp(argv[0],"exit") == 0)
+ exit(0);
+ else
+ cliSendCommand(argc, argv, 1);
+ }
+ /* Free the argument vector */
+ for (j = 0; j < argc; j++)
+ sdsfree(argv[j]);
+ free(argv);
+ }
+ /* linenoise() returns malloc-ed lines like readline() */
+ free(line);
+ }
+ exit(0);
+}
+