Remove Path::canWrite.
[oota-llvm.git] / include / llvm / Support / PathV1.h
1 //===- llvm/Support/PathV1.h - Path Operating System Concept ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the llvm::sys::Path class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_PATHV1_H
15 #define LLVM_SUPPORT_PATHV1_H
16
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/TimeValue.h"
20 #include <set>
21 #include <string>
22 #include <vector>
23
24 #define LLVM_PATH_DEPRECATED_MSG(replacement) \
25   "PathV1 has been deprecated and will be removed as soon as all LLVM and" \
26   " Clang clients have been moved over to PathV2. Please use `" #replacement \
27   "` from PathV2 instead."
28
29 namespace llvm {
30 namespace sys {
31
32   /// This structure provides basic file system information about a file. It
33   /// is patterned after the stat(2) Unix operating system call but made
34   /// platform independent and eliminates many of the unix-specific fields.
35   /// However, to support llvm-ar, the mode, user, and group fields are
36   /// retained. These pertain to unix security and may not have a meaningful
37   /// value on non-Unix platforms. However, the other fields should
38   /// always be applicable on all platforms.  The structure is filled in by
39   /// the PathWithStatus class.
40   /// @brief File status structure
41   class FileStatus {
42   public:
43     uint64_t    fileSize;   ///< Size of the file in bytes
44     TimeValue   modTime;    ///< Time of file's modification
45     uint32_t    mode;       ///< Mode of the file, if applicable
46     uint32_t    user;       ///< User ID of owner, if applicable
47     uint32_t    group;      ///< Group ID of owner, if applicable
48     bool        isDir  : 1; ///< True if this is a directory.
49     bool        isFile : 1; ///< True if this is a file.
50
51     FileStatus() : fileSize(0), modTime(0,0), mode(0777), user(999),
52                    group(999), isDir(false), isFile(false) { }
53
54     TimeValue getTimestamp() const { return modTime; }
55     uint64_t getSize() const { return fileSize; }
56     uint32_t getMode() const { return mode; }
57     uint32_t getUser() const { return user; }
58     uint32_t getGroup() const { return group; }
59   };
60
61   /// This class provides an abstraction for the path to a file or directory
62   /// in the operating system's filesystem and provides various basic operations
63   /// on it.  Note that this class only represents the name of a path to a file
64   /// or directory which may or may not be valid for a given machine's file
65   /// system. The class is patterned after the java.io.File class with various
66   /// extensions and several omissions (not relevant to LLVM).  A Path object
67   /// ensures that the path it encapsulates is syntactically valid for the
68   /// operating system it is running on but does not ensure correctness for
69   /// any particular file system. That is, a syntactically valid path might
70   /// specify path components that do not exist in the file system and using
71   /// such a Path to act on the file system could produce errors. There is one
72   /// invalid Path value which is permitted: the empty path.  The class should
73   /// never allow a syntactically invalid non-empty path name to be assigned.
74   /// Empty paths are required in order to indicate an error result in some
75   /// situations. If the path is empty, the isValid operation will return
76   /// false. All operations will fail if isValid is false. Operations that
77   /// change the path will either return false if it would cause a syntactically
78   /// invalid path name (in which case the Path object is left unchanged) or
79   /// throw an std::string exception indicating the error. The methods are
80   /// grouped into four basic categories: Path Accessors (provide information
81   /// about the path without accessing disk), Disk Accessors (provide
82   /// information about the underlying file or directory), Path Mutators
83   /// (change the path information, not the disk), and Disk Mutators (change
84   /// the disk file/directory referenced by the path). The Disk Mutator methods
85   /// all have the word "disk" embedded in their method name to reinforce the
86   /// notion that the operation modifies the file system.
87   /// @since 1.4
88   /// @brief An abstraction for operating system paths.
89   class Path {
90     /// @name Constructors
91     /// @{
92     public:
93       /// Construct a path to a unique temporary directory that is created in
94       /// a "standard" place for the operating system. The directory is
95       /// guaranteed to be created on exit from this function. If the directory
96       /// cannot be created, the function will throw an exception.
97       /// @returns an invalid path (empty) on error
98       /// @param ErrMsg Optional place for an error message if an error occurs
99       /// @brief Construct a path to an new, unique, existing temporary
100       /// directory.
101       static Path GetTemporaryDirectory(std::string* ErrMsg = 0);
102
103       /// Construct a path to the current directory for the current process.
104       /// @returns The current working directory.
105       /// @brief Returns the current working directory.
106       static Path GetCurrentDirectory();
107
108       /// Return the suffix commonly used on file names that contain an
109       /// executable.
110       /// @returns The executable file suffix for the current platform.
111       /// @brief Return the executable file suffix.
112       static StringRef GetEXESuffix();
113
114       /// GetMainExecutable - Return the path to the main executable, given the
115       /// value of argv[0] from program startup and the address of main itself.
116       /// In extremis, this function may fail and return an empty path.
117       static Path GetMainExecutable(const char *argv0, void *MainAddr);
118
119       /// This is one of the very few ways in which a path can be constructed
120       /// with a syntactically invalid name. The only *legal* invalid name is an
121       /// empty one. Other invalid names are not permitted. Empty paths are
122       /// provided so that they can be used to indicate null or error results in
123       /// other lib/System functionality.
124       /// @brief Construct an empty (and invalid) path.
125       Path() : path() {}
126       Path(const Path &that) : path(that.path) {}
127
128       /// This constructor will accept a char* or std::string as a path. No
129       /// checking is done on this path to determine if it is valid. To
130       /// determine validity of the path, use the isValid method.
131       /// @param p The path to assign.
132       /// @brief Construct a Path from a string.
133       explicit Path(StringRef p);
134
135       /// This constructor will accept a character range as a path.  No checking
136       /// is done on this path to determine if it is valid.  To determine
137       /// validity of the path, use the isValid method.
138       /// @param StrStart A pointer to the first character of the path name
139       /// @param StrLen The length of the path name at StrStart
140       /// @brief Construct a Path from a string.
141       Path(const char *StrStart, unsigned StrLen);
142
143     /// @}
144     /// @name Operators
145     /// @{
146     public:
147       /// Makes a copy of \p that to \p this.
148       /// @returns \p this
149       /// @brief Assignment Operator
150       Path &operator=(const Path &that) {
151         path = that.path;
152         return *this;
153       }
154
155       /// Makes a copy of \p that to \p this.
156       /// @param that A StringRef denoting the path
157       /// @returns \p this
158       /// @brief Assignment Operator
159       Path &operator=(StringRef that);
160
161       /// Compares \p this Path with \p that Path for equality.
162       /// @returns true if \p this and \p that refer to the same thing.
163       /// @brief Equality Operator
164       bool operator==(const Path &that) const;
165
166       /// Compares \p this Path with \p that Path for inequality.
167       /// @returns true if \p this and \p that refer to different things.
168       /// @brief Inequality Operator
169       bool operator!=(const Path &that) const { return !(*this == that); }
170
171       /// Determines if \p this Path is less than \p that Path. This is required
172       /// so that Path objects can be placed into ordered collections (e.g.
173       /// std::map). The comparison is done lexicographically as defined by
174       /// the std::string::compare method.
175       /// @returns true if \p this path is lexicographically less than \p that.
176       /// @brief Less Than Operator
177       bool operator<(const Path& that) const;
178
179     /// @}
180     /// @name Path Accessors
181     /// @{
182     public:
183       /// This function will use an operating system specific algorithm to
184       /// determine if the current value of \p this is a syntactically valid
185       /// path name for the operating system. The path name does not need to
186       /// exist, validity is simply syntactical. Empty paths are always invalid.
187       /// @returns true iff the path name is syntactically legal for the
188       /// host operating system.
189       /// @brief Determine if a path is syntactically valid or not.
190       bool isValid() const;
191
192       /// This function determines if the contents of the path name are empty.
193       /// That is, the path name has a zero length. This does NOT determine if
194       /// if the file is empty. To get the length of the file itself, Use the
195       /// PathWithStatus::getFileStatus() method and then the getSize() method
196       /// on the returned FileStatus object.
197       /// @returns true iff the path is empty.
198       /// @brief Determines if the path name is empty (invalid).
199       bool isEmpty() const { return path.empty(); }
200
201
202
203       /// Obtain a 'C' string for the path name.
204       /// @returns a 'C' string containing the path name.
205       /// @brief Returns the path as a C string.
206       const char *c_str() const { return path.c_str(); }
207       const std::string &str() const { return path; }
208
209
210       /// size - Return the length in bytes of this path name.
211       size_t size() const { return path.size(); }
212
213       /// empty - Returns true if the path is empty.
214       unsigned empty() const { return path.empty(); }
215
216     /// @}
217     /// @name Disk Accessors
218     /// @{
219     public:
220       /// This function determines if the path name in the object references an
221       /// archive file by looking at its magic number.
222       /// @returns true if the file starts with the magic number for an archive
223       /// file.
224       /// @brief Determine if the path references an archive file.
225       bool isArchive() const;
226
227       /// This function determines if the path name in the object references a
228       /// native Dynamic Library (shared library, shared object) by looking at
229       /// the file's magic number. The Path object must reference a file, not a
230       /// directory.
231       /// @returns true if the file starts with the magic number for a native
232       /// shared library.
233       /// @brief Determine if the path references a dynamic library.
234       bool isDynamicLibrary() const;
235
236       /// This function determines if the path name in the object references a
237       /// native object file by looking at it's magic number. The term object
238       /// file is defined as "an organized collection of separate, named
239       /// sequences of binary data." This covers the obvious file formats such
240       /// as COFF and ELF, but it also includes llvm ir bitcode, archives,
241       /// libraries, etc...
242       /// @returns true if the file starts with the magic number for an object
243       /// file.
244       /// @brief Determine if the path references an object file.
245       bool isObjectFile() const;
246
247       /// This function determines if the path name references an existing file
248       /// or directory in the file system.
249       /// @returns true if the pathname references an existing file or
250       /// directory.
251       /// @brief Determines if the path is a file or directory in
252       /// the file system.
253       LLVM_ATTRIBUTE_DEPRECATED(bool exists() const,
254         LLVM_PATH_DEPRECATED_MSG(fs::exists));
255
256       /// This function determines if the path name references an
257       /// existing directory.
258       /// @returns true if the pathname references an existing directory.
259       /// @brief Determines if the path is a directory in the file system.
260       LLVM_ATTRIBUTE_DEPRECATED(bool isDirectory() const,
261         LLVM_PATH_DEPRECATED_MSG(fs::is_directory));
262
263       /// This function determines if the path name references an
264       /// existing symbolic link.
265       /// @returns true if the pathname references an existing symlink.
266       /// @brief Determines if the path is a symlink in the file system.
267       LLVM_ATTRIBUTE_DEPRECATED(bool isSymLink() const,
268         LLVM_PATH_DEPRECATED_MSG(fs::is_symlink));
269
270       /// This function checks that what we're trying to work only on a regular
271       /// file. Check for things like /dev/null, any block special file, or
272       /// other things that aren't "regular" regular files.
273       /// @returns true if the file is S_ISREG.
274       /// @brief Determines if the file is a regular file
275       bool isRegularFile() const;
276
277       /// This function determines if the path name references an executable
278       /// file in the file system. This function checks for the existence and
279       /// executability (by the current program) of the file.
280       /// @returns true if the pathname references an executable file.
281       /// @brief Determines if the path is an executable file in the file
282       /// system.
283       bool canExecute() const;
284
285       /// This function builds a list of paths that are the names of the
286       /// files and directories in a directory.
287       /// @returns true if an error occurs, true otherwise
288       /// @brief Build a list of directory's contents.
289       bool getDirectoryContents(
290         std::set<Path> &paths, ///< The resulting list of file & directory names
291         std::string* ErrMsg    ///< Optional place to return an error message.
292       ) const;
293
294     /// @}
295     /// @name Path Mutators
296     /// @{
297     public:
298       /// The path name is cleared and becomes empty. This is an invalid
299       /// path name but is the *only* invalid path name. This is provided
300       /// so that path objects can be used to indicate the lack of a
301       /// valid path being found.
302       /// @brief Make the path empty.
303       void clear() { path.clear(); }
304
305       /// This method sets the Path object to \p unverified_path. This can fail
306       /// if the \p unverified_path does not pass the syntactic checks of the
307       /// isValid() method. If verification fails, the Path object remains
308       /// unchanged and false is returned. Otherwise true is returned and the
309       /// Path object takes on the path value of \p unverified_path
310       /// @returns true if the path was set, false otherwise.
311       /// @param unverified_path The path to be set in Path object.
312       /// @brief Set a full path from a StringRef
313       bool set(StringRef unverified_path);
314
315       /// One path component is removed from the Path. If only one component is
316       /// present in the path, the Path object becomes empty. If the Path object
317       /// is empty, no change is made.
318       /// @returns false if the path component could not be removed.
319       /// @brief Removes the last directory component of the Path.
320       bool eraseComponent();
321
322       /// The \p component is added to the end of the Path if it is a legal
323       /// name for the operating system. A directory separator will be added if
324       /// needed.
325       /// @returns false if the path component could not be added.
326       /// @brief Appends one path component to the Path.
327       bool appendComponent(StringRef component);
328
329       /// A period and the \p suffix are appended to the end of the pathname.
330       /// When the \p suffix is empty, no action is performed.
331       /// @brief Adds a period and the \p suffix to the end of the pathname.
332       void appendSuffix(StringRef suffix);
333
334       /// The suffix of the filename is erased. The suffix begins with and
335       /// includes the last . character in the filename after the last directory
336       /// separator and extends until the end of the name. If no . character is
337       /// after the last directory separator, then the file name is left
338       /// unchanged (i.e. it was already without a suffix) but the function
339       /// returns false.
340       /// @returns false if there was no suffix to remove, true otherwise.
341       /// @brief Remove the suffix from a path name.
342       bool eraseSuffix();
343
344       /// The current Path name is made unique in the file system. Upon return,
345       /// the Path will have been changed to make a unique file in the file
346       /// system or it will not have been changed if the current path name is
347       /// already unique.
348       /// @throws std::string if an unrecoverable error occurs.
349       /// @brief Make the current path name unique in the file system.
350       bool makeUnique( bool reuse_current /*= true*/, std::string* ErrMsg );
351
352       /// The current Path name is made absolute by prepending the
353       /// current working directory if necessary.
354       LLVM_ATTRIBUTE_DEPRECATED(
355         void makeAbsolute(),
356         LLVM_PATH_DEPRECATED_MSG(fs::make_absolute));
357
358     /// @}
359     /// @name Disk Mutators
360     /// @{
361     public:
362       /// This method attempts to make the file referenced by the Path object
363       /// available for reading so that the canRead() method will return true.
364       /// @brief Make the file readable;
365       bool makeReadableOnDisk(std::string* ErrMsg = 0);
366
367       /// This method attempts to make the file referenced by the Path object
368       /// available for writing so that the canWrite() method will return true.
369       /// @brief Make the file writable;
370       bool makeWriteableOnDisk(std::string* ErrMsg = 0);
371
372       /// This method allows the last modified time stamp and permission bits
373       /// to be set on the disk object referenced by the Path.
374       /// @throws std::string if an error occurs.
375       /// @returns true on error.
376       /// @brief Set the status information.
377       bool setStatusInfoOnDisk(const FileStatus &SI,
378                                std::string *ErrStr = 0) const;
379
380       /// This method attempts to create a directory in the file system with the
381       /// same name as the Path object. The \p create_parents parameter controls
382       /// whether intermediate directories are created or not. if \p
383       /// create_parents is true, then an attempt will be made to create all
384       /// intermediate directories, as needed. If \p create_parents is false,
385       /// then only the final directory component of the Path name will be
386       /// created. The created directory will have no entries.
387       /// @returns true if the directory could not be created, false otherwise
388       /// @brief Create the directory this Path refers to.
389       bool createDirectoryOnDisk(
390         bool create_parents = false, ///<  Determines whether non-existent
391            ///< directory components other than the last one (the "parents")
392            ///< are created or not.
393         std::string* ErrMsg = 0 ///< Optional place to put error messages.
394       );
395
396       /// This is like createFile except that it creates a temporary file. A
397       /// unique temporary file name is generated based on the contents of
398       /// \p this before the call. The new name is assigned to \p this and the
399       /// file is created.  Note that this will both change the Path object
400       /// *and* create the corresponding file. This function will ensure that
401       /// the newly generated temporary file name is unique in the file system.
402       /// @returns true if the file couldn't be created, false otherwise.
403       /// @brief Create a unique temporary file
404       bool createTemporaryFileOnDisk(
405         bool reuse_current = false, ///< When set to true, this parameter
406           ///< indicates that if the current file name does not exist then
407           ///< it will be used without modification.
408         std::string* ErrMsg = 0 ///< Optional place to put error messages
409       );
410
411       /// This method renames the file referenced by \p this as \p newName. The
412       /// file referenced by \p this must exist. The file referenced by
413       /// \p newName does not need to exist.
414       /// @returns true on error, false otherwise
415       /// @brief Rename one file as another.
416       bool renamePathOnDisk(const Path& newName, std::string* ErrMsg);
417
418       /// This method attempts to destroy the file or directory named by the
419       /// last component of the Path. If the Path refers to a directory and the
420       /// \p destroy_contents is false, an attempt will be made to remove just
421       /// the directory (the final Path component). If \p destroy_contents is
422       /// true, an attempt will be made to remove the entire contents of the
423       /// directory, recursively. If the Path refers to a file, the
424       /// \p destroy_contents parameter is ignored.
425       /// @param destroy_contents Indicates whether the contents of a destroyed
426       /// @param Err An optional string to receive an error message.
427       /// directory should also be destroyed (recursively).
428       /// @returns false if the file/directory was destroyed, true on error.
429       /// @brief Removes the file or directory from the filesystem.
430       bool eraseFromDisk(bool destroy_contents = false,
431                          std::string *Err = 0) const;
432
433     /// @}
434     /// @name Data
435     /// @{
436     protected:
437       // Our win32 implementation relies on this string being mutable.
438       mutable std::string path;   ///< Storage for the path name.
439
440
441     /// @}
442   };
443
444   /// This class is identical to Path class except it allows you to obtain the
445   /// file status of the Path as well. The reason for the distinction is one of
446   /// efficiency. First, the file status requires additional space and the space
447   /// is incorporated directly into PathWithStatus without an additional malloc.
448   /// Second, obtaining status information is an expensive operation on most
449   /// operating systems so we want to be careful and explicit about where we
450   /// allow this operation in LLVM.
451   /// @brief Path with file status class.
452   class PathWithStatus : public Path {
453     /// @name Constructors
454     /// @{
455     public:
456       /// @brief Default constructor
457       PathWithStatus() : Path(), status(), fsIsValid(false) {}
458
459       /// @brief Copy constructor
460       PathWithStatus(const PathWithStatus &that)
461         : Path(static_cast<const Path&>(that)), status(that.status),
462            fsIsValid(that.fsIsValid) {}
463
464       /// This constructor allows construction from a Path object
465       /// @brief Path constructor
466       PathWithStatus(const Path &other)
467         : Path(other), status(), fsIsValid(false) {}
468
469       /// This constructor will accept a char* or std::string as a path. No
470       /// checking is done on this path to determine if it is valid. To
471       /// determine validity of the path, use the isValid method.
472       /// @brief Construct a Path from a string.
473       explicit PathWithStatus(
474         StringRef p ///< The path to assign.
475       ) : Path(p), status(), fsIsValid(false) {}
476
477       /// This constructor will accept a character range as a path.  No checking
478       /// is done on this path to determine if it is valid.  To determine
479       /// validity of the path, use the isValid method.
480       /// @brief Construct a Path from a string.
481       explicit PathWithStatus(
482         const char *StrStart,  ///< Pointer to the first character of the path
483         unsigned StrLen        ///< Length of the path.
484       ) : Path(StrStart, StrLen), status(), fsIsValid(false) {}
485
486       /// Makes a copy of \p that to \p this.
487       /// @returns \p this
488       /// @brief Assignment Operator
489       PathWithStatus &operator=(const PathWithStatus &that) {
490         static_cast<Path&>(*this) = static_cast<const Path&>(that);
491         status = that.status;
492         fsIsValid = that.fsIsValid;
493         return *this;
494       }
495
496       /// Makes a copy of \p that to \p this.
497       /// @returns \p this
498       /// @brief Assignment Operator
499       PathWithStatus &operator=(const Path &that) {
500         static_cast<Path&>(*this) = static_cast<const Path&>(that);
501         fsIsValid = false;
502         return *this;
503       }
504
505     /// @}
506     /// @name Methods
507     /// @{
508     public:
509       /// This function returns status information about the file. The type of
510       /// path (file or directory) is updated to reflect the actual contents
511       /// of the file system.
512       /// @returns 0 on failure, with Error explaining why (if non-zero),
513       /// otherwise returns a pointer to a FileStatus structure on success.
514       /// @brief Get file status.
515       const FileStatus *getFileStatus(
516         bool forceUpdate = false, ///< Force an update from the file system
517         std::string *Error = 0    ///< Optional place to return an error msg.
518       ) const;
519
520     /// @}
521     /// @name Data
522     /// @{
523     private:
524       mutable FileStatus status; ///< Status information.
525       mutable bool fsIsValid;    ///< Whether we've obtained it or not
526
527     /// @}
528   };
529
530   /// This is the OS-specific path separator: a colon on Unix or a semicolon
531   /// on Windows.
532   extern const char PathSeparator;
533 }
534
535 }
536
537 #endif