Skip to contentSkip to conversation

convert: add support for different encodings

PATCH Superseded [email protected] 5 participants 22 messages Mar 15, 2018 – Apr 3, 2018 Documentation

v12 of 13 Superseded Latest is v13 →

lore
Share & tools
lore
#0 lore raw

v12 cover convert: add support for different encodings

From: Lars Schneider <[email protected]>

Hi,

Patches 1-6,9 are preparation and helper functions. Patch 4 is new. Patch 7,8,10 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 v11:

* die if w-t-e is configured with a true/false (=undefined!) value (Junio)
* improve same_encoding to detect all alternatives for UTF encodings (new commit, Junio)
* squash in "advise canonical UTF encoding names" and remove commit (Junio)
* fix erroneous # in comment (Junio)
* force segv for non-UTF encodings in validate_encoding() (Junio)

Thanks,
Lars

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]/
v9: https://public-inbox.org/git/[email protected]/
v10: https://public-inbox.org/git/[email protected]/
v11: https://public-inbox.org/git/[email protected]/

Base Ref:
Web-Diff: https://github.com/larsxschneider/git/commit/0daedbbd76
Checkout: git fetch https://github.com/larsxschneider/git encoding-v12 && git checkout 0daedbbd76

### Interdiff (v11..v12):

convert.c +5 -6
index c2d24882c1..2a002af66d 100644
@@ -280,13 +280,13 @@ static int validate_encoding(const char *path, const char *enc,
 			/*
 			 * This advice is shown for UTF-??BE and UTF-??LE encodings.
 			 * We cut off the last two characters of the encoding name
-			 # to generate the encoding name suitable for BOMs.
+			 * to generate the encoding name suitable for BOMs.
 			 */
 			const char *advise_msg = _(
 				"The file '%s' contains a byte order "
 				"mark (BOM). Please use UTF-%s as "
 				"working-tree-encoding.");
-			const char *stripped = "";
+			const char *stripped = NULL;
 			char *upper = xstrdup_toupper(enc);
 			upper[strlen(upper)-2] = '\0';
 			if (!skip_prefix(upper, "UTF-", &stripped))
@@ -307,7 +307,7 @@ static int validate_encoding(const char *path, const char *enc,
 				"mark (BOM). Please use UTF-%sBE or UTF-%sLE "
 				"(depending on the byte order) as "
 				"working-tree-encoding.");
-			const char *stripped = "";
+			const char *stripped = NULL;
 			char *upper = xstrdup_toupper(enc);
 			if (!skip_prefix(upper, "UTF-", &stripped))
 				skip_prefix(stripped, "UTF", &stripped);
@@ -1222,12 +1222,11 @@ static const char *git_path_check_encoding(struct attr_check_item *check)
 		return NULL;
 
 	if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
-		error(_("working-tree-encoding attribute requires a value"));
-		return NULL;
+		die(_("working-tree-encoding attribute requires a value"));
 	}
 
 	/* Don't encode to the default encoding */
-	if (is_encoding_utf8(value) && is_encoding_utf8(default_encoding))
+	if (same_encoding(value, default_encoding))
 		return NULL;
 
 	return value;
t/t0028-working-tree-encoding.sh +9 -11
index 07089bba2e..884f0878b1 100755
@@ -149,25 +149,23 @@ done
 test_expect_success 'check unsupported encodings' '
 	test_when_finished "git reset --hard HEAD" &&
 
-	echo "*.set text working-tree-encoding" >>.gitattributes &&
+	echo "*.set text working-tree-encoding" >.gitattributes &&
 	printf "set" >t.set &&
-	git add t.set 2>err.out &&
-	test_i18ngrep "error: working-tree-encoding attribute requires a value" err.out &&
+	test_must_fail git add t.set 2>err.out &&
+	test_i18ngrep "working-tree-encoding attribute requires a value" err.out &&
 
-	echo "*.unset text -working-tree-encoding" >>.gitattributes &&
+	echo "*.unset text -working-tree-encoding" >.gitattributes &&
 	printf "unset" >t.unset &&
-	git add t.unset 2>err.out &&
-	test_i18ngrep "error: working-tree-encoding attribute requires a value" err.out &&
+	git add t.unset &&
 
