Added a new source_context function

This commit is contained in:
John Wiegley 2009-02-26 04:41:38 -04:00
parent 513e2b59eb
commit fbb734689b
3 changed files with 43 additions and 23 deletions

View file

@ -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

View file

@ -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: \

View file

@ -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)