Move the file patching code

Moved from the Dependency class to a generalized utility of the
storages app.

Signed-off-by: Roberto Rosario <roberto.rosario@mayan-edms.com>
This commit is contained in:
Roberto Rosario
2019-11-21 01:46:16 -04:00
parent 45c8fefdc4
commit a36c2a6590
3 changed files with 40 additions and 28 deletions
+36
View File
@@ -1,10 +1,16 @@
from __future__ import unicode_literals
import fileinput
import logging
import os
import shutil
import tempfile
from pathlib2 import Path
from django.utils.encoding import force_text
from django.utils.module_loading import import_string
from .settings import setting_temporary_directory
logger = logging.getLogger(__name__)
@@ -49,6 +55,36 @@ def mkstemp(*args, **kwargs):
return tempfile.mkstemp(*args, **kwargs)
def patch_files(path=None, replace_list=None):
"""
Search and replace content from a list of file based on a pattern
replace_list[
{
'filename_pattern': '*.css',
'content_patterns': [
{
'search': '',
'replace': '',
}
]
}
]
"""
path_object = Path(path)
for replace_entry in replace_list or []:
for path_entry in path_object.glob('**/{}'.format(replace_entry['filename_pattern'])):
if path_entry.is_file():
# PY3
# Don't use context processor to allow working on Python 2.7
# Update on Mayan EDMS version >= 4.0
file_object = fileinput.FileInput(force_text(path_entry), inplace=True)
for line in file_object:
for pattern in replace_entry['content_patterns']:
line = line.replace(pattern['search'], pattern['replace'])
print(line, end='')
file_object.close()
def validate_path(path):
if not os.path.exists(path):
# If doesn't exist try to create it