cmWriteFileCommand.cxx 2.2 KB

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