cmWriteFileCommand.cxx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #include "cmWriteFileCommand.h"
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. // cmLibraryCommand
  14. bool cmWriteFileCommand
  15. ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
  16. {
  17. if(args.size() < 2 )
  18. {
  19. this->SetError("called with incorrect number of arguments");
  20. return false;
  21. }
  22. std::string message;
  23. std::vector<std::string>::const_iterator i = args.begin();
  24. std::string fileName = *i;
  25. bool overwrite = true;
  26. i++;
  27. for(;i != args.end(); ++i)
  28. {
  29. if ( *i == "APPEND" )
  30. {
  31. overwrite = false;
  32. }
  33. else
  34. {
  35. message += *i;
  36. }
  37. }
  38. if ( !this->Makefile->CanIWriteThisFile(fileName.c_str()) )
  39. {
  40. std::string e = "attempted to write a file: " + fileName
  41. + " into a source directory.";
  42. this->SetError(e.c_str());
  43. cmSystemTools::SetFatalErrorOccured();
  44. return false;
  45. }
  46. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  47. cmSystemTools::MakeDirectory(dir.c_str());
  48. mode_t mode =
  49. #if defined( _MSC_VER ) || defined( __MINGW32__ )
  50. S_IREAD | S_IWRITE
  51. #elif defined( __BORLANDC__ )
  52. S_IRUSR | S_IWUSR
  53. #else
  54. 0666
  55. #endif
  56. ;
  57. // Set permissions to writable
  58. if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
  59. {
  60. cmSystemTools::SetPermissions(fileName.c_str(),
  61. #if defined( _MSC_VER ) || defined( __MINGW32__ )
  62. S_IREAD | S_IWRITE
  63. #else
  64. 0666
  65. #endif
  66. );
  67. }
  68. // If GetPermissions fails, pretend like it is ok. File open will fail if
  69. // the file is not writable
  70. std::ofstream file(fileName.c_str(),
  71. overwrite?std::ios::out : std::ios::app);
  72. if ( !file )
  73. {
  74. std::string error = "Internal CMake error when trying to open file: ";
  75. error += fileName.c_str();
  76. error += " for writing.";
  77. this->SetError(error.c_str());
  78. return false;
  79. }
  80. file << message << std::endl;
  81. file.close();
  82. cmSystemTools::SetPermissions(fileName.c_str(), mode);
  83. return true;
  84. }