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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <exception>
#include <iterator>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "option.h"
#include "acconf.h"
#ifdef HAVE_UNIX_PIPES
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "fdstream.hpp"
#endif
#ifdef USE_BOOST_PYTHON
#include "pyledger.h"
#else
#include "ledger.h"
#endif
#include "debug.h"
using namespace ledger;
static inline
const std::string& either_or(const std::string& first,
const std::string& second)
{
if (first.empty())
return second;
else
return first;
}
#if 0
class print_addr : public repitem_t::select_callback_t {
virtual void operator()(repitem_t * item) {
std::cout << item << std::endl;
}
};
#endif
static int read_and_report(report_t * report, int argc, char * argv[],
char * envp[])
{
session_t& session(*report->session);
// Handle the command-line arguments
std::list<std::string> args;
process_arguments(argc - 1, argv + 1, false, report, args);
if (args.empty()) {
#if 0
help(std::cerr);
#endif
return 1;
}
strings_list::iterator arg = args.begin();
if (session.cache_file == "<none>")
session.use_cache = false;
else
session.use_cache = session.data_file.empty() && session.price_db.empty();
DEBUG_PRINT("ledger.session.cache", "1. use_cache = " << session.use_cache);
// Process the environment settings
TRACE(main, "Processing options and environment settings");
process_environment(const_cast<const char **>(envp), "LEDGER_", report);
const char * p = std::getenv("HOME");
std::string home = p ? p : "";
if (session.init_file.empty())
session.init_file = home + "/.ledgerrc";
if (session.price_db.empty())
session.price_db = home + "/.pricedb";
if (session.cache_file.empty())
session.cache_file = home + "/.ledger-cache";
if (session.data_file == session.cache_file)
session.use_cache = false;
DEBUG_PRINT("ledger.session.cache", "2. use_cache = " << session.use_cache);
TRACE(main, std::string("Initialization file is ") + session.init_file);
TRACE(main, std::string("Price database is ") + session.price_db);
TRACE(main, std::string("Binary cache is ") + session.cache_file);
TRACE(main, std::string("Main journal is ") + session.data_file);
TRACE(main, std::string("Based on option settings, binary cache ") +
(session.use_cache ? "WILL " : "will NOT ") + "be used");
// Read the command word and create a command object based on it
std::string verb = *arg++;
xml::xpath_t::functor_t * command = NULL;
if (false) {
;
}
#if 0
if (verb == "register" || verb == "reg" || verb == "r") {
command = new format_command
("register", either_or(report->format_string,
report->session->register_format));
}
else if (verb == "balance" || verb == "bal" || verb == "b") {
if (! report->raw_mode) {
report->transforms.push_back(new accounts_transform);
report->transforms.push_back(new clean_transform);
report->transforms.push_back(new compact_transform);
}
command = new format_command
("balance", either_or(report->format_string,
report->session->balance_format));
}
else if (verb == "print" || verb == "p") {
if (! report->raw_mode)
report->transforms.push_back(new optimize_transform);
command = new format_command
("print", either_or(report->format_string,
report->session->print_format));
}
else if (verb == "equity") {
if (! report->raw_mode)
report->transforms.push_back(new accounts_transform);
command = new format_command
("equity", either_or(report->format_string,
report->session->equity_format));
}
else if (verb == "entry")
command = new entry_command;
else if (verb == "dump")
command = new dump_command;
else if (verb == "output")
command = new output_command;
else if (verb == "prices")
command = new prices_command;
else if (verb == "pricesdb")
command = new pricesdb_command;
else if (verb == "csv")
command = new csv_command;
else if (verb == "emacs" || verb == "lisp")
command = new emacs_command;
#endif
else if (verb == "xml")
command = new xml_command;
else if (verb == "expr")
;
else if (verb == "xpath")
;
else if (verb == "parse") {
xml::xpath_t expr(*arg);
if (session.verbose_mode) {
std::cout << "Value expression tree:" << std::endl;
expr.dump(std::cout);
std::cout << std::endl;
std::cout << "Value expression parsed was:" << std::endl;
expr.write(std::cout);
std::cout << std::endl << std::endl;
std::cout << "Result of calculation: ";
}
std::cout << expr.calc((xml::document_t *)NULL, report).
strip_annotations() << std::endl;
return 0;
}
else {
char buf[128];
std::strcpy(buf, "command_");
std::strcat(buf, verb.c_str());
if (xml::xpath_t::op_t * def = report->lookup(buf))
command = def->functor_obj();
if (! command)
throw new error(std::string("Unrecognized command '") + verb + "'");
}
// Parse the initialization file, which can only be textual; then
// parse the journal data.
session.read_init();
journal_t * journal = session.read_data(report->account);
// Configure the output stream
#ifdef HAVE_UNIX_PIPES
int status, pfd[2]; // Pipe file descriptors
#endif
std::ostream * out = &std::cout;
if (! report->output_file.empty()) {
out = new std::ofstream(report->output_file.c_str());
}
#ifdef HAVE_UNIX_PIPES
else if (! report->pager.empty()) {
status = pipe(pfd);
if (status == -1)
throw new error("Failed to create pipe");
status = fork();
if (status < 0) {
throw new error("Failed to fork child process");
}
else if (status == 0) { // child
const char *arg0;
// Duplicate pipe's reading end into stdin
status = dup2(pfd[0], STDIN_FILENO);
if (status == -1)
perror("dup2");
// Close unuseful file descriptors: the pipe's writing and
// reading ends (the latter is not needed anymore, after the
// duplication).
close(pfd[1]);
close(pfd[0]);
// Find command name: its the substring starting right of the
// rightmost '/' character in the pager pathname. See manpage
// for strrchr.
arg0 = std::strrchr(report->pager.c_str(), '/');
if (arg0)
arg0++;
else
arg0 = report->pager.c_str(); // No slashes in pager.
execlp(report->pager.c_str(), arg0, (char *)0);
perror("execl");
exit(1);
}
else { // parent
close(pfd[0]);
out = new boost::fdostream(pfd[1]);
}
}
#endif
// Are we handling the expr commands? Do so now.
if (verb == "expr") {
xml::xpath_t expr(*arg);
if (session.verbose_mode) {
*out << "Value expression tree:" << std::endl;
expr.dump(*out);
*out << std::endl;
*out << "Value expression parsed was:" << std::endl;
expr.write(*out);
*out << std::endl << std::endl;
*out << "Result of calculation: ";
}
*out << expr.calc((xml::document_t *)NULL, report).
strip_annotations() << std::endl;
return 0;
}
else if (verb == "xpath") {
std::cout << "XPath parsed:" << std::endl;
xml::xpath_t xpath(*arg);
xpath.write(*out);
*out << std::endl;
#if 0
std::auto_ptr<repitem_t> items(repitem_t::wrap(&session, report, true));
print_addr cb;
items->select(path.get(), cb);
#endif
return 0;
}
// Cleanup memory -- if this is a beta or development build.
#if DEBUG_LEVEL >= BETA
{ TRACE_PUSH(cleanup, "Cleaning up allocated memory");
#ifdef USE_BOOST_PYTHON
shutdown_ledger_for_python();
#endif
if (! report->output_file.empty())
delete out;
TRACE_POP(cleanup, "Finished cleaning"); }
#endif
// Create the an argument scope containing the report command's
// arguments, and then invoke the command.
xml::xpath_t::scope_t * locals =
new xml::xpath_t::scope_t(report, xml::xpath_t::scope_t::ARGUMENT);
locals->args = new value_t::sequence_t;
locals->args.push_back(out);
locals->args.push_back(journal->document);
if (command->wants_args) {
#if 1
locals->args.push_back(&args);
#else
for (strings_list::iterator i = args.begin();
i != args.end();
i++)
locals->args.push_back(*i);
#endif
} else {
std::string regexps[4];
// Treat the remaining command-line arguments as regular
// expressions, used for refining report results.
int base = 0;
for (strings_list::iterator i = arg; i != args.end(); i++)
if ((*i)[0] == '-') {
if ((*i)[1] == '-') {
if (base == 0)
base += 2;
continue;
}
if (! regexps[base + 1].empty())
regexps[base + 1] += "|";
regexps[base + 1] += (*i).substr(1);
} else {
if (! regexps[base].empty())
regexps[base] += "|";
regexps[base] += *i;
}
#if 0
// jww (2006-09-21): Escape the \ in these strings!
if (! regexps[3].empty())
report->transforms.push_front
(new remove_transform
(std::string("//entry[payee =~ /(") + regexps[3] + ")/]"));
if (! regexps[2].empty())
report->transforms.push_front
(new select_transform
(std::string("//entry[payee =~ /(") + regexps[2] + ")/]"));
if (! regexps[1].empty())
report->transforms.push_front
(new remove_transform
(std::string("//xact[account =~ /(") + regexps[1] + ")/]"));
if (! regexps[0].empty())
report->transforms.push_front
(new select_transform
(std::string("//xact[account =~ /(") + regexps[0] + ")/]"));
#endif
}
#if 0
report->apply_transforms(items.get());
#endif
value_t temp;
(*command)(temp, locals);
// Write out the binary cache, if need be
if (session.use_cache && session.cache_dirty &&
! session.cache_file.empty()) {
TRACE_PUSH(binary_cache, "Writing journal file");
std::ofstream stream(session.cache_file.c_str());
#if 0
write_binary_journal(stream, journal);
#endif
TRACE_POP(binary_cache, "Finished writing");
}
// If the user specified a pager, wait for it to exit now
#ifdef HAVE_UNIX_PIPES
if (report->output_file.empty() && ! report->pager.empty()) {
delete out;
close(pfd[1]);
// Wait for child to finish
wait(&status);
if (status & 0xffff != 0)
throw new error("Something went wrong in the pager");
}
#endif
return 0;
}
int main(int argc, char * argv[], char * envp[])
{
try {
std::ios::sync_with_stdio(false);
ledger::tracing_active = true;
#if DEBUG_LEVEL < BETA
ledger::do_cleanup = false;
#endif
TRACE_PUSH(main, "Ledger starting");
std::auto_ptr<ledger::session_t> session(new ledger::session_t);
#if 0
session->register_parser(new binary_parser_t);
#endif
#if defined(HAVE_EXPAT) || defined(HAVE_XMLPARSE)
session->register_parser(new xml_parser_t);
session->register_parser(new gnucash_parser_t);
#endif
#ifdef HAVE_LIBOFX
session->register_parser(new ofx_parser_t);
#endif
session->register_parser(new qif_parser_t);
session->register_parser(new textual_parser_t);
std::auto_ptr<ledger::report_t> report(new ledger::report_t(session.get()));
int status = read_and_report(report.get(), argc, argv, envp);
if (! ledger::do_cleanup) {
report.release();
session.release();
}
TRACE_POP(main, "Ledger done");
DEBUG_IF("ledger.trace.memory") {
report_memory(std::cout);
}
ledger::tracing_active = false;
return status;
}
catch (error * err) {
std::cout.flush();
// Push a null here since there's no file context
if (err->context.empty() ||
! dynamic_cast<xact_context *>(err->context.front()))
err->context.push_front(new error_context(""));
err->reveal_context(std::cerr, "Error");
std::cerr << err->what() << std::endl;
delete err;
ledger::tracing_active = false;
return 1;
}
catch (fatal * err) {
std::cout.flush();
// Push a null here since there's no file context
if (err->context.empty() ||
! dynamic_cast<xact_context *>(err->context.front()))
err->context.push_front(new error_context(""));
err->reveal_context(std::cerr, "Fatal");
std::cerr << err->what() << std::endl;
delete err;
ledger::tracing_active = false;
return 1;
}
catch (const std::exception& err) {
std::cout.flush();
std::cerr << "Error: " << err.what() << std::endl;
ledger::tracing_active = false;
return 1;
}
catch (int status) {
ledger::tracing_active = false;
return status;
}
}
// main.cc ends here.
|