Skip to contentSkip to conversation

convert: add support for different encodings

PATCH Superseded [email protected] 5 participants 26 messages Mar 4, 2018 – Mar 7, 2018 Documentation

v9 of 13 Superseded Latest is v13 →

lore
Share & tools
lore
#0 lore raw

v9 cover convert: add support for different encodings

From: Lars Schneider <[email protected]>

Hi,

Patches 1-4,7 are preparation and helper functions. Patch 5,6,8 are the actual change.

This series depends on Torsten's 8462ff43e4 (convert_to_git():
safe_crlf/checksafe becomes int conv_flags, 2018-01-13) which is already in master.

Changes since v8:

* move UTF BOM error checks in a new dedicated function validate_encoding() and into a dedicated commit (6)
* remove unnecessary encoding struct (became a plain char*)
* fail early and do not try to run the reencode content in case of a validation error
* return early if roundtrip encoding was not found (avoid undefined pointer arithmetic)
* fix wrong argument order in encode_to_worktree() error message
* use test_when_finished to cleanup tests
* move UTF-16/32 BOM test file generation into "setup test"
* reduce code duplication in tests
* improve documentation:
- use *.rc and *.ps1 as examples as they are usually UTF-16 encoded
* fix comment: /advise/advice/

Thanks a lot Eric for your great review! I think I fixed everything you objected with one exception. You noticed that the current code only checks for BOMs corresponding to the declared size (16 or 32 bits) [1]. I understand your point of view and I agree that any BOM in these cases is *most likely* an error. However, according to the spec it might still be valid. The comments on my related question on StackOverflow seem to support that view [2]. Therefore, I would like to leave it as it is in this series. If it turns out to be a problem in practice, then I am happy to change it later. OK for you?

Thanks,
Lars

[1] https://public-inbox.org/git/[email protected]/
[2] https://stackoverflow.com/questions/49038872/is-a-utf-32be-bom-valid-in-an-utf-16le-declared-data-stream

RFC: https://public-inbox.org/git/[email protected]/
v1: https://public-inbox.org/git/[email protected]/
v2: https://public-inbox.org/git/[email protected]/
v3: https://public-inbox.org/git/[email protected]/
v4: https://public-inbox.org/git/[email protected]/
v5: https://public-inbox.org/git/[email protected]/
v6: https://public-inbox.org/git/[email protected]/
v7: https://public-inbox.org/git/[email protected]/
v8: https://public-inbox.org/git/[email protected]/

Base Ref:
Web-Diff: https://github.com/larsxschneider/git/commit/fdf0d63188
Checkout: git fetch https://github.com/larsxschneider/git encoding-v9 && git checkout fdf0d63188

### Interdiff (v8..v9):

Documentation/gitattributes.txt +11 -9
index 11315054f4..aa3deae392 100644
@@ -297,14 +297,16 @@ number of pitfalls:
   in your repository, then it is strongly recommended to ensure that all
   clients working with the repository support it.
 
-  If you declare `*.proj` files as UTF-16 and you add `foo.proj` with an
-  `working-tree-encoding` enabled Git client, then `foo.proj` will be
+  For example, Microsoft Visual Studio resources files (`*.rc`) or
+  PowerShell script files (`*.ps1`) are sometimes encoded in UTF-16.
+  If you declare `*.ps1` as files as UTF-16 and you add `foo.ps1` with
+  a `working-tree-encoding` enabled Git client, then `foo.ps1` will be
   stored as UTF-8 internally. A client without `working-tree-encoding`
-  support will checkout `foo.proj` as UTF-8 encoded file. This will
+  support will checkout `foo.ps1` as UTF-8 encoded file. This will
   typically cause trouble for the users of this file.
 
   If a Git client, that does not support the `working-tree-encoding`
-  attribute, adds a new file `bar.proj`, then `bar.proj` will be
+  attribute, adds a new file `bar.ps1`, then `bar.ps1` will be
   stored "as-is" internally (in this example probably as UTF-16).
   A client with `working-tree-encoding` support will interpret the
   internal contents as UTF-8 and try to convert it to UTF-16 on checkout.
@@ -325,22 +327,22 @@ Use the `working-tree-encoding` attribute only if you cannot store a file
 in UTF-8 encoding and if you want Git to be able to process the content
 as text.
 
-As an example, use the following attributes if your '*.proj' files are
+As an example, use the following attributes if your '*.ps1' files are
 UTF-16 encoded with byte order mark (BOM) and you want Git to perform
 automatic line ending conversion based on your platform.
 
 ------------------------
-*.proj		text working-tree-encoding=UTF-16
+*.ps1		text working-tree-encoding=UTF-16
 ------------------------
 
-Use the following attributes if your '*.proj' files are UTF-16 little
+Use the following attributes if your '*.ps1' files are UTF-16 little
 endian encoded without BOM and you want Git to use Windows line endings
 in the working directory. Please note, it is highly recommended to
 explicitly define the line endings with `eol` if the `working-tree-encoding`
 attribute is used to avoid ambiguity.
 
 ------------------------
-*.proj 		text working-tree-encoding=UTF-16LE eol=CRLF
+*.ps1		text working-tree-encoding=UTF-16LE eol=CRLF
 ------------------------
 
 You can get a list of all available encodings on your platform with the
@@ -354,7 +356,7 @@ If you do not know the encoding of a file, then you can use the `file`
 command to guess the encoding:
 
 ------------------------
-file foo.proj
+file foo.ps1
 ------------------------
 
 
convert.c +76 -65

244 lines not on this page · raw message

t/t0028-working-tree-encoding.sh +112 -148

369 lines not on this page · raw message

utf8.h +10 -7
index 62f86fba64..cce654a64a 100644
@@ -71,9 +71,9 @@ void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int wid
 		       const char *s);
 
 /*
- * Whenever a data stream is declared to be UTF-16BE, UTF-16LE, UTF-32BE
- * or UTF-32LE a BOM must not be used [1]. The function returns true if
- * this is the case.
+ * If a data stream is declared as UTF-16BE or UTF-16LE, then a UTF-16
+ * BOM must not be used [1]. The same applies for the UTF-32 equivalents.
+ * The function returns true if this rule is violated.
  *
  * [1] http://unicode.org/faq/utf_bom.html#bom10
  */
@@ -83,10 +83,13 @@ int has_prohibited_utf_bom(const char *enc, const char *data, size_t len);
  * If the endianness is not defined in the encoding name, then we
  * require a BOM. The function returns true if a required BOM is missing.
  *
- * The Unicode standard instructs to assume big-endian if there
- * in no BOM for UTF-16/32 [1][2]. However, the W3C/WHATWG
- * encoding standard used in HTML5 recommends to assume
- * little-endian to "deal with deployed content" [3].
+ * The Unicode standard instructs to assume big-endian if there in no
+ * BOM for UTF-16/32 [1][2]. However, the W3C/WHATWG encoding standard
+ * used in HTML5 recommends to assume little-endian to "deal with
+ * deployed content" [3].
+ *
+ * Therefore, strictly requiring a BOM seems to be the safest option for
+ * content in Git.
  *
  * [1] http://unicode.org/faq/utf_bom.html#gen6
  * [2] http://www.unicode.org/versions/Unicode10.0.0/ch03.pdf

