Rewrite the "print" command as a custom function

There ended up being too many corner cases for the generalized formatter
to handle.
This commit is contained in:
John Wiegley 2010-03-07 22:47:07 -05:00
parent 7e79cd82cd
commit 75b7294a6d
16 changed files with 362 additions and 102 deletions

View file

@ -38,7 +38,7 @@
#include "journal.h"
#include "session.h"
#include "report.h"
#include "output.h"
#include "print.h"
namespace ledger {
@ -520,10 +520,7 @@ value_t xact_command(call_scope_t& args)
// Only consider actual postings for the "xact" command
report.HANDLER(limit_).on(string("#xact"), "actual");
report.xact_report(post_handler_ptr
(new format_posts(report,
report.HANDLER(print_format_).str())),
*new_xact);
report.xact_report(post_handler_ptr(new print_xacts(report)), *new_xact);
return true;
}

View file

@ -65,8 +65,8 @@ bool item_t::has_tag(const mask_t& tag_mask,
if (tag_mask.match(data.first)) {
if (! value_mask)
return true;
else if (data.second)
return value_mask->match(*data.second);
else if (data.second.first)
return value_mask->match(*data.second.first);
}
}
}
@ -81,7 +81,7 @@ optional<string> item_t::get_tag(const string& tag) const
string_map::const_iterator i = metadata->find(tag);
if (i != metadata->end()) {
DEBUG("item.meta", "Found the item!");
return (*i).second;
return (*i).second.first;
}
}
return none;
@ -94,25 +94,33 @@ optional<string> item_t::get_tag(const mask_t& tag_mask,
foreach (const string_map::value_type& data, *metadata) {
if (tag_mask.match(data.first) &&
(! value_mask ||
(data.second && value_mask->match(*data.second))))
return data.second;
(data.second.first && value_mask->match(*data.second.first))))
return data.second.first;
}
}
return none;
}
void item_t::set_tag(const string& tag,
item_t::string_map::iterator item_t::set_tag(const string& tag,
const optional<string>& value)
{
assert(! tag.empty());
if (! metadata)
metadata = string_map();
DEBUG("item.meta", "Setting tag '" << tag << "' to value '"
<< (value ? *value : string("<none>")) << "'");
optional<string> data = value;
if (data && data->empty())
data = none;
std::pair<string_map::iterator, bool> result
= metadata->insert(string_map::value_type(tag, value));
= metadata->insert(string_map::value_type(tag, tag_data_t(data, false)));
assert(result.second);
return result.first;
}
void item_t::parse_tags(const char * p,
@ -149,15 +157,19 @@ void item_t::parse_tags(const char * p,
q = std::strtok(NULL, " \t")) {
const string::size_type len = std::strlen(q);
if (! tag.empty()) {
if (! has_tag(tag))
set_tag(tag, string(p + (q - buf.get())));
if (! has_tag(tag)) {
string_map::iterator i = set_tag(tag, string(p + (q - buf.get())));
(*i).second.second = true;
}
break;
}
else if (q[0] == ':' && q[len - 1] == ':') { // a series of tags
for (char * r = std::strtok(q + 1, ":");
r;
r = std::strtok(NULL, ":"))
set_tag(r);
r = std::strtok(NULL, ":")) {
string_map::iterator i = set_tag(r);
(*i).second.second = true;
}
}
else if (q[len - 1] == ':') { // a metadata setting
tag = string(q, len - 1);

View file

@ -106,7 +106,8 @@ public:
enum state_t { UNCLEARED = 0, CLEARED, PENDING };
typedef std::map<string, optional<string> > string_map;
typedef std::pair<optional<string>, bool> tag_data_t;
typedef std::map<string, tag_data_t> string_map;
state_t _state;
optional<date_t> _date;
@ -156,7 +157,7 @@ public:
virtual optional<string> get_tag(const mask_t& tag_mask,
const optional<mask_t>& value_mask = none) const;
virtual void set_tag(const string& tag,
virtual string_map::iterator set_tag(const string& tag,
const optional<string>& value = none);
virtual void parse_tags(const char * p,

View file

@ -42,10 +42,8 @@ namespace ledger {
format_posts::format_posts(report_t& _report,
const string& format,
bool _print_raw,
const optional<string>& _prepend_format)
: report(_report), last_xact(NULL), last_post(NULL),
print_raw(_print_raw)
: report(_report), last_xact(NULL), last_post(NULL)
{
TRACE_CTOR(format_posts, "report&, const string&, bool");
@ -80,24 +78,8 @@ void format_posts::operator()(post_t& post)
{
std::ostream& out(report.output_stream);
if (print_raw) {
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
out << between_format(xact_scope);
}
print_item(out, *post.xact);
out << '\n';
last_xact = post.xact;
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
else if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
bind_scope_t bound_scope(report, post);
if (prepend_format)

View file

@ -63,11 +63,9 @@ protected:
format_t prepend_format;
xact_t * last_xact;
post_t * last_post;
bool print_raw;
public:
format_posts(report_t& _report, const string& format,
bool _print_raw = false,
const optional<string>& _prepend_format = none);
virtual ~format_posts() {
TRACE_DTOR(format_posts);

View file

@ -576,7 +576,7 @@ void to_xml(std::ostream& out, const post_t& post)
if (post.metadata) {
push_xml y(out, "metadata");
foreach (const item_t::string_map::value_type& pair, *post.metadata) {
if (pair.second) {
if (pair.second.first) {
push_xml z(out, "variable");
{
push_xml z(out, "key");
@ -584,7 +584,7 @@ void to_xml(std::ostream& out, const post_t& post)
}
{
push_xml z(out, "value");
out << y.guard(*pair.second);
out << y.guard(*pair.second.first);
}
} else {
push_xml z(out, "tag");

View file

@ -52,10 +52,11 @@ class account_t;
class post_t : public item_t
{
public:
#define POST_VIRTUAL 0x10 // the account was specified with (parens)
#define POST_MUST_BALANCE 0x20 // posting must balance in the transaction
#define POST_CALCULATED 0x40 // posting's amount was calculated
#define POST_COST_CALCULATED 0x80 // posting's cost was calculated
#define POST_VIRTUAL 0x08 // the account was specified with (parens)
#define POST_MUST_BALANCE 0x10 // posting must balance in the transaction
#define POST_CALCULATED 0x20 // posting's amount was calculated
#define POST_COST_CALCULATED 0x40 // posting's cost was calculated
#define POST_COST_IN_FULL 0x80 // cost specified using @@
xact_t * xact; // only set for posts of regular xacts
account_t * account;

208
src/print.cc Normal file
View file

@ -0,0 +1,208 @@
/*
* Copyright (c) 2003-2010, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "print.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"
namespace ledger {
print_xacts::print_xacts(report_t& _report,
bool _print_raw)
: report(_report), print_raw(_print_raw)
{
TRACE_CTOR(print_xacts, "report&, bool");
}
namespace {
void print_note(std::ostream& out, const string& note)
{
if (note.length() > 15)
out << "\n ;";
else
out << " ;";
bool need_separator = false;
for (const char * p = note.c_str(); *p; p++) {
if (*p == '\n') {
need_separator = true;
} else {
if (need_separator) {
out << "\n ;";
need_separator = false;
}
out << *p;
}
}
}
void print_xact(report_t& report, std::ostream& out, xact_t& xact)
{
// jww (2010-03-07): Also add support for --raw
out << format_date(item_t::use_effective_date ?
xact.date() : xact.actual_date(),
FMT_WRITTEN);
if (! item_t::use_effective_date && xact.effective_date())
out << '=' << format_date(*xact.effective_date(), FMT_WRITTEN);
out << ' ';
// jww (2010-03-06): Output posting state, if different
out << (xact.state() == item_t::CLEARED ? "* " :
(xact.state() == item_t::PENDING ? "! " : ""));
if (xact.code)
out << '(' << *xact.code << ") ";
out << xact.payee;
if (xact.note)
print_note(out, *xact.note);
out << '\n';
if (xact.metadata) {
foreach (const item_t::string_map::value_type& data, *xact.metadata) {
if (! data.second.second) {
out << " ; ";
if (data.second.first)
out << data.first << ": " << *data.second.first;
else
out << ':' << data.first << ":";
out << '\n';
}
}
}
foreach (post_t * post, xact.posts) {
if (post->has_flags(ITEM_TEMP | ITEM_GENERATED) &&
! report.HANDLED(print_virtual))
continue;
out << " ";
// jww (2010-03-06): Output posting state, if different
std::ostringstream buf;
if (post->has_flags(POST_VIRTUAL)) {
if (post->has_flags(POST_MUST_BALANCE))
buf << '[';
else
buf << '(';
}
buf << post->account->fullname();
if (post->has_flags(POST_VIRTUAL)) {
if (post->has_flags(POST_MUST_BALANCE))
buf << ']';
else
buf << ')';
}
if (! post->has_flags(POST_CALCULATED) || report.HANDLED(print_virtual)) {
unistring name(buf.str());
out << name.extract();
int slip = 36 - static_cast<int>(name.length());
if (slip > 0)
out << string(slip, ' ');
std::ostringstream amt_str;
report.scrub(post->amount).print(amt_str, 12, -1, true);
string amt = amt_str.str();
string trimmed_amt(amt);
trim_left(trimmed_amt);
int amt_slip = (static_cast<int>(amt.length()) -
static_cast<int>(trimmed_amt.length()));
if (slip + amt_slip < 2)
out << string(2 - (slip + amt_slip), ' ');
out << amt;
if (post->cost && ! post->has_flags(POST_CALCULATED)) {
if (post->has_flags(POST_COST_IN_FULL))
out << " @@ " << report.scrub(post->cost->abs());
else
out << " @ " << report.scrub((*post->cost / post->amount).abs());
}
if (post->assigned_amount)
out << " = " << report.scrub(*post->assigned_amount);
} else {
out << buf.str();
}
if (post->note)
print_note(out, *post->note);
out << '\n';
}
}
}
void print_xacts::flush()
{
std::ostream& out(report.output_stream);
bool first = true;
foreach (xact_t * xact, xacts) {
if (first)
first = false;
else
out << '\n';
if (print_raw) {
print_item(out, *xact);
out << '\n';
} else {
print_xact(report, out, *xact);
}
}
out.flush();
}
void print_xacts::operator()(post_t& post)
{
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (xacts_present.find(post.xact) == xacts_present.end()) {
xacts_present.insert(xacts_present_map::value_type(post.xact, true));
xacts.push_back(post.xact);
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
}
}
} // namespace ledger

79
src/print.h Normal file
View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2003-2010, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @addtogroup data
*/
/**
* @file convert.h
* @author John Wiegley
*
* @ingroup data
*/
#ifndef _PRINT_H
#define _PRINT_H
#include "chain.h"
#include "predicate.h"
#include "format.h"
namespace ledger {
class xact_t;
class post_t;
class report_t;
class print_xacts : public item_handler<post_t>
{
protected:
typedef std::list<xact_t *> xacts_list;
typedef std::map<xact_t *, bool> xacts_present_map;
report_t& report;
xacts_present_map xacts_present;
xacts_list xacts;
bool print_raw;
public:
print_xacts(report_t& _report, bool _print_raw = false);
virtual ~print_xacts() {
TRACE_DTOR(print_xacts);
}
virtual void flush();
virtual void operator()(post_t& post);
};
} // namespace ledger
#endif // _PRINT_H

View file

@ -37,6 +37,7 @@
#include "format.h"
#include "query.h"
#include "output.h"
#include "print.h"
#include "iterators.h"
#include "filters.h"
#include "precmd.h"
@ -410,15 +411,20 @@ value_t report_t::fn_trim(call_scope_t& args)
}
}
value_t report_t::fn_scrub(call_scope_t& args)
value_t report_t::scrub(value_t val)
{
value_t temp(args.value().strip_annotations(what_to_keep()));
value_t temp(val.strip_annotations(what_to_keep()));
if (HANDLED(base))
return temp;
else
return temp.unreduced();
}
value_t report_t::fn_scrub(call_scope_t& args)
{
return scrub(args.value());
}
value_t report_t::fn_rounded(call_scope_t& args)
{
return args.value().rounded();
@ -880,9 +886,9 @@ option_t<report_t> * report_t::lookup_option(const char * p)
else OPT(price);
else OPT(prices_format_);
else OPT(pricedb_format_);
else OPT(print_format_);
else OPT(payee_width_);
else OPT(prepend_format_);
else OPT(print_virtual);
break;
case 'q':
OPT(quantity);
@ -1200,7 +1206,6 @@ expr_t::ptr_op_t report_t::lookup(const symbol_t::kind_t kind,
else if (is_eq(p, "cleared")) {
HANDLER(amount_).set_expr(string("#cleared"),
"(amount, cleared ? amount : 0)");
return expr_t::op_t::wrap_functor
(reporter<account_t, acct_handler_ptr, &report_t::accounts_report>
(new format_accounts(*this, report_format(HANDLER(cleared_format_)),
@ -1212,11 +1217,10 @@ expr_t::ptr_op_t report_t::lookup(const symbol_t::kind_t kind,
break;
case 'e':
if (is_eq(p, "equity"))
return WRAP_FUNCTOR
(reporter<>
(new format_posts(*this, report_format(HANDLER(print_format_))),
*this, "#equity"));
if (is_eq(p, "equity")) {
HANDLER(print_virtual).on_only(string("#equity"));
return WRAP_FUNCTOR(reporter<>(new print_xacts(*this), *this, "#equity"));
}
else if (is_eq(p, "entry"))
return WRAP_FUNCTOR(xact_command);
else if (is_eq(p, "emacs"))
@ -1229,9 +1233,7 @@ expr_t::ptr_op_t report_t::lookup(const symbol_t::kind_t kind,
case 'p':
if (*(p + 1) == '\0' || is_eq(p, "print"))
return WRAP_FUNCTOR
(reporter<>
(new format_posts(*this, report_format(HANDLER(print_format_)),
HANDLED(raw)), *this, "#print"));
(reporter<>(new print_xacts(*this, HANDLED(raw)), *this, "#print"));
else if (is_eq(p, "prices"))
return expr_t::op_t::wrap_functor
(reporter<post_t, post_handler_ptr, &report_t::commodities_report>
@ -1251,7 +1253,7 @@ expr_t::ptr_op_t report_t::lookup(const symbol_t::kind_t kind,
return WRAP_FUNCTOR
(reporter<>
(new format_posts(*this, report_format(HANDLER(register_format_)),
false, maybe_format(HANDLER(prepend_format_))),
maybe_format(HANDLER(prepend_format_))),
*this, "#register"));
else if (is_eq(p, "reload"))
return MAKE_FUNCTOR(report_t::reload_command);
@ -1286,11 +1288,13 @@ expr_t::ptr_op_t report_t::lookup(const symbol_t::kind_t kind,
return WRAP_FUNCTOR(format_command);
break;
case 'g':
if (is_eq(p, "generate"))
if (is_eq(p, "generate")) {
HANDLER(print_virtual).on_only(string("#generate"));
return expr_t::op_t::wrap_functor
(reporter<post_t, post_handler_ptr, &report_t::generate_report>
(new format_posts(*this, report_format(HANDLER(print_format_)),
false), *this, "#generate"));
(new print_xacts(*this), *this, "#generate"));
}
break;
case 'p':
if (is_eq(p, "parse"))
return WRAP_FUNCTOR(parse_command);

View file

@ -144,6 +144,7 @@ public:
value_t fn_is_seq(call_scope_t& scope);
value_t fn_strip(call_scope_t& scope);
value_t fn_trim(call_scope_t& scope);
value_t scrub(value_t val);
value_t fn_scrub(call_scope_t& scope);
value_t fn_quantity(call_scope_t& scope);
value_t fn_rounded(call_scope_t& scope);
@ -280,7 +281,7 @@ public:
HANDLER(price).report(out);
HANDLER(prices_format_).report(out);
HANDLER(pricedb_format_).report(out);
HANDLER(print_format_).report(out);
HANDLER(print_virtual).report(out);
HANDLER(quantity).report(out);
HANDLER(quarterly).report(out);
HANDLER(raw).report(out);
@ -748,23 +749,7 @@ public:
"P %(datetime) %(account) %(scrub(display_amount))\n");
});
OPTION__(report_t, print_format_, CTOR(report_t, print_format_) {
on(none,
"%(xact.date)"
"%(!effective & xact.effective_date ?"
" \"=\" + xact.effective_date : \"\")"
"%(xact.cleared ? \" *\" : (xact.pending ? \" !\" : \"\"))"
"%(code ? \" (\" + code + \")\" :"
" \"\") %(payee)%(xact.comment)\n"
" %(xact.uncleared ?"
" (cleared ? \"* \" : (pending ? \"! \" : \"\")) : \"\")"
"%(calculated ? account : justify(account, 34, -1, false))"
"%(calculated ? \"\" : \" \" + justify(scrub(amount), 12, -1, true))"
"%(has_cost & !cost_calculated ?"
" \" @ \" + justify(scrub(abs(cost / amount)), 0) : \"\")"
"%(comment)\n%/"
" %$7%$8%$9%$A%$B\n%/\n");
});
OPTION(report_t, print_virtual);
OPTION_(report_t, quantity, DO() { // -O
parent->HANDLER(revalued).off();

View file

@ -1031,6 +1031,7 @@ post_t * instance_t::parse_post(char * line,
if (*++next == '@') {
per_unit = false;
post->add_flags(POST_COST_IN_FULL);
DEBUG("textual.parse", "line " << linenum << ": "
<< "And it's for a total price");
}

View file

@ -755,7 +755,7 @@ void to_xml(std::ostream& out, const xact_t& xact)
if (xact.metadata) {
push_xml y(out, "metadata");
foreach (const item_t::string_map::value_type& pair, *xact.metadata) {
if (pair.second) {
if (pair.second.first) {
push_xml z(out, "variable");
{
push_xml w(out, "key");
@ -763,7 +763,7 @@ void to_xml(std::ostream& out, const xact_t& xact)
}
{
push_xml w(out, "value");
out << y.guard(*pair.second);
out << y.guard(*pair.second.first);
}
} else {
push_xml z(out, "tag");

View file

@ -1,10 +0,0 @@
print --print-format='%(amount)\n'
<<<
2007/02/02 RD VMMXX
Assets:Investments:Vanguard:VMMXX 0.350 VMMXX @ $1.00
Income:Dividends:Vanguard:VMMXX $-0.35
>>>1
0.350 VMMXX {$1.00} [2007/02/02]
$-0.35
>>>2
=== 0

View file

@ -77,6 +77,7 @@ libledger_report_la_SOURCES = \
src/draft.cc \
src/emacs.cc \
src/xml.cc \
src/print.cc \
src/output.cc \
src/precmd.cc \
src/chain.cc \
@ -140,6 +141,7 @@ pkginclude_HEADERS = \
src/draft.h \
src/generate.h \
src/stats.h \
src/print.h \
src/output.h \
src/xml.h \
src/emacs.h \