Refactor zoomsh to use YAZ options
[yaz-moved-to-github.git] / zoom / zoomsh.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2011 Index Data
3  * See the file LICENSE for details.
4  */
5 /** \file zoomsh.c
6     \brief ZOOM C command line tool (shell)
7 */
8 #if HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <yaz/wrbuf.h>
16 #include <yaz/log.h>
17 #include <yaz/options.h>
18
19 #if HAVE_READLINE_READLINE_H
20 #include <readline/readline.h> 
21 #endif
22 #if HAVE_READLINE_HISTORY_H
23 #include <readline/history.h>
24 #endif
25
26 #include <yaz/log.h>
27 #include <yaz/zoom.h>
28
29 #define MAX_CON 100
30
31 static void process_events(ZOOM_connection *c)
32 {
33     int i;
34
35     yaz_log(YLOG_DEBUG, "process_events");
36     while ((i = ZOOM_event(MAX_CON, c)) != 0)
37     {
38         int peek = ZOOM_connection_peek_event(c[i-1]);
39         int event = ZOOM_connection_last_event(c[i-1]);
40         yaz_log(YLOG_DEBUG, "no = %d peek = %d event = %d %s", i-1,
41                 peek,
42                 event,
43                 ZOOM_get_event_str(event));
44     }
45 }
46
47 static int next_token_chars(const char **cpp, const char **t_start,
48                             const char *tok_chars)
49 {
50     int len = 0;
51     const char *cp = *cpp;
52     while (*cp == ' ')
53         cp++;
54     if (*cp == '"')
55     {
56         cp++;
57         *t_start = cp;
58         while (*cp && *cp != '"')
59         {
60             cp++;
61             len++;
62         }
63         if (*cp)
64             cp++;
65     }
66     else
67     {
68         *t_start = cp;
69         while (*cp && !strchr(tok_chars, *cp))
70         {
71             cp++;
72             len++;
73         }
74         if (len == 0)
75             len = -1;
76     }
77     *cpp = cp;
78     return len;  /* return -1 if no token was read .. */
79 }
80
81 static int next_token(const char **cpp, const char **t_start)
82 {
83     return next_token_chars(cpp, t_start, "\r\n ");
84 }
85
86
87 static WRBUF next_token_new_wrbuf(const char **cpp)
88 {
89     WRBUF w = 0;
90     const char *start;
91     int len = next_token(cpp, &start);
92     if (len < 0)
93         return 0;
94     w = wrbuf_alloc();
95     if (len > 0)
96         wrbuf_write(w, start, len);
97     return w;
98 }
99
100 static int is_command(const char *cmd_str, const char *this_str, int this_len)
101 {
102     int cmd_len = strlen(cmd_str);
103     if (cmd_len != this_len)
104         return 0;
105     if (memcmp(cmd_str, this_str, cmd_len))
106         return 0;
107     return 1;
108 }
109
110 static void cmd_set(ZOOM_connection *c, ZOOM_resultset *r,
111                     ZOOM_options options,
112                     const char **args)
113 {
114     WRBUF key;
115     const char *val_buf;
116     int val_len;
117
118     if (!(key = next_token_new_wrbuf(args)))
119     {
120         printf("missing argument for set\n");
121         return ;
122     }
123     val_len = next_token_chars(args, &val_buf, "");
124     if (val_len != -1)
125         ZOOM_options_setl(options, wrbuf_cstr(key), val_buf, val_len);
126     else
127         ZOOM_options_set(options, wrbuf_cstr(key), 0);
128     wrbuf_destroy(key);
129 }
130
131 static void cmd_get(ZOOM_connection *c, ZOOM_resultset *r,
132                     ZOOM_options options,
133                     const char **args)
134 {
135     WRBUF key;
136     if (!(key = next_token_new_wrbuf(args)))
137     {
138         printf("missing argument for get\n");
139     }
140     else
141     {
142         const char *val = ZOOM_options_get(options, wrbuf_cstr(key));
143         printf("%s = %s\n", wrbuf_cstr(key), val ? val : "<null>");
144         wrbuf_destroy(key);
145     }
146 }
147
148 static void cmd_rget(ZOOM_connection *c, ZOOM_resultset *r,
149                      ZOOM_options options,
150                      const char **args)
151 {
152     WRBUF key;
153     if (!(key = next_token_new_wrbuf(args)))
154     {
155         printf("missing argument for get\n");
156     }
157     else
158     {
159         int i;
160         for (i = 0; i<MAX_CON; i++)
161         {
162             const char *val;
163             if (!r[i])
164                 continue;
165             
166             val = ZOOM_resultset_option_get(r[i], wrbuf_cstr(key));
167             printf("%s = %s\n", wrbuf_cstr(key), val ? val : "<null>");
168         }
169         wrbuf_destroy(key);
170     }
171 }
172
173 static void cmd_close(ZOOM_connection *c, ZOOM_resultset *r,
174                       ZOOM_options options,
175                       const char **args)
176 {
177     WRBUF host;
178     int i;
179     host = next_token_new_wrbuf(args);
180     for (i = 0; i<MAX_CON; i++)
181     {
182         const char *h;
183         if (!c[i])
184             continue;
185         if (!host)
186         {
187             ZOOM_connection_destroy(c[i]);
188             c[i] = 0;
189         }
190         else if ((h = ZOOM_connection_option_get(c[i], "host"))
191                  && !strcmp(h, wrbuf_cstr(host)))
192         {
193             ZOOM_connection_destroy(c[i]);
194             c[i] = 0;
195         }
196     }
197     if (host)
198         wrbuf_destroy(host);
199 }
200
201 static void display_records(ZOOM_connection c,
202                             ZOOM_resultset r,
203                             size_t start, size_t count, const char *type)
204 {
205     size_t i;
206     for (i = 0; i < count; i++)
207     {
208         size_t pos = i + start;
209         ZOOM_record rec = ZOOM_resultset_record(r, pos);
210         const char *db = ZOOM_record_get(rec, "database", 0);
211         
212         if (ZOOM_record_error(rec, 0, 0, 0))
213         {
214             const char *msg;
215             const char *addinfo;
216             const char *diagset;
217             int error = ZOOM_record_error(rec, &msg, &addinfo, &diagset);
218             
219             printf("%lld %s: %s (%s:%d) %s\n", (long long) pos,
220                    (db ? db : "unknown"),
221                    msg, diagset, error, addinfo ? addinfo : "none");
222         }
223         else
224         {
225             int len;
226             const char *render = ZOOM_record_get(rec, type, &len);
227             const char *syntax = ZOOM_record_get(rec, "syntax", 0);
228             const char *schema = ZOOM_record_get(rec, "schema", 0);
229             /* if rec is non-null, we got a record for display */
230             if (rec)
231             {
232                 printf("%lld database=%s syntax=%s schema=%s\n",
233                        (long long) pos, (db ? db : "unknown"), syntax,
234                        schema ? schema : "unknown");
235                 if (render)
236                 {
237                     if (fwrite(render, 1, len, stdout) != (size_t) len)
238                     {
239                         printf("write to stdout failed\n");
240                     }
241                 }
242                 printf("\n");
243             }
244         }
245     }
246 }
247
248 static void cmd_show(ZOOM_connection *c, ZOOM_resultset *r,
249                      ZOOM_options options,
250                      const char **args)
251 {
252     int i;
253     size_t start = 0, count = 1;
254     const char *type = "render";
255     WRBUF render_str = 0;
256
257     {
258         WRBUF tmp;
259
260         if ((tmp = next_token_new_wrbuf(args)))
261         {
262             start = atoi(wrbuf_cstr(tmp));
263             wrbuf_destroy(tmp);
264         }
265
266         if ((tmp = next_token_new_wrbuf(args)))
267         {
268             count = atoi(wrbuf_cstr(tmp));
269             wrbuf_destroy(tmp);
270         }
271         render_str = next_token_new_wrbuf(args);
272     }
273     if (render_str)
274         type = wrbuf_cstr(render_str);
275
276     for (i = 0; i < MAX_CON; i++)
277         ZOOM_resultset_records(r[i], 0, start, count);
278     process_events(c);
279
280     for (i = 0; i < MAX_CON; i++)
281     {
282         int error;
283         const char *errmsg, *addinfo, *dset;
284         /* display errors if any */
285         if (!c[i])
286             continue;
287         if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
288             printf("%s error: %s (%s:%d) %s\n",
289                    ZOOM_connection_option_get(c[i], "host"), errmsg,
290                    dset, error, addinfo);
291         else if (r[i])
292         {
293             /* OK, no major errors. Display records... */
294             display_records(c[i], r[i], start, count, type);
295         }
296     }
297     if (render_str)
298         wrbuf_destroy(render_str);
299        
300 }
301
302 static void display_facets(ZOOM_facet_field *facets, int count) {
303     int index;
304     printf("Facets: \n");
305     for (index = 0; index <  count; index++) {
306         int term_index;
307         const char *facet_name = ZOOM_facet_field_name(facets[index]);
308         printf("  %s: \n", facet_name);
309         for (term_index = 0; term_index < ZOOM_facet_field_term_count(facets[index]); term_index++) {
310             int freq = 0;
311             const char *term = ZOOM_facet_field_get_term(facets[index], term_index, &freq);
312             printf("    %s(%d) \n", term,  freq);
313         }
314     }
315 }
316
317 static void cmd_facets(ZOOM_connection *c, ZOOM_resultset *r,
318                      ZOOM_options options,
319                      const char **args)
320 {
321     int i;
322
323     process_events(c);
324
325     for (i = 0; i < MAX_CON; i++)
326     {
327         int error;
328         const char *errmsg, *addinfo, *dset;
329         /* display errors if any */
330         if (!c[i])
331             continue;
332         if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
333             printf("%s error: %s (%s:%d) %s\n",
334                    ZOOM_connection_option_get(c[i], "host"), errmsg,
335                    dset, error, addinfo);
336         else if (r[i])
337         {
338             int num_facets = ZOOM_resultset_facets_size(r[i]);
339             if (num_facets) {
340                 ZOOM_facet_field  *facets = ZOOM_resultset_facets(r[i]);
341                 display_facets(facets, num_facets);
342             }
343         }
344     }
345 }
346
347 static void cmd_ext(ZOOM_connection *c, ZOOM_resultset *r,
348                     ZOOM_options options,
349                     const char **args)
350 {
351     ZOOM_package p[MAX_CON];
352     int i;
353     WRBUF ext_type_str = next_token_new_wrbuf(args);
354     
355     for (i = 0; i<MAX_CON; i++)
356     {
357         if (c[i])
358         {
359             p[i] = ZOOM_connection_package(c[i], 0);
360             ZOOM_package_send(p[i], ext_type_str ? wrbuf_cstr(ext_type_str):0);
361         }
362         else
363             p[i] = 0;
364     }
365
366     process_events(c);
367
368     for (i = 0; i<MAX_CON; i++)
369     {
370         int error;
371         const char *errmsg, *addinfo, *dset;
372         /* display errors if any */
373         if (!p[i])
374             continue;
375         if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
376             printf("%s error: %s (%s:%d) %s\n",
377                    ZOOM_connection_option_get(c[i], "host"), errmsg,
378                    dset, error, addinfo);
379         else if (p[i])
380         {
381             const char *v;
382             printf("ok\n");
383             v = ZOOM_package_option_get(p[i], "targetReference");
384             if (v)
385                 printf("targetReference: %s\n", v);
386             v = ZOOM_package_option_get(p[i], "xmlUpdateDoc");
387             if (v)
388                 printf("xmlUpdateDoc: %s\n", v);
389         }
390         ZOOM_package_destroy(p[i]);
391     }
392     if (ext_type_str)
393         wrbuf_destroy(ext_type_str);
394 }
395
396 static void cmd_debug(ZOOM_connection *c, ZOOM_resultset *r,
397                       ZOOM_options options,
398                       const char **args)
399 {
400     yaz_log_init_level(YLOG_ALL);
401 }
402
403 static void cmd_search(ZOOM_connection *c, ZOOM_resultset *r,
404                        ZOOM_options options,
405                        const char **args)
406 {
407     ZOOM_query s;
408     const char *query_str = *args;
409     int i;
410     
411     s = ZOOM_query_create();
412     while (*query_str == ' ')
413         query_str++;
414     if (memcmp(query_str, "cql:", 4) == 0)
415     {
416         ZOOM_query_cql(s, query_str + 4);
417     }
418     else if (ZOOM_query_prefix(s, query_str))
419     {
420         printf("Bad PQF: %s\n", query_str);
421         return;
422     }
423     for (i = 0; i<MAX_CON; i++)
424     {
425
426         if (c[i])
427         {
428             ZOOM_resultset_destroy(r[i]);
429             r[i] = 0;
430         }
431         if (c[i])
432             r[i] = ZOOM_connection_search(c[i], s);
433     }
434     ZOOM_query_destroy(s);
435
436     process_events(c);
437
438     for (i = 0; i<MAX_CON; i++)
439     {
440         int error;
441         const char *errmsg, *addinfo, *dset;
442         /* display errors if any */
443         if (!c[i])
444             continue;
445         if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
446             printf("%s error: %s (%s:%d) %s\n",
447                    ZOOM_connection_option_get(c[i], "host"), errmsg,
448                    dset, error, addinfo);
449         else if (r[i])
450         {
451             /* OK, no major errors. Look at the result count */
452             int start = ZOOM_options_get_int(options, "start", 0);
453             int count = ZOOM_options_get_int(options, "count", 0);
454             int facet_num;
455
456             printf("%s: %lld hits\n", ZOOM_connection_option_get(c[i], "host"),
457                    (long long int) ZOOM_resultset_size(r[i]));
458             
459             facet_num = ZOOM_resultset_facets_size(r[i]);
460             if (facet_num)
461             {
462                 ZOOM_facet_field *facets = ZOOM_resultset_facets(r[i]);
463                 int facet_idx;
464                 for (facet_idx = 0; facet_idx < facet_num; facet_idx++)
465                 {
466                     const char *name = ZOOM_facet_field_name(facets[facet_idx]);
467                     size_t term_idx;
468                     size_t term_num = ZOOM_facet_field_term_count(facets[facet_idx]);
469                     printf("facet: %s\n", name);
470                     for (term_idx = 0; term_idx < term_num; term_idx++ )
471                     {
472                         int freq;
473                         const char *term =
474                             ZOOM_facet_field_get_term(facets[facet_idx], term_idx, &freq);
475                         printf("term: %s %d\n", term, freq);
476                     }
477                 }
478             }
479             /* and display */
480             display_records(c[i], r[i], start, count, "render");
481         }
482     }
483 }
484
485 static void cmd_scan(ZOOM_connection *c, ZOOM_resultset *r,
486                      ZOOM_options options,
487                      const char **args)
488 {
489     const char *query_str = *args;
490     ZOOM_query query = ZOOM_query_create();
491     int i;
492     ZOOM_scanset s[MAX_CON];
493     
494     while (*query_str == ' ')
495         query_str++;
496
497     if (memcmp(query_str, "cql:", 4) == 0)
498     {
499         ZOOM_query_cql(query, query_str + 4);
500     }
501     else if (ZOOM_query_prefix(query, query_str))
502     {
503         printf("Bad PQF: %s\n", query_str);
504         return;
505     }
506
507     for (i = 0; i<MAX_CON; i++)
508     {
509         if (c[i])
510             s[i] = ZOOM_connection_scan1(c[i], query);
511         else
512             s[i] = 0;
513     }
514     ZOOM_query_destroy(query);
515
516     process_events(c);
517
518     for (i = 0; i<MAX_CON; i++)
519     {
520         int error;
521         const char *errmsg, *addinfo, *dset;
522         /* display errors if any */
523         if (!c[i])
524             continue;
525         if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
526             printf("%s error: %s (%s:%d) %s\n",
527                    ZOOM_connection_option_get(c[i], "host"), errmsg,
528                    dset, error, addinfo);
529
530         if (s[i]) {
531             size_t p, sz = ZOOM_scanset_size(s[i]);
532             for (p = 0; p < sz; p++)
533             {
534                 size_t occ = 0;
535                 size_t len = 0;
536                 const char *term = ZOOM_scanset_display_term(s[i], p,
537                                                              &occ, &len);
538                 printf("%.*s %lld\n", (int) len, term, (long long int) occ);
539             }            
540             ZOOM_scanset_destroy(s[i]);
541         }
542     }
543 }
544
545 static void cmd_sort(ZOOM_connection *c, ZOOM_resultset *r,
546                      ZOOM_options options,
547                      const char **args)
548 {
549     const char *sort_spec = *args;
550     int i;
551     
552     while (*sort_spec == ' ')
553         sort_spec++;
554     
555     for (i = 0; i<MAX_CON; i++)
556     {
557         if (r[i])
558             ZOOM_resultset_sort(r[i], "yaz", sort_spec);
559     }
560     process_events(c);
561 }
562
563 static void cmd_help(ZOOM_connection *c, ZOOM_resultset *r,
564                      ZOOM_options options,
565                      const char **args)
566 {
567     printf("connect <zurl>\n");
568     printf("search <pqf>\n");
569     printf("show [<start> [<count> [<type]]]\n");
570     printf("facets\n");
571     printf("scan <term>\n");
572     printf("quit\n");
573     printf("close <zurl>\n");
574     printf("ext <type>\n");
575     printf("set <option> [<value>]\n");
576     printf("get <option>\n");
577     printf("\n");
578     printf("options:\n");
579     printf(" start\n");
580     printf(" count\n");
581     printf(" databaseName\n");
582     printf(" preferredRecordSyntax\n");
583     printf(" proxy\n");
584     printf(" elementSetName\n");
585     printf(" maximumRecordSize\n");
586     printf(" preferredRecordSize\n");
587     printf(" async\n");
588     printf(" piggyback\n");
589     printf(" group\n");
590     printf(" user\n");
591     printf(" password\n");
592     printf(" implementationName\n");
593     printf(" charset\n");
594     printf(" lang\n");
595     printf(" timeout\n");
596     printf(" facets\n");
597 }
598
599 static void cmd_connect(ZOOM_connection *c, ZOOM_resultset *r,
600                         ZOOM_options options,
601                         const char **args)
602 {
603     int error;
604     const char *errmsg, *addinfo, *dset;
605     int j, i;
606     WRBUF host = next_token_new_wrbuf(args);
607     if (!host)
608     {
609         printf("missing host after connect\n");
610         return ;
611     }
612     for (j = -1, i = 0; i<MAX_CON; i++)
613     {
614         const char *h;
615         if (c[i] && (h = ZOOM_connection_option_get(c[i], "host")) &&
616             !strcmp(h, wrbuf_cstr(host)))
617         {
618             ZOOM_connection_destroy(c[i]);
619             break;
620         }
621         else if (c[i] == 0 && j == -1)
622             j = i;
623     }
624     if (i == MAX_CON)  /* no match .. */
625     {
626         if (j == -1)
627         {
628             printf("no more connection available\n");
629             wrbuf_destroy(host);
630             return;
631         }
632         i = j;   /* OK, use this one is available */
633     }
634     c[i] = ZOOM_connection_create(options);
635     ZOOM_connection_connect(c[i], wrbuf_cstr(host), 0);
636         
637     if ((error = ZOOM_connection_error_x(c[i], &errmsg, &addinfo, &dset)))
638         printf("%s error: %s (%s:%d) %s\n",
639                ZOOM_connection_option_get(c[i], "host"), errmsg,
640                dset, error, addinfo);
641     wrbuf_destroy(host);
642 }
643
644 static int cmd_parse(ZOOM_connection *c, ZOOM_resultset *r,
645                      ZOOM_options options, 
646                      const char **buf)
647 {
648     int cmd_len;
649     const char *cmd_str;
650
651     cmd_len = next_token(buf, &cmd_str);
652     if (cmd_len < 0)
653         return 1;
654     if (is_command("quit", cmd_str, cmd_len))
655         return 0;
656     else if (is_command("set", cmd_str, cmd_len))
657         cmd_set(c, r, options, buf);
658     else if (is_command("get", cmd_str, cmd_len))
659         cmd_get(c, r, options, buf);
660     else if (is_command("rget", cmd_str, cmd_len))
661         cmd_rget(c, r, options, buf);
662     else if (is_command("connect", cmd_str, cmd_len))
663         cmd_connect(c, r, options, buf);
664     else if (is_command("open", cmd_str, cmd_len))
665         cmd_connect(c, r, options, buf);
666     else if (is_command("search", cmd_str, cmd_len))
667         cmd_search(c, r, options, buf);
668     else if (is_command("facets", cmd_str, cmd_len))
669         cmd_facets(c, r, options, buf);
670     else if (is_command("find", cmd_str, cmd_len))
671         cmd_search(c, r, options, buf);
672     else if (is_command("show", cmd_str, cmd_len))
673         cmd_show(c, r, options, buf);
674     else if (is_command("close", cmd_str, cmd_len))
675         cmd_close(c, r, options, buf);
676     else if (is_command("help", cmd_str, cmd_len))
677         cmd_help(c, r, options, buf);
678     else if (is_command("ext", cmd_str, cmd_len))
679         cmd_ext(c, r, options, buf);
680     else if (is_command("debug", cmd_str, cmd_len))
681         cmd_debug(c, r, options, buf);
682     else if (is_command("scan", cmd_str, cmd_len))
683         cmd_scan(c, r, options, buf);
684     else if (is_command("sort", cmd_str, cmd_len))
685         cmd_sort(c, r, options, buf);
686     else
687         printf("unknown command %.*s\n", cmd_len, cmd_str);
688     return 2;
689 }
690
691 void shell(ZOOM_connection *c, ZOOM_resultset *r,
692            ZOOM_options options)
693 {
694     while (1)
695     {
696         char buf[1000];
697         char *cp;
698         const char *bp = buf;
699 #if HAVE_READLINE_READLINE_H
700         char* line_in;
701         line_in=readline("ZOOM>");
702         if (!line_in)
703             break;
704 #if HAVE_READLINE_HISTORY_H
705         if (*line_in)
706             add_history(line_in);
707 #endif
708         if(strlen(line_in) > 999) {
709             printf("Input line too long\n");
710             break;
711         };
712         strcpy(buf,line_in);
713         free(line_in);
714 #else    
715         printf("ZOOM>"); fflush(stdout);
716         if (!fgets(buf, 999, stdin))
717             break;
718 #endif 
719         if ((cp = strchr(buf, '\n')))
720             *cp = '\0';
721         if (!cmd_parse(c, r, options, &bp))
722             break;
723     }
724 }
725
726 static void zoomsh(int argc, char **argv)
727 {
728     ZOOM_options zoom_options = ZOOM_options_create();
729     int i, res = 1;
730     ZOOM_connection z39_con[MAX_CON];
731     ZOOM_resultset  z39_res[MAX_CON];
732
733     for (i = 0; i<MAX_CON; i++)
734     {
735         z39_con[i] = 0;
736         z39_res[i] = 0;
737     }
738     while (res)
739     {
740         int mask;
741         char *arg = 0;
742         int option_ret = options("v:", argv, argc, &arg);
743         const char *bp = arg;
744         switch (option_ret)
745         {
746         case 0:
747             res = cmd_parse(z39_con, z39_res, zoom_options, &bp);
748             /* returns res == 0 on quit */
749             break;
750         case YAZ_OPTIONS_EOF:
751             shell(z39_con, z39_res, zoom_options);
752             res = 0;
753             break;
754         case 'v':
755             mask = yaz_log_mask_str(arg);
756             yaz_log_init_level(mask);
757             break;
758         default:
759             fprintf(stderr, "zoomsh: [-v] [commands]\n");
760             res = 0;
761         }
762     }
763
764     for (i = 0; i<MAX_CON; i++)
765     {
766         ZOOM_connection_destroy(z39_con[i]);
767         ZOOM_resultset_destroy(z39_res[i]);
768     }
769 }
770
771 int main(int argc, char **argv)
772 {
773     zoomsh(argc, argv);
774     exit(0);
775 }
776 /*
777  * Local variables:
778  * c-basic-offset: 4
779  * c-file-style: "Stroustrup"
780  * indent-tabs-mode: nil
781  * End:
782  * vim: shiftwidth=4 tabstop=8 expandtab
783  */
784