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