File: //var/opt/nydus/ops/customer_local_ops/util/helpers.py
# -*- coding: utf-8 -*-
"""\
© Copyright. All rights reserved.
"""
from __future__ import unicode_literals
from fileinput import FileInput
from functools import reduce
import sys
class HandledFailureException(Exception):
pass
def edit_file_lines(filename, editfunc):
"""Iterates through the lines of the named file, calling the editfunc
for each line, replacing the original file with the new
output.
"""
with FileInput(files=(filename,), inplace=True) as f:
for line in f:
sys.stdout.write(editfunc(line))
def replace_file_lines_multiple(filename, replace_dict, firstword=True):
"""Iterates through the lines of the named file, and through a
dictionary of match -> replace pairs, replacing all that apply for each line,
and replacing the original file with the new output.
"""
with FileInput(files=(filename,), inplace=True) as f:
for line in f:
updated_line = line
for match, replace in replace_dict.items():
updated_line = replace_line(updated_line, match, replace, firstword)
sys.stdout.write(updated_line)
def replace_line(line, match, replace, firstword=True):
"""Checks `line` to see if it starts with `match`; if yes, return
`replace`, otherwise return the original `line`. If
`firstword` is True, then the match must be followed by at
least one space or tab (unless it matches the entire line),
otherwise it is matched directly.
Suitable for use as an editfunc with `edit_file_lines`.
"""
# pylint: disable=too-many-boolean-expressions
if (
line.strip() == match
or (firstword and (line.startswith(match+' ') or line.startswith(match+'\t')))
or (not firstword and line.startswith(match))
):
return replace
return line
def append_line(filename, line):
"""Appends a line to to the specified file.
"""
with open(filename, 'a', encoding='UTF-8') as file:
file.write('\n')
file.write(line)
def create_file(filename, contents):
"""Creates the specified file, with the specified contents.
Overwrites any file already existing at that location.
"""
with open(filename, 'w', encoding='UTF-8') as wf:
wf.write(contents)
def compose(*funcs):
return reduce(lambda f, g: lambda x: f(g(x)), funcs, lambda x: x)