cmWriteFileCommand.cxx 2.4 KB

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