dd8296059d92e68d423b8d546938f7990a62df92
[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/page-break-item.h"
34 #include "output/pivot-output.h"
35 #include "output/pivot-table.h"
36 #include "output/table-item.h"
37 #include "output/table-provider.h"
38
39 #include "gl/minmax.h"
40 #include "gl/xalloc.h"
41 #include "gl/xvasprintf.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* Comma-separated value output driver. */
47 struct csv_driver
48   {
49     struct output_driver driver;
50
51     char *separator;            /* Field separator (usually comma or tab). */
52     int quote;                  /* Quote character (usually ' or ") or 0. */
53     char *quote_set;            /* Characters that force quoting. */
54     bool titles;                /* Print table titles? */
55     bool captions;              /* Print table captions? */
56
57     struct file_handle *handle;
58     FILE *file;                 /* Output file. */
59     int n_items;                /* Number of items output so far. */
60   };
61
62 static const struct output_driver_class csv_driver_class;
63
64 static struct csv_driver *
65 csv_driver_cast (struct output_driver *driver)
66 {
67   assert (driver->class == &csv_driver_class);
68   return UP_CAST (driver, struct csv_driver, driver);
69 }
70
71 static struct driver_option *
72 opt (struct output_driver *d, struct string_map *options, const char *key,
73      const char *default_value)
74 {
75   return driver_option_get (d, options, key, default_value);
76 }
77
78 static struct output_driver *
79 csv_create (struct file_handle *fh, enum settings_output_devices device_type,
80             struct string_map *o)
81 {
82   struct output_driver *d;
83   struct csv_driver *csv;
84   char *quote;
85
86   csv = xzalloc (sizeof *csv);
87   d = &csv->driver;
88   output_driver_init (&csv->driver, &csv_driver_class, fh_get_file_name (fh), device_type);
89
90   csv->separator = parse_string (opt (d, o, "separator", ","));
91   quote = parse_string (opt (d, o, "quote", "\""));
92   csv->quote = quote[0];
93   free (quote);
94   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
95   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
96   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
97   csv->handle = fh;
98   csv->file = fn_open (fh, "w");
99   csv->n_items = 0;
100
101   if (csv->file == NULL)
102     {
103       msg_error (errno, _("error opening output file `%s'"), fh_get_file_name (fh));
104       output_driver_destroy (d);
105       return NULL;
106     }
107
108   return d;
109 }
110
111 static void
112 csv_destroy (struct output_driver *driver)
113 {
114   struct csv_driver *csv = csv_driver_cast (driver);
115
116   if (csv->file != NULL)
117     fn_close (csv->handle, csv->file);
118
119   free (csv->separator);
120   free (csv->quote_set);
121   fh_unref (csv->handle);
122   free (csv);
123 }
124
125 static void
126 csv_flush (struct output_driver *driver)
127 {
128   struct csv_driver *csv = csv_driver_cast (driver);
129   if (csv->file != NULL)
130     fflush (csv->file);
131 }
132
133 static void
134 csv_output_field__ (struct csv_driver *csv, struct substring field)
135 {
136   ss_ltrim (&field, ss_cstr (" "));
137
138   if (csv->quote && ss_cspan (field, ss_cstr (csv->quote_set)) < field.length)
139     {
140       putc (csv->quote, csv->file);
141       for (size_t i = 0; i < field.length; i++)
142         {
143           if (field.string[i] == csv->quote)
144             putc (csv->quote, csv->file);
145           putc (field.string[i], csv->file);
146         }
147       putc (csv->quote, csv->file);
148     }
149   else
150     fwrite (field.string, field.length, 1, csv->file);
151 }
152
153 static void
154 csv_output_field (struct csv_driver *csv, const char *field)
155 {
156   csv_output_field__ (csv, ss_cstr (field));
157 }
158
159 static void
160 csv_put_separator (struct csv_driver *csv)
161 {
162   if (csv->n_items++ > 0)
163     putc ('\n', csv->file);
164 }
165
166 static void
167 csv_output_lines (struct csv_driver *csv, const char *text_)
168 {
169   struct substring text = ss_cstr (text_);
170   struct substring line;
171   size_t save_idx = 0;
172   while (ss_separate (text, ss_cstr ("\n"), &save_idx, &line))
173     {
174       csv_output_field__ (csv, line);
175       putc ('\n', csv->file);
176     }
177 }
178
179 static void
180 csv_output_table_cell (struct csv_driver *csv, const struct pivot_table *pt,
181                        const struct table_cell *cell, const char *leader)
182 {
183   struct string s = DS_EMPTY_INITIALIZER;
184   if (leader)
185     ds_put_format (&s, "%s: ", leader);
186   pivot_value_format (cell->value, pt, &s);
187   csv_output_field (csv, ds_cstr (&s));
188   ds_destroy (&s);
189 }
190
191 static void
192 csv_output_table__ (struct csv_driver *csv, const struct pivot_table *pt,
193                     const struct table *t, const char *leader)
194 {
195   if (!t)
196     return;
197
198   for (int y = 0; y < t->n[TABLE_VERT]; y++)
199     {
200       for (int x = 0; x < t->n[TABLE_HORZ]; x++)
201         {
202           struct table_cell cell;
203
204           table_get_cell (t, x, y, &cell);
205
206           if (x > 0)
207             fputs (csv->separator, csv->file);
208
209           if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
210             csv_output_field (csv, "");
211           else
212             csv_output_table_cell (csv, pt, &cell, !x ? leader : NULL);
213         }
214       putc ('\n', csv->file);
215     }
216 }
217
218 static void
219 csv_output_table_layer (struct csv_driver *csv, const struct pivot_table *pt,
220                         const size_t *layer_indexes)
221 {
222   struct table *title, *layers, *body, *caption, *footnotes;
223   pivot_output (pt, layer_indexes, true, &title, &layers, &body,
224                 &caption, &footnotes, NULL, NULL);
225
226   csv_put_separator (csv);
227   csv_output_table__ (csv, pt, title, "Table");
228   csv_output_table__ (csv, pt, layers, "Layer");
229   csv_output_table__ (csv, pt, body, NULL);
230   csv_output_table__ (csv, pt, caption, "Caption");
231   csv_output_table__ (csv, pt, footnotes, "Footnote");
232
233   table_unref (title);
234   table_unref (layers);
235   table_unref (body);
236   table_unref (caption);
237   table_unref (footnotes);
238 }
239
240 static void
241 csv_submit (struct output_driver *driver,
242             const struct output_item *output_item)
243 {
244   struct csv_driver *csv = csv_driver_cast (driver);
245
246   if (is_table_item (output_item))
247     {
248       const struct pivot_table *pt = to_table_item (output_item)->pt;
249
250       size_t *layer_indexes;
251       PIVOT_OUTPUT_FOR_EACH_LAYER (layer_indexes, pt, true)
252         csv_output_table_layer (csv, pt, layer_indexes);
253     }
254   else if (is_text_item (output_item))
255     {
256       const struct text_item *text_item = to_text_item (output_item);
257
258       enum text_item_type type = text_item_get_type (text_item);
259       if (type == TEXT_ITEM_SYNTAX || type == TEXT_ITEM_PAGE_TITLE)
260         return;
261
262       csv_put_separator (csv);
263
264       char *text = text_item_get_plain_text (text_item);
265       csv_output_lines (csv, text);
266       free (text);
267     }
268   else if (is_page_break_item (output_item))
269     {
270       csv_put_separator (csv);
271       csv_output_lines (csv, "");
272     }
273   else if (is_message_item (output_item))
274     {
275       const struct message_item *message_item = to_message_item (output_item);
276       char *s = msg_to_string (message_item_get_msg (message_item));
277       csv_put_separator (csv);
278       csv_output_field (csv, s);
279       free (s);
280       putc ('\n', csv->file);
281     }
282 }
283
284 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
285
286 static const struct output_driver_class csv_driver_class =
287   {
288     "csv",
289     csv_destroy,
290     csv_submit,
291     csv_flush,
292   };