763d19137219c0aaa38a77ad0e41879e818a646d
[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/minmax.h"
37 #include "gl/xalloc.h"
38 #include "gl/xvasprintf.h"
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 /* Comma-separated value output driver. */
44 struct csv_driver
45   {
46     struct output_driver driver;
47
48     char *separator;            /* Field separator (usually comma or tab). */
49     int quote;                  /* Quote character (usually ' or ") or 0. */
50     char *quote_set;            /* Characters that force quoting. */
51     bool titles;                /* Print table titles? */
52     bool captions;              /* Print table captions? */
53
54     struct file_handle *handle;
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_format_footnotes (const struct footnote **f, size_t n, struct string *s)
169 {
170   for (size_t i = 0; i < n; i++)
171     ds_put_format (s, "[%s]", f[i]->marker);
172 }
173
174 static void
175 csv_output_table_item_text (struct csv_driver *csv,
176                             const struct table_item_text *text,
177                             const char *leader)
178 {
179   if (!text)
180     return;
181
182   struct string s = DS_EMPTY_INITIALIZER;
183   ds_put_format (&s, "%s: %s", leader, text->content);
184   csv_format_footnotes (text->footnotes, text->n_footnotes, &s);
185   csv_output_field (csv, ds_cstr (&s));
186   ds_destroy (&s);
187   putc ('\n', csv->file);
188 }
189
190 static void
191 csv_put_separator (struct csv_driver *csv)
192 {
193   if (csv->n_items++ > 0)
194     putc ('\n', csv->file);
195 }
196
197 static void
198 csv_submit (struct output_driver *driver,
199             const struct output_item *output_item)
200 {
201   struct csv_driver *csv = csv_driver_cast (driver);
202
203   if (is_table_item (output_item))
204     {
205       struct table_item *table_item = to_table_item (output_item);
206       const struct table *t = table_item_get_table (table_item);
207       int x, y;
208
209       csv_put_separator (csv);
210
211       if (csv->titles)
212         csv_output_table_item_text (csv, table_item_get_title (table_item),
213                                     "Table");
214
215       for (y = 0; y < table_nr (t); y++)
216         {
217           for (x = 0; x < table_nc (t); x++)
218             {
219               struct table_cell cell;
220
221               table_get_cell (t, x, y, &cell);
222
223               if (x > 0)
224                 fputs (csv->separator, csv->file);
225
226               if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
227                 csv_output_field (csv, "");
228               else if (cell.n_contents == 1
229                        && cell.contents[0].text != NULL
230                        && cell.contents[0].n_footnotes == 0)
231                 csv_output_field (csv, cell.contents[0].text);
232               else
233                 {
234                   struct string s;
235                   size_t i;
236
237                   ds_init_empty (&s);
238                   for (i = 0; i < cell.n_contents; i++)
239                     {
240                       const struct cell_contents *c = &cell.contents[i];
241
242                       if (i > 0)
243                         ds_put_cstr (&s, "\n\n");
244
245                       ds_put_cstr (&s, c->text);
246                       csv_format_footnotes (c->footnotes, c->n_footnotes, &s);
247                     }
248                   csv_output_field (csv, ds_cstr (&s));
249                   ds_destroy (&s);
250                 }
251
252               table_cell_free (&cell);
253             }
254           putc ('\n', csv->file);
255         }
256
257       if (csv->captions)
258         csv_output_table_item_text (csv, table_item_get_caption (table_item),
259                                     "Caption");
260
261       const struct footnote **f;
262       size_t n_footnotes = table_collect_footnotes (table_item, &f);
263       if (n_footnotes)
264         {
265           fputs ("\nFootnotes:\n", csv->file);
266
267           for (size_t i = 0; i < n_footnotes; i++)
268             if (f[i])
269               {
270                 csv_output_field (csv, f[i]->marker);
271                 fputs (csv->separator, csv->file);
272                 csv_output_field (csv, f[i]->content);
273                 putc ('\n', csv->file);
274               }
275
276           free (f);
277         }
278     }
279   else if (is_text_item (output_item))
280     {
281       const struct text_item *text_item = to_text_item (output_item);
282       enum text_item_type type = text_item_get_type (text_item);
283       const char *text = text_item_get_text (text_item);
284
285       if (type == TEXT_ITEM_COMMAND_OPEN || type == TEXT_ITEM_COMMAND_CLOSE
286           || type == TEXT_ITEM_SYNTAX)
287         return;
288
289       csv_put_separator (csv);
290       switch (type)
291         {
292         case TEXT_ITEM_TITLE:
293           csv_output_field_format (csv, "Title: %s", text);
294           break;
295
296         case TEXT_ITEM_SUBTITLE:
297           csv_output_field_format (csv, "Subtitle: %s", text);
298           break;
299
300         default:
301           csv_output_field (csv, text);
302           break;
303         }
304       putc ('\n', csv->file);
305     }
306   else if (is_message_item (output_item))
307     {
308       const struct message_item *message_item = to_message_item (output_item);
309       const struct msg *msg = message_item_get_msg (message_item);
310       char *s = msg_to_string (msg, message_item->command_name);
311       csv_put_separator (csv);
312       csv_output_field (csv, s);
313       free (s);
314       putc ('\n', csv->file);
315     }
316 }
317
318 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
319
320 static const struct output_driver_class csv_driver_class =
321   {
322     "csv",
323     csv_destroy,
324     csv_submit,
325     csv_flush,
326   };