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