lib/string: add `Text::escape_to_mk` to escape to Makefiles
authorJean Privat <jean@pryen.org>
Mon, 10 Nov 2014 21:24:43 +0000 (16:24 -0500)
committerJean Privat <jean@pryen.org>
Tue, 11 Nov 2014 03:09:49 +0000 (22:09 -0500)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/string.nit

index 28ad7b5..0ffb303 100644 (file)
@@ -515,6 +515,29 @@ abstract class Text
                return b.to_s
        end
 
+       # Escape to include in a Makefile
+       #
+       # Unfortunately, some characters are not escapable in Makefile.
+       # These characters are `;`, `|`, `\`, and the non-printable ones.
+       # They will be rendered as `"?{hex}"`.
+       fun escape_to_mk: String do
+               var b = new FlatBuffer
+               for i in [0..length[ do
+                       var c = chars[i]
+                       if c == '$' then
+                               b.append("$$")
+                       else if c == ':' or c == ' ' or c == '#' then
+                               b.add('\\')
+                               b.add(c)
+                       else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
+                               b.append("?{c.ascii.to_base(16, false)}")
+                       else
+                               b.add(c)
+                       end
+               end
+               return b.to_s
+       end
+
        # Return a string where Nit escape sequences are transformed.
        #
        #     var s = "\\n"