cmWriteFileCommand.cxx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 = 0;
  49. // Set permissions to writable
  50. if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
  51. {
  52. cmSystemTools::SetPermissions(fileName.c_str(),
  53. #if defined( _MSC_VER ) || defined( __MINGW32__ )
  54. mode | S_IWRITE
  55. #else
  56. mode | S_IWUSR | S_IWGRP
  57. #endif
  58. );
  59. }
  60. // If GetPermissions fails, pretend like it is ok. File open will fail if
  61. // the file is not writable
  62. std::ofstream file(fileName.c_str(),
  63. overwrite?std::ios::out : std::ios::app);
  64. if ( !file )
  65. {
  66. std::string error = "Internal CMake error when trying to open file: ";
  67. error += fileName.c_str();
  68. error += " for writing.";
  69. this->SetError(error.c_str());
  70. return false;
  71. }
  72. file << message << std::endl;
  73. file.close();
  74. if(mode)
  75. {
  76. cmSystemTools::SetPermissions(fileName.c_str(), mode);
  77. }
  78. return true;
  79. }