-	echo "*.empty text working-tree-encoding=" >>.gitattributes &&
+	echo "*.empty text working-tree-encoding=" >.gitattributes &&
 	printf "empty" >t.empty &&
-	git add t.empty 2>err.out &&
-	test_i18ngrep "error: working-tree-encoding attribute requires a value" err.out &&
+	git add t.empty &&
 
-	echo "*.garbage text working-tree-encoding=garbage" >>.gitattributes &&
+	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
+	test_i18ngrep "failed to encode" err.out
 '
 
 test_expect_success 'error if encoding round trip is not the same during refresh' '
utf8.c +25 -7
index 81c6678df1..2d8821d36e 100644
@@ -401,11 +401,27 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
 	strbuf_release(&sb_dst);
 }
 
+/*
+ * Returns true (1) if the src encoding name matches the dst encoding
+ * name directly or one of its alternative names. E.g. UTF-16BE is the
+ * same as UTF16BE.
+ */
+static int same_utf_encoding(const char *src, const char *dst)
+{
+	if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
+		/* src[3] or dst[3] might be '\0' */
+		int i = (src[3] == '-' ? 4 : 3);
+		int j = (dst[3] == '-' ? 4 : 3);
+		return !strcasecmp(src+i, dst+j);
+	}
+	return 0;
+}
+
 int is_encoding_utf8(const char *name)
 {
 	if (!name)
 		return 1;
-	if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
+	if (same_utf_encoding("utf-8", name))
 		return 1;
 	return 0;
 }
@@ -414,6 +430,8 @@ int same_encoding(const char *src, const char *dst)
 {
 	if (is_encoding_utf8(src) && is_encoding_utf8(dst))
 		return 1;
+	if (same_utf_encoding(src, dst))
+		return 1;
 	return !strcasecmp(src, dst);
 }
 
@@ -552,13 +570,13 @@ 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 (
-	  (!strcasecmp(enc, "UTF-16BE") || !strcasecmp(enc, "UTF-16LE") ||
-	   !strcasecmp(enc, "UTF16BE") || !strcasecmp(enc, "UTF16LE")) &&
+	  (same_utf_encoding("UTF-16BE", enc) ||
+	   same_utf_encoding("UTF-16LE", enc)) &&
 	  (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
 	   has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
 	) || (
-	  (!strcasecmp(enc, "UTF-32BE") || !strcasecmp(enc, "UTF-32LE") ||
-	   !strcasecmp(enc, "UTF32BE") || !strcasecmp(enc, "UTF32LE")) &&
+	  (same_utf_encoding("UTF-32BE",  enc) ||
+	   same_utf_encoding("UTF-32LE", enc)) &&
 	  (has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
 	   has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
 	);
@@ -567,11 +585,11 @@ 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 (
-	   (!strcasecmp(enc, "UTF-16") || !strcasecmp(enc, "UTF16")) &&
+	   (same_utf_encoding(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)))
 	) || (
-	   (!strcasecmp(enc, "UTF-32") || !strcasecmp(enc, "UTF32")) &&
+	   (same_utf_encoding(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)))
 	);

### Patches

Lars Schneider (10):
strbuf: remove unnecessary NUL assignment in xstrdup_tolower()
strbuf: add xstrdup_toupper()
strbuf: add a case insensitive starts_with()
utf8: teach same_encoding() alternative UTF encoding names
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                        | 276 ++++++++++++++++++++++++++++++++++++++-
 convert.h                        |   2 +
 environment.c                    |   1 +
 git-compat-util.h                |   1 +
 sha1_file.c                      |   2 +-
 strbuf.c                         |  22 +++-
 strbuf.h                         |   1 +
 t/t0028-working-tree-encoding.sh | 245 ++++++++++++++++++++++++++++++++++
 utf8.c                           |  59 ++++++++-
 utf8.h                           |  28 ++++
 13 files changed, 732 insertions(+), 4 deletions(-)
 create mode 100755 t/t0028-working-tree-encoding.sh

base-commit: 8a2f0888555ce46ac87452b194dec5cb66fb1417 --
2.16.2

#1 lore raw

PATCH v12 1/10 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 v12 2/10 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 v12 3/10 strbuf: add a case insensitive starts_with()

In reply to [email protected]

From: Lars Schneider <[email protected]>

