Debian Codegraph @

Utilities/KWSys/SystemTools.hxx.in

raw
1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
3 #ifndef @KWSYS_NAMESPACE@_SystemTools_hxx
4 #define @KWSYS_NAMESPACE@_SystemTools_hxx
5
6 #include <@KWSYS_NAMESPACE@/Configure.hxx>
7 #include <@KWSYS_NAMESPACE@/Status.hxx>
8
9 #include <iosfwd>
10 #include <map>
11 #include <string>
12 #include <vector>
13
14 #include <sys/types.h>
15 // include sys/stat.h after sys/types.h
16 #include <sys/stat.h>
17
18 #if !defined(_WIN32) || defined(__CYGWIN__)
19 # include <unistd.h> // For access permissions for use with access()
20 #endif
21
22 // Required for va_list
23 #include <stdarg.h>
24 // Required for FILE*
25 #include <stdio.h>
26 #if !defined(va_list)
27 // Some compilers move va_list into the std namespace and there is no way to
28 // tell that this has been done. Playing with things being included before or
29 // after stdarg.h does not solve things because we do not have control over
30 // what the user does. This hack solves this problem by moving va_list to our
31 // own namespace that is local for kwsys.
32 namespace std {
33 } // Required for platforms that do not have std namespace
34 namespace @KWSYS_NAMESPACE@_VA_LIST {
35 using namespace std;
36 typedef va_list hack_va_list;
37 }
38 namespace @KWSYS_NAMESPACE@ {
39 typedef @KWSYS_NAMESPACE@_VA_LIST::hack_va_list va_list;
40 }
41 #endif // va_list
42
43 namespace @KWSYS_NAMESPACE@ {
44
45 class SystemToolsStatic;
46
47 /** \class SystemToolsManager
48 * \brief Use to make sure SystemTools is initialized before it is used
49 * and is the last static object destroyed
50 */
51 class @KWSYS_NAMESPACE@_EXPORT SystemToolsManager
52 {
53 public:
54 SystemToolsManager();
55 ~SystemToolsManager();
56
57 SystemToolsManager(const SystemToolsManager&) = delete;
58 SystemToolsManager& operator=(const SystemToolsManager&) = delete;
59 };
60
61 // This instance will show up in any translation unit that uses
62 // SystemTools. It will make sure SystemTools is initialized
63 // before it is used and is the last static object destroyed.
64 static SystemToolsManager SystemToolsManagerInstance;
65
66 // Flags for use with TestFileAccess. Use a typedef in case any operating
67 // system in the future needs a special type. These are flags that may be
68 // combined using the | operator.
69 typedef int TestFilePermissions;
70 #if defined(_WIN32) && !defined(__CYGWIN__)
71 // On Windows (VC), no system header defines these constants...
72 static const TestFilePermissions TEST_FILE_OK = 0;
73 static const TestFilePermissions TEST_FILE_READ = 4;
74 static const TestFilePermissions TEST_FILE_WRITE = 2;
75 static const TestFilePermissions TEST_FILE_EXECUTE = 1;
76 #else
77 // Standard POSIX constants
78 static const TestFilePermissions TEST_FILE_OK = F_OK;
79 static const TestFilePermissions TEST_FILE_READ = R_OK;
80 static const TestFilePermissions TEST_FILE_WRITE = W_OK;
81 static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
82 #endif
83
84 /** \class SystemTools
85 * \brief A collection of useful platform-independent system functions.
86 */
87 class @KWSYS_NAMESPACE@_EXPORT SystemTools
88 {
89 public:
90 /** -----------------------------------------------------------------
91 * String Manipulation Routines
92 * -----------------------------------------------------------------
93 */
94
95 /**
96 * Replace symbols in str that are not valid in C identifiers as
97 * defined by the 1999 standard, ie. anything except [A-Za-z0-9_].
98 * They are replaced with `_' and if the first character is a digit
99 * then an underscore is prepended. Note that this can produce
100 * identifiers that the standard reserves (_[A-Z].* and __.*).
101 */
102 static std::string MakeCidentifier(const std::string& s);
103
104 static std::string MakeCindentifier(const std::string& s)
105 {
106 return MakeCidentifier(s);
107 }
108
109 /**
110 * Replace replace all occurrences of the string in the source string.
111 */
112 static void ReplaceString(std::string& source, const char* replace,
113 const char* with);
114 static void ReplaceString(std::string& source, const std::string& replace,
115 const std::string& with);
116
117 /**
118 * Return a capitalized string (i.e the first letter is uppercased,
119 * all other are lowercased).
120 */
121 static std::string Capitalized(const std::string&);
122
123 /**
124 * Return a 'capitalized words' string (i.e the first letter of each word
125 * is uppercased all other are left untouched though).
126 */
127 static std::string CapitalizedWords(const std::string&);
128
129 /**
130 * Return a 'uncapitalized words' string (i.e the first letter of each word
131 * is lowercased all other are left untouched though).
132 */
133 static std::string UnCapitalizedWords(const std::string&);
134
135 /**
136 * Return a lower case string
137 */
138 static std::string LowerCase(const std::string&);
139
140 /**
141 * Return a lower case string
142 */
143 static std::string UpperCase(const std::string&);
144
145 /**
146 * Count char in string
147 */
148 static size_t CountChar(const char* str, char c);
149
150 /**
151 * Remove some characters from a string.
152 * Return a pointer to the new resulting string (allocated with 'new')
153 */
154 static char* RemoveChars(const char* str, const char* toremove);
155
156 /**
157 * Remove remove all but 0->9, A->F characters from a string.
158 * Return a pointer to the new resulting string (allocated with 'new')
159 */
160 static char* RemoveCharsButUpperHex(const char* str);
161
162 /**
163 * Replace some characters by another character in a string (in-place)
164 * Return a pointer to string
165 */
166 static char* ReplaceChars(char* str, const char* toreplace,
167 char replacement);
168
169 /**
170 * Returns true if str1 starts (respectively ends) with str2
171 */
172 static bool StringStartsWith(const char* str1, const char* str2);
173 static bool StringStartsWith(const std::string& str1, const char* str2);
174 static bool StringEndsWith(const char* str1, const char* str2);
175 static bool StringEndsWith(const std::string& str1, const char* str2);
176
177 /**
178 * Returns a pointer to the last occurrence of str2 in str1
179 */
180 static const char* FindLastString(const char* str1, const char* str2);
181
182 /**
183 * Make a duplicate of the string similar to the strdup C function
184 * but use new to create the 'new' string, so one can use
185 * 'delete' to remove it. Returns 0 if the input is empty.
186 */
187 static char* DuplicateString(const char* str);
188
189 /**
190 * Return the string cropped to a given length by removing chars in the
191 * center of the string and replacing them with an ellipsis (...)
192 */
193 static std::string CropString(const std::string&, size_t max_len);
194
195 /** split a path by separator into an array of strings, default is /.
196 If isPath is true then the string is treated like a path and if
197 s starts with a / then the first element of the returned array will
198 be /, so /foo/bar will be [/, foo, bar]
199 */
200 static std::vector<std::string> SplitString(const std::string& s,
201 char separator = '/',
202 bool isPath = false);
203 /**
204 * Perform a case-independent string comparison
205 */
206 static int Strucmp(const char* s1, const char* s2);
207
208 /**
209 * Split a string on its newlines into multiple lines
210 * Return false only if the last line stored had no newline
211 */
212 static bool Split(const std::string& s, std::vector<std::string>& l);
213 static bool Split(const std::string& s, std::vector<std::string>& l,
214 char separator);
215
216 /**
217 * Joins a vector of strings into a single string, with separator in between
218 * each string.
219 */
220 static std::string Join(const std::vector<std::string>& list,
221 const std::string& separator);
222
223 /**
224 * Return string with space added between capitalized words
225 * (i.e. EatMyShorts becomes Eat My Shorts )
226 * (note that IEatShorts becomes IEat Shorts)
227 */
228 static std::string AddSpaceBetweenCapitalizedWords(const std::string&);
229
230 /**
231 * Append two or more strings and produce new one.
232 * Programmer must 'delete []' the resulting string, which was allocated
233 * with 'new'.
234 * Return 0 if inputs are empty or there was an error
235 */
236 static char* AppendStrings(const char* str1, const char* str2);
237 static char* AppendStrings(const char* str1, const char* str2,
238 const char* str3);
239
240 /**
241 * Estimate the length of the string that will be produced
242 * from printing the given format string and arguments. The
243 * returned length will always be at least as large as the string
244 * that will result from printing.
245 * WARNING: since va_arg is called to iterate of the argument list,
246 * you will not be able to use this 'ap' anymore from the beginning.
247 * It's up to you to call va_end though.
248 */
249 static int EstimateFormatLength(const char* format, va_list ap);
250
251 /**
252 * Escape specific characters in 'str'.
253 */
254 static std::string EscapeChars(const char* str, const char* chars_to_escape,
255 char escape_char = '\\');
256
257 /** -----------------------------------------------------------------
258 * Filename Manipulation Routines
259 * -----------------------------------------------------------------
260 */
261
262 /**
263 * Replace Windows file system slashes with Unix-style slashes.
264 */
265 static void ConvertToUnixSlashes(std::string& path);
266
267 #ifdef _WIN32
268 /** Calls Encoding::ToWindowsExtendedPath. */
269 static std::wstring ConvertToWindowsExtendedPath(const std::string&);
270 #endif
271
272 /**
273 * For windows this calls ConvertToWindowsOutputPath and for unix
274 * it calls ConvertToUnixOutputPath
275 */
276 static std::string ConvertToOutputPath(const std::string&);
277
278 /**
279 * Convert the path to a string that can be used in a unix makefile.
280 * double slashes are removed, and spaces are escaped.
281 */
282 static std::string ConvertToUnixOutputPath(const std::string&);
283
284 /**
285 * Convert the path to string that can be used in a windows project or
286 * makefile. Double slashes are removed if they are not at the start of
287 * the string, the slashes are converted to windows style backslashes, and
288 * if there are spaces in the string it is double quoted.
289 */
290 static std::string ConvertToWindowsOutputPath(const std::string&);
291
292 /**
293 * Return true if a path with the given name exists in the current directory.
294 */
295 static bool PathExists(const std::string& path);
296
297 /**
298 * Return true if a file exists in the current directory.
299 * If isFile = true, then make sure the file is a file and
300 * not a directory. If isFile = false, then return true
301 * if it is a file or a directory. Note that the file will
302 * also be checked for read access. (Currently, this check
303 * for read access is only done on POSIX systems.)
304 */
305 static bool FileExists(const char* filename, bool isFile);
306 static bool FileExists(const std::string& filename, bool isFile);
307 static bool FileExists(const char* filename);
308 static bool FileExists(const std::string& filename);
309
310 /**
311 * Test if a file exists and can be accessed with the requested
312 * permissions. Symbolic links are followed. Returns true if
313 * the access test was successful.
314 *
315 * On POSIX systems (including Cygwin), this maps to the access
316 * function. On Windows systems, all existing files are
317 * considered readable, and writable files are considered to
318 * have the read-only file attribute cleared.
319 */
320 static bool TestFileAccess(const char* filename,
321 TestFilePermissions permissions);
322 static bool TestFileAccess(const std::string& filename,
323 TestFilePermissions permissions);
324 /**
325 * Cross platform wrapper for stat struct
326 */
327 #if defined(_WIN32) && !defined(__CYGWIN__)
328 typedef struct _stat64 Stat_t;
329 #else
330 typedef struct stat Stat_t;
331 #endif
332
333 /**
334 * Cross platform wrapper for stat system call
335 *
336 * On Windows this may not work for paths longer than 250 characters
337 * due to limitations of the underlying '_wstat64' call.
338 */
339 static int Stat(const char* path, Stat_t* buf);
340 static int Stat(const std::string& path, Stat_t* buf);
341
342 /**
343 * Return file length
344 */
345 static unsigned long FileLength(const std::string& filename);
346
347 /**
348 Change the modification time or create a file
349 */
350 static Status Touch(std::string const& filename, bool create);
351
352 /**
353 * Compare file modification times.
354 * Return true for successful comparison and false for error.
355 * When true is returned, result has -1, 0, +1 for
356 * f1 older, same, or newer than f2.
357 */
358 static Status FileTimeCompare(std::string const& f1, std::string const& f2,
359 int* result);
360
361 /**
362 * Get the file extension (including ".") needed for an executable
363 * on the current platform ("" for unix, ".exe" for Windows).
364 */
365 static const char* GetExecutableExtension();
366
367 /**
368 * Given a path on a Windows machine, return the actual case of
369 * the path as it exists on disk. Path components that do not
370 * exist on disk are returned unchanged. Relative paths are always
371 * returned unchanged. Drive letters are always made upper case.
372 * This does nothing on non-Windows systems but return the path.
373 */
374 static std::string GetActualCaseForPath(const std::string& path);
375
376 /**
377 * Given the path to a program executable, get the directory part of
378 * the path with the file stripped off. If there is no directory
379 * part, the empty string is returned.
380 */
381 static std::string GetProgramPath(const std::string&);
382 static bool SplitProgramPath(const std::string& in_name, std::string& dir,
383 std::string& file, bool errorReport = true);
384
385 /**
386 * Given argv[0] for a unix program find the full path to a running
387 * executable. argv0 can be null for windows WinMain programs
388 * in this case GetModuleFileName will be used to find the path
389 * to the running executable. If argv0 is not a full path,
390 * then this will try to find the full path. If the path is not
391 * found false is returned, if found true is returned. An error
392 * message of the attempted paths is stored in errorMsg.
393 * exeName is the name of the executable.
394 * buildDir is a possibly null path to the build directory.
395 * installPrefix is a possibly null pointer to the install directory.
396 */
397 static bool FindProgramPath(const char* argv0, std::string& pathOut,
398 std::string& errorMsg);
399
400 /**
401 * Given a path to a file or directory, convert it to a full path.
402 * This collapses away relative paths relative to the cwd argument
403 * (which defaults to the current working directory). The full path
404 * is returned.
405 */
406 static std::string CollapseFullPath(std::string const& in_path);
407 static std::string CollapseFullPath(std::string const& in_path,
408 const char* in_base);
409 static std::string CollapseFullPath(std::string const& in_path,
410 std::string const& in_base);
411
412 /**
413 * Get the real path for a given path, removing all symlinks. In
414 * the event of an error (non-existent path, permissions issue,
415 * etc.) the original path is returned if errorMessage pointer is
416 * nullptr. Otherwise empty string is returned and errorMessage
417 * contains error description.
418 */
419 static std::string GetRealPath(const std::string& path,
420 std::string* errorMessage = nullptr);
421
422 /**
423 * Split a path name into its root component and the rest of the
424 * path. The root component is one of the following:
425 * "/" = UNIX full path
426 * "c:/" = Windows full path (can be any drive letter)
427 * "c:" = Windows drive-letter relative path (can be any drive letter)
428 * "//" = Network path
429 * "~/" = Home path for current user
430 * "~u/" = Home path for user 'u'
431 * "" = Relative path
432 *
433 * A pointer to the rest of the path after the root component is
434 * returned. The root component is stored in the "root" string if
435 * given.
436 */
437 static const char* SplitPathRootComponent(const std::string& p,
438 std::string* root = nullptr);
439
440 /**
441 * Split a path name into its basic components. The first component
442 * always exists and is the root returned by SplitPathRootComponent.
443 * The remaining components form the path. If there is a trailing
444 * slash then the last component is the empty string. The
445 * components can be recombined as "c[0]c[1]/c[2]/.../c[n]" to
446 * produce the original path. Home directory references are
447 * automatically expanded if expand_home_dir is true and this
448 * platform supports them.
449 *
450 * This does *not* normalize the input path. All components are
451 * preserved, including empty ones. Typically callers should use
452 * this only on paths that have already been normalized.
453 */
454 static void SplitPath(const std::string& p,
455 std::vector<std::string>& components,
456 bool expand_home_dir = true);
457
458 /**
459 * Join components of a path name into a single string. See
460 * SplitPath for the format of the components.
461 *
462 * This does *not* normalize the input path. All components are
463 * preserved, including empty ones. Typically callers should use
464 * this only on paths that have already been normalized.
465 */
466 static std::string JoinPath(const std::vector<std::string>& components);
467 static std::string JoinPath(std::vector<std::string>::const_iterator first,
468 std::vector<std::string>::const_iterator last);
469
470 /**
471 * Compare a path or components of a path.
472 */
473 static bool ComparePath(const std::string& c1, const std::string& c2);
474
475 /**
476 * Return path of a full filename (no trailing slashes)
477 */
478 static std::string GetFilenamePath(const std::string&);
479
480 /**
481 * Return file name of a full filename (i.e. file name without path)
482 */
483 static std::string GetFilenameName(const std::string&);
484
485 /**
486 * Return longest file extension of a full filename (dot included)
487 */
488 static std::string GetFilenameExtension(const std::string&);
489
490 /**
491 * Return shortest file extension of a full filename (dot included)
492 */
493 static std::string GetFilenameLastExtension(const std::string& filename);
494
495 /**
496 * Return file name without extension of a full filename
497 */
498 static std::string GetFilenameWithoutExtension(const std::string&);
499
500 /**
501 * Return file name without its last (shortest) extension
502 */
503 static std::string GetFilenameWithoutLastExtension(const std::string&);
504
505 /**
506 * Return whether the path represents a full path (not relative)
507 */
508 static bool FileIsFullPath(const std::string&);
509 static bool FileIsFullPath(const char*);
510
511 /**
512 * For windows return the short path for the given path,
513 * Unix just a pass through
514 */
515 static Status GetShortPath(std::string const& path, std::string& result);
516
517 /**
518 * Read line from file. Make sure to read a full line and truncates it if
519 * requested via sizeLimit. Returns true if any data were read before the
520 * end-of-file was reached. If the has_newline argument is specified, it will
521 * be true when the line read had a newline character.
522 */
523 static bool GetLineFromStream(
524 std::istream& istr, std::string& line, bool* has_newline = nullptr,
525 std::string::size_type sizeLimit = std::string::npos);
526
527 /**
528 * Get the parent directory of the directory or file
529 */
530 static std::string GetParentDirectory(const std::string& fileOrDir);
531
532 /**
533 * Check if the given file or directory is in subdirectory of dir
534 */
535 static bool IsSubDirectory(const std::string& fileOrDir,
536 const std::string& dir);
537
538 /** -----------------------------------------------------------------
539 * File Manipulation Routines
540 * -----------------------------------------------------------------
541 */
542
543 /**
544 * Open a file considering unicode. On Windows, if 'e' is present in
545 * mode it is first discarded.
546 */
547 static FILE* Fopen(const std::string& file, const char* mode);
548
549 /**
550 * Visual C++ does not define mode_t.
551 */
552 #if defined(_MSC_VER)
553 typedef unsigned short mode_t;
554 #endif
555
556 /**
557 * Make a new directory if it is not there. This function
558 * can make a full path even if none of the directories existed
559 * prior to calling this function.
560 */
561 static Status MakeDirectory(const char* path, const mode_t* mode = nullptr);
562 static Status MakeDirectory(std::string const& path,
563 const mode_t* mode = nullptr);
564
565 /**
566 * Represent the result of a file copy operation.
567 * This is the result 'Status' and, if the operation failed,
568 * an indication of whether the error occurred on the source
569 * or destination path.
570 */
571 struct CopyStatus : public Status
572 {
573 enum WhichPath
574 {
575 NoPath,
576 SourcePath,
577 DestPath,
578 };
579 CopyStatus() = default;
580 CopyStatus(Status s, WhichPath p)
581 : Status(s)
582 , Path(p)
583 {
584 }
585 WhichPath Path = NoPath;
586 };
587
588 /**
589 * Copy the source file to the destination file only
590 * if the two files differ.
591 */
592 static CopyStatus CopyFileIfDifferent(std::string const& source,
593 std::string const& destination);
594
595 /**
596 * Compare the contents of two files. Return true if different
597 */
598 static bool FilesDiffer(const std::string& source,
599 const std::string& destination);
600
601 /**
602 * Compare the contents of two files, ignoring line ending differences.
603 * Return true if different
604 */
605 static bool TextFilesDiffer(const std::string& path1,
606 const std::string& path2);
607
608 /**
609 * Blockwise copy source to destination file
610 */
611 static CopyStatus CopyFileContentBlockwise(std::string const& source,
612 std::string const& destination);
613 /**
614 * Clone the source file to the destination file
615 */
616 static CopyStatus CloneFileContent(std::string const& source,
617 std::string const& destination);
618
619 /**
620 * Return true if the two files are the same file
621 */
622 static bool SameFile(const std::string& file1, const std::string& file2);
623
624 /**
625 * Copy a file.
626 */
627 static CopyStatus CopyFileAlways(std::string const& source,
628 std::string const& destination);
629
630 /**
631 * Copy a file. If the "always" argument is true the file is always
632 * copied. If it is false, the file is copied only if it is new or
633 * has changed.
634 */
635 static CopyStatus CopyAFile(std::string const& source,
636 std::string const& destination,
637 bool always = true);
638
639 /**
640 * Copy content directory to another directory with all files and
641 * subdirectories. If the "always" argument is true all files are
642 * always copied. If it is false, only files that have changed or
643 * are new are copied.
644 */
645 static Status CopyADirectory(std::string const& source,
646 std::string const& destination,
647 bool always = true);
648
649 /**
650 * Remove a file
651 */
652 static Status RemoveFile(std::string const& source);
653
654 /**
655 * Remove a directory
656 */
657 static Status RemoveADirectory(std::string const& source);
658
659 /**
660 * Get the maximum full file path length
661 */
662 static size_t GetMaximumFilePathLength();
663
664 /**
665 * Find a file in the system PATH, with optional extra paths
666 */
667 static std::string FindFile(
668 const std::string& name,
669 const std::vector<std::string>& path = std::vector<std::string>(),
670 bool no_system_path = false);
671
672 /**
673 * Find a directory in the system PATH, with optional extra paths
674 */
675 static std::string FindDirectory(
676 const std::string& name,
677 const std::vector<std::string>& path = std::vector<std::string>(),
678 bool no_system_path = false);
679
680 /**
681 * Find an executable in the system PATH, with optional extra paths
682 */
683 static std::string FindProgram(
684 const char* name,
685 const std::vector<std::string>& path = std::vector<std::string>(),
686 bool no_system_path = false);
687 static std::string FindProgram(
688 const std::string& name,
689 const std::vector<std::string>& path = std::vector<std::string>(),
690 bool no_system_path = false);
691 static std::string FindProgram(
692 const std::vector<std::string>& names,
693 const std::vector<std::string>& path = std::vector<std::string>(),
694 bool no_system_path = false);
695
696 /**
697 * Find a library in the system PATH, with optional extra paths
698 */
699 static std::string FindLibrary(const std::string& name,
700 const std::vector<std::string>& path);
701
702 /**
703 * Return true if the file is a directory
704 */
705 static bool FileIsDirectory(const std::string& name);
706
707 /**
708 * Return true if the file is an executable
709 */
710 static bool FileIsExecutable(const std::string& name);
711
712 #if defined(_WIN32)
713 /**
714 * Return true if the file with FileAttributes `attr` is a symlink
715 * Only available on Windows. This avoids an expensive `GetFileAttributesW`
716 * call.
717 */
718 static bool FileIsSymlinkWithAttr(const std::wstring& path,
719 unsigned long attr);
720 #endif
721
722 /**
723 * Return true if the file is a symlink
724 */
725 static bool FileIsSymlink(const std::string& name);
726
727 /**
728 * Return true if the file is a FIFO
729 */
730 static bool FileIsFIFO(const std::string& name);
731
732 /**
733 * Return true if the file has a given signature (first set of bytes)
734 */
735 static bool FileHasSignature(const char* filename, const char* signature,
736 long offset = 0);
737
738 /**
739 * Attempt to detect and return the type of a file.
740 * Up to 'length' bytes are read from the file, if more than 'percent_bin' %
741 * of the bytes are non-textual elements, the file is considered binary,
742 * otherwise textual. Textual elements are bytes in the ASCII [0x20, 0x7E]
743 * range, but also \\n, \\r, \\t.
744 * The algorithm is simplistic, and should probably check for usual file
745 * extensions, 'magic' signature, unicode, etc.
746 */
747 enum FileTypeEnum
748 {
749 FileTypeUnknown,
750 FileTypeBinary,
751 FileTypeText
752 };
753 static SystemTools::FileTypeEnum DetectFileType(const char* filename,
754 unsigned long length = 256,
755 double percent_bin = 0.05);
756
757 /**
758 * Create a symbolic link if the platform supports it. Returns whether
759 * creation succeeded.
760 */
761 static Status CreateSymlink(std::string const& origName,
762 std::string const& newName);
763
764 /**
765 * Read the contents of a symbolic link. Returns whether reading
766 * succeeded.
767 */
768 static Status ReadSymlink(std::string const& newName, std::string& origName);
769
770 /**
771 * Try to locate the file 'filename' in the directory 'dir'.
772 * If 'filename' is a fully qualified filename, the basename of the file is
773 * used to check for its existence in 'dir'.
774 * If 'dir' is not a directory, GetFilenamePath() is called on 'dir' to
775 * get its directory first (thus, you can pass a filename as 'dir', as
776 * a convenience).
777 * 'filename_found' is assigned the fully qualified name/path of the file
778 * if it is found (not touched otherwise).
779 * If 'try_filename_dirs' is true, try to find the file using the
780 * components of its path, i.e. if we are looking for c:/foo/bar/bill.txt,
781 * first look for bill.txt in 'dir', then in 'dir'/bar, then in 'dir'/foo/bar
782 * etc.
783 * Return true if the file was found, false otherwise.
784 */
785 static bool LocateFileInDir(const char* filename, const char* dir,
786 std::string& filename_found,
787 int try_filename_dirs = 0);
788
789 /** compute the relative path from local to remote. local must
790 be a directory. remote can be a file or a directory.
791 Both remote and local must be full paths. Basically, if
792 you are in directory local and you want to access the file in remote
793 what is the relative path to do that. For example:
794 /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
795 from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
796 */
797 static std::string RelativePath(const std::string& local,
798 const std::string& remote);
799
800 /**
801 * Return file's modified time
802 */
803 static long int ModifiedTime(const std::string& filename);
804
805 /**
806 * Return file's creation time (Win32: works only for NTFS, not FAT)
807 */
808 static long int CreationTime(const std::string& filename);
809
810 /**
811 * Get and set permissions of the file. If honor_umask is set, the umask
812 * is queried and applied to the given permissions. Returns false if
813 * failure.
814 *
815 * WARNING: A non-thread-safe method is currently used to get the umask
816 * if a honor_umask parameter is set to true.
817 */
818 static Status GetPermissions(const char* file, mode_t& mode);
819 static Status GetPermissions(std::string const& file, mode_t& mode);
820 static Status SetPermissions(const char* file, mode_t mode,
821 bool honor_umask = false);
822 static Status SetPermissions(std::string const& file, mode_t mode,
823 bool honor_umask = false);
824
825 /** -----------------------------------------------------------------
826 * Time Manipulation Routines
827 * -----------------------------------------------------------------
828 */
829
830 /** Get current time in seconds since Posix Epoch (Jan 1, 1970). */
831 static double GetTime();
832
833 /**
834 * Get current date/time
835 */
836 static std::string GetCurrentDateTime(const char* format);
837
838 /** -----------------------------------------------------------------
839 * Registry Manipulation Routines
840 * -----------------------------------------------------------------
841 */
842
843 /**
844 * Specify access to the 32-bit or 64-bit application view of
845 * registry values. The default is to match the currently running
846 * binary type.
847 */
848 enum KeyWOW64
849 {
850 KeyWOW64_Default,
851 KeyWOW64_32,
852 KeyWOW64_64
853 };
854
855 /**
856 * Get a list of subkeys.
857 */
858 static bool GetRegistrySubKeys(const std::string& key,
859 std::vector<std::string>& subkeys,
860 KeyWOW64 view = KeyWOW64_Default);
861
862 /**
863 * Read a registry value
864 */
865 static bool ReadRegistryValue(const std::string& key, std::string& value,
866 KeyWOW64 view = KeyWOW64_Default);
867
868 /**
869 * Write a registry value
870 */
871 static bool WriteRegistryValue(const std::string& key,
872 const std::string& value,
873 KeyWOW64 view = KeyWOW64_Default);
874
875 /**
876 * Delete a registry value
877 */
878 static bool DeleteRegistryValue(const std::string& key,
879 KeyWOW64 view = KeyWOW64_Default);
880
881 /** -----------------------------------------------------------------
882 * Environment Manipulation Routines
883 * -----------------------------------------------------------------
884 */
885
886 /**
887 * Add the paths from the environment variable PATH to the
888 * string vector passed in. If env is set then the value
889 * of env will be used instead of PATH.
890 */
891 static void GetPath(std::vector<std::string>& path,
892 const char* env = nullptr);
893
894 /**
895 * Read an environment variable
896 */
897 static const char* GetEnv(const char* key);
898 static const char* GetEnv(const std::string& key);
899 static bool GetEnv(const char* key, std::string& result);
900 static bool GetEnv(const std::string& key, std::string& result);
901 static bool HasEnv(const char* key);
902 static bool HasEnv(const std::string& key);
903
904 /** Put a string into the environment
905 of the form var=value */
906 static bool PutEnv(const std::string& env);
907
908 /** Remove a string from the environment.
909 Input is of the form "var" or "var=value" (value is ignored). */
910 static bool UnPutEnv(const std::string& env);
911
912 /**
913 * Get current working directory CWD
914 */
915 static std::string GetCurrentWorkingDirectory();
916
917 /**
918 * Change directory to the directory specified
919 */
920 static Status ChangeDirectory(std::string const& dir);
921
922 /**
923 * Get the result of strerror(errno)
924 */
925 static std::string GetLastSystemError();
926
927 /**
928 * When building DEBUG with MSVC, this enables a hook that prevents
929 * error dialogs from popping up if the program is being run from
930 * DART.
931 */
932 static void EnableMSVCDebugHook();
933
934 /**
935 * Get the width of the terminal window. The code may or may not work, so
936 * make sure you have some reasonable defaults prepared if the code returns
937 * some bogus size.
938 */
939 static int GetTerminalWidth();
940
941 #if @KWSYS_NAMESPACE@_SYSTEMTOOLS_USE_TRANSLATION_MAP
942 /**
943 * Add an entry in the path translation table.
944 */
945 static void AddTranslationPath(const std::string& dir,
946 const std::string& refdir);
947
948 /**
949 * If dir is different after CollapseFullPath is called,
950 * Then insert it into the path translation table
951 */
952 static void AddKeepPath(const std::string& dir);
953
954 /**
955 * Update path by going through the Path Translation table;
956 */
957 static void CheckTranslationPath(std::string& path);
958 #endif
959
960 /**
961 * Delay the execution for a specified amount of time specified
962 * in milliseconds
963 */
964 static void Delay(unsigned int msec);
965
966 /**
967 * Get the operating system name and version
968 * This is implemented for Win32 only for the moment
969 */
970 static std::string GetOperatingSystemNameAndVersion();
971
972 /** -----------------------------------------------------------------
973 * URL Manipulation Routines
974 * -----------------------------------------------------------------
975 */
976
977 /**
978 * Parse a character string :
979 * protocol://dataglom
980 * and fill protocol as appropriate.
981 * decode the dataglom using DecodeURL if set to true.
982 * Return false if the URL does not have the required form, true otherwise.
983 */
984 static bool ParseURLProtocol(const std::string& URL, std::string& protocol,
985 std::string& dataglom, bool decode = false);
986
987 /**
988 * Parse a string (a URL without protocol prefix) with the form:
989 * protocol://[[username[':'password]'@']hostname[':'dataport]]'/'[datapath]
990 * and fill protocol, username, password, hostname, dataport, and datapath
991 * when values are found.
992 * decode all string except the protocol using DecodeUrl if set to true.
993 * Return true if the string matches the format; false otherwise.
994 */
995 static bool ParseURL(const std::string& URL, std::string& protocol,
996 std::string& username, std::string& password,
997 std::string& hostname, std::string& dataport,
998 std::string& datapath, bool decode = false);
999
1000 /**
1001 * Decode the percent-encoded string from an URL or an URI
1002 * into their correct char values.
1003 * Does not perform any other sort of validation.
1004 * Return the decoded string
1005 */
1006 static std::string DecodeURL(const std::string& url);
1007
1008 private:
1009 /**
1010 * Allocate the stl map that serve as the Path Translation table.
1011 */
1012 static void ClassInitialize();
1013
1014 /**
1015 * Deallocate the stl map that serve as the Path Translation table.
1016 */
1017 static void ClassFinalize();
1018
1019 /**
1020 * This method prevents warning on SGI
1021 */
1022 SystemToolsManager* GetSystemToolsManager()
1023 {
1024 return &SystemToolsManagerInstance;
1025 }
1026
1027 friend class SystemToolsStatic;
1028 friend class SystemToolsManager;
1029 };
1030
1031 } // namespace @KWSYS_NAMESPACE@
1032
1033 #endif