File: rec2csv.c

package info (click to toggle)
recutils 1.5-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 10,212 kB
  • sloc: ansic: 55,227; sh: 16,411; lisp: 1,431; yacc: 1,373; makefile: 304; lex: 223; sed: 16
file content (349 lines) | stat: -rw-r--r-- 8,370 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/* -*- mode: C -*-
 *
 *       File:         rec2csv.c
 *       Date:         Mon Jan 31 22:12:29 2011
 *
 *       GNU recutils - rec to csv converter.
 *
 */

/* Copyright (C) 2011, 2012 Jose E. Marchesi */

/* This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <xalloc.h>
#include <gettext.h>
#define _(str) gettext (str)

#include <csv.h>
#include <rec.h>
#include <recutl.h>

/* Forward declarations.  */
static void rec2csv_parse_args (int argc, char **argv);
static bool rec2csv_process_data (rec_db_t db);
static rec_fex_t rec2csv_determine_fields (rec_rset_t rset);
static void rec2csv_generate_csv (rec_rset_t rset, rec_fex_t fex);

/*
 * Types
 */

/*
 * Global variables
 */

char             *rec2csv_record_type   = NULL;
rec_field_name_t  rec2csv_sort_by_field = NULL;

/*
 * Command line options management
 */

enum
  {
    COMMON_ARGS,
    RECORD_TYPE_ARG,
    SORT_ARG
  };

static const struct option GNU_longOptions[] =
  {
    COMMON_LONG_ARGS,
    {"type", required_argument, NULL, RECORD_TYPE_ARG},
    {"sort", required_argument, NULL, SORT_ARG},
    {NULL, 0, NULL, 0}
  };


/*
 * Functions.
 */

void
recutl_print_help (void)
{
  /* TRANSLATORS: --help output, rec2csv synopsis.
     no-wrap */
  printf (_("\
Usage: rec2csv [OPTIONS]... [REC_FILE]\n"));

  /* TRANSLATORS: --help output, rec2csv short description.
     no-wrap */
  fputs (_("\
Convert rec data into csv data.\n"), stdout);

  puts ("");
  /* TRANSLATORS: --help output, rec2csv options.
     no-wrap */
  fputs (_("\
  -t, --type=TYPE                     record set to convert to csv; if this parameter\n\
                                        is omitted then the default record set is used\n\
  -S, --sort=FIELD                    sort the output by the specified field.\n"),
         stdout);

  recutl_print_help_common ();
  puts ("");
  recutl_print_help_footer ();
}

static void
rec2csv_parse_args (int argc,
                    char **argv)
{
  int ret;
  char c;

  while ((ret = getopt_long (argc,
                             argv,
                             "t:S:",
                             GNU_longOptions,
                             NULL)) != -1)
    {
      c = ret;
      switch (c)
        {
          COMMON_ARGS_CASES
        case RECORD_TYPE_ARG:
        case 't':
          {
            rec2csv_record_type = xstrdup (optarg);
            break;
          }
        case SORT_ARG:
        case 'S':
          {
            if (rec2csv_sort_by_field)
              {
                recutl_fatal (_("only one field can be specified as a sorting criteria.\n"));
              }

            /* Parse the field name.  */
            rec2csv_sort_by_field = rec_parse_field_name_str (optarg);
            if (!rec2csv_sort_by_field)
              {
                recutl_fatal (_("invalid field name in -S.\n"));
              }

            break;
          }
        default:
          {
            exit (EXIT_FAILURE);
          }
        }
    }
}

