Skip to content

Commit

Permalink
uniqueFilePath
Browse files Browse the repository at this point in the history
  • Loading branch information
elpaso committed Jan 5, 2023
1 parent 863a126 commit 1ac4dd3
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
18 changes: 18 additions & 0 deletions python/core/auto_generated/qgsfileutils.sip.in
Expand Up @@ -193,6 +193,24 @@ E.g. if ``path`` is "/home/user/Pictures/test.png", the returned list will conta

.. versionadded:: 3.28
%End

static QString uniquePath( const QString &path );
%Docstring
Creates a unique file path name from a desired path by appending "_<n>" (where "<n>" is an integer number) before the file suffix.

E.g. if "/path/my_image.png" already exists "/path/my_image_1.png" (and "_2", "_3" etc.) will be checked until a file path that does not already exist is found.

:param path: the desired path.

:return: the unmodified path if path is already unique or the new path with "_<n>" (where "<n>" is an integer number) appended to the file name before the suffix.

.. note::

This function does not make any check on path validity and write permissions.

.. versionadded:: 3.30
%End

};

/************************************************************************
Expand Down
20 changes: 20 additions & 0 deletions src/core/qgsfileutils.cpp
Expand Up @@ -529,3 +529,23 @@ QStringList QgsFileUtils::splitPathToComponents( const QString &input )
std::reverse( result.begin(), result.end() );
return result;
}

QString QgsFileUtils::uniquePath( const QString &path )
{
if ( ! QFileInfo::exists( path ) )
{
return path;
}

QFileInfo info { path };
const QString suffix { info.completeSuffix() };
const QString pathPattern { QString( suffix.length() > 0 ? path.chopped( suffix.length() + 1 ) : path ).append( QStringLiteral( "_%1." ) ).append( suffix ) };
int i { 1 };
QString uniquePath { pathPattern.arg( i ) };
while ( QFileInfo::exists( uniquePath ) )
{
++i;
uniquePath = pathPattern.arg( i );
}
return uniquePath;
}
13 changes: 13 additions & 0 deletions src/core/qgsfileutils.h
Expand Up @@ -224,6 +224,19 @@ class CORE_EXPORT QgsFileUtils
* \since QGIS 3.28
*/
static QStringList splitPathToComponents( const QString &path );

/**
* Creates a unique file path name from a desired path by appending "_<n>" (where "<n>" is an integer number) before the file suffix.
*
* E.g. if "/path/my_image.png" already exists "/path/my_image_1.png" (and "_2", "_3" etc.) will be checked until a file path that does not already exist is found.
*
* \param path the desired path.
* \return the unmodified path if path is already unique or the new path with "_<n>" (where "<n>" is an integer number) appended to the file name before the suffix.
* \note This function does not make any check on path validity and write permissions.
* \since QGIS 3.30
*/
static QString uniquePath( const QString &path );

};

#endif // QGSFILEUTILS_H

0 comments on commit 1ac4dd3

Please sign in to comment.