Check in a case insensitive manner if one string is a prefix of another string.

This function is used in a subsequent commit.

---
 git-compat-util.h | 1 +
 strbuf.c          | 9 +++++++++
 2 files changed, 10 insertions(+)
git-compat-util.h +1 -0
index 68b2ad531e..95c9b34832 100644
@@ -455,6 +455,7 @@ extern void (*get_warn_routine(void))(const char *warn, va_list params);
 extern void set_die_is_recursing_routine(int (*routine)(void));
 
 extern int starts_with(const char *str, const char *prefix);
+extern int istarts_with(const char *str, const char *prefix);
 
 /*
  * If the string "str" begins with the string found in "prefix", return 1.
strbuf.c +9 -0
index b635f0bdc4..99812b8488 100644
@@ -11,6 +11,15 @@ int starts_with(const char *str, const char *prefix)
 			return 0;
 }
 
+int istarts_with(const char *str, const char *prefix)
+{
+	for (; ; str++, prefix++)
+		if (!*prefix)
+			return 1;
+		else if (tolower(*str) != tolower(*prefix))
+			return 0;
+}
+
 int skip_to_optional_arg_default(const char *str, const char *prefix,
 				 const char **arg, const char *def)
 {
Signature · 1 line
2.16.2
#4 lore raw

Re: [PATCH v12 03/10] strbuf: add a case insensitive starts_with()

You need to cast those arguments of tolower to (unsigned char). That's arguably a bug of the language.

Character values less than zero aren't valid for tolower, unless they happen to equal
EOF in which case the tolower calls don't mean what you want them to mean. Per the man page:

"If c is neither an unsigned char value nor EOF, the behavior of these functions is undefined."

M.

Quoted 48 lines · On Thu, Mar 15, 2018 at 6:57 PM, <[email protected]> wrote:

From: Lars Schneider <[email protected]>

Check in a case insensitive manner if one string is a prefix of another string.

This function is used in a subsequent commit.

---
 git-compat-util.h | 1 +
 strbuf.c          | 9 +++++++++
 2 files changed, 10 insertions(+)
git-compat-util.h +1 -0
index 68b2ad531e..95c9b34832 100644
@@ -455,6 +455,7 @@ extern void (*get_warn_routine(void))(const char *warn, va_list params);
 extern void set_die_is_recursing_routine(int (*routine)(void));
 
 extern int starts_with(const char *str, const char *prefix);
+extern int istarts_with(const char *str, const char *prefix);
 
 /*
  * If the string "str" begins with the string found in "prefix", return 1.
strbuf.c +9 -1
index b635f0bdc4..99812b8488 100644
@@ -11,6 +11,15 @@ int starts_with(const char *str, const char *prefix)
                        return 0;
 }
 
+int istarts_with(const char *str, const char *prefix)
+{
+       for (; ; str++, prefix++)
+               if (!*prefix)
+                       return 1;
+               else if (tolower(*str) != tolower(*prefix))
+                       return 0;
+}
+
 int skip_to_optional_arg_default(const char *str, const char *prefix,
                                 const char **arg, const char *def)
 {
--

2.16.2

#5 lore raw

Re: [PATCH v12 03/10] strbuf: add a case insensitive starts_with()

Quoted 2 lines · Morten Welinder

You need to cast those arguments of tolower to (unsigned char). That's arguably a bug of the language.

Don't we do so in git-compat-util.h already?

#6 lore raw

PATCH v12 4/10 utf8: teach same_encoding() alternative UTF encoding names

In reply to [email protected]

From: Lars Schneider <[email protected]>

The function same_encoding() checked only for alternative UTF-8 encoding names. Teach it to check for all kinds of alternative UTF encoding names.

This function is used in a subsequent commit.

---
 utf8.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
utf8.c +19 -1
index 2c27ce0137..c30daf4d34 100644
@@ -401,11 +401,27 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
 	strbuf_release(&sb_dst);
 }
 
+/*
+ * Returns true (1) if the src encoding name matches the dst encoding
+ * name directly or one of its alternative names. E.g. UTF-16BE is the
+ * same as UTF16BE.
+ */
+static int same_utf_encoding(const char *src, const char *dst)
+{
+	if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
+		/* src[3] or dst[3] might be '\0' */
+		int i = (src[3] == '-' ? 4 : 3);
+		int j = (dst[3] == '-' ? 4 : 3);
+		return !strcasecmp(src+i, dst+j);
+	}
+	return 0;
+}
+
 int is_encoding_utf8(const char *name)
 {
 	if (!name)
 		return 1;
-	if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
+	if (same_utf_encoding("utf-8", name))
 		return 1;
 	return 0;
 }