static void
rec2csv_generate_csv (rec_rset_t rset,
                      rec_fex_t fex)
{
  rec_mset_iterator_t iter;
  rec_fex_elem_t fex_elem;
  rec_record_t record;
  rec_field_t field;
  char *field_name_str;
  char *tmp;
  size_t i;

  /* Generate the row with headers.  */
  for (i = 0; i < rec_fex_size (fex); i++)
    {
      if (i != 0)
        {
          putc (',', stdout);
        }

      fex_elem = rec_fex_get (fex, i);
      field_name_str = xstrdup (rec_fex_elem_field_name_str (fex_elem));

      /* The header is FNAME or FNAME_N where N is the index starting
         at 1.  Note that we shall remove the trailing ':', if any. */

      if (field_name_str[strlen(field_name_str)-1] == ':')
        {
          field_name_str[strlen(field_name_str)-1] = '\0';
        }


      if (rec_fex_elem_min (fex_elem) != 0)
        {
          if (asprintf (&tmp, "%s_%d",
                        field_name_str,
                        rec_fex_elem_min (fex_elem) + 1) == -1)
            {
              recutl_fatal (_("out of memory"));
            }
        }
      else
        {
          if (asprintf (&tmp, "%s", field_name_str) == -1)
            {
              recutl_fatal (_("out of memory"));
            }
        }

      csv_fwrite (stdout, tmp, strlen(tmp));
      free (field_name_str);
      free (tmp);
    }

  putc ('\n', stdout);

  /* Generate the data rows.  */

  iter = rec_mset_iterator (rec_rset_mset (rset));
  while (rec_mset_iterator_next (&iter, MSET_RECORD, (const void**) &record, NULL))
    {
      for (i = 0; i < rec_fex_size (fex); i++)
        {
          if (i != 0)
            {
              putc (',', stdout);
            }

          fex_elem = rec_fex_get (fex, i);
          field = rec_record_get_field_by_name (record,
                                                rec_fex_elem_field_name (fex_elem),
                                                rec_fex_elem_min (fex_elem));
          if (field)
            {
              csv_fwrite (stdout,
                          rec_field_value (field),
                          strlen (rec_field_value (field)));
            }
        }

      putc ('\n', stdout);
    }

  rec_mset_iterator_free (&iter);
}

static rec_fex_t
rec2csv_determine_fields (rec_rset_t rset)
{
  rec_fex_t fields;
  rec_mset_iterator_t iter_rset;
  rec_mset_iterator_t iter_record;
  rec_record_t record;
  rec_field_t field;
  int field_index;
  
  fields = rec_fex_new (NULL, REC_FEX_SIMPLE);

  iter_rset = rec_mset_iterator (rec_rset_mset (rset));
  while (rec_mset_iterator_next (&iter_rset, MSET_RECORD, (const void **) &record, NULL))
    {
      iter_record = rec_mset_iterator (rec_record_mset (record));
      while (rec_mset_iterator_next (&iter_record, MSET_FIELD, (const void **) &field, NULL))
        {
          field_index = rec_record_get_field_index_by_name (record, field);
          
          if (!rec_fex_member_p (fields,
                                 rec_field_name (field),
                                 field_index, field_index))
            {
              rec_fex_append (fields,
                              rec_field_name (field),
                              field_index, field_index);
            }
        }

      rec_mset_iterator_free (&iter_record);
    }

  rec_mset_iterator_free (&iter_rset);

  return fields;
}

static bool
rec2csv_process_data (rec_db_t db)
{
  bool ret;
  rec_fex_t row_fields;
  size_t i;
  rec_rset_t rset;

  ret = true;

  for (i = 0; i < rec_db_size (db); i++)
    {
      rset = rec_db_get_rset (db, i);
      if (((rec2csv_record_type)
           && rec_rset_type (rset)
           && (strcmp (rec_rset_type (rset),
                       rec2csv_record_type) == 0))
          || (!rec2csv_record_type
              && (!rec_rset_type (rset) ||
                  (rec_db_size (db) == 1))))
        {
          /* Process this record set.  */

          rec_rset_sort (rset, rec2csv_sort_by_field);

          /* Build the fields that will appear in the row. */
          row_fields = rec2csv_determine_fields (rset);
  
          /* Generate the csv data.  */
          rec2csv_generate_csv (rset, row_fields);

          /* Cleanup.  */
          rec_fex_destroy (row_fields);
        }
    }

  return ret;
}

int
main (int argc, char *argv[])
{
  int res;
  rec_db_t db;

  res = 0;

  recutl_init ("rec2csv");

  /* Parse arguments.  */
  rec2csv_parse_args (argc, argv);

  /* Get the input data.  */
  db = recutl_build_db (argc, argv);
  if (!db)
    {
      res = 1;
    }

  /* Process the data.  */
  if (!rec2csv_process_data (db))
    {
      res = 1;
    }

  rec_db_destroy (db);
  
  return res;
}

/* End of rec2csv.c */