Build tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compdb.cc 1.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "compdb.h"
  2. namespace compdb {
  3. std::string escape(const std::string &str) {
  4. std::string out;
  5. out.reserve(str.size() * 1.5);
  6. // TODO: Handle unicode according to JSON spec
  7. for (char ch: str) {
  8. if (ch == '\\' || ch == '\"') {
  9. out += '\\';
  10. out += ch;
  11. } else if (ch == '\r') {
  12. out += '\\';
  13. out += 'r';
  14. } else if (ch == '\n') {
  15. out += '\\';
  16. out += 'n';
  17. } else {
  18. out += ch;
  19. }
  20. }
  21. return out;
  22. }
  23. void Writer::write(
  24. const std::string &dir, const std::string &file,
  25. const std::vector<std::string> &cmd) {
  26. if (first_) {
  27. stream_ << "[\n\t{\n";
  28. first_ = false;
  29. } else {
  30. stream_ << ", {\n";
  31. }
  32. stream_
  33. << "\t\t\"directory\": \"" << escape(dir) << "\",\n"
  34. << "\t\t\"file\": \"" << escape(file) << "\",\n"
  35. << "\t\t\"command\": \"" << escape(cmd[0]);
  36. for (size_t i = 1; i < cmd.size(); ++i) {
  37. stream_ << ' ' << escape('"' + escape(cmd[i]) + '"');
  38. }
  39. stream_ << "\"\n\t}";
  40. }
  41. Writer::~Writer() {
  42. if (first_) {
  43. stream_ << "[]\n";
  44. } else {
  45. stream_ << "\n]\n";
  46. }
  47. }
  48. }