@@ -414,6 +430,8 @@ int same_encoding(const char *src, const char *dst)
 {
 	if (is_encoding_utf8(src) && is_encoding_utf8(dst))
 		return 1;
+	if (same_utf_encoding(src, dst))
+		return 1;
 	return !strcasecmp(src, dst);
 }
 
Signature · 1 line
2.16.2
#7 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 8 lines · On Thu, Mar 15, 2018 at 6:57 PM, <[email protected]> wrote:

The function same_encoding() checked only for alternative UTF-8 encoding names. Teach it to check for all kinds of alternative UTF encoding names.

---

utf8.c void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width, · line 410

Quoted 10 lines
utf8.c +10 -0
@@ -401,11 +401,27 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
+static int same_utf_encoding(const char *src, const char *dst)
+{
+       if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
+               /* src[3] or dst[3] might be '\0' */
+               int i = (src[3] == '-' ? 4 : 3);
+               int j = (dst[3] == '-' ? 4 : 3);
+               return !strcasecmp(src+i, dst+j);
+       }
+       return 0;
+}

Alternate implementation without magic numbers:

    if (iskip_prefix(src, "utf", &src) &&
        iskip_prefix(dst, "utf", &dst)) {
        if (*src == '-')
            src++;
        if (*dst == '-')
            dst++;
        return !strcasecmp(src, dst);
    }
    return 0;

... assuming you add an iskip_prefix() function (patterned after skip_prefix()).

Quoted 10 lines
utf8.c +1 -1
 int is_encoding_utf8(const char *name)
 {
        if (!name)
                return 1;
-       if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
+       if (same_utf_encoding("utf-8", name))
                return 1;
        return 0;
 }

utf8.c int same_encoding(const char *src, const char *dst) · line 436

Quoted 7 lines
utf8.c +2 -0
@@ -414,6 +430,8 @@ int same_encoding(const char *src, const char *dst)
 {
        if (is_encoding_utf8(src) && is_encoding_utf8(dst))
                return 1;
+       if (same_utf_encoding(src, dst))
+               return 1;
        return !strcasecmp(src, dst);
 }

This seems odd. I would have expected the newly-added generalized conditional to replace the original UTF-8-specific conditional, not supplement it. That is, shouldn't the entire function body be:

    if (same_utf_encoding(src, dst))
        return 1;
    return !strcasecmp(src, dst);

?

#8 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 35 lines · Eric Sunshine
Quoted 8 lines · On Thu, Mar 15, 2018 at 6:57 PM, <[email protected]> wrote:

The function same_encoding() checked only for alternative UTF-8 encoding names. Teach it to check for all kinds of alternative UTF encoding names.

---

utf8.c void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width, · line 410

Quoted 10 lines
utf8.c +10 -0
@@ -401,11 +401,27 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
+static int same_utf_encoding(const char *src, const char *dst)
+{
+       if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
+               /* src[3] or dst[3] might be '\0' */
+               int i = (src[3] == '-' ? 4 : 3);
+               int j = (dst[3] == '-' ? 4 : 3);
+               return !strcasecmp(src+i, dst+j);
+       }
+       return 0;
+}

Alternate implementation without magic numbers:

   if (iskip_prefix(src, "utf", &src) &&
       iskip_prefix(dst, "utf", &dst)) {
       if (*src == '-')
           src++;
       if (*dst == '-')
           dst++;
       return !strcasecmp(src, dst);
   }
   return 0;
Quoted 1 line

... assuming you add an iskip_prefix() function (patterned after skip_prefix()).

If a reroll is necessary, then I can do this.

Quoted 22 lines
Quoted 10 lines
utf8.c +1 -1
 int is_encoding_utf8(const char *name)
 {
       if (!name)
               return 1;
-       if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
+       if (same_utf_encoding("utf-8", name))
               return 1;
       return 0;
 }