### Patches

Lars Schneider (8):
strbuf: remove unnecessary NUL assignment in xstrdup_tolower()
strbuf: add xstrdup_toupper()
utf8: add function to detect prohibited UTF-16/32 BOM
utf8: add function to detect a missing UTF-16/32 BOM
convert: add 'working-tree-encoding' attribute
convert: check for detectable errors in UTF encodings
convert: add tracing for 'working-tree-encoding' attribute
convert: add round trip check based on 'core.checkRoundtripEncoding'

 Documentation/config.txt         |   6 +
 Documentation/gitattributes.txt  |  88 +++++++++++++
 config.c                         |   5 +
 convert.c                        | 267 ++++++++++++++++++++++++++++++++++++++-
 convert.h                        |   2 +
 environment.c                    |   1 +
 sha1_file.c                      |   2 +-
 strbuf.c                         |  13 +-
 strbuf.h                         |   1 +
 t/t0028-working-tree-encoding.sh | 233 ++++++++++++++++++++++++++++++++++
 utf8.c                           |  37 ++++++
 utf8.h                           |  28 ++++
 12 files changed, 680 insertions(+), 3 deletions(-)
 create mode 100755 t/t0028-working-tree-encoding.sh

base-commit: 8a2f0888555ce46ac87452b194dec5cb66fb1417 --
2.16.2

#1 lore raw

PATCH v9 1/8 strbuf: remove unnecessary NUL assignment in xstrdup_tolower()

From: Lars Schneider <[email protected]>

Since 3733e69464 (use xmallocz to avoid size arithmetic, 2016-02-22) we allocate the buffer for the lower case string with xmallocz(). This already ensures a NUL at the end of the allocated buffer.

Remove the unnecessary assignment.

---
 strbuf.c | 1 -
 1 file changed, 1 deletion(-)
strbuf.c +0 -1
index 1df674e919..55b7daeb35 100644
@@ -781,7 +781,6 @@ char *xstrdup_tolower(const char *string)
 	result = xmallocz(len);
 	for (i = 0; i < len; i++)
 		result[i] = tolower(string[i]);
-	result[i] = '\0';
 	return result;
 }
 
Signature · 1 line
2.16.2
#2 lore raw

PATCH v9 2/8 strbuf: add xstrdup_toupper()

In reply to [email protected]

From: Lars Schneider <[email protected]>

Create a copy of an existing string and make all characters upper case. Similar xstrdup_tolower().

This function is used in a subsequent commit.

---
 strbuf.c | 12 ++++++++++++
 strbuf.h |  1 +
 2 files changed, 13 insertions(+)
strbuf.c +12 -0
index 55b7daeb35..b635f0bdc4 100644
@@ -784,6 +784,18 @@ char *xstrdup_tolower(const char *string)
 	return result;
 }
 
+char *xstrdup_toupper(const char *string)
+{
+	char *result;
+	size_t len, i;
+
+	len = strlen(string);
+	result = xmallocz(len);
+	for (i = 0; i < len; i++)
+		result[i] = toupper(string[i]);
+	return result;
+}
+
 char *xstrvfmt(const char *fmt, va_list ap)
 {
 	struct strbuf buf = STRBUF_INIT;
strbuf.h +1 -0
index 14c8c10d66..df7ced53ed 100644
@@ -607,6 +607,7 @@ __attribute__((format (printf,2,3)))
 extern int fprintf_ln(FILE *fp, const char *fmt, ...);
 
 char *xstrdup_tolower(const char *);
+char *xstrdup_toupper(const char *);
 
 /**
  * Create a newly allocated string using printf format. You can do this easily
Signature · 1 line
2.16.2
#3 lore raw

PATCH v9 3/8 utf8: add function to detect prohibited UTF-16/32 BOM

In reply to [email protected]

From: Lars Schneider <[email protected]>

Whenever a data stream is declared to be UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE a BOM must not be used [1]. The function returns true if this is the case.

This function is used in a subsequent commit.

[1] http://unicode.org/faq/utf_bom.html#bom10

---
 utf8.c | 24 ++++++++++++++++++++++++
 utf8.h |  9 +++++++++
 2 files changed, 33 insertions(+)
utf8.c +24 -0
index 2c27ce0137..914881cd1f 100644
@@ -538,6 +538,30 @@ char *reencode_string_len(const char *in, int insz,
 }
 #endif
 
+static int has_bom_prefix(const char *data, size_t len,
+			  const char *bom, size_t bom_len)
+{
+	return (len >= bom_len) && !memcmp(data, bom, bom_len);
+}
+
+static const char utf16_be_bom[] = {0xFE, 0xFF};
+static const char utf16_le_bom[] = {0xFF, 0xFE};
+static const char utf32_be_bom[] = {0x00, 0x00, 0xFE, 0xFF};
+static const char utf32_le_bom[] = {0xFF, 0xFE, 0x00, 0x00};
+
+int has_prohibited_utf_bom(const char *enc, const char *data, size_t len)
+{
+	return (
+	  (!strcmp(enc, "UTF-16BE") || !strcmp(enc, "UTF-16LE")) &&
+	  (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+	   has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+	) || (
+	  (!strcmp(enc, "UTF-32BE") || !strcmp(enc, "UTF-32LE")) &&
+	  (has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+	   has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
+	);
+}
+
 /*
  * Returns first character length in bytes for multi-byte `text` according to
  * `encoding`.
utf8.h +9 -0
index 6bbcf31a83..0db1db4519 100644
@@ -70,4 +70,13 @@ typedef enum {
 void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
 		       const char *s);
 
+/*
+ * If a data stream is declared as UTF-16BE or UTF-16LE, then a UTF-16
+ * BOM must not be used [1]. The same applies for the UTF-32 equivalents.
+ * The function returns true if this rule is violated.
+ *
+ * [1] http://unicode.org/faq/utf_bom.html#bom10
+ */
+int has_prohibited_utf_bom(const char *enc, const char *data, size_t len);
+
 #endif
Signature · 1 line
2.16.2
#4 lore raw

PATCH v9 4/8 utf8: add function to detect a missing UTF-16/32 BOM

In reply to [email protected]

From: Lars Schneider <[email protected]>

If the endianness is not defined in the encoding name, then let's be strict and require a BOM to avoid any encoding confusion. The is_missing_required_utf_bom() function returns true if a required BOM is missing.

The Unicode standard instructs to assume big-endian if there in no BOM for UTF-16/32 [1][2]. However, the W3C/WHATWG encoding standard used in HTML5 recommends to assume little-endian to "deal with deployed content" [3]. Strictly requiring a BOM seems to be the safest option for content in Git.

This function is used in a subsequent commit.

[1] http://unicode.org/faq/utf_bom.html#gen6
[2] http://www.unicode.org/versions/Unicode10.0.0/ch03.pdf

     Section 3.10, D98, page 132

[3] https://encoding.spec.whatwg.org/#utf-16le

---
 utf8.c | 13 +++++++++++++
 utf8.h | 19 +++++++++++++++++++
 2 files changed, 32 insertions(+)
utf8.c +13 -0
index 914881cd1f..5113d26e56 100644
@@ -562,6 +562,19 @@ int has_prohibited_utf_bom(const char *enc, const char *data, size_t len)
 	);
 }
 
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
+{
+	return (
+	   !strcmp(enc, "UTF-16") &&
+	   !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+	     has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+	) || (
+	   !strcmp(enc, "UTF-32") &&
+	   !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+	     has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
+	);
+}
+
 /*
  * Returns first character length in bytes for multi-byte `text` according to
  * `encoding`.
utf8.h +19 -0
index 0db1db4519..cce654a64a 100644
@@ -79,4 +79,23 @@ void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int wid
  */
 int has_prohibited_utf_bom(const char *enc, const char *data, size_t len);
 
