Skip to content

Commit c7bd7b3

Browse files
committedDec 19, 2017
Add method to ensure file name string is safe
1 parent 0a02ed4 commit c7bd7b3

File tree

4 files changed

+27
-0
lines changed

4 files changed

+27
-0
lines changed
 

‎python/core/qgsfileutils.sip

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ will be returned unchanged.
6565
.. seealso:: :py:func:`extensionsFromFilter()`
6666

6767
.. seealso:: :py:func:`ensureFileNameHasExtension()`
68+
%End
69+
70+
static QString stringToSafeFilename( const QString &string );
71+
%Docstring
72+
Converts a ``string`` to a safe filename, replacing characters which are not safe
73+
for filenames with an '_' character.
74+
75+
This method should be called with file names only, not complete paths.
6876
%End
6977
};
7078

‎src/core/qgsfileutils.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,11 @@ QString QgsFileUtils::addExtensionFromFilter( const QString &fileName, const QSt
6969
const QStringList extensions = extensionsFromFilter( filter );
7070
return ensureFileNameHasExtension( fileName, extensions );
7171
}
72+
73+
QString QgsFileUtils::stringToSafeFilename( const QString &string )
74+
{
75+
QRegularExpression rx( "[^\\w\\-. ]" );
76+
QString s = string;
77+
s.replace( rx, QStringLiteral( "_" ) );
78+
return s;
79+
}

‎src/core/qgsfileutils.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@ class CORE_EXPORT QgsFileUtils
7070
* \see ensureFileNameHasExtension()
7171
*/
7272
static QString addExtensionFromFilter( const QString &fileName, const QString &filter );
73+
74+
/**
75+
* Converts a \a string to a safe filename, replacing characters which are not safe
76+
* for filenames with an '_' character.
77+
*
78+
* This method should be called with file names only, not complete paths.
79+
*/
80+
static QString stringToSafeFilename( const QString &string );
7381
};
7482

7583
#endif // QGSFILEUTILS_H

‎tests/src/python/test_qgsfileutils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ def testAddExtensionFromFilter(self):
5555
self.assertEqual(QgsFileUtils.addExtensionFromFilter('test.tif', 'All Files (*.*)'), 'test.tif')
5656
self.assertEqual(QgsFileUtils.addExtensionFromFilter('test', 'All Files (*.*)'), 'test')
5757

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

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

0 commit comments

Comments
 (0)
Please sign in to comment.