packaging: Initial packaging
[platform/upstream/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 GUIs 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         GetInterruptFlag();
97     }
98   ///! If this is set to true, cmake stops processing commands.
99   static void SetFatalErrorOccured()
100     {
101       cmSystemTools::s_FatalErrorOccured = true;
102     }
103   static void SetErrorOccured()
104     {
105       cmSystemTools::s_ErrorOccured = true;
106     }
107  ///! Return true if there was an error at any point.
108   static bool GetFatalErrorOccured()
109     {
110       return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
111     }
112
113   ///! Set the error occured flag and fatal error back to false
114   static void ResetErrorOccuredFlag()
115     {
116       cmSystemTools::s_FatalErrorOccured = false;
117       cmSystemTools::s_ErrorOccured = false;
118     }
119
120   /**
121    * Does a string indicates that CMake/CPack/CTest internally
122    * forced this value. This is not the same as On, but this
123    * may be considered as "internally switched on".
124    */
125   static bool IsInternallyOn(const char* val);
126   /**
127    * does a string indicate a true or on value ? This is not the same
128    * as ifdef.
129    */
130   static bool IsOn(const char* val);
131
132   /**
133    * does a string indicate a false or off value ? Note that this is
134    * not the same as !IsOn(...) because there are a number of
135    * ambiguous values such as "/usr/local/bin" a path will result in
136    * IsON and IsOff both returning false. Note that the special path
137    * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
138    */
139   static bool IsOff(const char* val);
140
141   ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
142   static bool IsNOTFOUND(const char* value);
143   ///! Return true if the path is a framework
144   static bool IsPathToFramework(const char* value);
145
146   static bool DoesFileExistWithExtensions(
147     const char *name,
148     const std::vector<std::string>& sourceExts);
149
150   /**
151    * Check if the given file exists in one of the parent directory of the
152    * given file or directory and if it does, return the name of the file.
153    * Toplevel specifies the top-most directory to where it will look.
154    */
155   static std::string FileExistsInParentDirectories(const char* fname,
156     const char* directory, const char* toplevel);
157
158   static void Glob(const char *directory, const char *regexp,
159                    std::vector<std::string>& files);
160   static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
161
162   /**
163    * Try to find a list of files that match the "simple" globbing
164    * expression. At this point in time the globbing expressions have
165    * to be in form: /directory/partial_file_name*. The * character has
166    * to be at the end of the string and it does not support ?
167    * []... The optional argument type specifies what kind of files you
168    * want to find. 0 means all files, -1 means directories, 1 means
169    * files only. This method returns true if search was succesfull.
170    */
171   static bool SimpleGlob(const cmStdString& glob,
172                          std::vector<cmStdString>& files,
173                          int type = 0);
174
175   ///! Copy a file.
176   static bool cmCopyFile(const char* source, const char* destination);
177   static bool CopyFileIfDifferent(const char* source,
178     const char* destination);
179
180   /** Rename a file or directory within a single disk volume (atomic
181       if possible).  */
182   static bool RenameFile(const char* oldname, const char* newname);
183
184   ///! Compute the md5sum of a file
185   static bool ComputeFileMD5(const char* source, char* md5out);
186
187   /** Compute the md5sum of a string.  */
188   static std::string ComputeStringMD5(const char* input);
189
190   /**
191    * Run an executable command and put the stdout in output.
192    * A temporary file is created in the binaryDir for storing the
193    * output because windows does not have popen.
194    *
195    * If verbose is false, no user-viewable output from the program
196    * being run will be generated.
197    *
198    * If timeout is specified, the command will be terminated after
199    * timeout expires.
200    */
201   static bool RunCommand(const char* command, std::string& output,
202                          const char* directory = 0,
203                          bool verbose = true, int timeout = 0);
204   static bool RunCommand(const char* command, std::string& output,
205                          int &retVal, const char* directory = 0,
206                          bool verbose = true, int timeout = 0);
207   /**
208    * Run a single executable command
209    *
210    * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
211    * user-viewable output from the program being run will be generated.
212    * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
213    * into stdout.  OUTPUT_NORMAL passes through the output to stdout/stderr as
214    * it was received.  OUTPUT_PASSTHROUGH passes through the original handles.
215    *
216    * If timeout is specified, the command will be terminated after
217    * timeout expires. Timeout is specified in seconds.
218    *
219    * Argument retVal should be a pointer to the location where the
220    * exit code will be stored. If the retVal is not specified and
221    * the program exits with a code other than 0, then the this
222    * function will return false.
223    *
224    * If the command has spaces in the path the caller MUST call
225    * cmSystemTools::ConvertToRunCommandPath on the command before passing
226    * it into this function or it will not work.  The command must be correctly
227    * escaped for this to with spaces.
228    */
229    enum OutputOption
230    {
231      OUTPUT_NONE = 0,
232      OUTPUT_MERGE,
233      OUTPUT_NORMAL,
234      OUTPUT_PASSTHROUGH
235    };
236   static bool RunSingleCommand(const char* command, std::string* output = 0,
237                                int* retVal = 0, const char* dir = 0,
238                                OutputOption outputflag = OUTPUT_MERGE,
239                                double timeout = 0.0);
240   /**
241    * In this version of RunSingleCommand, command[0] should be
242    * the command to run, and each argument to the command should
243    * be in comand[1]...command[command.size()]
244    */
245   static bool RunSingleCommand(std::vector<cmStdString> const& command,
246                                std::string* output = 0,
247                                int* retVal = 0, const char* dir = 0,
248                                OutputOption outputflag = OUTPUT_MERGE,
249                                double timeout = 0.0);
250
251   /**
252    * Parse arguments out of a single string command
253    */
254   static std::vector<cmStdString> ParseArguments(const char* command);
255
256   /** Parse arguments out of a windows command line string.  */
257   static void ParseWindowsCommandLine(const char* command,
258                                       std::vector<std::string>& args);
259
260   /** Parse arguments out of a unix command line string.  */
261   static void ParseUnixCommandLine(const char* command,
262                                    std::vector<std::string>& args);
263   static void ParseUnixCommandLine(const char* command,
264                                    std::vector<cmStdString>& args);
265
266   /** Compute an escaped version of the given argument for use in a
267       windows shell.  See kwsys/System.h.in for details.  */
268   static std::string EscapeWindowsShellArgument(const char* arg,
269                                                 int shell_flags);
270
271   static void EnableMessages() { s_DisableMessages = false; }
272   static void DisableMessages() { s_DisableMessages = true; }
273   static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
274   static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
275   static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
276
277   /**
278    * Some constants for different file formats.
279    */
280   enum FileFormat {
281     NO_FILE_FORMAT = 0,
282     C_FILE_FORMAT,
283     CXX_FILE_FORMAT,
284     FORTRAN_FILE_FORMAT,
285     JAVA_FILE_FORMAT,
286     HEADER_FILE_FORMAT,
287     RESOURCE_FILE_FORMAT,
288     DEFINITION_FILE_FORMAT,
289     STATIC_LIBRARY_FILE_FORMAT,
290     SHARED_LIBRARY_FILE_FORMAT,
291     MODULE_FILE_FORMAT,
292     OBJECT_FILE_FORMAT,
293     UNKNOWN_FILE_FORMAT
294   };
295
296   enum CompareOp {
297     OP_LESS,
298     OP_GREATER,
299     OP_EQUAL
300   };
301
302   /**
303    * Compare versions
304    */
305   static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
306
307   /**
308    * Determine the file type based on the extension
309    */
310   static FileFormat GetFileFormat(const char* ext);
311
312   /**
313    * On Windows 9x we need a comspec (command.com) substitute to run
314    * programs correctly. This string has to be constant available
315    * through the running of program. This method does not create a copy.
316    */
317   static void SetWindows9xComspecSubstitute(const char*);
318   static const char* GetWindows9xComspecSubstitute();
319
320   /** Windows if this is true, the CreateProcess in RunCommand will
321    *  not show new consol windows when running programs.
322    */
323   static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
324   static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
325   /** Call cmSystemTools::Error with the message m, plus the
326    * result of strerror(errno)
327    */
328   static void ReportLastSystemError(const char* m);
329
330   /** a general output handler for cmsysProcess  */
331   static int WaitForLine(cmsysProcess* process, std::string& line,
332                          double timeout,
333                          std::vector<char>& out,
334                          std::vector<char>& err);
335
336   /** Split a string on its newlines into multiple lines.  Returns
337       false only if the last line stored had no newline.  */
338   static bool Split(const char* s, std::vector<cmStdString>& l);
339   static void SetForceUnixPaths(bool v)
340     {
341       s_ForceUnixPaths = v;
342     }
343   static bool GetForceUnixPaths()
344     {
345       return s_ForceUnixPaths;
346     }
347
348   // ConvertToOutputPath use s_ForceUnixPaths
349   static std::string ConvertToOutputPath(const char* path);
350   static void ConvertToOutputSlashes(std::string& path);
351
352   // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
353   // be used when RunCommand is called from cmake, because the
354   // running cmake needs paths to be in its format
355   static std::string ConvertToRunCommandPath(const char* path);
356   //! Check if the first string ends with the second one.
357   static bool StringEndsWith(const char* str1, const char* str2);
358
359   /** compute the relative path from local to remote.  local must
360       be a directory.  remote can be a file or a directory.
361       Both remote and local must be full paths.  Basically, if
362       you are in directory local and you want to access the file in remote
363       what is the relative path to do that.  For example:
364       /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
365       from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
366   */
367   static std::string RelativePath(const char* local, const char* remote);
368
369   /** Joins two paths while collapsing x/../ parts
370    * For example CollapseCombinedPath("a/b/c", "../../d") results in "a/d"
371    */
372   static std::string CollapseCombinedPath(std::string const& dir,
373                                           std::string const& file);
374
375 #ifdef CMAKE_BUILD_WITH_CMAKE
376   /** Remove an environment variable */
377   static bool UnsetEnv(const char* value);
378
379   /** Get the list of all environment variables */
380   static std::vector<std::string> GetEnvironmentVariables();
381
382   /** Append multiple variables to the current environment. */
383   static void AppendEnv(std::vector<std::string> const& 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 guess the install name of a shared library.  */
450   static bool GuessLibraryInstallName(std::string const& fullPath,
451                                  std::string& soname);
452
453   /** Try to set the RPATH in an ELF binary.  */
454   static bool ChangeRPath(std::string const& file,
455                           std::string const& oldRPath,
456                           std::string const& newRPath,
457                           std::string* emsg = 0,
458                           bool* changed = 0);
459
460   /** Try to remove the RPATH from an ELF binary.  */
461   static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
462                           bool* removed = 0);
463
464   /** Check whether the RPATH in an ELF binary contains the path
465       given.  */
466   static bool CheckRPath(std::string const& file,
467                          std::string const& newRPath);
468
469   /** Remove a directory; repeat a few times in case of locked files.  */
470   static bool RepeatedRemoveDirectory(const char* dir);
471
472   /** Tokenize a string */
473   static std::vector<std::string> tokenize(const std::string& str,
474                                            const std::string& sep);
475 private:
476   static bool s_ForceUnixPaths;
477   static bool s_RunCommandHideConsole;
478   static bool s_ErrorOccured;
479   static bool s_FatalErrorOccured;
480   static bool s_DisableMessages;
481   static bool s_DisableRunCommandOutput;
482   static ErrorCallback s_ErrorCallback;
483   static StdoutCallback s_StdoutCallback;
484   static InterruptCallback s_InterruptCallback;
485   static void* s_ErrorCallbackClientData;
486   static void* s_StdoutCallbackClientData;
487   static void* s_InterruptCallbackClientData;
488
489   static std::string s_Windows9xComspecSubstitute;
490 };
491
492 #endif