Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] Allow regexes when patching files (tools.replace_regex_in_file) #7007

Open
1 task done
madebr opened this issue May 12, 2020 · 0 comments
Open
1 task done

Comments

@madebr
Copy link
Contributor

madebr commented May 12, 2020

Often, when packaging external software, patching is required.
Right now the main tools we have are:

  • tools.replace_in_file (tools.replace_path_in_file, tools.replace_prefix_in_pc_file)
  • tools.save_append
  • tools.patch

Having the ability to use regex'es to patch sources would be nice.

Example usage:
conan-io/conan-center-index#1607.

This contans a for loop with 2 replaces:

for e in ["MDd", "MTd", "MD", "MT"]:
    tools.replace_in_file(filename, "/%s " % e, "/%s " % self.settings.compiler.runtime, strict=False)
    tools.replace_in_file(filename, "/%s\"" % e, "/%s\"" % self.settings.compiler.runtime, strict=False)

A regex can replace this with:

tools.replace_regex_in_file(os.path.join(filename, "/M[TD]d?([\" ])", "/{}\\1".format(self.settings.compiler.runtime))

Notice also how the strict=False can be removed which gives greater confidence that a patch is working.

example implementation (not tested):

import re


def replace_regex_in_file(file_path, pattern, repl, flags=None, strict=True, output=None, encoding=None):
    output = default_output(output, 'replace_regex_in_file')

    encoding_in = encoding or "auto"
    encoding_out = encoding or "utf-8"
    content = load(file_path, encoding=encoding_in)

    content, nb = re.subn(pattern, repl, content, flags=flags)
    if nb == 0:
        _manage_text_not_found(pattern, file_path, strict, 'replace_regex_in_file', output=output)

    content = content.encode(encoding_out)
    save(file_path, content, only_if_modified=False, encoding=encoding_out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants