ef49759566d9b27829a2d8011d271c149e9ef6f9
[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     FILE *file;                 /* Output file. */
55     int n_items;                /* Number of items output so far. */
56   };
57
58 static const struct output_driver_class csv_driver_class;
59
60 static struct csv_driver *
61 csv_driver_cast (struct output_driver *driver)
62 {
63   assert (driver->class == &csv_driver_class);
64   return UP_CAST (driver, struct csv_driver, driver);
65 }
66
67 static struct driver_option *
68 opt (struct output_driver *d, struct string_map *options, const char *key,
69      const char *default_value)
70 {
71   return driver_option_get (d, options, key, default_value);
72 }
73
74 static struct output_driver *
75 csv_create (struct file_handle *fh, enum settings_output_devices device_type,
76             struct string_map *o)
77 {
78   struct output_driver *d;
79   struct csv_driver *csv;
80   char *quote;
81
82   csv = xzalloc (sizeof *csv);
83   d = &csv->driver;
84   output_driver_init (&csv->driver, &csv_driver_class, fh_get_file_name (fh), device_type);
85
86   csv->separator = parse_string (opt (d, o, "separator", ","));
87   quote = parse_string (opt (d, o, "quote", "\""));
88   csv->quote = quote[0];
89   free (quote);
90   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
91   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
92   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
93   csv->handle = fh;
94   csv->file = fn_open (fh, "w");
95   csv->n_items = 0;
96
97   if (csv->file == NULL)
98     {
99       msg_error (errno, _("error opening output file `%s'"), fh_get_file_name (fh));
100       output_driver_destroy (d);
101       return NULL;
102     }
103
104   return d;
105 }
106
107 static void
108 csv_destroy (struct output_driver *driver)
109 {
110   struct csv_driver *csv = csv_driver_cast (driver);
111
112   if (csv->file != NULL)
113     fn_close (csv->handle, csv->file);
114
115   free (csv->separator);
116   free (csv->quote_set);
117   fh_unref (csv->handle);
118   free (csv);
119 }
120
121 static void
122 csv_flush (struct output_driver *driver)
123 {
124   struct csv_driver *csv = csv_driver_cast (driver);
125   if (csv->file != NULL)
126     fflush (csv->file);
127 }
128
129 static void
130 csv_output_field (struct csv_driver *csv, const char *field)
131 {
132   while (*field == ' ')
133     field++;
134
135   if (csv->quote && field[strcspn (field, csv->quote_set)])
136     {
137       const char *p;
138
139       putc (csv->quote, csv->file);
140       for (p = field; *p != '\0'; p++)
141         {
142           if (*p == csv->quote)
143             putc (csv->quote, csv->file);
144           putc (*p, csv->file);
145         }
146       putc (csv->quote, csv->file);
147     }
148   else
149     fputs (field, csv->file);
150 }
151
152 static void PRINTF_FORMAT (2, 3)
153 csv_output_field_format (struct csv_driver *csv, const char *format, ...)
154 {
155   va_list args;
156   char *s;
157
158   va_start (args, format);
159   s = xvasprintf (format, args);
160   va_end (args);
161
162   csv_output_field (csv, s);
163   free (s);
164 }
165
166 static void
167 csv_put_separator (struct csv_driver *csv)
168 {
169   if (csv->n_items++ > 0)
170     putc ('\n', csv->file);
171 }
172
173 static void
174 csv_submit (struct output_driver *driver,
175             const struct output_item *output_item)
176 {
177   struct csv_driver *csv = csv_driver_cast (driver);
178
179   if (is_table_item (output_item))
180     {
181       struct table_item *table_item = to_table_item (output_item);
182       const char *title = table_item_get_title (table_item);
183       const char *caption = table_item_get_caption (table_item);
184       const struct table *t = table_item_get_table (table_item);
185       int footnote_idx;
186       int x, y;
187
188       csv_put_separator (csv);
189
190       if (csv->titles && title != NULL)
191         {
192           csv_output_field_format (csv, "Table: %s", title);
193           putc ('\n', csv->file);
194         }
195
196       footnote_idx = 0;
197       for (y = 0; y < table_nr (t); y++)
198         {
199           for (x = 0; x < table_nc (t); x++)
200             {
201               struct table_cell cell;
202
203               table_get_cell (t, x, y, &cell);
204
205               if (x > 0)
206                 fputs (csv->separator, csv->file);
207
208               if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
209                 csv_output_field (csv, "");
210               else if (cell.n_contents == 1
211                        && cell.contents[0].text != NULL
212                        && cell.contents[0].n_footnotes == 0)
213                 csv_output_field (csv, cell.contents[0].text);
214               else
215                 {
216                   struct string s;
217                   size_t i;
218
219                   ds_init_empty (&s);
220                   for (i = 0; i < cell.n_contents; i++)
221                     {
222                       const struct cell_contents *c = &cell.contents[i];
223                       int j;
224
225                       if (i > 0)
226                         ds_put_cstr (&s, "\n\n");
227
228                       ds_put_cstr (&s, c->text);
229
230                       for (j = 0; j < c->n_footnotes; j++)
231                         {
232                           char marker[16];
233
234                           str_format_26adic (++footnote_idx, false,
235                                              marker, sizeof marker);
236                           ds_put_format (&s, "[%s]", marker);
237                         }
238                     }
239                   csv_output_field (csv, ds_cstr (&s));
240                   ds_destroy (&s);
241                 }
242
243               table_cell_free (&cell);
244             }
245           putc ('\n', csv->file);
246         }
247
248       if (csv->captions && caption != NULL)
249         {
250           csv_output_field_format (csv, "Caption: %s", caption);
251           putc ('\n', csv->file);
252         }
253
254       if (footnote_idx)
255         {
256           size_t i;
257
258           fputs ("\nFootnotes:\n", csv->file);
259
260           footnote_idx = 0;
261           for (y = 0; y < table_nr (t); y++)
262             {
263               struct table_cell cell;
264               for (x = 0; x < table_nc (t); x = cell.d[TABLE_HORZ][1])
265                 {
266                   table_get_cell (t, x, y, &cell);
267
268                   if (x == cell.d[TABLE_HORZ][0] && y == cell.d[TABLE_VERT][0])
269                     for (i = 0; i < cell.n_contents; i++)
270                       {
271                         const struct cell_contents *c = &cell.contents[i];
272                         int j;
273
274                         for (j = 0; j < c->n_footnotes; j++)
275                           {
276                             char marker[16];
277
278                             str_format_26adic (++footnote_idx, false,
279                                                marker, sizeof marker);
280                             csv_output_field (csv, marker);
281                             fputs (csv->separator, csv->file);
282                             csv_output_field (csv, c->footnotes[j]);
283                             putc ('\n', csv->file);
284                           }
285                       }
286                   table_cell_free (&cell);
287                 }
288             }
289         }
290     }
291   else if (is_text_item (output_item))
292     {
293       const struct text_item *text_item = to_text_item (output_item);
294       enum text_item_type type = text_item_get_type (text_item);
295       const char *text = text_item_get_text (text_item);
296
297       if (type == TEXT_ITEM_COMMAND_OPEN || type == TEXT_ITEM_COMMAND_CLOSE
298           || type == TEXT_ITEM_SYNTAX)
299         return;
300
301       csv_put_separator (csv);
302       switch (type)
303         {
304         case TEXT_ITEM_TITLE:
305           csv_output_field_format (csv, "Title: %s", text);
306           break;
307
308         case TEXT_ITEM_SUBTITLE:
309           csv_output_field_format (csv, "Subtitle: %s", text);
310           break;
311
312         default:
313           csv_output_field (csv, text);
314           break;
315         }
316       putc ('\n', csv->file);
317     }
318   else if (is_message_item (output_item))
319     {
320       const struct message_item *message_item = to_message_item (output_item);
321       const struct msg *msg = message_item_get_msg (message_item);
322       char *s = msg_to_string (msg, message_item->command_name);
323       csv_put_separator (csv);
324       csv_output_field (csv, s);
325       free (s);
326       putc ('\n', csv->file);
327     }
328 }
329
330 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
331
332 static const struct output_driver_class csv_driver_class =
333   {
334     "csv",
335     csv_destroy,
336     csv_submit,
337     csv_flush,
338   };