LibrePCB Developers Documentation
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
FilePath Class Referencefinal

This class represents absolute, well-formatted paths to files or directories. More...

#include <filepath.h>

+ Collaboration diagram for FilePath:

Public Types

enum  CleanFileNameOption
 

Public Member Functions

 Q_DECLARE_FLAGS (CleanFileNameOptions, CleanFileNameOption)
 
 FilePath () noexcept
 The default constructor (this will create an invalid object!) More...
 
 FilePath (const QString &filepath) noexcept
 Constructor to create a FilePath object from a QString. More...
 
 FilePath (const FilePath &other) noexcept
 The copy constructor. More...
 
bool setPath (const QString &filepath) noexcept
 Set a new filepath. More...
 
bool isValid () const noexcept
 Check whether this object contains a valid filepath or not. More...
 
bool isExistingFile () const noexcept
 Check if the specified filepath is an existing file. More...
 
bool isExistingDir () const noexcept
 Check if the specified filepath is an existing directory. More...
 
bool isEmptyDir () const noexcept
 Check if the specified filepath is an existing, empty directory. More...
 
bool isRoot () const noexcept
 Check if the specified filepath is the root directory. More...
 
bool isLocatedInDir (const FilePath &dir) const noexcept
 Check if the filepath is located inside another directory. More...
 
QString toStr () const noexcept
 Get the absolute and well-formatted filepath as a QString. More...
 
