Index: sdk/lib/_internal/pub/lib/src/utils.dart |
diff --git a/sdk/lib/_internal/pub/lib/src/utils.dart b/sdk/lib/_internal/pub/lib/src/utils.dart |
index 08b0fb44c26f48661fd0dcee321590223c9fa8e8..392f8f5e6b9ca6685ba10ae3a212477168aa9910 100644 |
--- a/sdk/lib/_internal/pub/lib/src/utils.dart |
+++ b/sdk/lib/_internal/pub/lib/src/utils.dart |
@@ -9,6 +9,7 @@ import 'dart:async'; |
import 'dart:crypto'; |
import 'dart:io'; |
import 'dart:isolate'; |
+import 'dart:json' as json; |
import 'dart:mirrors'; |
import 'dart:uri'; |
@@ -457,6 +458,68 @@ Future resetStack(fn()) { |
return completer.future; |
} |
+/// The subset of strings that don't need quoting in YAML. This is pattern does |
+/// not strictly follow the plain scalar grammar of YAML, which means some |
+/// strings may be unnecessarily quoted, but it much simpler. |
nweiz
2013/05/23 23:26:00
"it" -> "it's"
Bob Nystrom
2013/05/23 23:47:52
Done.
|
+final _unquotableYamlString = new RegExp(r"^[a-zA-Z_\-][a-zA-Z_0-9\-]*$"); |
nweiz
2013/05/23 23:26:00
I don't think you need to escape trailing hyphens
Bob Nystrom
2013/05/23 23:47:52
Done.
|
+ |
+/// Converts [data], which is a parsed YAML object to a pretty-printed string, |
nweiz
2013/05/23 23:26:00
"object" -> "object,"
Bob Nystrom
2013/05/23 23:47:52
Done.
|
+/// using indentation for maps. |
+String yamlToString(data) { |
+ var buffer = new StringBuffer(); |
+ |
+ _stringify(bool isMapValue, String indent, data) { |
+ // TODO(nweiz): Serialize using the YAML library once it supports |
+ // serialization. |
+ |
+ // Use indentation for maps. |
+ if (data is Map) { |
+ if (isMapValue) { |
+ buffer.writeln(); |
+ indent += ' '; |
+ } |
+ |
+ // Sort the keys. This minimizes deltas in diffs. |
+ var keys = data.keys.toList(); |
+ keys.sort((a, b) => a.toString().compareTo(b.toString())); |
+ |
+ var first = true; |
+ for (var key in keys) { |
+ if (!first) buffer.writeln(); |
+ first = false; |
+ |
+ var keyString = key; |
+ if (key is! String || !_unquotableYamlString.hasMatch(key)) { |
+ keyString = json.stringify(key); |
+ } |
+ |
+ buffer.write('$indent$keyString:'); |
+ _stringify(true, indent, data[key]); |
+ } |
+ |
+ return; |
+ } |
+ |
+ // Everything else we just stringify using JSON to handle escapes in |
+ // strings and number formatting. |
+ var string = data; |
+ |
+ // Don't quote plain strings if not needed. |
+ if (data is! String || !_unquotableYamlString.hasMatch(data)) { |
+ string = json.stringify(data); |
+ } |
+ |
+ if (isMapValue) { |
+ buffer.write(' $string'); |
+ } else { |
+ buffer.write('$indent$string'); |
+ } |
+ } |
+ |
+ _stringify(false, '', data); |
+ return buffer.toString(); |
+} |
+ |
/// An exception class for exceptions that are intended to be seen by the user. |
/// These exceptions won't have any debugging information printed when they're |
/// thrown. |