+/*
+ * If the endianness is not defined in the encoding name, then we
+ * require a BOM. The function returns true if a required BOM is missing.
+ *
+ * The Unicode standard instructs to assume big-endian if there in no
+ * BOM for UTF-16/32 [1][2]. However, the W3C/WHATWG encoding standard
+ * used in HTML5 recommends to assume little-endian to "deal with
+ * deployed content" [3].
+ *
+ * Therefore, strictly requiring a BOM seems to be the safest option for
+ * content in Git.
+ *
+ * [1] http://unicode.org/faq/utf_bom.html#gen6
+ * [2] http://www.unicode.org/versions/Unicode10.0.0/ch03.pdf
+ *     Section 3.10, D98, page 132
+ * [3] https://encoding.spec.whatwg.org/#utf-16le
+ */
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len);
+
 #endif
Signature · 1 line
2.16.2
#5 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

utf8.c int has_prohibited_utf_bom(const char *enc, const char *data, size_t len) · line 576

Quoted 12 lines · [email protected] writes:
utf8.c +12 -0
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
+{
+	return (
+	   !strcmp(enc, "UTF-16") &&
+	   !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+	     has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+	) || (
+	   !strcmp(enc, "UTF-32") &&
+	   !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+	     has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
+	);
+}

These strcmp() calls seem inconsistent with the principle embodied by utf8.c::fallback_encoding(), i.e. "be lenient to what we accept", and make the interface uneven. I am wondering if we also want to complain when the user gave us "utf16" and there is no byte order mark in the contents, for example? Also "UTF16" or other spelling the platform may support but this code fails to recognise will go unchecked.

Which actually may be a feature, not a bug, to be able to bypass this check---I dunno.

The same comment applies to the previous step.

#6 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 15 lines · Junio C Hamano
Quoted 10 lines · [email protected] writes:
utf8.c +10 -0
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
+{
+	return (
+	   !strcmp(enc, "UTF-16") &&
+	   !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+	     has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+	) || (
+	   !strcmp(enc, "UTF-32") &&
+	   !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+	     has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
Quoted 8 lines

utf8.c int has_prohibited_utf_bom(const char *enc, const char *data, size_t len) · line 576

Quoted 2 lines
utf8.c +2 -0
+	);
+}

These strcmp() calls seem inconsistent with the principle embodied by utf8.c::fallback_encoding(), i.e. "be lenient to what we accept", and make the interface uneven. I am wondering if we also want to complain when the user gave us "utf16" and there is no byte order mark in the contents, for example?

Well, if I use stricmp() then I don't need to call and cleanup xstrdup_toupper() as discussed with Eric [1]. Is there a case insensitive starts_with() method?

[1] https://public-inbox.org/git/CAPig+cQE0pKs-AMvh4GndyCXBMnx=70jPpDM6K4jJTe-74FecQ@mail.gmail.com/

Quoted 3 lines

Also "UTF16" or other spelling
the platform may support but this code fails to recognise will go unchecked.

That is true. However, I would assume all iconv implementations use the same encoding names for UTF encodings, no? That means UTF16 would never be valid. Would you agree?

- Lars

#7 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 7 lines · Lars Schneider
Quoted 3 lines

Also "UTF16" or other spelling
the platform may support but this code fails to recognise will go unchecked.

That is true. However, I would assume all iconv implementations use the same encoding names for UTF encodings, no? That means UTF16 would never be valid. Would you agree?

After seeing "UTF16" and others in "iconv -l | grep -i utf" output, I am not sure what you mean by "Would you agree?" People can say in their .gitattributes file that this path is in "UTF16" without dash and that is what will be fed to this coe, no?

#8 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 9 lines · Junio C Hamano
Quoted 4 lines · Lars Schneider
Quoted 3 lines

Also "UTF16" or other spelling
the platform may support but this code fails to recognise will go unchecked.

Quoted 8 lines
Quoted 3 lines

That is true. However, I would assume all iconv implementations use the same encoding names for UTF encodings, no? That means UTF16 would never be valid. Would you agree?

After seeing "UTF16" and others in "iconv -l | grep -i utf" output, I am not sure what you mean by "Would you agree?" People can say in their .gitattributes file that this path is in "UTF16" without dash and that is what will be fed to this coe, no?

On macOS I don't see UTF16... but I just checked on my Linux box and there it is. Consequently, we need to check both versions: with and without dash.

I'll reroll ASAP (I try to do it first thing in the morning).

Thanks,
Lars

#9 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

In reply to Junio C Hamano
Quoted 6 lines · Junio C Hamano
Quoted 4 lines · Lars Schneider
Quoted 3 lines

Also "UTF16" or other spelling
the platform may support but this code fails to recognise will go unchecked.

Quoted 8 lines
Quoted 3 lines

That is true. However, I would assume all iconv implementations use the same encoding names for UTF encodings, no? That means UTF16 would never be valid. Would you agree?

After seeing "UTF16" and others in "iconv -l | grep -i utf" output, I am not sure what you mean by "Would you agree?" People can say in their .gitattributes file that this path is in "UTF16" without dash and that is what will be fed to this code, no?

FWIW, "iconv -f utf8 -t utf16" seems not to complain, so I am reasonably sure that people expect downcased ones to work as well.

#10 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 15 lines · Junio C Hamano
Quoted 10 lines · Junio C Hamano
Quoted 7 lines · Lars Schneider
Quoted 3 lines

Also "UTF16" or other spelling
the platform may support but this code fails to recognise will go unchecked.

That is true. However, I would assume all iconv implementations use the same encoding names for UTF encodings, no? That means UTF16 would never be valid. Would you agree?

Quoted 7 lines
Quoted 4 lines

After seeing "UTF16" and others in "iconv -l | grep -i utf" output, I am not sure what you mean by "Would you agree?" People can say in their .gitattributes file that this path is in "UTF16" without dash and that is what will be fed to this code, no?

FWIW, "iconv -f utf8 -t utf16" seems not to complain, so I am reasonably sure that people expect downcased ones to work as well.

Sure! That's why I normalized it to upper case:
https://public-inbox.org/git/CAPig+cQE0pKs-AMvh4GndyCXBMnx=70jPpDM6K4jJTe-74FecQ@mail.gmail.com/

After thinking about it I wonder if we should barf on "utf16" without dash. Your Linux iconv would handle this correctly. My macOS iconv would not. That means the repo would checkout correctly on your machine but not on mine.

What do you think?

- Lars

#11 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 5 lines · Lars Schneider