utf8.c int same_encoding(const char *src, const char *dst) · line 436

Quoted 7 lines
utf8.c +2 -0
@@ -414,6 +430,8 @@ int same_encoding(const char *src, const char *dst)
 {
       if (is_encoding_utf8(src) && is_encoding_utf8(dst))
               return 1;
+       if (same_utf_encoding(src, dst))
+               return 1;
       return !strcasecmp(src, dst);
 }

This seems odd. I would have expected the newly-added generalized conditional to replace the original UTF-8-specific conditional, not supplement it. That is, shouldn't the entire function body be:

Quoted 3 lines
   if (same_utf_encoding(src, dst))
       return 1;
   return !strcasecmp(src, dst);

No, because is_encoding_utf8() returns "true" (=1) if the encoding is NULL. That is not the case for UTF-16 et al. The caller of same_encoding() might expect that behavior.

I could have moved the "UTF-8" == NULL assumption into same_utf_encoding() but that did not feel right.

Does this make sense?

- Lars

#9 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 16 lines · Lars Schneider
Quoted 8 lines · Eric Sunshine
Quoted 6 lines
       if (is_encoding_utf8(src) && is_encoding_utf8(dst))
               return 1;
utf8.c +2 -0
+       if (same_utf_encoding(src, dst))
+               return 1;
       return !strcasecmp(src, dst);

}

Quoted 7 lines

This seems odd. I would have expected the newly-added generalized conditional to replace the original UTF-8-specific conditional, not supplement it. That is, shouldn't the entire function body be:

   if (same_utf_encoding(src, dst))
       return 1;
   return !strcasecmp(src, dst);
Quoted 6 lines

No, because is_encoding_utf8() returns "true" (=1) if the encoding is NULL. That is not the case for UTF-16 et al. The caller of same_encoding() might expect that behavior.
I could have moved the "UTF-8" == NULL assumption into same_utf_encoding() but that did not feel right.
Does this make sense?

Not particularly.

Looking at 677cfed56a (commit-tree: cope with different ways "utf-8" can be spelled., 2006-12-30), which introduced is_encoding_utf8() along with its builtin NULL-check, I can see why that function wants to treat NULL the same as UTF-8.

However, I'm having a tough time imagining cases in which callers would want same_encoding() to return true if both arguments are NULL, but outright crash if only one is NULL (which is the behavior even before this patch). In other words, same_encoding() takes advantage of is_encoding_utf8() for its convenience, not for its NULL-handling. Given that view, the two explicit is_encoding_utf8() calls in same_encoding() seem redundant once the same_utf_encoding() call is added.

#10 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 8 lines · Eric Sunshine

However, I'm having a tough time imagining cases in which callers would want same_encoding() to return true if both arguments are NULL, but outright crash if only one is NULL (which is the behavior even before this patch). In other words, same_encoding() takes advantage of is_encoding_utf8() for its convenience, not for its NULL-handling. Given that view, the two explicit is_encoding_utf8() calls in same_encoding() seem redundant once the same_utf_encoding() call is added.

So... does that mean we'd want something like this, or do you have something else in mind?

	int same_encoding(const char *src, const char *dst)
	{
		static const char utf8[] = "UTF-8";

		if (!src)
			src = utf8;
		if (!dst)
			dst = utf8;
		if (same_utf_encoding(src, dst))
			return 1;
	 	return !strcasecmp(src, dst);
	}
#11 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 13 lines · Junio C Hamano
Quoted 8 lines · Eric Sunshine

However, I'm having a tough time imagining cases in which callers would want same_encoding() to return true if both arguments are NULL, but outright crash if only one is NULL (which is the behavior even before this patch). In other words, same_encoding() takes advantage of is_encoding_utf8() for its convenience, not for its NULL-handling. Given that view, the two explicit is_encoding_utf8() calls in same_encoding() seem redundant once the same_utf_encoding() call is added.

So... does that mean we'd want something like this, or do you have something else in mind?

Quoted 12 lines
        int same_encoding(const char *src, const char *dst)
        {
                static const char utf8[] = "UTF-8";

                if (!src)
                        src = utf8;
                if (!dst)
                        dst = utf8;
                if (same_utf_encoding(src, dst))
                        return 1;
                return !strcasecmp(src, dst);
        }

