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