After thinking about it I wonder if we should barf on "utf16" without dash. Your Linux iconv would handle this correctly. My macOS iconv would not. That means the repo would checkout correctly on your machine but not on mine.

What do you think?

To be bluntly honest, I prefer not to have excess "sanity checks"; there is no need to barf on utf16 in a project run by those who are without macOS friends, for example. For that matter, while I do not hate it so much to reject it, I am not all that supportive of this "The consortium says without -LE or -BE suffix there must be BOM, and this lacks one, so barf loudly" step in this topic myself.

#12 lore raw

Re: [PATCH v9 4/8] utf8: add function to detect a missing UTF-16/32 BOM

Quoted 6 lines · Junio C Hamano
Quoted 4 lines · Lars Schneider

After thinking about it I wonder if we should barf on "utf16" without dash. Your Linux iconv would handle this correctly. My macOS iconv would not. That means the repo would checkout correctly on your machine but not on mine.

Quoted 8 lines
Quoted 1 line

What do you think?

To be bluntly honest, I prefer not to have excess "sanity checks"; there is no need to barf on utf16 in a project run by those who are without macOS friends, for example. For that matter, while I do not hate it so much to reject it, I am not all that supportive of this "The consortium says without -LE or -BE suffix there must be BOM, and this lacks one, so barf loudly" step in this topic myself.

Loosing or adding a BOM couild render a file useless, depending on the SW that reads and processes it.

The main reason for being critacal is to make sure that the material in the working-tree does a safe roundtrip when commited, pushed, pulled, checked out...

The best thing we can do is probably to follow the specification as good as possible.

Having a clear specification (UTF-16LE/BE has no BOM, UTF-16 has none, UTF-16 has a BOM) would even open the chance to work around a buggy iconv library, because Git can check the BOM.
If, and only if, a platform messes it up, and we want to make a (compile time) workaround in Git for this very platform.

A consistant behavior across all platforms is a good thing, sometimes I have a network share mounted to Linux, MacOS and Windows and it doesn't matter under which Git on which machine I checkout or commit.

Oh, I see, there is a new patch coming...

#13 lore raw

PATCH v9 5/8 convert: add 'working-tree-encoding' attribute

In reply to [email protected]

From: Lars Schneider <[email protected]>

Git recognizes files encoded with ASCII or one of its supersets (e.g. UTF-8 or ISO-8859-1) as text files. All other encodings are usually interpreted as binary and consequently built-in Git text processing tools (e.g. 'git diff') as well as most Git web front ends do not visualize the content.

Add an attribute to tell Git what encoding the user has defined for a given file. If the content is added to the index, then Git converts the content to a canonical UTF-8 representation. On checkout Git will reverse the conversion.

---
 Documentation/gitattributes.txt  |  80 +++++++++++++++++++++++
 convert.c                        | 114 ++++++++++++++++++++++++++++++++-
 convert.h                        |   1 +
 sha1_file.c                      |   2 +-
 t/t0028-working-tree-encoding.sh | 135 +++++++++++++++++++++++++++++++++++++++
 5 files changed, 330 insertions(+), 2 deletions(-)
 create mode 100755 t/t0028-working-tree-encoding.sh
Documentation/gitattributes.txt +80 -0
index 30687de81a..31a4f92840 100644
@@ -272,6 +272,86 @@ few exceptions.  Even though...
   catch potential problems early, safety triggers.
 
 
+`working-tree-encoding`
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Git recognizes files encoded in ASCII or one of its supersets (e.g.
+UTF-8, ISO-8859-1, ...) as text files. Files encoded in certain other
+encodings (e.g. UTF-16) are interpreted as binary and consequently
+built-in Git text processing tools (e.g. 'git diff') as well as most Git
+web front ends do not visualize the contents of these files by default.
+
+In these cases you can tell Git the encoding of a file in the working
+directory with the `working-tree-encoding` attribute. If a file with this
+attribute is added to Git, then Git reencodes the content from the
+specified encoding to UTF-8. Finally, Git stores the UTF-8 encoded
+content in its internal data structure (called "the index"). On checkout
+the content is reencoded back to the specified encoding.
+
+Please note that using the `working-tree-encoding` attribute may have a
+number of pitfalls:
+
+- Alternative Git implementations (e.g. JGit or libgit2) and older Git
+  versions (as of March 2018) do not support the `working-tree-encoding`
+  attribute. If you decide to use the `working-tree-encoding` attribute
+  in your repository, then it is strongly recommended to ensure that all
+  clients working with the repository support it.
+
+  For example, Microsoft Visual Studio resources files (`*.rc`) or
+  PowerShell script files (`*.ps1`) are sometimes encoded in UTF-16.
+  If you declare `*.ps1` as files as UTF-16 and you add `foo.ps1` with
+  a `working-tree-encoding` enabled Git client, then `foo.ps1` will be
+  stored as UTF-8 internally. A client without `working-tree-encoding`
+  support will checkout `foo.ps1` as UTF-8 encoded file. This will
+  typically cause trouble for the users of this file.
+
+  If a Git client, that does not support the `working-tree-encoding`
+  attribute, adds a new file `bar.ps1`, then `bar.ps1` will be
+  stored "as-is" internally (in this example probably as UTF-16).
+  A client with `working-tree-encoding` support will interpret the
+  internal contents as UTF-8 and try to convert it to UTF-16 on checkout.
+  That operation will fail and cause an error.
+
+- Reencoding content requires resources that might slow down certain
+  Git operations (e.g 'git checkout' or 'git add').
+
+Use the `working-tree-encoding` attribute only if you cannot store a file
+in UTF-8 encoding and if you want Git to be able to process the content
+as text.
+
+As an example, use the following attributes if your '*.ps1' files are
+UTF-16 encoded with byte order mark (BOM) and you want Git to perform
+automatic line ending conversion based on your platform.
+
+------------------------
+*.ps1		text working-tree-encoding=UTF-16
+------------------------
+
+Use the following attributes if your '*.ps1' files are UTF-16 little
+endian encoded without BOM and you want Git to use Windows line endings
+in the working directory. Please note, it is highly recommended to
+explicitly define the line endings with `eol` if the `working-tree-encoding`
+attribute is used to avoid ambiguity.
+
+------------------------
+*.ps1		text working-tree-encoding=UTF-16LE eol=CRLF
+------------------------
+
+You can get a list of all available encodings on your platform with the
+following command:
+
+------------------------
+iconv --list
+------------------------
+
+If you do not know the encoding of a file, then you can use the `file`
+command to guess the encoding:
+
+------------------------
+file foo.ps1
+------------------------
+
+
 `ident`
 ^^^^^^^
 
convert.c +113 -1

174 lines not on this page · raw message

convert.h +1 -0
index 65ab3e5167..1d9539ed0b 100644
@@ -12,6 +12,7 @@ struct index_state;
 #define CONV_EOL_RNDTRP_WARN  (1<<1) /* Warn if CRLF to LF to CRLF is different */
 #define CONV_EOL_RENORMALIZE  (1<<2) /* Convert CRLF to LF */
 #define CONV_EOL_KEEP_CRLF    (1<<3) /* Keep CRLF line endings as is */
+#define CONV_WRITE_OBJECT     (1<<4) /* Content is written to the index */
 
 extern int global_conv_flags_eol;
 
