mirror of
https://github.com/qgis/QGIS.git
synced 2025-04-14 00:07:35 -04:00
Add method to ensure file name string is safe
This commit is contained in:
parent
0a02ed4312
commit
c7bd7b3d67
@ -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 @@ class TestQgsFileUtils(unittest.TestCase):
|
||||
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()
|
||||
|
Loading…
x
Reference in New Issue
Block a user