From cc293f90a245aad5c2eae4b1c28b49101563b134 Mon Sep 17 00:00:00 2001 From: Alexei Znamensky <103110+russoz@users.noreply.github.com> Date: Sun, 23 May 2021 08:20:37 +1200 Subject: [PATCH] ini_file - opening file as utf-8-sig (#2578) * opening file as utf-8-sig * added changelog fragment * using io.open() * Update tests/integration/targets/ini_file/tasks/main.yml Co-authored-by: Felix Fontein Co-authored-by: Felix Fontein --- .../fragments/2578-ini-file-utf8-bom.yml | 2 ++ plugins/modules/files/ini_file.py | 3 +- .../targets/ini_file/tasks/main.yml | 34 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/2578-ini-file-utf8-bom.yml diff --git a/changelogs/fragments/2578-ini-file-utf8-bom.yml b/changelogs/fragments/2578-ini-file-utf8-bom.yml new file mode 100644 index 0000000000..00640c0b23 --- /dev/null +++ b/changelogs/fragments/2578-ini-file-utf8-bom.yml @@ -0,0 +1,2 @@ +minor_changes: + - ini_file - opening file with encoding ``utf-8-sig`` (https://github.com/ansible-collections/community.general/issues/2189). diff --git a/plugins/modules/files/ini_file.py b/plugins/modules/files/ini_file.py index ac4c6d0cf3..ea857cefa9 100644 --- a/plugins/modules/files/ini_file.py +++ b/plugins/modules/files/ini_file.py @@ -104,6 +104,7 @@ EXAMPLES = r''' backup: yes ''' +import io import os import re import tempfile @@ -141,7 +142,7 @@ def do_ini(module, filename, section=None, option=None, value=None, os.makedirs(destpath) ini_lines = [] else: - with open(filename, 'r') as ini_file: + with io.open(filename, 'r', encoding="utf-8-sig") as ini_file: ini_lines = ini_file.readlines() if module._diff: diff --git a/tests/integration/targets/ini_file/tasks/main.yml b/tests/integration/targets/ini_file/tasks/main.yml index 2e84147c72..be5835669b 100644 --- a/tests/integration/targets/ini_file/tasks/main.yml +++ b/tests/integration/targets/ini_file/tasks/main.yml @@ -480,3 +480,37 @@ assert: that: - content15 == expected15 + +- name: Create starting ini file + copy: + # The content below is the following text file with BOM: + # [section1] + # var1=aaa + # var2=bbb + # [section2] + # var3=ccc + content: !!binary | + 77u/W3NlY3Rpb24xXQp2YXIxPWFhYQp2YXIyPWJiYgpbc2VjdGlvbjJdCnZhcjM9Y2NjCg== + dest: "{{ output_file }}" +- name: Test ini breakage + ini_file: + path: "{{ output_file }}" + section: section1 + option: var4 + value: 0 + +- name: read content from output file + slurp: + src: "{{ output_file }}" + register: output_content + +- name: set expected content and get current ini file content + set_fact: + expected16: "[section1]\nvar1=aaa\nvar2=bbb\nvar4 = 0\n[section2]\nvar3=ccc\n" + content16: "{{ output_content.content | b64decode }}" +- debug: + var: content16 +- name: Verify content of ini file is as expected + assert: + that: + - content16 == expected16