cmWriteFileCommand.cxx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmWriteFileCommand.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmMakefile.h"
  6. #include "cmSystemTools.h"
  7. #include "cm_sys_stat.h"
  8. class cmExecutionStatus;
  9. // cmLibraryCommand
  10. bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args,
  11. cmExecutionStatus&)
  12. {
  13. if (args.size() < 2) {
  14. this->SetError("called with incorrect number of arguments");
  15. return false;
  16. }
  17. std::string message;
  18. std::vector<std::string>::const_iterator i = args.begin();
  19. std::string const& fileName = *i;
  20. bool overwrite = true;
  21. i++;
  22. for (; i != args.end(); ++i) {
  23. if (*i == "APPEND") {
  24. overwrite = false;
  25. } else {
  26. message += *i;
  27. }
  28. }
  29. if (!this->Makefile->CanIWriteThisFile(fileName)) {
  30. std::string e =
  31. "attempted to write a file: " + fileName + " into a source directory.";
  32. this->SetError(e);
  33. cmSystemTools::SetFatalErrorOccured();
  34. return false;
  35. }
  36. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  37. cmSystemTools::MakeDirectory(dir);
  38. mode_t mode = 0;
  39. // Set permissions to writable
  40. if (cmSystemTools::GetPermissions(fileName.c_str(), mode)) {
  41. cmSystemTools::SetPermissions(fileName.c_str(),
  42. #if defined(_MSC_VER) || defined(__MINGW32__)
  43. mode | S_IWRITE
  44. #else
  45. mode | S_IWUSR | S_IWGRP
  46. #endif
  47. );
  48. }
  49. // If GetPermissions fails, pretend like it is ok. File open will fail if
  50. // the file is not writable
  51. cmsys::ofstream file(fileName.c_str(),
  52. overwrite ? std::ios::out : std::ios::app);
  53. if (!file) {
  54. std::string error = "Internal CMake error when trying to open file: ";
  55. error += fileName;
  56. error += " for writing.";
  57. this->SetError(error);
  58. return false;
  59. }
  60. file << message << std::endl;
  61. file.close();
  62. if (mode) {
  63. cmSystemTools::SetPermissions(fileName.c_str(), mode);
  64. }
  65. return true;
  66. }