diff options
author | John Wiegley <johnw@newartisans.com> | 2009-02-26 04:41:38 -0400 |
---|---|---|
committer | John Wiegley <johnw@newartisans.com> | 2009-02-26 04:41:38 -0400 |
commit | fbb734689b8989bb8bc5df8217b1469e084ca64b (patch) | |
tree | 2384d5cad88c82c50c885d24efa2e1129815b2b2 /src | |
parent | 513e2b59eb71de874cf685f887d74fc3b7792d8f (diff) | |
download | fork-ledger-fbb734689b8989bb8bc5df8217b1469e084ca64b.tar.gz fork-ledger-fbb734689b8989bb8bc5df8217b1469e084ca64b.tar.bz2 fork-ledger-fbb734689b8989bb8bc5df8217b1469e084ca64b.zip |
Added a new source_context function
Diffstat (limited to 'src')
-rw-r--r-- | src/error.cc | 36 | ||||
-rw-r--r-- | src/error.h | 5 | ||||
-rw-r--r-- | src/item.cc | 25 |
3 files changed, 43 insertions, 23 deletions
diff --git a/src/error.cc b/src/error.cc index ffcd2941..5a45318f 100644 --- a/src/error.cc +++ b/src/error.cc @@ -77,4 +77,40 @@ string line_context(const string& line, return buf.str(); } +string source_context(const path& file, + std::size_t pos, + std::size_t end_pos, + const string& prefix) +{ + std::size_t len = end_pos - pos; + if (! len) + return _("<no source context>"); + + assert(len > 0); + assert(len < 2048); + + std::ostringstream out; + + ifstream in(file); + in.seekg(pos, std::ios::beg); + + scoped_array<char> buf(new char[len + 1]); + in.read(buf.get(), len); + assert(static_cast<std::size_t>(in.gcount()) == len); + buf[len] = '\0'; + + bool first = true; + for (char * p = std::strtok(buf.get(), "\n"); + p; + p = std::strtok(NULL, "\n")) { + if (first) + first = false; + else + out << '\n'; + out << prefix << p; + } + + return out.str(); +} + } // namespace ledger diff --git a/src/error.h b/src/error.h index 2c0c4d09..1b4c7e12 100644 --- a/src/error.h +++ b/src/error.h @@ -81,6 +81,11 @@ string line_context(const string& line, std::size_t pos = 0, std::size_t end_pos = 0); +string source_context(const path& file, + std::size_t pos, + std::size_t end_pos, + const string& prefix = ""); + #define DECLARE_EXCEPTION(name, kind) \ class name : public kind { \ public: \ diff --git a/src/item.cc b/src/item.cc index 91a62ff7..f45e87e3 100644 --- a/src/item.cc +++ b/src/item.cc @@ -367,30 +367,9 @@ bool item_t::valid() const return true; } -void print_item(std::ostream& out, - const item_t& item, - const string& prefix) +void print_item(std::ostream& out, const item_t& item, const string& prefix) { - std::size_t len = item.end_pos - item.beg_pos; - - ifstream in(item.pathname); - in.seekg(item.beg_pos, std::ios::beg); - - scoped_array<char> buf(new char[len + 1]); - in.read(buf.get(), len); - assert(static_cast<std::size_t>(in.gcount()) == len); - buf[len] = '\0'; - - bool first = true; - for (char * p = std::strtok(buf.get(), "\n"); - p; - p = std::strtok(NULL, "\n")) { - if (first) - first = false; - else - out << '\n'; - out << prefix << p; - } + out << source_context(item.pathname, item.beg_pos, item.end_pos, prefix); } string item_context(const item_t& item, const string& desc) |