I am not proposing anything like that for this patch or patch series. I'm merely asking why, after this patch, same_encoding() still contains the (in my mind) now-unneeded conditional:

    if (is_encoding_utf8(src) && is_encoding_utf8(dst))
        return 1;

If I'm reading the current code correctly, same_encoding() will crash when either (but not both) of its arguments is NULL and the non-NULL argument is not a variation of "UTF-8". If both arguments are NULL, then it won't crash, but I don't believe that it was intentional that it should crash for some NULL cases but not others; rather, not crashing when both are NULL is an _accidental_ side-effect of relying upon is_encoding_utf8().

If I understood him correctly, Lars's justification for retaining the conditional in question even after the patch is to maintain the non-crashing behavior for both arguments being NULL, even though it will continue to crash when only one is NULL. That justification doesn't makes sense to me since I can't imagine clients relying on accidental behavior of sometimes crashing, sometimes not, hence my question to Lars.

As for your snippet above which ensures that 'src' and 'dst' are non-NULL, that (or some variation) would be fine if we ever expect callers of same_encoding() to pass NULL for either of those arguments, but such a fix is outside the scope of this patch and even this patch series (which does not require such a fix), IMHO.

#12 lore raw

Re: [PATCH v12 04/10] utf8: teach same_encoding() alternative UTF encoding names

Quoted 30 lines · Eric Sunshine
Quoted 13 lines · Junio C Hamano
Quoted 8 lines · Eric Sunshine

However, I'm having a tough time imagining cases in which callers would want same_encoding() to return true if both arguments are NULL, but outright crash if only one is NULL (which is the behavior even before this patch). In other words, same_encoding() takes advantage of is_encoding_utf8() for its convenience, not for its NULL-handling. Given that view, the two explicit is_encoding_utf8() calls in same_encoding() seem redundant once the same_utf_encoding() call is added.

So... does that mean we'd want something like this, or do you have something else in mind?

Quoted 12 lines
       int same_encoding(const char *src, const char *dst)
       {
               static const char utf8[] = "UTF-8";

               if (!src)
                       src = utf8;
               if (!dst)
                       dst = utf8;
               if (same_utf_encoding(src, dst))
                       return 1;
               return !strcasecmp(src, dst);
       }
Quoted 6 lines

I am not proposing anything like that for this patch or patch series. I'm merely asking why, after this patch, same_encoding() still contains the (in my mind) now-unneeded conditional:

   if (is_encoding_utf8(src) && is_encoding_utf8(dst))
       return 1;

My main motivation was to keep the existing behavior "as-is" to avoid any regressions.

However, I agree with your critic of the inconsistencies.

Therefore, I will use Junio's suggestion above as it makes the intented behaivior clear.

Thanks,
Lars

#13 lore raw

PATCH v12 5/10 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 | 26 ++++++++++++++++++++++++++
 utf8.h |  9 +++++++++
 2 files changed, 35 insertions(+)