QString toNative () const noexcept
 Get the absolute filepath with native directory separators ("/" resp. "\") More...
 
FilePath toUnique () const noexcept
 Get a unique version of the filepath (resolve symbolic links if possible) More...
 
QString toRelative (const FilePath &base) const noexcept
 Convert an absolute filepath to a relative filepath (relative to another filepath) More...
 
QUrl toQUrl () const noexcept
 Create and return a QUrl object with this filepath. More...
 
QString getBasename () const noexcept
 Get the basename of the file or directory. More...
 
QString getCompleteBasename () const noexcept
 Get the complete basename of the file or directory. More...
 
QString getSuffix () const noexcept
 Get the suffix of the file or directory. More...
 
QString getCompleteSuffix () const noexcept
 Get the complete suffix of the file or directory. More...
 
QString getFilename () const noexcept
 Get the whole filename (without the path) of the file or directory. More...
 
FilePath getParentDir () const noexcept
 Get the filepath of the parent directory of the file or directory. More...
 
FilePath getPathTo (const QString &filename) const noexcept
 Get the filepath to a file or directory which is relative to this filepath. More...
 
FilePathoperator= (const FilePath &rhs) noexcept
 The assign operator to copy a FilePath into another FilePath object. More...
 
bool operator== (const FilePath &rhs) const noexcept
 The "==" operator to compare two FilePath objects. More...
 
bool operator!= (const FilePath &rhs) const noexcept
 The "!=" operator to compare two FilePath objects. More...
 

Static Public Member Functions

static FilePath fromRelative (const FilePath &base, const QString &relative) noexcept
 Build an absolute and well-formatted filepath from a relative filepath. More...
 
static FilePath getTempPath () noexcept
 Get the path to the temporary directory (e.g. "/tmp" on Unix/Linux) More...
 
static FilePath getApplicationTempPath () noexcept
 Get the path to the temporary application directory (e.g. "/tmp/librepcb") More...
 
static FilePath getRandomTempPath () noexcept
 Get a random temporary directory path (e.g. "/tmp/librepcb/42") More...
 
static QString cleanFileName (const QString &userInput, CleanFileNameOptions options) noexcept
 Clean a given string so that it becomes a valid filename. More...
 

Static Private Member Functions

static QString makeWellFormatted (const QString &filepath) noexcept
 Make a filepath well-formatted (except making it absolute!) More...
 

Private Attributes

bool mIsValid
 
QFileInfo mFileInfo
 the absolute and well-formatted filepath in a QFileInfo More...
 

Detailed Description

This class represents absolute, well-formatted paths to files or directories.

Why we need well-formatted paths and what do they look like

Using QString for paths to directories or files works not bad, but there are some disadventages. As the receiver of a filepath in form of a QString, you...

  • never know whether it uses native separators or not ("/" or "\", depends on the OS)
  • never know whether it is an absolute or a relative filepath
  • never know whether it contains redundant separators ("//" or "\\")
  • never know whether it contains "." or ".." entries
  • never know whether a filepath to a directory ends with a separator or not

This means, you have to make a lot of checks at runtime to verify the filepath. But that's annoying and can lead into problems if you do not make these checks always solid.

The class FilePath provides a way to avoid such problems and tries to reduce the count of runtime checks you have to perform yourself (the checks will be performed anyway, but the class FilePath will do this for you).

For compatibility reasons between different operating systems, we should follow these rules for all paths in the whole project (if not explicitly needed other formats):

  • Always use absolute paths, never relative paths (relative paths can be dangerous!)
  • Always use "/" as directory separator (UNIX style), never "\" (Windows style)
  • A filepath to a directory must never end with a slash (except the UNIX root "/")
  • Never use redundant separators ("//") in paths
  • Never use "." and ".." in paths
Note
For convenience, a filepath which satisfies ALL these rules is called a "well formatted filepath" in this documentation.

To reach this goal, you need to convert each filepath which comes from outside the application (user input, read from file, ...) immediately into such a well-formatted filepath (make absolute, convert separators, remove redundant entries and so on). Then the filepath can be proccessed by the application. If a filepath must be printed to outside the application (print to a message box, write to a file, ...), the filepath can be converted (back) to the needed format (maybe "\" instead of "/", maybe relative instead of absolute, ...).

How the class FilePath works and how to use it

The class FilePath represents a well-formatted filepath to a file or directory and provides methods to convert paths between different formats. Every FilePath object represents either a well-formatted filepath or an invalid object (see isValid()). It's not possible to create FilePath objects with non-well-formatted filepaths.

Example:

FilePath fp("C:\foo\bar.txt"); // a file
qDebug(fp.toStr()); // "C:/foo/bar.txt" <-- this is the
well-formatted filepath qDebug(fp.toNative()); // "C:\foo\bar.txt" on
Windows, otherwise "C:/foo/bar.txt" fp.setPath("/foo/bar/"); // a
directory qDebug(fp.toStr()); // "/foo/bar" <-- well-formatted (no
slash at the end!) qDebug(fp.toNative()); // "\foo\bar" on Windows,
otherwise "/foo/bar"
Note
A filepath represented by a FilePath object do not need to exist on the file system. Most methods of this class do not depend on whether a filepath exists or not. Exceptions: toUnique(), isExistingFile(), isExistingDir().
Warning
Please consider that the conversion from filepaths with backslashes as directory separator (Windows style) to filepaths with slashes as directory separator (UNIX style, well-formatted paths) will work only on windows! The reason is that backslashes are allowed in UNIX filepaths (and are NOT interpreted as directory separator), so it's not allowed to replace all backslashes in a UNIX filepath with slashes!
Be careful with special characters in filepaths! Especially (relative) filepaths in the library or in projects must always work on all operating systems (the whole workspace must be platform independent!). This means that only characters are allowed which can be used in filepaths on all operating systems (for example the backslash "\" is allowed in UNIX filenames, but not in Windows filenames). Other filepaths, like filepaths to recently used projects (which are stored in the user's profile), do not need to be platform independent.
Author
ubruhin
Date
2014-07-31

Member Enumeration Documentation

Enumerator
KeepSpaces 
ReplaceSpaces 
KeepCase 
ToLowerCase 
ToUpperCase 
Default 

Constructor & Destructor Documentation

FilePath ( )
noexcept

The default constructor (this will create an invalid object!)

+ Here is the caller graph for this function:

FilePath ( const QString &  filepath)
explicitnoexcept

Constructor to create a FilePath object from a QString.

Parameters
filepathSee setPath()

+ Here is the call graph for this function:

FilePath ( const FilePath other)
noexcept

The copy constructor.

Parameters
otherThe object to copy

Member Function Documentation

Q_DECLARE_FLAGS ( CleanFileNameOptions  ,
CleanFileNameOption   
)
bool setPath ( const QString &  filepath)
noexcept

Set a new filepath.

Parameters
filepathAn absolute (!) filepath to a file or directory (the target do not need to exist). On Windows, both forward ("/") and backward ("\") slashes are allowed as directory separators (also mixed in one filepath). On other operating systems, only forward slashes ("/") are allowed!. Also ".", ".." and redundant directory separators are allowed.
Returns
true on success, false on error (then this object will be invalid!)

+ Here is the caller graph for this function:

bool isValid ( ) const
inlinenoexcept

Check whether this object contains a valid filepath or not.

Returns
true if the filepath is valid, false if not

+ Here is the caller graph for this function:

bool isExistingFile ( ) const
noexcept

Check if the specified filepath is an existing file.

Returns
true if the path points to an existing file, false otherwise

+ Here is the caller graph for this function:

bool isExistingDir ( ) const
noexcept

Check if the specified filepath is an existing directory.

Returns
true if the path points to an existing directory, false otherwise

+ Here is the caller graph for this function:

bool isEmptyDir ( ) const
noexcept

Check if the specified filepath is an existing, empty directory.

Returns
true if the path points to an existing, empty directory, false otherwise

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool isRoot ( ) const
noexcept

Check if the specified filepath is the root directory.

Returns
True if the filepath is the filesystem root, false otherwise

+ Here is the caller graph for this function:

bool isLocatedInDir ( const FilePath dir) const
noexcept

Check if the filepath is located inside another directory.

Returns
True if the filepath points to an item inside "dir", false otherwise

+ Here is the caller graph for this function:

QString toStr ( ) const
noexcept

Get the absolute and well-formatted filepath as a QString.

Returns
The absolute and well-formatted filepath, or an empty QString if this object is invalid.

+ Here is the caller graph for this function:

QString toNative ( ) const
noexcept

Get the absolute filepath with native directory separators ("/" resp. "\")

Returns
The same as toStr(), but with native separators (on other platforms than Windows, this method is identical to toStr())

+ Here is the caller graph for this function:

FilePath toUnique ( ) const
noexcept

Get a unique version of the filepath (resolve symbolic links if possible)

Because of symbolic links, the user is able to have different paths which all point to the same file/directory. But sometimes you want to determine whether two paths point to the same file/directory ("equal paths") or not ("different paths"). For this purpose you can use toUnique(). This method will resolve symbolic links if possible (this is only possible if the filepath exists!). If the filepath does not exist, this method will return the same as toStr().

Returns
The filepath with resolved symbolic links (if possible, otherwise the unchanged filepath)

+ Here is the call graph for this function:

QString toRelative ( const FilePath base) const
noexcept

Convert an absolute filepath to a relative filepath (relative to another filepath)

Parameters
baseThe base of the relative filepath (the part which will be removed from the absolute filepath). This must be a filepath to a directory, paths to a file will produce wrong results!
Returns
A relative filepath with "/" as directory separators (can contain "../")
Note
This method is very useful to store relative paths in (text) files.
See Also
fromRelative()

+ Here is the caller graph for this function:

QUrl toQUrl ( ) const
inlinenoexcept

Create and return a QUrl object with this filepath.

Returns
QUrl object which points to this local file (QUrl::fromLocalFile())

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

QString getBasename ( ) const
noexcept

Get the basename of the file or directory.

Returns
The filename before the first '.' character

+ Here is the caller graph for this function:

QString getCompleteBasename ( ) const
noexcept

Get the complete basename of the file or directory.

Returns
The filename before the last '.' character

+ Here is the caller graph for this function:

QString getSuffix ( ) const
noexcept

Get the suffix of the file or directory.

Returns
The filename after the last '.' character

+ Here is the caller graph for this function:

QString getCompleteSuffix ( ) const
noexcept

Get the complete suffix of the file or directory.

Returns
The filename after the first '.' character
QString getFilename ( ) const
noexcept

Get the whole filename (without the path) of the file or directory.

Returns
The whole filename

+ Here is the caller graph for this function:

FilePath getParentDir ( ) const
noexcept

Get the filepath of the parent directory of the file or directory.

Returns
A FilePath object with the parent directory (can be invalid if you try to get the parent directory of the filesystem root!)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

FilePath getPathTo ( const QString &  filename) const
noexcept

Get the filepath to a file or directory which is relative to this filepath.

Parameters
filenameA relative filepath to a file or directory, like "file.txt" or "subdir/file.txt"
Returns
A FilePath object to the specified file or directory
Warning
This method works only correct if this filepath represents a directory!
Note
This method is equal to FilePath::fromRelative(*this, filename);

+ Here is the caller graph for this function:

FilePath fromRelative ( const FilePath base,
const QString &  relative 
)
staticnoexcept

Build an absolute and well-formatted filepath from a relative filepath.

Parameters
baseThe base of the relative filepath (the part which is missed from the absolute filepath). This must be a filepath to a directory, paths to a file will produce wrong results!
relativeThe relative path (relative to "base")
Returns
A FilePath object with the absolute filepath
Note
This method is very useful to load relative paths from (text) files.
See Also
toRelative()

+ Here is the caller graph for this function:

FilePath getTempPath ( )
staticnoexcept

Get the path to the temporary directory (e.g. "/tmp" on Unix/Linux)

Returns
The filepath (in case of an error, the path can be invalid!)
Todo:
test this method on windows and mac!

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

FilePath getApplicationTempPath ( )
staticnoexcept

Get the path to the temporary application directory (e.g. "/tmp/librepcb")

Returns
The filepath (in case of an error, the path can be invalid!)
Todo:
test this method on windows and mac!

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

FilePath getRandomTempPath ( )
staticnoexcept

Get a random temporary directory path (e.g. "/tmp/librepcb/42")

Returns
The random filepath (in case of an error, the path can be invalid!)

+ Here is the call graph for this function:

QString cleanFileName ( const QString &  userInput,
CleanFileNameOptions  options 
)
staticnoexcept

Clean a given string so that it becomes a valid filename.

Every time a file- or directory name needs to be constructed (e.g. from user input), you must use this function to replace/remove all characters which are not allowed for file/dir paths.

These are the only allowed characters: "-._ 0-9A-Za-z"

In addition, the length of the filename will be limited to 120 characters.

Parameters
userInputAn arbitrary string (may be directly from a user input field)
optionsSome options to define how the filename should be escaped
Returns
A string which is either empty or a valid filename (based on userInput)
Note
This function does exectly the same on all supported platforms, even if the set of allowed characters depends on the platform. This way we can guarantee that all created files/directories are platform independent.

+ Here is the caller graph for this function:

FilePath & operator= ( const FilePath rhs)
noexcept

The assign operator to copy a FilePath into another FilePath object.

bool operator== ( const FilePath rhs) const
noexcept

The "==" operator to compare two FilePath objects.

Note
This method compares the return values of toStr() of both objects.
Returns
true if both filepaths are identical, false otherwise
bool operator!= ( const FilePath rhs) const
noexcept

The "!=" operator to compare two FilePath objects.

Note
This method compares the return values of toStr() of both objects.
Returns
false if both filepaths are identical, true otherwise
QString makeWellFormatted ( const QString &  filepath)
staticprivatenoexcept

Make a filepath well-formatted (except making it absolute!)

Parameters
filepathAn absolute or relative filepath which may isn't well-formatted
Returns
A filepath which satisfies all rules for well-formatted paths, except that it is absolute (it can be relative!)

Member Data Documentation

bool mIsValid
private
QFileInfo mFileInfo
private

the absolute and well-formatted filepath in a QFileInfo


The documentation for this class was generated from the following files: