STYLE: fixed misspellings of Mac OS X
[cmake.git] / Source / kwsys / SystemTools.hxx.in
blobdf1db28474efdf284e30bffdc80895f7fe907ca7
1 /*=========================================================================
3 Program: KWSys - Kitware System Library
4 Module: $RCSfile: SystemTools.hxx.in,v $
6 Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
7 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9 This software is distributed WITHOUT ANY WARRANTY; without even
10 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 PURPOSE. See the above copyright notices for more information.
13 =========================================================================*/
14 #ifndef @KWSYS_NAMESPACE@_SystemTools_hxx
15 #define @KWSYS_NAMESPACE@_SystemTools_hxx
17 #include <@KWSYS_NAMESPACE@/ios/iosfwd>
18 #include <@KWSYS_NAMESPACE@/stl/string>
19 #include <@KWSYS_NAMESPACE@/stl/vector>
20 #include <@KWSYS_NAMESPACE@/stl/map>
22 #include <@KWSYS_NAMESPACE@/Configure.h>
23 #include <@KWSYS_NAMESPACE@/String.hxx>
25 #include <sys/types.h>
27 // Required for va_list
28 #include <stdarg.h>
29 #if @KWSYS_NAMESPACE@_STL_HAVE_STD && !defined(va_list)
30 // Some compilers move va_list into the std:: namespace and there is no way to
31 // tell that this has been done. Playing with things being included before or
32 // after stdarg.h does not solve things because we do not have control over
33 // what the user does. This hack solves this problem by moving va_list to our
34 // own namespace that is local for kwsys.
35 namespace std {} // Required for platforms that do not have std::
36 namespace @KWSYS_NAMESPACE@_VA_LIST
38 using namespace std;
39 typedef va_list hack_va_list;
41 namespace @KWSYS_NAMESPACE@
43 typedef @KWSYS_NAMESPACE@_VA_LIST::hack_va_list va_list;
45 #endif // va_list
47 #if defined( _MSC_VER )
48 typedef unsigned short mode_t;
49 #endif
51 /* Define these macros temporarily to keep the code readable. */
52 #if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
53 # define kwsys_stl @KWSYS_NAMESPACE@_stl
54 # define kwsys_ios @KWSYS_NAMESPACE@_ios
55 #endif
57 namespace @KWSYS_NAMESPACE@
60 class SystemToolsTranslationMap;
61 /** \class SystemToolsManager
62 * \brief Use to make sure SystemTools is initialized before it is used
63 * and is the last static object destroyed
65 class @KWSYS_NAMESPACE@_EXPORT SystemToolsManager
67 public:
68 SystemToolsManager();
69 ~SystemToolsManager();
72 // This instance will show up in any translation unit that uses
73 // SystemTools. It will make sure SystemTools is initialized
74 // before it is used and is the last static object destroyed.
75 static SystemToolsManager SystemToolsManagerInstance;
77 /** \class SystemTools
78 * \brief A collection of useful platform-independent system functions.
80 class @KWSYS_NAMESPACE@_EXPORT SystemTools
82 public:
84 /** -----------------------------------------------------------------
85 * String Manipulation Routines
86 * -----------------------------------------------------------------
89 /**
90 * Replace symbols in str that are not valid in C identifiers as
91 * defined by the 1999 standard, ie. anything except [A-Za-z0-9_].
92 * They are replaced with `_' and if the first character is a digit
93 * then an underscore is prepended. Note that this can produce
94 * identifiers that the standard reserves (_[A-Z].* and __.*).
96 static kwsys_stl::string MakeCindentifier(const char* s);
98 /**
99 * Replace replace all occurences of the string in the source string.
101 static void ReplaceString(kwsys_stl::string& source,
102 const char* replace,
103 const char* with);
106 * Return a capitalized string (i.e the first letter is uppercased,
107 * all other are lowercased).
109 static kwsys_stl::string Capitalized(const kwsys_stl::string&);
112 * Return a 'capitalized words' string (i.e the first letter of each word
113 * is uppercased all other are left untouched though).
115 static kwsys_stl::string CapitalizedWords(const kwsys_stl::string&);
118 * Return a 'uncapitalized words' string (i.e the first letter of each word
119 * is lowercased all other are left untouched though).
121 static kwsys_stl::string UnCapitalizedWords(const kwsys_stl::string&);
124 * Return a lower case string
126 static kwsys_stl::string LowerCase(const kwsys_stl::string&);
129 * Return a lower case string
131 static kwsys_stl::string UpperCase(const kwsys_stl::string&);
134 * Count char in string
136 static size_t CountChar(const char* str, char c);
139 * Remove some characters from a string.
140 * Return a pointer to the new resulting string (allocated with 'new')
142 static char* RemoveChars(const char* str, const char *toremove);
145 * Remove remove all but 0->9, A->F characters from a string.
146 * Return a pointer to the new resulting string (allocated with 'new')
148 static char* RemoveCharsButUpperHex(const char* str);
151 * Replace some characters by another character in a string (in-place)
152 * Return a pointer to string
154 static char* ReplaceChars(char* str, const char *toreplace,char replacement);
157 * Returns true if str1 starts (respectively ends) with str2
159 static bool StringStartsWith(const char* str1, const char* str2);
160 static bool StringEndsWith(const char* str1, const char* str2);
163 * Returns a pointer to the last occurence of str2 in str1
165 static const char* FindLastString(const char* str1, const char* str2);
168 * Make a duplicate of the string similar to the strdup C function
169 * but use new to create the 'new' string, so one can use
170 * 'delete' to remove it. Returns 0 if the input is empty.
172 static char* DuplicateString(const char* str);
175 * Return the string cropped to a given length by removing chars in the
176 * center of the string and replacing them with an ellipsis (...)
178 static kwsys_stl::string CropString(const kwsys_stl::string&,size_t max_len);
180 /** split a path by separator into an array of strings, default is /.
181 If isPath is true then the string is treated like a path and if
182 s starts with a / then the first element of the returned array will
183 be /, so /foo/bar will be [/, foo, bar]
185 static kwsys_stl::vector<String> SplitString(const char* s, char separator = '/',
186 bool isPath = false);
188 * Perform a case-independent string comparison
190 static int Strucmp(const char *s1, const char *s2);
192 /**
193 * Convert a string in __DATE__ or __TIMESTAMP__ format into a time_t.
194 * Return false on error, true on success
196 static bool ConvertDateMacroString(const char *str, time_t *tmt);
197 static bool ConvertTimeStampMacroString(const char *str, time_t *tmt);
200 * Split a string on its newlines into multiple lines
201 * Return false only if the last line stored had no newline
203 static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l);
204 static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l, char separator);
206 /**
207 * Return string with space added between capitalized words
208 * (i.e. EatMyShorts becomes Eat My Shorts )
209 * (note that IEatShorts becomes IEat Shorts)
211 static kwsys_stl::string AddSpaceBetweenCapitalizedWords(
212 const kwsys_stl::string&);
215 * Append two or more strings and produce new one.
216 * Programmer must 'delete []' the resulting string, which was allocated
217 * with 'new'.
218 * Return 0 if inputs are empty or there was an error
220 static char* AppendStrings(
221 const char* str1, const char* str2);
222 static char* AppendStrings(
223 const char* str1, const char* str2, const char* str3);
226 * Estimate the length of the string that will be produced
227 * from printing the given format string and arguments. The
228 * returned length will always be at least as large as the string
229 * that will result from printing.
230 * WARNING: since va_arg is called to iterate of the argument list,
231 * you will not be able to use this 'ap' anymore from the beginning.
232 * It's up to you to call va_end though.
234 static int EstimateFormatLength(const char *format, va_list ap);
237 * Escape specific characters in 'str'.
239 static kwsys_stl::string EscapeChars(
240 const char *str, const char *chars_to_escape, char escape_char = '\\');
242 /** -----------------------------------------------------------------
243 * Filename Manipulation Routines
244 * -----------------------------------------------------------------
248 * Replace Windows file system slashes with Unix-style slashes.
250 static void ConvertToUnixSlashes(kwsys_stl::string& path);
253 * For windows this calls ConvertToWindowsOutputPath and for unix
254 * it calls ConvertToUnixOutputPath
256 static kwsys_stl::string ConvertToOutputPath(const char*);
259 * Convert the path to a string that can be used in a unix makefile.
260 * double slashes are removed, and spaces are escaped.
262 static kwsys_stl::string ConvertToUnixOutputPath(const char*);
265 * Convert the path to string that can be used in a windows project or
266 * makefile. Double slashes are removed if they are not at the start of
267 * the string, the slashes are converted to windows style backslashes, and
268 * if there are spaces in the string it is double quoted.
270 static kwsys_stl::string ConvertToWindowsOutputPath(const char*);
273 * Return true if a file exists in the current directory
275 static bool FileExists(const char* filename);
278 * Return file length
280 static unsigned long FileLength(const char *filename);
283 * Compare file modification times.
284 * Return true for successful comparison and false for error.
285 * When true is returned, result has -1, 0, +1 for
286 * f1 older, same, or newer than f2.
288 static bool FileTimeCompare(const char* f1, const char* f2,
289 int* result);
292 * Get the file extension (including ".") needed for an executable
293 * on the current platform ("" for unix, ".exe" for Windows).
295 static const char* GetExecutableExtension();
298 * Given a path that exists on a windows machine, return the
299 * actuall case of the path as it was created. If the file
300 * does not exist path is returned unchanged. This does nothing
301 * on unix but return path.
303 static kwsys_stl::string GetActualCaseForPath(const char* path);
306 * Given the path to a program executable, get the directory part of
307 * the path with the file stripped off. If there is no directory
308 * part, the empty string is returned.
310 static kwsys_stl::string GetProgramPath(const char*);
311 static bool SplitProgramPath(const char* in_name,
312 kwsys_stl::string& dir,
313 kwsys_stl::string& file,
314 bool errorReport = true);
317 * Given argv[0] for a unix program find the full path to a running
318 * executable. argv0 can be null for windows WinMain programs
319 * in this case GetModuleFileName will be used to find the path
320 * to the running executable. If argv0 is not a full path,
321 * then this will try to find the full path. If the path is not
322 * found false is returned, if found true is returned. An error
323 * message of the attempted paths is stored in errorMsg.
324 * exeName is the name of the executable.
325 * buildDir is a possibly null path to the build directory.
326 * installPrefix is a possibly null pointer to the install directory.
328 static bool FindProgramPath(const char* argv0,
329 kwsys_stl::string& pathOut,
330 kwsys_stl::string& errorMsg,
331 const char* exeName = 0,
332 const char* buildDir = 0,
333 const char* installPrefix = 0);
336 * Given a path to a file or directory, convert it to a full path.
337 * This collapses away relative paths relative to the cwd argument
338 * (which defaults to the current working directory). The full path
339 * is returned.
341 static kwsys_stl::string CollapseFullPath(const char* in_relative);
342 static kwsys_stl::string CollapseFullPath(const char* in_relative,
343 const char* in_base);
346 * Split a path name into its basic components. The first component
347 * is one of the following roots:
348 * "/" = UNIX
349 * "c:/" = Windows full path (can be any drive letter)
350 * "c:" = Windows drive-letter relative path (can be any drive letter)
351 * "//" = Network path
352 * "" = Relative path
353 * The remaining components form the path. If there is a trailing
354 * slash then the last component is the empty string. The
355 * components can be recombined as "c[0]c[1]/c[2]/.../c[n]" to
356 * produce the original path.
358 static void SplitPath(const char* p,
359 kwsys_stl::vector<kwsys_stl::string>& components);
362 * Join components of a path name into a single string. See
363 * SplitPath for the format of the components.
365 static kwsys_stl::string JoinPath(
366 const kwsys_stl::vector<kwsys_stl::string>& components);
367 static kwsys_stl::string JoinPath(
368 kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
369 kwsys_stl::vector<kwsys_stl::string>::const_iterator last);
372 * Compare a path or components of a path.
374 static bool ComparePath(const char* c1, const char* c2);
378 * Return path of a full filename (no trailing slashes)
380 static kwsys_stl::string GetFilenamePath(const kwsys_stl::string&);
383 * Return file name of a full filename (i.e. file name without path)
385 static kwsys_stl::string GetFilenameName(const kwsys_stl::string&);
388 * Split a program from its arguments and handle spaces in the paths
390 static void SplitProgramFromArgs(
391 const char* path,
392 kwsys_stl::string& program, kwsys_stl::string& args);
395 * Return longest file extension of a full filename (dot included)
397 static kwsys_stl::string GetFilenameExtension(const kwsys_stl::string&);
400 * Return shortest file extension of a full filename (dot included)
402 static kwsys_stl::string GetFilenameLastExtension(
403 const kwsys_stl::string& filename);
406 * Return file name without extension of a full filename
408 static kwsys_stl::string GetFilenameWithoutExtension(
409 const kwsys_stl::string&);
412 * Return file name without its last (shortest) extension
414 static kwsys_stl::string GetFilenameWithoutLastExtension(
415 const kwsys_stl::string&);
418 * Return whether the path represents a full path (not relative)
420 static bool FileIsFullPath(const char*);
423 * For windows return the short path for the given path,
424 * Unix just a pass through
426 static bool GetShortPath(const char* path, kwsys_stl::string& result);
429 * Read line from file. Make sure to get everything. Due to a buggy stream
430 * library on the HP and another on Mac OS X, we need this very carefully
431 * written version of getline. Returns true if any data were read before the
432 * end-of-file was reached. If the has_newline argument is specified, it will
433 * be true when the line read had a newline character.
435 static bool GetLineFromStream(kwsys_ios::istream& istr,
436 kwsys_stl::string& line,
437 bool* has_newline=0,
438 long sizeLimit=-1);
441 * Get the parent directory of the directory or file
443 static kwsys_stl::string GetParentDirectory(const char* fileOrDir);
446 * Check if the given file or directory is in subdirectory of dir
448 static bool IsSubDirectory(const char* fileOrDir, const char* dir);
450 /** -----------------------------------------------------------------
451 * File Manipulation Routines
452 * -----------------------------------------------------------------
456 * Make a new directory if it is not there. This function
457 * can make a full path even if none of the directories existed
458 * prior to calling this function.
460 static bool MakeDirectory(const char* path);
463 * Copy the source file to the destination file only
464 * if the two files differ.
466 static bool CopyFileIfDifferent(const char* source,
467 const char* destination);
470 * Compare the contents of two files. Return true if different
472 static bool FilesDiffer(const char* source, const char* destination);
475 * Return true if the two files are the same file
477 static bool SameFile(const char* file1, const char* file2);
480 * Copy a file
482 static bool CopyFileAlways(const char* source, const char* destination);
485 * Copy a file. If the "always" argument is true the file is always
486 * copied. If it is false, the file is copied only if it is new or
487 * has changed.
489 static bool CopyAFile(const char* source, const char* destination,
490 bool always = true);
493 * Copy content directory to another directory with all files and
494 * subdirectories. If the "always" argument is true all files are
495 * always copied. If it is false, only files that have changed or
496 * are new are copied.
498 static bool CopyADirectory(const char* source, const char* destination,
499 bool always = true);
502 * Remove a file
504 static bool RemoveFile(const char* source);
507 * Remove a directory
509 static bool RemoveADirectory(const char* source);
512 * Get the maximum full file path length
514 static size_t GetMaximumFilePathLength();
517 * Find a file in the system PATH, with optional extra paths
519 static kwsys_stl::string FindFile(
520 const char* name,
521 const kwsys_stl::vector<kwsys_stl::string>& path =
522 kwsys_stl::vector<kwsys_stl::string>(),
523 bool no_system_path = false);
526 * Find a directory in the system PATH, with optional extra paths
528 static kwsys_stl::string FindDirectory(
529 const char* name,
530 const kwsys_stl::vector<kwsys_stl::string>& path =
531 kwsys_stl::vector<kwsys_stl::string>(),
532 bool no_system_path = false);
535 * Find an executable in the system PATH, with optional extra paths
537 static kwsys_stl::string FindProgram(
538 const char* name,
539 const kwsys_stl::vector<kwsys_stl::string>& path =
540 kwsys_stl::vector<kwsys_stl::string>(),
541 bool no_system_path = false);
542 static kwsys_stl::string FindProgram(
543 const kwsys_stl::vector<kwsys_stl::string>& names,
544 const kwsys_stl::vector<kwsys_stl::string>& path =
545 kwsys_stl::vector<kwsys_stl::string>(),
546 bool no_system_path = false);
549 * Find a library in the system PATH, with optional extra paths
551 static kwsys_stl::string FindLibrary(
552 const char* name,
553 const kwsys_stl::vector<kwsys_stl::string>& path);
556 * Return true if the file is a directory
558 static bool FileIsDirectory(const char* name);
561 * Return true if the file is a symlink
563 static bool FileIsSymlink(const char* name);
566 * Return true if the file has a given signature (first set of bytes)
568 static bool FileHasSignature(
569 const char* filename, const char *signature, long offset = 0);
572 * Attempt to detect and return the type of a file.
573 * Up to 'length' bytes are read from the file, if more than 'percent_bin' %
574 * of the bytes are non-textual elements, the file is considered binary,
575 * otherwise textual. Textual elements are bytes in the ASCII [0x20, 0x7E]
576 * range, but also \n, \r, \t.
577 * The algorithm is simplistic, and should probably check for usual file
578 * extensions, 'magic' signature, unicode, etc.
580 enum FileTypeEnum
582 FileTypeUnknown,
583 FileTypeBinary,
584 FileTypeText
586 static SystemTools::FileTypeEnum DetectFileType(
587 const char* filename,
588 unsigned long length = 256,
589 double percent_bin = 0.05);
592 * Create a symbolic link if the platform supports it. Returns whether
593 * creation succeded.
595 static bool CreateSymlink(const char* origName, const char* newName);
598 * Read the contents of a symbolic link. Returns whether reading
599 * succeded.
601 static bool ReadSymlink(const char* newName, kwsys_stl::string& origName);
604 * Try to locate the file 'filename' in the directory 'dir'.
605 * If 'filename' is a fully qualified filename, the basename of the file is
606 * used to check for its existence in 'dir'.
607 * If 'dir' is not a directory, GetFilenamePath() is called on 'dir' to
608 * get its directory first (thus, you can pass a filename as 'dir', as
609 * a convenience).
610 * 'filename_found' is assigned the fully qualified name/path of the file
611 * if it is found (not touched otherwise).
612 * If 'try_filename_dirs' is true, try to find the file using the
613 * components of its path, i.e. if we are looking for c:/foo/bar/bill.txt,
614 * first look for bill.txt in 'dir', then in 'dir'/bar, then in 'dir'/foo/bar
615 * etc.
616 * Return true if the file was found, false otherwise.
618 static bool LocateFileInDir(const char *filename,
619 const char *dir,
620 kwsys_stl::string& filename_found,
621 int try_filename_dirs = 0);
623 /**
624 * Check if the given file exists in one of the parent directory of the
625 * given file or directory and if it does, return the name of the file.
626 * Toplevel specifies the top-most directory to where it will look.
628 static kwsys_stl::string FileExistsInParentDirectories(const char* fname,
629 const char* directory, const char* toplevel);
631 /** compute the relative path from local to remote. local must
632 be a directory. remote can be a file or a directory.
633 Both remote and local must be full paths. Basically, if
634 you are in directory local and you want to access the file in remote
635 what is the relative path to do that. For example:
636 /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
637 from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
639 static kwsys_stl::string RelativePath(const char* local, const char* remote);
642 * Return file's modified time
644 static long int ModifiedTime(const char* filename);
647 * Return file's creation time (Win32: works only for NTFS, not FAT)
649 static long int CreationTime(const char* filename);
652 * Get and set permissions of the file.
654 static bool GetPermissions(const char* file, mode_t& mode);
655 static bool SetPermissions(const char* file, mode_t mode);
657 /** -----------------------------------------------------------------
658 * Time Manipulation Routines
659 * -----------------------------------------------------------------
663 * Get current time as a double. On certain platforms this will
664 * return higher resolution than seconds:
665 * (1) gettimeofday() -- resolution in microseconds
666 * (2) ftime() -- resolution in milliseconds
667 * (3) time() -- resolution in seconds
669 static double GetTime();
672 * Get current date/time
674 static kwsys_stl::string GetCurrentDateTime(const char* format);
676 /** -----------------------------------------------------------------
677 * Registry Manipulation Routines
678 * -----------------------------------------------------------------
682 * Read a registry value
684 static bool ReadRegistryValue(const char *key, kwsys_stl::string &value);
687 * Write a registry value
689 static bool WriteRegistryValue(const char *key, const char *value);
692 * Delete a registry value
694 static bool DeleteRegistryValue(const char *key);
696 /** -----------------------------------------------------------------
697 * Environment Manipulation Routines
698 * -----------------------------------------------------------------
702 * Add the paths from the environment variable PATH to the
703 * string vector passed in. If env is set then the value
704 * of env will be used instead of PATH.
706 static void GetPath(kwsys_stl::vector<kwsys_stl::string>& path,
707 const char* env=0);
710 * Read an environment variable
712 static const char* GetEnv(const char* key);
713 static bool GetEnv(const char* key, kwsys_stl::string& result);
716 * Get current working directory CWD
718 static kwsys_stl::string GetCurrentWorkingDirectory(bool collapse =true);
721 * Change directory the the directory specified
723 static int ChangeDirectory(const char* dir);
726 * Get the result of strerror(errno)
728 static kwsys_stl::string GetLastSystemError();
731 * When building DEBUG with MSVC, this enables a hook that prevents
732 * error dialogs from popping up if the program is being run from
733 * DART.
735 static void EnableMSVCDebugHook();
738 * Get the width of the terminal window. The code may or may not work, so
739 * make sure you have some resonable defaults prepared if the code returns
740 * some bogus size.
742 static int GetTerminalWidth();
745 * Add an entry in the path translation table.
747 static void AddTranslationPath(const char * dir, const char * refdir);
750 * If dir is different after CollapseFullPath is called,
751 * Then insert it into the path translation table
753 static void AddKeepPath(const char* dir);
756 * Update path by going through the Path Translation table;
758 static void CheckTranslationPath(kwsys_stl::string & path);
761 * Delay the execution for a specified amount of time specified
762 * in miliseconds
764 static void Delay(unsigned int msec);
767 * Get the operating system name and version
768 * This is implemented for Win32 only for the moment
770 static kwsys_stl::string GetOperatingSystemNameAndVersion();
773 * Convert windows-style arguments given as a command-line string
774 * into more traditional argc/argv arguments.
775 * Note that argv[0] will be assigned the executable name using
776 * the ::GetModuleFileName function.
778 static void ConvertWindowsCommandLineToUnixArguments(
779 const char *cmd_line, int *argc, char ***argv);
781 private:
783 * Allocate the std::map that serve as the Path Translation table.
785 static void ClassInitialize();
788 * Deallocate the std::map that serve as the Path Translation table.
790 static void ClassFinalize();
793 * This method prevents warning on SGI
795 SystemToolsManager* GetSystemToolsManager()
797 return &SystemToolsManagerInstance;
801 * Find a filename (file or directory) in the system PATH, with
802 * optional extra paths.
804 static kwsys_stl::string FindName(
805 const char* name,
806 const kwsys_stl::vector<kwsys_stl::string>& path =
807 kwsys_stl::vector<kwsys_stl::string>(),
808 bool no_system_path = false);
812 * Path translation table from dir to refdir
813 * Each time 'dir' will be found it will be replace by 'refdir'
815 static SystemToolsTranslationMap *TranslationMap;
816 static SystemToolsTranslationMap *LongPathMap;
817 friend class SystemToolsManager;
820 } // namespace @KWSYS_NAMESPACE@
822 /* Undefine temporary macros. */
823 #if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
824 # undef kwsys_stl
825 # undef kwsys_ios
826 #endif
828 #endif