utf8.c +26 -0
index c30daf4d34..d16dc1f244 100644
@@ -556,6 +556,32 @@ 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 (
+	  (same_utf_encoding("UTF-16BE", enc) ||
+	   same_utf_encoding("UTF-16LE", enc)) &&
+	  (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+	   has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+	) || (
+	  (same_utf_encoding("UTF-32BE",  enc) ||
+	   same_utf_encoding("UTF-32LE", enc)) &&
+	  (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
#14 lore raw

PATCH v12 6/10 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 d16dc1f244..2d8821d36e 100644
@@ -582,6 +582,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 (
+	   (same_utf_encoding(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)))
+	) || (
+	   (same_utf_encoding(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
#15 lore raw

PATCH v12 7/10 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                        | 113 ++++++++++++++++++++++++++++++-
 convert.h                        |   1 +
 sha1_file.c                      |   2 +-
 t/t0028-working-tree-encoding.sh | 142 +++++++++++++++++++++++++++++++++++++++
 5 files changed, 336 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 +112 -1

173 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 +142 -0

142 lines not on this page · raw message

Signature · 1 line
2.16.2
#16 lore raw

PATCH v12 8/10 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                        | 61 +++++++++++++++++++++++++++++++++++++++
 t/t0028-working-tree-encoding.sh | 62 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 123 insertions(+)
convert.c +61 -0
index 85e49741af..3cab4fa907 100644
@@ -266,6 +266,64 @@ 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)
+{
+	/* We only check for UTF here as UTF?? can be an alias for UTF-?? */
+	if (istarts_with(enc, "UTF")) {
+		/*
+		 * 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 cut off the last two characters of the encoding name
+			 * to generate the encoding name suitable for BOMs.
+			 */
+			const char *advise_msg = _(
+				"The file '%s' contains a byte order "
+				"mark (BOM). Please use UTF-%s as "
+				"working-tree-encoding.");
+			const char *stripped = NULL;
+			char *upper = xstrdup_toupper(enc);
+			upper[strlen(upper)-2] = '\0';
+			if (!skip_prefix(upper, "UTF-", &stripped))
+				skip_prefix(stripped, "UTF", &stripped);
+			advise(advise_msg, path, stripped);
+			free(upper);
+			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 UTF-%sBE or UTF-%sLE "
+				"(depending on the byte order) as "
+				"working-tree-encoding.");
+			const char *stripped = NULL;
+			char *upper = xstrdup_toupper(enc);
+			if (!skip_prefix(upper, "UTF-", &stripped))
+				skip_prefix(stripped, "UTF", &stripped);
+			advise(advise_msg, path, stripped, stripped);
+			free(upper);
+			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 +349,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 +62 -0

72 lines not on this page · raw message

Signature · 1 line
2.16.2
#17 lore raw

PATCH v12 9/10 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 3cab4fa907..ba6f2019a3 100644
@@ -324,6 +324,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,
@@ -352,6 +375,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) {
@@ -369,6 +393,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 1bb528b339..2ff7541b34 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
#18 lore raw

PATCH v12 10/10 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                        | 77 ++++++++++++++++++++++++++++++++++++++++
 convert.h                        |  1 +
 environment.c                    |  1 +
 t/t0028-working-tree-encoding.sh | 39 ++++++++++++++++++++
 7 files changed, 137 insertions(+)
Documentation/config.txt +6 -0
index 0e25b2c92b..7dcac9b540 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 and/or whitespace 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 +77 -0

89 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 2ff7541b34..884f0878b1 100755
@@ -203,4 +203,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
#19 lore raw
In reply to [email protected]
Quoted 8 lines · [email protected] writes:

From: Lars Schneider <[email protected]>

Patches 1-6,9 are preparation and helper functions. Patch 4 is new. Patch 7,8,10 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.

I didn't see any further review comments on this round, and as far as I can tell from my reading, these patches looked more-or-less ready.

Except for 04/10 that had a few messages around "who should be responsible for handling the 'NULL is for the default UTF-8'?", that is.

So, what's the doneness of this thing?

#20 lore raw
Quoted 18 lines · Junio C Hamano
Quoted 8 lines · [email protected] writes:

From: Lars Schneider <[email protected]>

Patches 1-6,9 are preparation and helper functions. Patch 4 is new. Patch 7,8,10 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.

I didn't see any further review comments on this round, and as far as I can tell from my reading, these patches looked more-or-less ready.

Quoted 5 lines

Except for 04/10 that had a few messages around "who should be responsible for handling the 'NULL is for the default UTF-8'?", that is.

So, what's the doneness of this thing?

Almost. I'll send a new round tomorrow. I hope to make this the final round.

- Lars

#21 lore raw
Quoted 21 lines · Lars Schneider
Quoted 19 lines · Junio C Hamano
Quoted 8 lines · [email protected] writes:

From: Lars Schneider <[email protected]>

Patches 1-6,9 are preparation and helper functions. Patch 4 is new. Patch 7,8,10 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.

I didn't see any further review comments on this round, and as far as I can tell from my reading, these patches looked more-or-less ready.

Quoted 8 lines
Quoted 5 lines

Except for 04/10 that had a few messages around "who should be responsible for handling the 'NULL is for the default UTF-8'?", that is.

So, what's the doneness of this thing?

Almost. I'll send a new round tomorrow. I hope to make this the final round.

@Junio: Can you remind me of your preference? Should I rebase my series to 2.17.0 or keep the base to make it easier for you to check the interdiff?

Thanks,
Lars