455584914e7c4a470e8c506640880d6b94bad1f7
[pspp] / src / output / csv.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2012, 2013, 2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <errno.h>
20 #include <stdlib.h>
21
22 #include "data/file-name.h"
23 #include "data/file-handle-def.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/compiler.h"
26 #include "libpspp/message.h"
27 #include "libpspp/str.h"
28 #include "libpspp/string-map.h"
29 #include "output/text-item.h"
30 #include "output/driver-provider.h"
31 #include "output/options.h"
32 #include "output/message-item.h"
33 #include "output/table-item.h"
34 #include "output/table-provider.h"
35
36 #include "gl/xalloc.h"
37 #include "gl/xvasprintf.h"
38
39 #include "gettext.h"
40 #define _(msgid) gettext (msgid)
41
42 /* Comma-separated value output driver. */
43 struct csv_driver
44   {
45     struct output_driver driver;
46
47     char *separator;            /* Field separator (usually comma or tab). */
48     int quote;                  /* Quote character (usually ' or ") or 0. */
49     char *quote_set;            /* Characters that force quoting. */
50     bool titles;                /* Print table titles? */
51     bool captions;              /* Print table captions? */
52
53     struct file_handle *handle;
54     char *command_name;         /* Current command. */
55     FILE *file;                 /* Output file. */
56     int n_items;                /* Number of items output so far. */
57   };
58
59 static const struct output_driver_class csv_driver_class;
60
61 static struct csv_driver *
62 csv_driver_cast (struct output_driver *driver)
63 {
64   assert (driver->class == &csv_driver_class);
65   return UP_CAST (driver, struct csv_driver, driver);
66 }
67
68 static struct driver_option *
69 opt (struct output_driver *d, struct string_map *options, const char *key,
70      const char *default_value)
71 {
72   return driver_option_get (d, options, key, default_value);
73 }
74
75 static struct output_driver *
76 csv_create (struct file_handle *fh, enum settings_output_devices device_type,
77             struct string_map *o)
78 {
79   struct output_driver *d;
80   struct csv_driver *csv;
81   char *quote;
82
83   csv = xzalloc (sizeof *csv);
84   d = &csv->driver;
85   output_driver_init (&csv->driver, &csv_driver_class, fh_get_file_name (fh), device_type);
86
87   csv->separator = parse_string (opt (d, o, "separator", ","));
88   quote = parse_string (opt (d, o, "quote", "\""));
89   csv->quote = quote[0];
90   free (quote);
91   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
92   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
93   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
94   csv->handle = fh;
95   csv->file = fn_open (fh, "w");
96   csv->n_items = 0;
97
98   if (csv->file == NULL)
99     {
100       msg_error (errno, _("error opening output file `%s'"), fh_get_file_name (fh));
101       output_driver_destroy (d);
102       return NULL;
103     }
104
105   return d;
106 }
107
108 static void
109 csv_destroy (struct output_driver *driver)
110 {
111   struct csv_driver *csv = csv_driver_cast (driver);
112
113   if (csv->file != NULL)
114     fn_close (csv->handle, csv->file);
115
116   free (csv->separator);
117   free (csv->quote_set);
118   fh_unref (csv->handle);
119   free (csv);
120 }
121
122 static void
123 csv_flush (struct output_driver *driver)
124 {
125   struct csv_driver *csv = csv_driver_cast (driver);
126   if (csv->file != NULL)
127     fflush (csv->file);
128 }
129
130 static void
131 csv_output_field (struct csv_driver *csv, const char *field)
132 {
133   while (*field == ' ')
134     field++;
135
136   if (csv->quote && field[strcspn (field, csv->quote_set)])
137     {
138       const char *p;
139
140       putc (csv->quote, csv->file);
141       for (p = field; *p != '\0'; p++)
142         {
143           if (*p == csv->quote)
144             putc (csv->quote, csv->file);
145           putc (*p, csv->file);
146         }
147       putc (csv->quote, csv->file);
148     }
149   else
150     fputs (field, csv->file);
151 }
152
153 static void PRINTF_FORMAT (2, 3)
154 csv_output_field_format (struct csv_driver *csv, const char *format, ...)
155 {
156   va_list args;
157   char *s;
158
159   va_start (args, format);
160   s = xvasprintf (format, args);
161   va_end (args);
162
163   csv_output_field (csv, s);
164   free (s);
165 }
166
167 static void
168 csv_put_field (struct csv_driver *csv, struct string *s, const char *field)
169 {
170   while (*field == ' ')
171     field++;
172
173   if (csv->quote && field[strcspn (field, csv->quote_set)])
174     {
175       const char *p;
176
177       ds_put_byte (s, csv->quote);
178       for (p = field; *p != '\0'; p++)
179         {
180           if (*p == csv->quote)
181             ds_put_byte (s, csv->quote);
182           ds_put_byte (s, *p);
183         }
184       ds_put_byte (s, csv->quote);
185     }
186   else
187     ds_put_cstr (s, field);
188 }
189
190 static void
191 csv_output_subtable (struct csv_driver *csv, struct string *s,
192                      const struct table_item *item)
193 {
194   const struct table *t = table_item_get_table (item);
195   const char *title = table_item_get_title (item);
196   const char *caption = table_item_get_caption (item);
197   int y, x;
198
199   if (csv->titles && title != NULL)
200     {
201       csv_output_field_format (csv, "Table: %s", title);
202       putc ('\n', csv->file);
203     }
204
205   for (y = 0; y < table_nr (t); y++)
206     {
207       if (y > 0)
208         ds_put_byte (s, '\n');
209
210       for (x = 0; x < table_nc (t); x++)
211         {
212           struct table_cell cell;
213
214           table_get_cell (t, x, y, &cell);
215
216           if (x > 0)
217             ds_put_cstr (s, csv->separator);
218
219           if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
220             csv_put_field (csv, s, "");
221           else if (cell.n_contents == 1 && cell.contents[0].text != NULL)
222             csv_put_field (csv, s, cell.contents[0].text);
223           else
224             {
225               struct string s2;
226               size_t i;
227
228               ds_init_empty (&s2);
229               for (i = 0; i < cell.n_contents; i++)
230                 {
231                   if (i > 0)
232                     ds_put_cstr (&s2, "\n\n");
233
234                   if (cell.contents[i].text != NULL)
235                     ds_put_cstr (&s2, cell.contents[i].text);
236                   else
237                     csv_output_subtable (csv, &s2, cell.contents[i].table);
238                 }
239               csv_put_field (csv, s, ds_cstr (&s2));
240               ds_destroy (&s2);
241             }
242
243           table_cell_free (&cell);
244         }
245     }
246
247   if (csv->captions && caption != NULL)
248     {
249       csv_output_field_format (csv, "Caption: %s", caption);
250       putc ('\n', csv->file);
251     }
252 }
253
254 static void
255 csv_put_separator (struct csv_driver *csv)
256 {
257   if (csv->n_items++ > 0)
258     putc ('\n', csv->file);
259 }
260
261 static void
262 csv_submit (struct output_driver *driver,
263             const struct output_item *output_item)
264 {
265   struct csv_driver *csv = csv_driver_cast (driver);
266
267   output_driver_track_current_command (output_item, &csv->command_name);
268
269   if (is_table_item (output_item))
270     {
271       struct table_item *table_item = to_table_item (output_item);
272       const char *title = table_item_get_title (table_item);
273       const char *caption = table_item_get_caption (table_item);
274       const struct table *t = table_item_get_table (table_item);
275       int footnote_idx;
276       int x, y;
277
278       csv_put_separator (csv);
279
280       if (csv->titles && title != NULL)
281         {
282           csv_output_field_format (csv, "Table: %s", title);
283           putc ('\n', csv->file);
284         }
285
286       footnote_idx = 0;
287       for (y = 0; y < table_nr (t); y++)
288         {
289           for (x = 0; x < table_nc (t); x++)
290             {
291               struct table_cell cell;
292
293               table_get_cell (t, x, y, &cell);
294
295               if (x > 0)
296                 fputs (csv->separator, csv->file);
297
298               if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
299                 csv_output_field (csv, "");
300               else if (cell.n_contents == 1
301                        && cell.contents[0].text != NULL
302                        && cell.contents[0].n_footnotes == 0)
303                 csv_output_field (csv, cell.contents[0].text);
304               else
305                 {
306                   struct string s;
307                   size_t i;
308
309                   ds_init_empty (&s);
310                   for (i = 0; i < cell.n_contents; i++)
311                     {
312                       const struct cell_contents *c = &cell.contents[i];
313                       int j;
314
315                       if (i > 0)
316                         ds_put_cstr (&s, "\n\n");
317
318                       if (c->text != NULL)
319                         ds_put_cstr (&s, c->text);
320                       else
321                         csv_output_subtable (csv, &s, c->table);
322
323                       for (j = 0; j < c->n_footnotes; j++)
324                         {
325                           char marker[16];
326
327                           str_format_26adic (++footnote_idx, false,
328                                              marker, sizeof marker);
329                           ds_put_format (&s, "[%s]", marker);
330                         }
331                     }
332                   csv_output_field (csv, ds_cstr (&s));
333                   ds_destroy (&s);
334                 }
335
336               table_cell_free (&cell);
337             }
338           putc ('\n', csv->file);
339         }
340
341       if (csv->captions && caption != NULL)
342         {
343           csv_output_field_format (csv, "Caption: %s", caption);
344           putc ('\n', csv->file);
345         }
346
347       if (footnote_idx)
348         {
349           size_t i;
350
351           fputs ("\nFootnotes:\n", csv->file);
352
353           footnote_idx = 0;
354           for (y = 0; y < table_nr (t); y++)
355             {
356               struct table_cell cell;
357               for (x = 0; x < table_nc (t); x = cell.d[TABLE_HORZ][1])
358                 {
359                   table_get_cell (t, x, y, &cell);
360
361                   if (x == cell.d[TABLE_HORZ][0] && y == cell.d[TABLE_VERT][0])
362                     for (i = 0; i < cell.n_contents; i++)
363                       {
364                         const struct cell_contents *c = &cell.contents[i];
365                         int j;
366
367                         for (j = 0; j < c->n_footnotes; j++)
368                           {
369                             char marker[16];
370
371                             str_format_26adic (++footnote_idx, false,
372                                                marker, sizeof marker);
373                             csv_output_field (csv, marker);
374                             fputs (csv->separator, csv->file);
375                             csv_output_field (csv, c->footnotes[j]);
376                             putc ('\n', csv->file);
377                           }
378                       }
379                   table_cell_free (&cell);
380                 }
381             }
382         }
383     }
384   else if (is_text_item (output_item))
385     {
386       const struct text_item *text_item = to_text_item (output_item);
387       enum text_item_type type = text_item_get_type (text_item);
388       const char *text = text_item_get_text (text_item);
389
390       if (type == TEXT_ITEM_COMMAND_OPEN || type == TEXT_ITEM_COMMAND_CLOSE
391           || type == TEXT_ITEM_SYNTAX)
392         return;
393
394       csv_put_separator (csv);
395       switch (type)
396         {
397         case TEXT_ITEM_TITLE:
398           csv_output_field_format (csv, "Title: %s", text);
399           break;
400
401         case TEXT_ITEM_SUBTITLE:
402           csv_output_field_format (csv, "Subtitle: %s", text);
403           break;
404
405         default:
406           csv_output_field (csv, text);
407           break;
408         }
409       putc ('\n', csv->file);
410     }
411   else if (is_message_item (output_item))
412     {
413       const struct message_item *message_item = to_message_item (output_item);
414       const struct msg *msg = message_item_get_msg (message_item);
415       char *s = msg_to_string (msg, csv->command_name);
416       csv_put_separator (csv);
417       csv_output_field (csv, s);
418       free (s);
419       putc ('\n', csv->file);
420     }
421 }
422
423 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
424
425 static const struct output_driver_class csv_driver_class =
426   {
427     "csv",
428     csv_destroy,
429     csv_submit,
430     csv_flush,
431   };