Skip to content
Permalink
Browse files

Add method to ensure file name string is safe

  • Loading branch information
nyalldawson committed Dec 19, 2017
1 parent 0a02ed4 commit c7bd7b3d67038e377c1a79a9fbbca3a28830e515
Showing with 27 additions and 0 deletions.
  1. +8 −0 python/core/qgsfileutils.sip
  2. +8 −0 src/core/qgsfileutils.cpp
  3. +8 −0 src/core/qgsfileutils.h
  4. +3 −0 tests/src/python/test_qgsfileutils.py
@@ -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
};

@@ -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;
}
@@ -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
@@ -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.
You can’t perform that action at this time.