1
0

cmWriteFileCommand.cxx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. bool writable = false;
  40. // Set permissions to writable
  41. if (cmSystemTools::GetPermissions(fileName.c_str(), mode)) {
  42. #if defined(_MSC_VER) || defined(__MINGW32__)
  43. writable = mode & S_IWRITE;
  44. mode_t newMode = mode | S_IWRITE;
  45. #else
  46. writable = mode & S_IWUSR;
  47. mode_t newMode = mode | S_IWUSR | S_IWGRP;
  48. #endif
  49. if (!writable) {
  50. cmSystemTools::SetPermissions(fileName.c_str(), newMode);
  51. }
  52. }
  53. // If GetPermissions fails, pretend like it is ok. File open will fail if
  54. // the file is not writable
  55. cmsys::ofstream file(fileName.c_str(),
  56. overwrite ? std::ios::out : std::ios::app);
  57. if (!file) {
  58. std::string error = "Internal CMake error when trying to open file: ";
  59. error += fileName;
  60. error += " for writing.";
  61. this->SetError(error);
  62. return false;
  63. }
  64. file << message << std::endl;
  65. file.close();
  66. if (mode && !writable) {
  67. cmSystemTools::SetPermissions(fileName.c_str(), mode);
  68. }
  69. return true;
  70. }