TZIVI-254: IVI needs a newer version of cmake
[profile/ivi/cmake.git] / Source / cmSystemTools.h
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 #ifndef cmSystemTools_h
13 #define cmSystemTools_h
14
15 #include "cmStandardIncludes.h"
16
17 #include <cmsys/SystemTools.hxx>
18 #include <cmsys/Process.h>
19
20 class cmSystemToolsFileTime;
21
22 /** \class cmSystemTools
23  * \brief A collection of useful functions for CMake.
24  *
25  * cmSystemTools is a class that provides helper functions
26  * for the CMake build system.
27  */
28 class cmSystemTools: public cmsys::SystemTools
29 {
30 public:
31   typedef cmsys::SystemTools Superclass;
32
33   /** Expand out any arguments in the vector that have ; separated
34    *  strings into multiple arguments.  A new vector is created
35    *  containing the expanded versions of all arguments in argsIn.
36    */
37   static void ExpandList(std::vector<std::string> const& argsIn,
38                          std::vector<std::string>& argsOut);
39   static void ExpandListArgument(const std::string& arg,
40                                  std::vector<std::string>& argsOut,
41                                  bool emptyArgs=false);
42
43   /**
44    * Look for and replace registry values in a string
45    */
46   static void ExpandRegistryValues(std::string& source,
47                                    KeyWOW64 view = KeyWOW64_Default);
48
49   ///! Escape quotes in a string.
50   static std::string EscapeQuotes(const char* str);
51
52   /**
53    * Returns a string that has whitespace removed from the start and the end.
54    */
55   static std::string TrimWhitespace(const std::string& s);
56
57   typedef  void (*ErrorCallback)(const char*, const char*, bool&, void*);
58   /**
59    *  Set the function used by GUI's to display error messages
60    *  Function gets passed: message as a const char*,
61    *  title as a const char*, and a reference to bool that when
62    *  set to false, will disable furthur messages (cancel).
63    */
64   static void SetErrorCallback(ErrorCallback f, void* clientData=0);
65
66   /**
67    * Display an error message.
68    */
69   static void Error(const char* m, const char* m2=0,
70                     const char* m3=0, const char* m4=0);
71
72   /**
73    * Display a message.
74    */
75   static void Message(const char* m, const char* title=0);
76
77   ///! Send a string to stdout
78   static void Stdout(const char* s);
79   static void Stdout(const char* s, int length);
80   typedef  void (*StdoutCallback)(const char*, int length, void*);
81   static void SetStdoutCallback(StdoutCallback, void* clientData=0);
82
83   ///! Send a string to stderr. Stdout callbacks will not be invoced.
84   static void Stderr(const char* s, int length);
85
86
87   typedef bool (*InterruptCallback)(void*);
88   static void SetInterruptCallback(InterruptCallback f, void* clientData=0);
89   static bool GetInterruptFlag();
90
91   ///! Return true if there was an error at any point.
92   static bool GetErrorOccuredFlag()
93     {
94       return cmSystemTools::s_ErrorOccured ||
95         cmSystemTools::s_FatalErrorOccured;
96     }
97   ///! If this is set to true, cmake stops processing commands.
98   static void SetFatalErrorOccured()
99     {
100       cmSystemTools::s_FatalErrorOccured = true;
101     }
102   static void SetErrorOccured()
103     {
104       cmSystemTools::s_ErrorOccured = true;
105     }
106  ///! Return true if there was an error at any point.
107   static bool GetFatalErrorOccured()
108     {
109       return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
110     }
111
112   ///! Set the error occured flag and fatal error back to false
113   static void ResetErrorOccuredFlag()
114     {
115       cmSystemTools::s_FatalErrorOccured = false;
116       cmSystemTools::s_ErrorOccured = false;
117     }
118
119   /**
120    * Does a string indicates that CMake/CPack/CTest internally
121    * forced this value. This is not the same as On, but this
122    * may be considered as "internally switched on".
123    */
124   static bool IsInternallyOn(const char* val);
125   /**
126    * does a string indicate a true or on value ? This is not the same
127    * as ifdef.
128    */
129   static bool IsOn(const char* val);
130
131   /**
132    * does a string indicate a false or off value ? Note that this is
133    * not the same as !IsOn(...) because there are a number of
134    * ambiguous values such as "/usr/local/bin" a path will result in
135    * IsON and IsOff both returning false. Note that the special path
136    * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
137    */
138   static bool IsOff(const char* val);
139
140   ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
141   static bool IsNOTFOUND(const char* value);
142   ///! Return true if the path is a framework
143   static bool IsPathToFramework(const char* value);
144
145   static bool DoesFileExistWithExtensions(
146     const char *name,
147     const std::vector<std::string>& sourceExts);
148
149   /**
150    * Check if the given file exists in one of the parent directory of the
151    * given file or directory and if it does, return the name of the file.
152    * Toplevel specifies the top-most directory to where it will look.
153    */
154   static std::string FileExistsInParentDirectories(const char* fname,
155     const char* directory, const char* toplevel);
156
157   static void Glob(const char *directory, const char *regexp,
158                    std::vector<std::string>& files);
159   static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
160
161   /**
162    * Try to find a list of files that match the "simple" globbing
163    * expression. At this point in time the globbing expressions have
164    * to be in form: /directory/partial_file_name*. The * character has
165    * to be at the end of the string and it does not support ?
166    * []... The optional argument type specifies what kind of files you
167    * want to find. 0 means all files, -1 means directories, 1 means
168    * files only. This method returns true if search was succesfull.
169    */
170   static bool SimpleGlob(const cmStdString& glob,
171                          std::vector<cmStdString>& files,
172                          int type = 0);
173
174   ///! Copy a file.
175   static bool cmCopyFile(const char* source, const char* destination);
176   static bool CopyFileIfDifferent(const char* source,
177     const char* destination);
178
179   /** Rename a file or directory within a single disk volume (atomic
180       if possible).  */
181   static bool RenameFile(const char* oldname, const char* newname);
182
183   ///! Compute the md5sum of a file
184   static bool ComputeFileMD5(const char* source, char* md5out);
185
186   /** Compute the md5sum of a string.  */
187   static std::string ComputeStringMD5(const char* input);
188
189   /**
190    * Run an executable command and put the stdout in output.
191    * A temporary file is created in the binaryDir for storing the
192    * output because windows does not have popen.
193    *
194    * If verbose is false, no user-viewable output from the program
195    * being run will be generated.
196    *
197    * If timeout is specified, the command will be terminated after
198    * timeout expires.
199    */
200   static bool RunCommand(const char* command, std::string& output,
201                          const char* directory = 0,
202                          bool verbose = true, int timeout = 0);
203   static bool RunCommand(const char* command, std::string& output,
204                          int &retVal, const char* directory = 0,
205                          bool verbose = true, int timeout = 0);
206   /**
207    * Run a single executable command
208    *
209    * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
210    * user-viewable output from the program being run will be generated.
211    * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
212    * into stdout.  OUTPUT_NORMAL passes through the output to stdout/stderr as
213    * it was received.
214    *
215    * If timeout is specified, the command will be terminated after
216    * timeout expires. Timeout is specified in seconds.
217    *
218    * Argument retVal should be a pointer to the location where the
219    * exit code will be stored. If the retVal is not specified and
220    * the program exits with a code other than 0, then the this
221    * function will return false.
222    *
223    * If the command has spaces in the path the caller MUST call
224    * cmSystemTools::ConvertToRunCommandPath on the command before passing
225    * it into this function or it will not work.  The command must be correctly
226    * escaped for this to with spaces.
227    */
228    enum OutputOption
229    {
230      OUTPUT_NONE = 0,
231      OUTPUT_MERGE,
232      OUTPUT_NORMAL
233    };
234   static bool RunSingleCommand(const char* command, std::string* output = 0,
235                                int* retVal = 0, const char* dir = 0,
236                                OutputOption outputflag = OUTPUT_MERGE,
237                                double timeout = 0.0);
238   /**
239    * In this version of RunSingleCommand, command[0] should be
240    * the command to run, and each argument to the command should
241    * be in comand[1]...command[command.size()]
242    */
243   static bool RunSingleCommand(std::vector<cmStdString> const& command,
244                                std::string* output = 0,
245                                int* retVal = 0, const char* dir = 0,
246                                OutputOption outputflag = OUTPUT_MERGE,
247                                double timeout = 0.0);
248
249   /**
250    * Parse arguments out of a single string command
251    */
252   static std::vector<cmStdString> ParseArguments(const char* command);
253
254   /** Parse arguments out of a windows command line string.  */
255   static void ParseWindowsCommandLine(const char* command,
256                                       std::vector<std::string>& args);
257
258   /** Parse arguments out of a unix command line string.  */
259   static void ParseUnixCommandLine(const char* command,
260                                    std::vector<std::string>& args);
261   static void ParseUnixCommandLine(const char* command,
262                                    std::vector<cmStdString>& args);
263
264   /** Compute an escaped version of the given argument for use in a
265       windows shell.  See kwsys/System.h.in for details.  */
266   static std::string EscapeWindowsShellArgument(const char* arg,
267                                                 int shell_flags);
268
269   static void EnableMessages() { s_DisableMessages = false; }
270   static void DisableMessages() { s_DisableMessages = true; }
271   static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
272   static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
273   static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
274
275   /**
276    * Come constants for different file formats.
277    */
278   enum FileFormat {
279     NO_FILE_FORMAT = 0,
280     C_FILE_FORMAT,
281     CXX_FILE_FORMAT,
282     FORTRAN_FILE_FORMAT,
283     JAVA_FILE_FORMAT,
284     HEADER_FILE_FORMAT,
285     RESOURCE_FILE_FORMAT,
286     DEFINITION_FILE_FORMAT,
287     STATIC_LIBRARY_FILE_FORMAT,
288     SHARED_LIBRARY_FILE_FORMAT,
289     MODULE_FILE_FORMAT,
290     OBJECT_FILE_FORMAT,
291     UNKNOWN_FILE_FORMAT
292   };
293
294   enum CompareOp {
295     OP_LESS,
296     OP_GREATER,
297     OP_EQUAL
298   };
299
300   /**
301    * Compare versions
302    */
303   static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
304
305   /**
306    * Determine the file type based on the extension
307    */
308   static FileFormat GetFileFormat(const char* ext);
309
310   /**
311    * On Windows 9x we need a comspec (command.com) substitute to run
312    * programs correctly. This string has to be constant available
313    * through the running of program. This method does not create a copy.
314    */
315   static void SetWindows9xComspecSubstitute(const char*);
316   static const char* GetWindows9xComspecSubstitute();
317
318   /** Windows if this is true, the CreateProcess in RunCommand will
319    *  not show new consol windows when running programs.
320    */
321   static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
322   static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
323   /** Call cmSystemTools::Error with the message m, plus the
324    * result of strerror(errno)
325    */
326   static void ReportLastSystemError(const char* m);
327
328   /** a general output handler for cmsysProcess  */
329   static int WaitForLine(cmsysProcess* process, std::string& line,
330                          double timeout,
331                          std::vector<char>& out,
332                          std::vector<char>& err);
333
334   /** Split a string on its newlines into multiple lines.  Returns
335       false only if the last line stored had no newline.  */
336   static bool Split(const char* s, std::vector<cmStdString>& l);
337   static void SetForceUnixPaths(bool v)
338     {
339       s_ForceUnixPaths = v;
340     }
341   static bool GetForceUnixPaths()
342     {
343       return s_ForceUnixPaths;
344     }
345
346   // ConvertToOutputPath use s_ForceUnixPaths
347   static std::string ConvertToOutputPath(const char* path);
348   static void ConvertToOutputSlashes(std::string& path);
349
350   // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
351   // be used when RunCommand is called from cmake, because the
352   // running cmake needs paths to be in its format
353   static std::string ConvertToRunCommandPath(const char* path);
354   //! Check if the first string ends with the second one.
355   static bool StringEndsWith(const char* str1, const char* str2);
356
357   /** compute the relative path from local to remote.  local must
358       be a directory.  remote can be a file or a directory.
359       Both remote and local must be full paths.  Basically, if
360       you are in directory local and you want to access the file in remote
361       what is the relative path to do that.  For example:
362       /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
363       from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
364   */
365   static std::string RelativePath(const char* local, const char* remote);
366
367 #ifdef CMAKE_BUILD_WITH_CMAKE
368   /** Remove an environment variable */
369   static bool UnsetEnv(const char* value);
370
371   /** Get the list of all environment variables */
372   static std::vector<std::string> GetEnvironmentVariables();
373
374   /** Append multiple variables to the current environment.
375       Return the original environment, as it was before the
376       append. */
377   static std::vector<std::string> AppendEnv(
378     std::vector<std::string>* env);
379
380   /** Restore the full environment to "env" - use after
381       AppendEnv to put the environment back to the way it
382       was. */
383   static void RestoreEnv(const std::vector<std::string>& env);
384
385   /** Helper class to save and restore the environment.
386       Instantiate this class as an automatic variable on
387       the stack. Its constructor saves a copy of the current
388       environment and then its destructor restores the
389       original environment. */
390   class SaveRestoreEnvironment
391   {
392   public:
393     SaveRestoreEnvironment();
394     virtual ~SaveRestoreEnvironment();
395   private:
396     std::vector<std::string> Env;
397   };
398 #endif
399
400   /** Setup the environment to enable VS 8 IDE output.  */
401   static void EnableVSConsoleOutput();
402
403   /** Create tar */
404   static bool ListTar(const char* outFileName,
405                       bool gzip, bool verbose);
406   static bool CreateTar(const char* outFileName,
407                         const std::vector<cmStdString>& files, bool gzip,
408                         bool bzip2, bool verbose);
409   static bool ExtractTar(const char* inFileName, bool gzip,
410                          bool verbose);
411   // This should be called first thing in main
412   // it will keep child processes from inheriting the
413   // stdin and stdout of this process.  This is important
414   // if you want to be able to kill child processes and
415   // not get stuck waiting for all the output on the pipes.
416   static void DoNotInheritStdPipes();
417
418   /** Copy the file create/access/modify times from the file named by
419       the first argument to that named by the second.  */
420   static bool CopyFileTime(const char* fromFile, const char* toFile);
421
422   /** Save and restore file times.  */
423   static cmSystemToolsFileTime* FileTimeNew();
424   static void FileTimeDelete(cmSystemToolsFileTime*);
425   static bool FileTimeGet(const char* fname, cmSystemToolsFileTime* t);
426   static bool FileTimeSet(const char* fname, cmSystemToolsFileTime* t);
427
428   /** Random seed generation.  */
429   static unsigned int RandomSeed();
430
431   /** Find the directory containing the running executable.  Save it
432    in a global location to be queried by GetExecutableDirectory
433    later.  */
434   static void FindExecutableDirectory(const char* argv0);
435
436   /** Get the directory containing the currently running executable.  */
437   static const char* GetExecutableDirectory();
438
439 #if defined(CMAKE_BUILD_WITH_CMAKE)
440   /** Echo a message in color using KWSys's Terminal cprintf.  */
441   static void MakefileColorEcho(int color, const char* message,
442                                 bool newLine, bool enabled);
443 #endif
444
445   /** Try to guess the soname of a shared library.  */
446   static bool GuessLibrarySOName(std::string const& fullPath,
447                                  std::string& soname);
448
449   /** Try to set the RPATH in an ELF binary.  */
450   static bool ChangeRPath(std::string const& file,
451                           std::string const& oldRPath,
452                           std::string const& newRPath,
453                           std::string* emsg = 0,
454                           bool* changed = 0);
455
456   /** Try to remove the RPATH from an ELF binary.  */
457   static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
458                           bool* removed = 0);
459
460   /** Check whether the RPATH in an ELF binary contains the path
461       given.  */
462   static bool CheckRPath(std::string const& file,
463                          std::string const& newRPath);
464
465   /** Remove a directory; repeat a few times in case of locked files.  */
466   static bool RepeatedRemoveDirectory(const char* dir);
467
468   /** Tokenize a string */
469   static std::vector<std::string> tokenize(const std::string& str,
470                                            const std::string& sep);
471 private:
472   static bool s_ForceUnixPaths;
473   static bool s_RunCommandHideConsole;
474   static bool s_ErrorOccured;
475   static bool s_FatalErrorOccured;
476   static bool s_DisableMessages;
477   static bool s_DisableRunCommandOutput;
478   static ErrorCallback s_ErrorCallback;
479   static StdoutCallback s_StdoutCallback;
480   static InterruptCallback s_InterruptCallback;
481   static void* s_ErrorCallbackClientData;
482   static void* s_StdoutCallbackClientData;
483   static void* s_InterruptCallbackClientData;
484
485   static std::string s_Windows9xComspecSubstitute;
486 };
487
488 #endif