Chromium Code Reviews| Index: utils/pub/utils.dart |
| diff --git a/utils/pub/utils.dart b/utils/pub/utils.dart |
| index 21079f62ba86df7297c130806d064e681c68322b..c5889e98aec88fca7667bc8c7ef2fee3a22cff79 100644 |
| --- a/utils/pub/utils.dart |
| +++ b/utils/pub/utils.dart |
| @@ -9,6 +9,7 @@ library utils; |
| import 'dart:crypto'; |
| import 'dart:isolate'; |
| +import 'dart:uri'; |
| /** A pair of values. */ |
| class Pair<E, F> { |
| @@ -150,3 +151,49 @@ List<String> split1(String toSplit, String pattern) { |
| return [toSplit.substring(0, index), |
| toSplit.substring(index + pattern.length)]; |
| } |
| + |
|
Bob Nystrom
2012/11/28 19:35:41
Did you copy these from pkg/http? If so, leave a c
nweiz
2012/11/28 19:42:14
Done.
|
| +/// Adds additional query parameters to [url], overwriting the original |
| +/// parameters if a name conflict occurs. |
| +Uri addQueryParameters(Uri url, Map<String, String> parameters) { |
|
Bob Nystrom
2012/11/28 19:35:41
"add" -> "set" since it replaces.
nweiz
2012/11/28 19:42:14
"set" seems like it implies that it mutates the UR
|
| + var queryMap = queryToMap(url.query); |
| + mapAddAll(queryMap, parameters); |
| + return url.resolve("?${mapToQuery(queryMap)}"); |
| +} |
| + |
| +/// Convert a URL query string (or `application/x-www-form-urlencoded` body) |
| +/// into a [Map] from parameter names to values. |
| +Map<String, String> queryToMap(String queryList) { |
| + var map = <String>{}; |
| + for (var pair in queryList.split("&")) { |
| + var split = split1(pair, "="); |
| + if (split.isEmpty) continue; |
| + var key = urlDecode(split[0]); |
| + var value = split.length > 1 ? urlDecode(split[1]) : ""; |
| + map[key] = value; |
| + } |
| + return map; |
| +} |
| + |
| +/// Convert a [Map] from parameter names to values to a URL query string. |
| +String mapToQuery(Map<String, String> map) { |
| + var pairs = <List<String>>[]; |
| + map.forEach((key, value) { |
| + key = encodeUriComponent(key); |
| + value = (value == null || value.isEmpty) ? null : encodeUriComponent(value); |
| + pairs.add([key, value]); |
| + }); |
| + return Strings.join(pairs.map((pair) { |
| + if (pair[1] == null) return pair[0]; |
| + return "${pair[0]}=${pair[1]}"; |
| + }), "&"); |
| +} |
| + |
| +/// Add all key/value pairs from [source] to [destination], overwriting any |
| +/// pre-existing values. |
| +void mapAddAll(Map destination, Map source) => |
| + source.forEach((key, value) => destination[key] = value); |
| + |
| +/// Decodes a URL-encoded string. Unlike [decodeUriComponent], this includes |
| +/// replacing `+` with ` `. |
| +String urlDecode(String encoded) => |
| + decodeUriComponent(encoded.replaceAll("+", " ")); |