Skip to content

Commit

Permalink
Add method to ensure file name string is safe
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Dec 19, 2017
1 parent 0a02ed4 commit c7bd7b3
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions python/core/qgsfileutils.sip
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ will be returned unchanged.
.. seealso:: :py:func:`extensionsFromFilter()`

.. seealso:: :py:func:`ensureFileNameHasExtension()`
%End

static QString stringToSafeFilename( const QString &string );
%Docstring
Converts a ``string`` to a safe filename, replacing characters which are not safe
for filenames with an '_' character.

This method should be called with file names only, not complete paths.
%End
};

Expand Down
8 changes: 8 additions & 0 deletions src/core/qgsfileutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,11 @@ QString QgsFileUtils::addExtensionFromFilter( const QString &fileName, const QSt
const QStringList extensions = extensionsFromFilter( filter );
return ensureFileNameHasExtension( fileName, extensions );
}

QString QgsFileUtils::stringToSafeFilename( const QString &string )
{
QRegularExpression rx( "[^\\w\\-. ]" );
QString s = string;
s.replace( rx, QStringLiteral( "_" ) );
return s;
}
8 changes: 8 additions & 0 deletions src/core/qgsfileutils.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ class CORE_EXPORT QgsFileUtils
* \see ensureFileNameHasExtension()
*/
static QString addExtensionFromFilter( const QString &fileName, const QString &filter );

/**
* Converts a \a string to a safe filename, replacing characters which are not safe
* for filenames with an '_' character.
*
* This method should be called with file names only, not complete paths.
*/
static QString stringToSafeFilename( const QString &string );
};

#endif // QGSFILEUTILS_H
3 changes: 3 additions & 0 deletions tests/src/python/test_qgsfileutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ def testAddExtensionFromFilter(self):
self.assertEqual(QgsFileUtils.addExtensionFromFilter('test.tif', 'All Files (*.*)'), 'test.tif')
self.assertEqual(QgsFileUtils.addExtensionFromFilter('test', 'All Files (*.*)'), 'test')

def testStringToSafeFilename(self):
self.assertEqual(QgsFileUtils.stringToSafeFilename('my FiLe v2.0_new.tif'), 'my FiLe v2.0_new.tif')
self.assertEqual(QgsFileUtils.stringToSafeFilename('rendered map_final? rev (12-03-1017)_real@#$&*#%&*$!!@$%^&(*(.tif'), 'rendered map_final_ rev _12-03-1017__real____________________.tif')

if __name__ == '__main__':
unittest.main()

0 comments on commit c7bd7b3

Please sign in to comment.