Implement journaling. Bug #17240.
[pspp-builds.git] / src / output / journal.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007 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 <output/journal.h>
20
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include <libpspp/str.h>
26
27 #include "fwriteerror.h"
28 #include "error.h"
29 #include "xalloc.h"
30
31 #include "gettext.h"
32 #define _(msgid) gettext (msgid)
33
34 /* Journaling enabled? */
35 static bool journal_enabled = false;
36
37 /* Name of the journal file. */
38 static char *journal_file_name = NULL;
39
40 /* Journal file. */
41 static FILE *journal_file = NULL;
42
43 /* Enables journaling. */
44 void
45 journal_enable (void)
46 {
47   journal_enabled = true;
48 }
49
50 /* Disables journaling. */
51 void
52 journal_disable (void)
53 {
54   journal_enabled = false;
55   if (journal_file != NULL)
56     fflush (journal_file);
57 }
58
59 /* Sets the name of the journal file to FILE_NAME. */
60 void
61 journal_set_file_name (const char *file_name)
62 {
63   assert (file_name != NULL);
64
65   if (journal_file != NULL)
66     {
67       if (fwriteerror (journal_file))
68         error (0, errno, _("error writing \"%s\""), journal_file_name);
69     }
70
71   free (journal_file_name);
72   journal_file_name = xstrdup (file_name);
73 }
74
75 /* Writes LINE to the journal file (if journaling is enabled).
76    If PREFIX is non-null, the line will be prefixed by "> ". */
77 void
78 journal_write (bool prefix, const char *line)
79 {
80   if (!journal_enabled)
81     return;
82
83   if (journal_file == NULL)
84     {
85       if (journal_file_name == NULL)
86         journal_file_name = xstrdup ("pspp.jnl");
87       journal_file = fopen (journal_file_name, "w");
88       if (journal_file == NULL)
89         {
90           error (0, errno, _("error creating \"%s\""), journal_file_name);
91           journal_enabled = false;
92           return;
93         }
94     }
95
96   if (prefix)
97     fputs ("> ", journal_file);
98   fputs (line, journal_file);
99   if (strchr (line, '\n') == NULL)
100     putc ('\n', journal_file);
101 }