sha1_file.c +1 -1
index 6bc7c6ada9..e2f319d677 100644
@@ -138,7 +138,7 @@ static int get_conv_flags(unsigned flags)
 	if (flags & HASH_RENORMALIZE)
 		return CONV_EOL_RENORMALIZE;
 	else if (flags & HASH_WRITE_OBJECT)
-	  return global_conv_flags_eol;
+		return global_conv_flags_eol | CONV_WRITE_OBJECT;
 	else
 		return 0;
 }
t/t0028-working-tree-encoding.sh new file +135 -0

135 lines not on this page · raw message

Signature · 1 line
2.16.2
#14 lore raw

Re: [PATCH v9 5/8] convert: add 'working-tree-encoding' attribute

Quoted 10 lines · On Sun, Mar 4, 2018 at 3:14 PM, <[email protected]> wrote:

Git recognizes files encoded with ASCII or one of its supersets (e.g. UTF-8 or ISO-8859-1) as text files. All other encodings are usually interpreted as binary and consequently built-in Git text processing tools (e.g. 'git diff') as well as most Git web front ends do not visualize the content.

---

convert.c static int ident_to_worktree(const char *path, const char *src, size_t len, · line 1058

Quoted 8 lines
convert.c +8 -0
@@ -978,6 +1051,25 @@ static int ident_to_worktree(const char *path, const char *src, size_t len,
+static const char *git_path_check_encoding(struct attr_check_item *check)
+{
+       [...]
+       /*
+        * Ensure encoding names are always upper case (e.g. UTF-8) to
+        * simplify subsequent string comparisons.
+        */
+       return xstrdup_toupper(value);

xstrdup_toupper() allocates memory...

convert.c struct conv_attrs { · line 1128

Quoted 6 lines
convert.c +2 -0
+}
@@ -1033,6 +1125,7 @@ struct conv_attrs {
        enum crlf_action attr_action; /* What attr says */
        enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
        int ident;
+       const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */

...which is assigned to 'const char *'...

convert.c static void convert_attrs(struct conv_attrs *ca, const char *path) · line 1161

Quoted 6 lines
convert.c +1 -0
 };
@@ -1064,6 +1158,7 @@ static void convert_attrs(struct conv_attrs *ca, const char *path)
                        else if (eol_attr == EOL_CRLF)
                                ca->crlf_action = CRLF_TEXT_CRLF;
                }
+               ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);

...by this code, and eventually leaked.

It's too bad it isn't cleaned up (freed), but looking at the callers, fixing this leak would be mildly noisy (though not particularly invasive). How much do we care about this leak?

t/t0028-working-tree-encoding.sh line 2

Quoted 7 lines
convert.c +0 -0
        } else {
                ca->drv = NULL;
                ca->crlf_action = CRLF_UNDEFINED;
t/t0028-working-tree-encoding.sh +2 -0
@@ -0,0 +1,135 @@
+test_expect_success 'check $GIT_DIR/info/attributes support' '
+       test_when_finished "rm -f test.utf8.raw test.utf32.raw test.utf32.git" &&

It seems weird to be cleaning up files this test didn't create (test.utf8.raw and test.utf32.raw).

t/t0028-working-tree-encoding.sh line 103

Quoted 12 lines
t/t0028-working-tree-encoding.sh +12 -0
+       test_when_finished "git reset --hard HEAD" &&
+
+       echo "*.utf32 text working-tree-encoding=utf-32" >.git/info/attributes &&
+       git add test.utf32 &&
+
+       git cat-file -p :test.utf32 >test.utf32.git &&
+       test_cmp_bin test.utf8.raw test.utf32.git
+'
+
+test_expect_success 'check unsupported encodings' '
+       test_when_finished "rm -f err.out" &&
+       test_when_finished "git reset --hard HEAD" &&

Resetting to HEAD here is an important cleanup action, but tests don't usually clean up files such as 'err.out' since such detritus doesn't usually impact subsequent tests negatively. (Just an observation; no re-roll needed.)

Quoted 9 lines
t/t0028-working-tree-encoding.sh +9 -0
+       echo "*.nothing text working-tree-encoding=" >>.gitattributes &&
+       printf "nothing" >t.nothing &&
+       git add t.nothing &&
+
+       echo "*.garbage text working-tree-encoding=garbage" >>.gitattributes &&
+       printf "garbage" >t.garbage &&
+       test_must_fail git add t.garbage 2>err.out &&
+       test_i18ngrep "fatal: failed to encode" err.out
+'
#15 lore raw

Re: [PATCH v9 5/8] convert: add 'working-tree-encoding' attribute

Quoted 43 lines · Eric Sunshine
Quoted 10 lines · On Sun, Mar 4, 2018 at 3:14 PM, <[email protected]> wrote:

Git recognizes files encoded with ASCII or one of its supersets (e.g. UTF-8 or ISO-8859-1) as text files. All other encodings are usually interpreted as binary and consequently built-in Git text processing tools (e.g. 'git diff') as well as most Git web front ends do not visualize the content.

---

convert.c static int ident_to_worktree(const char *path, const char *src, size_t len, · line 1058

Quoted 8 lines
convert.c +8 -0
@@ -978,6 +1051,25 @@ static int ident_to_worktree(const char *path, const char *src, size_t len,
+static const char *git_path_check_encoding(struct attr_check_item *check)
+{
+       [...]
+       /*
+        * Ensure encoding names are always upper case (e.g. UTF-8) to
+        * simplify subsequent string comparisons.
+        */
+       return xstrdup_toupper(value);

xstrdup_toupper() allocates memory...

convert.c struct conv_attrs { · line 1128

Quoted 6 lines
convert.c +2 -0
+}
@@ -1033,6 +1125,7 @@ struct conv_attrs {
       enum crlf_action attr_action; /* What attr says */
       enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
       int ident;
+       const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */

...which is assigned to 'const char *'...

convert.c static void convert_attrs(struct conv_attrs *ca, const char *path) · line 1161

Quoted 6 lines
convert.c +1 -0
 };
@@ -1064,6 +1158,7 @@ static void convert_attrs(struct conv_attrs *ca, const char *path)
                       else if (eol_attr == EOL_CRLF)
                               ca->crlf_action = CRLF_TEXT_CRLF;
               }
+               ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);

...by this code, and eventually leaked.

Quoted 3 lines

It's too bad it isn't cleaned up (freed), but looking at the callers, fixing this leak would be mildly noisy (though not particularly invasive). How much do we care about this leak?

Hmm. You are right. That was previously handled by the encoding struct linked list that I removed in this iteration. I forgot about that aspect :/ I don't like it leaking. I think I would like to reintroduce the linked list. This way every encoding is only once in memory. What do you think?

Quoted 10 lines

t/t0028-working-tree-encoding.sh line 2

Quoted 7 lines
convert.c +0 -0
       } else {
               ca->drv = NULL;
               ca->crlf_action = CRLF_UNDEFINED;
t/t0028-working-tree-encoding.sh +2 -0
@@ -0,0 +1,135 @@
+test_expect_success 'check $GIT_DIR/info/attributes support' '
+       test_when_finished "rm -f test.utf8.raw test.utf32.raw test.utf32.git" &&

It seems weird to be cleaning up files this test didn't create (test.utf8.raw and test.utf32.raw).

Agreed.

Quoted 9 lines
Quoted 9 lines
t/t0028-working-tree-encoding.sh +9 -0
+       test_when_finished "git reset --hard HEAD" &&
+
+       echo "*.utf32 text working-tree-encoding=utf-32" >.git/info/attributes &&
+       git add test.utf32 &&
+
+       git cat-file -p :test.utf32 >test.utf32.git &&
+       test_cmp_bin test.utf8.raw test.utf32.git
+'
+
Quoted 8 lines

t/t0028-working-tree-encoding.sh line 103

Quoted 3 lines
t/t0028-working-tree-encoding.sh +3 -0
+test_expect_success 'check unsupported encodings' '
+       test_when_finished "rm -f err.out" &&
+       test_when_finished "git reset --hard HEAD" &&

Resetting to HEAD here is an important cleanup action, but tests don't usually clean up files such as 'err.out' since such detritus doesn't usually impact subsequent tests negatively. (Just an observation; no re-roll needed.)

OK. I'll fix it if I reroll.

- Lars

#16 lore raw

Re: [PATCH v9 5/8] convert: add 'working-tree-encoding' attribute

Quoted 14 lines · Lars Schneider
Quoted 14 lines · Eric Sunshine
Quoted 1 line · On Sun, Mar 4, 2018 at 3:14 PM, <[email protected]> wrote:

+ return xstrdup_toupper(value);

xstrdup_toupper() allocates memory...

Quoted 1 line

+ const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */

...which is assigned to 'const char *'...

Quoted 1 line

+ ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);

...by this code, and eventually leaked.

Quoted 8 lines
Quoted 3 lines

It's too bad it isn't cleaned up (freed), but looking at the callers, fixing this leak would be mildly noisy (though not particularly invasive). How much do we care about this leak?

Hmm. You are right. That was previously handled by the encoding struct linked list that I removed in this iteration. I forgot about that aspect :/ I don't like it leaking. I think I would like to reintroduce the linked list. This way every encoding is only once in memory. What do you think?

It's subjective, but I find the use of a linked-list just for the purpose of not leaking these strings unnecessarily confusing.

If I was doing it, I'd probably add a conv_attrs_free() function and call it from each function allocates a 'struct conv_attrs' (including calling it before early returns -- which prompted my earlier comment about it being a "mildly noisy" fix).

#17 lore raw

PATCH v9 6/8 convert: check for detectable errors in UTF encodings

In reply to [email protected]

From: Lars Schneider <[email protected]>

Check that new content is valid with respect to the user defined 'working-tree-encoding' attribute.

---
 convert.c                        | 50 +++++++++++++++++++++++++++++++++++
 t/t0028-working-tree-encoding.sh | 57 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 107 insertions(+)
convert.c +50 -0
index 2f864df258..9647b06679 100644
@@ -266,6 +266,53 @@ static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
 
 }
 
