snippet_extractor.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright Frank Mori Hess 2009.
  2. //
  3. // Quick hack to extract code snippets from example programs, so
  4. // they can be included into boostbook.
  5. //
  6. // Use, modification and
  7. // distribution is subject to the Boost Software License, Version
  8. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. #include <fstream>
  11. #include <iostream>
  12. #include <sstream>
  13. #include <stdexcept>
  14. int main(int argc, const char *argv[])
  15. {
  16. if(argc < 3)
  17. {
  18. std::cerr << "Too few arguments: need output directory and input file name(s).\n";
  19. return -1;
  20. }
  21. static const std::string output_directory = argv[1];
  22. static const int num_files = argc - 2;
  23. int i;
  24. for(i = 0; i < num_files; ++i)
  25. {
  26. const std::string file_name = argv[2 + i];
  27. std::cout << "opening file: " << file_name << std::endl;
  28. std::ifstream infile(file_name.c_str());
  29. bool inside_snippet = false;
  30. std::ofstream snippet_out_file;
  31. while(infile.good())
  32. {
  33. std::string line;
  34. getline(infile, line);
  35. if(infile.bad()) break;
  36. if(inside_snippet)
  37. {
  38. size_t snippet_end_pos = line.find("//]");
  39. if(snippet_end_pos == std::string::npos)
  40. {
  41. snippet_out_file << line << "\n";
  42. }else
  43. {
  44. snippet_out_file << "]]></code>";
  45. inside_snippet = false;
  46. std::cout << "done.\n";
  47. continue;
  48. }
  49. }else
  50. {
  51. size_t snippet_start_pos = line.find("//[");
  52. if(snippet_start_pos == std::string::npos)
  53. {
  54. continue;
  55. }else
  56. {
  57. inside_snippet = true;
  58. std::string snippet_name = line.substr(snippet_start_pos + 3);
  59. std::istringstream snippet_stream(snippet_name);
  60. snippet_stream >> snippet_name;
  61. if(snippet_name == "")
  62. {
  63. throw std::runtime_error("failed to obtain snippet name");
  64. }
  65. snippet_out_file.close();
  66. snippet_out_file.clear();
  67. snippet_out_file.open(std::string(output_directory + "/" + snippet_name + ".xml").c_str());
  68. snippet_out_file << "<!-- Code snippet \"" << snippet_name <<
  69. "\" extracted from \"" << file_name << "\" by snippet_extractor.\n" <<
  70. "--><code><![CDATA[";
  71. std::cout << "processing snippet \"" << snippet_name << "\"... ";
  72. continue;
  73. }
  74. }
  75. }
  76. }
  77. return 0;
  78. }