+static int validate_encoding(const char *path, const char *enc,
+		      const char *data, size_t len, int die_on_error)
+{
+	if (!memcmp("UTF-", enc, 4)) {
+		/*
+		 * Check for detectable errors in UTF encodings
+		 */
+		if (has_prohibited_utf_bom(enc, data, len)) {
+			const char *error_msg = _(
+				"BOM is prohibited in '%s' if encoded as %s");
+			/*
+			 * This advice is shown for UTF-??BE and UTF-??LE
+			 * encodings. We truncate the encoding name to 6
+			 * chars with %.6s to cut off the last two "byte
+			 * order" characters.
+			 */
+			const char *advise_msg = _(
+				"The file '%s' contains a byte order "
+				"mark (BOM). Please use %.6s as "
+				"working-tree-encoding.");
+			advise(advise_msg, path, enc);
+			if (die_on_error)
+				die(error_msg, path, enc);
+			else {
+				return error(error_msg, path, enc);
+			}
+
+		} else if (is_missing_required_utf_bom(enc, data, len)) {
+			const char *error_msg = _(
+				"BOM is required in '%s' if encoded as %s");
+			const char *advise_msg = _(
+				"The file '%s' is missing a byte order "
+				"mark (BOM). Please use %sBE or %sLE "
+				"(depending on the byte order) as "
+				"working-tree-encoding.");
+			advise(advise_msg, path, enc, enc);
+			if (die_on_error)
+				die(error_msg, path, enc);
+			else {
+				return error(error_msg, path, enc);
+			}
+		}
+
+	}
+	return 0;
+}
+
 static const char *default_encoding = "UTF-8";
 
 static int encode_to_git(const char *path, const char *src, size_t src_len,
@@ -291,6 +338,9 @@ static int encode_to_git(const char *path, const char *src, size_t src_len,
 	if (!buf && !src)
 		return 1;
 
+	if (validate_encoding(path, enc, src, src_len, die_on_error))
+		return 0;
+
 	dst = reencode_string_len(src, src_len, default_encoding, enc,
 				  &dst_len);
 	if (!dst) {
t/t0028-working-tree-encoding.sh +57 -0

67 lines not on this page · raw message

Signature · 1 line
2.16.2
#18 lore raw

Re: [PATCH v9 6/8] convert: check for detectable errors in UTF encodings

convert.c static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats, · line 272

Quoted 4 lines · [email protected] writes:
convert.c +4 -0
+static int validate_encoding(const char *path, const char *enc,
+		      const char *data, size_t len, int die_on_error)
+{
+	if (!memcmp("UTF-", enc, 4)) {

Does the caller already know that enc is sufficiently long that using memcmp is safe?

#19 lore raw

Re: [PATCH v9 6/8] convert: check for detectable errors in UTF encodings

Quoted 12 lines · Junio C Hamano

convert.c static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats, · line 272

Quoted 4 lines · [email protected] writes:
convert.c +4 -0
+static int validate_encoding(const char *path, const char *enc,
+		      const char *data, size_t len, int die_on_error)
+{
+	if (!memcmp("UTF-", enc, 4)) {

Does the caller already know that enc is sufficiently long that using memcmp is safe?

No :-(

Would you be willing to squash that in?

    if (strlen(enc) > 4 && !memcmp("UTF-", enc, 4)) {

I deliberately used "> 4" as plain "UTF-" is not even valid.

Thanks for spotting this,
Lars

#20 lore raw

Re: [PATCH v9 6/8] convert: check for detectable errors in UTF encodings

Quoted 12 lines · Lars Schneider
Quoted 11 lines · Junio C Hamano

convert.c static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats, · line 272

Quoted 4 lines · [email protected] writes:
convert.c +4 -0
+static int validate_encoding(const char *path, const char *enc,
+		      const char *data, size_t len, int die_on_error)
+{
+	if (!memcmp("UTF-", enc, 4)) {

Does the caller already know that enc is sufficiently long that using memcmp is safe?

Quoted 7 lines

No :-(

Would you be willing to squash that in?

    if (strlen(enc) > 4 && !memcmp("UTF-", enc, 4)) {

I deliberately used "> 4" as plain "UTF-" is not even valid.

I'd rather not. The code does not have to even look at 6th and later bytes in the enc[] even if it wanted to reject "UTF-" followed by nothing, but use of strlen() forces it to look at everything.

Stepping back, shouldn't

	if (starts_with(enc, "UTF-") 

be sufficient? If you really care about the case where "UTF-" alone comes here, you could write

	if (starts_with(enc, "UTF-") && enc[4])

but I do not think "&& enc[4]" is even needed. The functions called from this block would not consider "UTF-" alone as something valid anyway, so with that "&& enf[4]" we would be piling more code only for invalid/rare case.

#21 lore raw

Re: [PATCH v9 6/8] convert: check for detectable errors in UTF encodings

Quoted 36 lines · Junio C Hamano
Quoted 12 lines · Lars Schneider
Quoted 11 lines · Junio C Hamano

convert.c static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats, · line 272

Quoted 4 lines · [email protected] writes:
convert.c +4 -0
+static int validate_encoding(const char *path, const char *enc,
+		      const char *data, size_t len, int die_on_error)
+{
+	if (!memcmp("UTF-", enc, 4)) {

Does the caller already know that enc is sufficiently long that using memcmp is safe?

Quoted 7 lines

No :-(

Would you be willing to squash that in?

   if (strlen(enc) > 4 && !memcmp("UTF-", enc, 4)) {

I deliberately used "> 4" as plain "UTF-" is not even valid.

I'd rather not. The code does not have to even look at 6th and later bytes in the enc[] even if it wanted to reject "UTF-" followed by nothing, but use of strlen() forces it to look at everything.

Stepping back, shouldn't

	if (starts_with(enc, "UTF-") 

be sufficient? If you really care about the case where "UTF-" alone comes here, you could write

Quoted 6 lines
	if (starts_with(enc, "UTF-") && enc[4])

but I do not think "&& enc[4]" is even needed. The functions called from this block would not consider "UTF-" alone as something valid anyway, so with that "&& enf[4]" we would be piling more code only for invalid/rare case.

Agreed, "if (starts_with(enc, "UTF-"))" is sufficient. Can you squash that in? Thanks for pointing me to starts_with() as I forgot about this function!

- Lars

#22 lore raw

Re: [PATCH v9 6/8] convert: check for detectable errors in UTF encodings

In reply to [email protected]
Quoted 23 lines · On Sun, Mar 4, 2018 at 3:14 PM, <[email protected]> wrote:

Check that new content is valid with respect to the user defined 'working-tree-encoding' attribute.

---

convert.c +15 -0
@@ -266,6 +266,53 @@ static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
+static int validate_encoding(const char *path, const char *enc,
+                     const char *data, size_t len, int die_on_error)
+{
+       if (!memcmp("UTF-", enc, 4)) {
+               [...]
+               if (has_prohibited_utf_bom(enc, data, len)) {
+                       [...]
+                       if (die_on_error)
+                               die(error_msg, path, enc);
+                       else {
+                               return error(error_msg, path, enc);
+                       }
+               } [...]
+       return 0;
+}

convert.c static int encode_to_git(const char *path, const char *src, size_t src_len, · line 339

Quoted 2 lines
convert.c +2 -0
@@ -291,6 +338,9 @@ static int encode_to_git(const char *path, const char *src, size_t src_len,
+       if (validate_encoding(path, enc, src, src_len, die_on_error))
+               return 0;

There could be a cleaner separation of responsibilities here which, as a nice side-effect, would eliminate the repeated "if (die_on_error) die(...); else return error(...);" pattern. Rather than passing a 'die_on_error' flag to validate_encoding(), it could accept a 'strbuf *err' to populate in case of error:

    static int validate_encoding(..., struct strbuf *err)
    {
        if validation error:
            populate 'err'
            return -1;
        return 0
    }

and let the caller be responsible for deciding how to handle failure:

    struct strbuf err = STRBUF_INIT;
    ...
    if (validate_encoding(..., &err)) {
        if (die_on_error)
            die(err.buf);
        else {
            error(err.buf);
            strbuf_release(&err);
            return 0;
        }
    }

Not necessarily worth a re-roll, but perhaps a cleanup someone could submit at some point if interested.

Quoted 2 lines
convert.c +0 -0
        dst = reencode_string_len(src, src_len, default_encoding, enc,
                                  &dst_len);
#23 lore raw

PATCH v9 7/8 convert: add tracing for 'working-tree-encoding' attribute

In reply to [email protected]

From: Lars Schneider <[email protected]>

Add the GIT_TRACE_WORKING_TREE_ENCODING environment variable to enable tracing for content that is reencoded with the 'working-tree-encoding' attribute. This is useful to debug encoding issues.

---
 convert.c                        | 25 +++++++++++++++++++++++++
 t/t0028-working-tree-encoding.sh |  2 ++
 2 files changed, 27 insertions(+)
convert.c +25 -0
index 9647b06679..eec34a94b9 100644
@@ -313,6 +313,29 @@ static int validate_encoding(const char *path, const char *enc,
 	return 0;
 }
 
+static void trace_encoding(const char *context, const char *path,
+			   const char *encoding, const char *buf, size_t len)
+{
+	static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
+	struct strbuf trace = STRBUF_INIT;
+	int i;
+
+	strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
+	for (i = 0; i < len && buf; ++i) {
+		strbuf_addf(
+			&trace,"| \e[2m%2i:\e[0m %2x \e[2m%c\e[0m%c",
+			i,
+			(unsigned char) buf[i],
+			(buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
+			((i+1) % 8 && (i+1) < len ? ' ' : '\n')
+		);
+	}
+	strbuf_addchars(&trace, '\n', 1);
+
+	trace_strbuf(&coe, &trace);
+	strbuf_release(&trace);
+}
+
 static const char *default_encoding = "UTF-8";
 
 static int encode_to_git(const char *path, const char *src, size_t src_len,
@@ -341,6 +364,7 @@ static int encode_to_git(const char *path, const char *src, size_t src_len,
 	if (validate_encoding(path, enc, src, src_len, die_on_error))
 		return 0;
 
+	trace_encoding("source", path, enc, src, src_len);
 	dst = reencode_string_len(src, src_len, default_encoding, enc,
 				  &dst_len);
 	if (!dst) {
@@ -358,6 +382,7 @@ static int encode_to_git(const char *path, const char *src, size_t src_len,
 			return 0;
 		}
 	}
+	trace_encoding("destination", path, default_encoding, dst, dst_len);
 
 	strbuf_attach(buf, dst, dst_len, dst_len + 1);
 	return 1;
t/t0028-working-tree-encoding.sh +2 -0
index 5c7e36a164..bdc487b44f 100755
@@ -4,6 +4,8 @@ test_description='working-tree-encoding conversion via gitattributes'
 
 . ./test-lib.sh
 
+GIT_TRACE_WORKING_TREE_ENCODING=1 && export GIT_TRACE_WORKING_TREE_ENCODING
+
 test_expect_success 'setup test files' '
 	git config core.eol lf &&
 
Signature · 1 line
2.16.2
#24 lore raw

PATCH v9 8/8 convert: add round trip check based on 'core.checkRoundtripEncoding'

In reply to [email protected]

From: Lars Schneider <[email protected]>

UTF supports lossless conversion round tripping and conversions between UTF and other encodings are mostly round trip safe as Unicode aims to be a superset of all other character encodings. However, certain encodings (e.g. SHIFT-JIS) are known to have round trip issues [1].

Add 'core.checkRoundtripEncoding', which contains a comma separated list of encodings, to define for what encodings Git should check the conversion round trip if they are used in the 'working-tree-encoding' attribute.

Set SHIFT-JIS as default value for 'core.checkRoundtripEncoding'.

[1] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode

---
 Documentation/config.txt         |  6 ++++
 Documentation/gitattributes.txt  |  8 +++++
 config.c                         |  5 +++
 convert.c                        | 78 ++++++++++++++++++++++++++++++++++++++++
 convert.h                        |  1 +
 environment.c                    |  1 +
 t/t0028-working-tree-encoding.sh | 39 ++++++++++++++++++++
 7 files changed, 138 insertions(+)
Documentation/config.txt +6 -0
index 0e25b2c92b..d7a56054a5 100644
@@ -530,6 +530,12 @@ core.autocrlf::
 	This variable can be set to 'input',
 	in which case no output conversion is performed.
 
+core.checkRoundtripEncoding::
+	A comma separated list of encodings that Git performs UTF-8 round
+	trip checks on if they are used in an `working-tree-encoding`
+	attribute (see linkgit:gitattributes[5]). The default value is
+	`SHIFT-JIS`.
+
 core.symlinks::
 	If false, symbolic links are checked out as small plain files that
 	contain the link text. linkgit:git-update-index[1] and
Documentation/gitattributes.txt +8 -0
index 31a4f92840..aa3deae392 100644
@@ -312,6 +312,14 @@ number of pitfalls:
   internal contents as UTF-8 and try to convert it to UTF-16 on checkout.
   That operation will fail and cause an error.
 
+- Reencoding content to non-UTF encodings can cause errors as the
+  conversion might not be UTF-8 round trip safe. If you suspect your
+  encoding to not be round trip safe, then add it to
+  `core.checkRoundtripEncoding` to make Git check the round trip
+  encoding (see linkgit:git-config[1]). SHIFT-JIS (Japanese character
+  set) is known to have round trip issues with UTF-8 and is checked by
+  default.
+
 - Reencoding content requires resources that might slow down certain
   Git operations (e.g 'git checkout' or 'git add').
 
config.c +5 -0
index 1f003fbb90..d0ada9fcd4 100644
@@ -1172,6 +1172,11 @@ static int git_default_core_config(const char *var, const char *value)
 		return 0;
 	}
 
+	if (!strcmp(var, "core.checkroundtripencoding")) {
+		check_roundtrip_encoding = xstrdup(value);
+		return 0;
+	}
+
 	if (!strcmp(var, "core.notesref")) {
 		notes_ref_name = xstrdup(value);
 		return 0;
convert.c +78 -0

90 lines not on this page · raw message

convert.h +1 -0
index 1d9539ed0b..765abfbd60 100644
@@ -56,6 +56,7 @@ struct delayed_checkout {
 };
 
 extern enum eol core_eol;
+extern char *check_roundtrip_encoding;
 extern const char *get_cached_convert_stats_ascii(const struct index_state *istate,
 						  const char *path);
 extern const char *get_wt_convert_stats_ascii(const char *path);
environment.c +1 -0
index 10a32c20ac..5bae9131ad 100644
@@ -50,6 +50,7 @@ int check_replace_refs = 1;
 char *git_replace_ref_base;
 enum eol core_eol = EOL_UNSET;
 int global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
+char *check_roundtrip_encoding = "SHIFT-JIS";
 unsigned whitespace_rule_cfg = WS_DEFAULT_RULE;
 enum branch_track git_branch_track = BRANCH_TRACK_REMOTE;
 enum rebase_setup_type autorebase = AUTOREBASE_NEVER;
t/t0028-working-tree-encoding.sh +39 -0
index bdc487b44f..23e89ae623 100755
@@ -191,4 +191,43 @@ test_expect_success 'error if encoding garbage is already in Git' '
 	test_i18ngrep "error: BOM is required" err.out
 '
 
+test_expect_success 'check roundtrip encoding' '
+	test_when_finished "rm -f roundtrip.shift roundtrip.utf16" &&
+	test_when_finished "git reset --hard HEAD" &&
+
+	text="hallo there!\nroundtrip test here!" &&
+	printf "$text" | iconv -f UTF-8 -t SHIFT-JIS >roundtrip.shift &&
+	printf "$text" | iconv -f UTF-8 -t UTF-16 >roundtrip.utf16 &&
+	echo "*.shift text working-tree-encoding=SHIFT-JIS" >>.gitattributes &&
+
+	# SHIFT-JIS encoded files are round-trip checked by default...
+	GIT_TRACE=1 git add .gitattributes roundtrip.shift 2>&1 |
+		grep "Checking roundtrip encoding for SHIFT-JIS" &&
+	git reset &&
+
+	# ... unless we overwrite the Git config!
+	! GIT_TRACE=1 git -c core.checkRoundtripEncoding=garbage \
+		add .gitattributes roundtrip.shift 2>&1 |
+		grep "Checking roundtrip encoding for SHIFT-JIS" &&
+	git reset &&
+
+	# UTF-16 encoded files should not be round-trip checked by default...
+	! GIT_TRACE=1 git add roundtrip.utf16 2>&1 |
+		grep "Checking roundtrip encoding for UTF-16" &&
+	git reset &&
+
+	# ... unless we tell Git to check it!
+	GIT_TRACE=1 git -c core.checkRoundtripEncoding="UTF-16, UTF-32" \
+		add roundtrip.utf16 2>&1 |
+		grep "Checking roundtrip encoding for UTF-16" &&
+	git reset &&
+
+	# ... unless we tell Git to check it!
+	# (here we also check that the casing of the encoding is irrelevant)
+	GIT_TRACE=1 git -c core.checkRoundtripEncoding="UTF-32, utf-16" \
+		add roundtrip.utf16 2>&1 |
+		grep "Checking roundtrip encoding for UTF-16" &&
+	git reset
+'
+
 test_done
Signature · 1 line
2.16.2
#25 lore raw
In reply to [email protected]
Quoted 11 lines · On Sun, Mar 4, 2018 at 3:14 PM, <[email protected]> wrote:

Changes since v8: [...]

Thanks a lot Eric for your great review! I think I fixed everything you objected with one exception. You noticed that the current code only checks for BOMs corresponding to the declared size (16 or 32 bits) [1]. I understand your point of view and I agree that any BOM in these cases is *most likely* an error. However, according to the spec it might still be valid. The comments on my related question on StackOverflow seem to support that view [2]. Therefore, I would like to leave it as it is in this series. If it turns out to be a problem in practice, then I am happy to change it later. OK for you?

Fine. As this is not a correctness issue with the conversion itself, but rather an attempt to detect misconfiguration by the user, it can always be revisited later if someone comes up with a more solid argument that one interpretation is more correct than the other.

I did leave a few review comments on v9, but I don't think any are necessarily worth a re-roll. If anything, and if they seem actionable, then perhaps a patch or two atop the series could address them (at some point).