├── CONTRIBUTING ├── LICENSE ├── README.md ├── url_diff.py └── url_diff_test.py /CONTRIBUTING: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | Before we can use your code, you must sign the 5 | [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) 6 | (CLA), which you can do online. The CLA is necessary mainly because you own the 7 | copyright to your changes, even after your contribution becomes part of our 8 | codebase, so we need your permission to use and distribute your code. We also 9 | need to be sure of various other things—for instance that you'll tell us if you 10 | know that your code infringes on other people's patents. You don't have to sign 11 | the CLA until after you've submitted your code for review and a member has 12 | approved it, but you must do it before we can put your code into our codebase. 13 | Before you start working on a larger contribution, you should get in touch with 14 | us first through the issue tracker with your idea so that we can help out and 15 | possibly guide you. Coordinating up front makes it much easier to avoid 16 | frustration later on. 17 | 18 | ### Code reviews 19 | All submissions, including submissions by project members, require review. We 20 | use Github pull requests for this purpose. 21 | 22 | ### The small print 23 | Contributions made by corporations are covered by a different agreement than 24 | the one above, the Software Grant and Corporate Contributor License Agreement. 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2013 Google Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | url_diff 2 | ======== 3 | 4 | A tool (like diff) to show the differences between 2 URLs. 5 | 6 | In my job I work with a lot of URLs, and often need to know which parameters (names and/or values) differ between the two. I got fed up with "eye-balling" URLs to figure out the difference (esp. with different param orderings) so I'm developing a tool to do it for me. 7 | 8 | enter url_diff 9 | -------------- 10 | 11 | for example, what's different between these 2 URLs: 12 | `http://example.com/?foo=bar&cake=lie&you=monster&beer=good&speech=free&breaking=bad` 13 | `http://example.com/?&speech=free&beer=good&aperture=science&foo=bar&you=here&breaking=over` 14 | 15 | url_diff.py 'http://example.com/?foo=bar&cake=lie&you=monster&beer=good&speech=free&breaking=bad' \ 16 | 'http://example.com/?&speech=free&beer=good&aperture=science&foo=bar&you=here&breaking=over' 17 | breaking 18 | < bad 19 | > over 20 | 21 | cake 22 | < lie 23 | 24 | you 25 | < monster 26 | > here 27 | 28 | aperture 29 | > science 30 | 31 | Also, you can use url_diff to enumerate the parameters of a single URL (which I 32 | think is easier to read): 33 | 34 | python url_diff.py 'http://localhost/?param=val&readable=i%20think%20so' 35 | readable 36 | < i%20think%20so 37 | 38 | param 39 | < val 40 | 41 | The help message should explain the rest: 42 | 43 | python url_diff.py --help 44 | 45 | usage: url_diff.py [-h] [--hostname] [--names] [--decode] [--quiet] 46 | [--case_insensitive] 47 | [] 48 | 49 | show the difference between 2 urls. Inspired by the unix utility diff 50 | 51 | positional arguments: 52 | URL to diff against. Logically handled as the left argurmnt of diff. 53 | URL to diff against. Logically handled as the right argurmnt of diff. 54 | 55 | optional arguments: 56 | -h, --help show this help message and exit 57 | --hostname also diff URL hostname 58 | --names, -n only diff URL parameter names. 59 | --decode, -d URL decode parameter names and values (if applicable). 60 | Decoded params will be used for comparison and printing. 61 | --quiet, -q suppress output and return non-zero if URLs differ. 62 | --case_insensitive, -i 63 | Perform case insensitive diff. NOTE: this converts all input to lowercase. 64 | 65 | Currently this tool discards everything after '#' if it is present. see 66 | https://github.com/google/url_diff for more information. 67 | 68 | Please keep in mind this is still in alpha, and it's currently a weekend project. Hope y'all find it useful too. 69 | 70 | Currently it runs on versions of Python between 2.7 and 3.5 71 | -------------------------------------------------------------------------------- /url_diff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Copyright 2014 Google Inc. All Rights Reserved. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | """ 17 | 18 | """A tool to show the difference between URLs. 19 | 20 | This tool is inspired by the UNIX utility `diff`. 21 | """ 22 | 23 | import argparse 24 | import base64 25 | import copy 26 | import logging 27 | import sys 28 | 29 | class Error(Exception): 30 | """Base exception class.""" 31 | pass 32 | 33 | class ParamDiffTypeError(Error): 34 | """Raised when an incorrect diff type used.""" 35 | pass 36 | 37 | class HostnameParseError(Error): 38 | """Raised when unable to parse hostname from URL.""" 39 | pass 40 | 41 | # TODO(macpd): investigate making this a namedtuple 42 | class ParamDiffEntry(object): 43 | """Represents difference of 2 URL params with same name.""" 44 | LEFT_ONLY = 1 45 | RIGHT_ONLY = 2 46 | BOTH_DIFFER = 3 47 | LEFT_HEADER_FORMAT = '{0}\n< {1}' 48 | LEFT_ADDITIONAL_SEPARATOR = '\n< ' 49 | RIGHT_HEADER_FORMAT = '{0}\n> {1}' 50 | RIGHT_ADDITIONAL_SEPARATOR = '\n> ' 51 | 52 | def __init__(self, name, left_value, right_value, diff_type): 53 | self._name = name 54 | self._left_val = list(left_value) if left_value else [] 55 | self._right_val = list(right_value) if right_value else [] 56 | try: 57 | if self._valid_diff_type(diff_type): 58 | self._type = diff_type 59 | except ParamDiffTypeError: 60 | logging.error("Incorrect diff type: %s", diff_type) 61 | self._type = self.BOTH_DIFFER 62 | 63 | def _valid_diff_type(self, diff_type): 64 | if (diff_type != self.LEFT_ONLY and diff_type != self.RIGHT_ONLY and 65 | diff_type != self.BOTH_DIFFER): 66 | raise ParamDiffTypeError('%s is not a valid diff type. ', diff_type) 67 | return True 68 | 69 | @property 70 | def name(self): 71 | return self._name 72 | 73 | def __str__(self): 74 | ret = self._name 75 | if self._type == self.LEFT_ONLY or self._type == self.BOTH_DIFFER: 76 | ret = self.LEFT_HEADER_FORMAT.format(ret, self.LEFT_ADDITIONAL_SEPARATOR.join(self._left_val)) 77 | if self._type == self.RIGHT_ONLY or self._type == self.BOTH_DIFFER: 78 | ret = self.RIGHT_HEADER_FORMAT.format(ret, self.RIGHT_ADDITIONAL_SEPARATOR.join(self._right_val)) 79 | return ret 80 | 81 | 82 | class UrlDiffer(object): 83 | """Object to diff URLs. 84 | 85 | Diffs URLs upon intialization.""" 86 | 87 | PATH_DELIM = '?' 88 | PARAM_DELIM = '&' 89 | NAME_VAL_DELIM = '=' 90 | SCHEME_DELIM = '://' 91 | UNIX_SLASH = '/' 92 | URL_ESCAPE_CHAR = '%' 93 | URL_ESCAPE_SEQ_LEN = 3 # expected length of URL espace sequences, aka len('%25') 94 | 95 | def __init__(self, left_url, right_url, names_only=False, hostnames=False, 96 | url_decode_params=False, case_insensitive=False): 97 | """Initializes object and performs URL diffing.""" 98 | self._left_url = self._normalize_url(left_url) 99 | self._right_url = self._normalize_url(right_url) 100 | self._names_only = names_only 101 | self._wants_hostname_diff = hostnames 102 | self._url_decode_params = url_decode_params 103 | self._case_insensitive = case_insensitive 104 | self._diffs = [] 105 | self._do_diff() 106 | 107 | def __str__(self): 108 | ret = [] 109 | for diff in self._diffs: 110 | if self._names_only: 111 | ret.append(diff.name) 112 | else: 113 | ret.append(str(diff)) 114 | join_delim = '\n' if self._names_only else '\n\n' 115 | return join_delim.join(ret) 116 | 117 | def _normalize_url(self, url): 118 | """Strips white space, and removes all chars after #""" 119 | ret = url.strip() 120 | if '#' in ret: 121 | idx = ret.index('#') 122 | ret = ret[:idx] 123 | return ret 124 | 125 | def _get_hostname(self, url): 126 | """Parses the hostname from a URL" 127 | 128 | Finds hostname between scheme and first unix slash. 129 | """ 130 | if self.SCHEME_DELIM in url: 131 | scheme_idx = url.index(self.SCHEME_DELIM) 132 | hostname_begin = scheme_idx + len(self.SCHEME_DELIM) 133 | else: 134 | hostname_begin = 0 135 | 136 | if self.UNIX_SLASH in url[hostname_begin:]: 137 | hostname_end = url.index(self.UNIX_SLASH, hostname_begin) 138 | else: 139 | hostname_end = hostname_begin + len(url[hostname_begin:]) 140 | 141 | return url[hostname_begin:hostname_end] 142 | 143 | def _diff_hostnames(self, left, right): 144 | """Diffs hostnames, if different appends ParamDiffEntry to diffs list. 145 | 146 | Args: 147 | left: String; left hostname. 148 | right: String; right hostname. 149 | Returns: 150 | Bool; True if different, else False. 151 | """ 152 | if left == right: 153 | self._hostnames_differ = False 154 | else: 155 | self._hostnames_differ = True 156 | self._diffs.append(ParamDiffEntry('Hostname', [left], [right], 157 | ParamDiffEntry.BOTH_DIFFER)) 158 | 159 | return self._hostnames_differ 160 | 161 | def _get_params(self, url): 162 | """Returns a dict of the url params. 163 | 164 | Args: 165 | url: String; URL to get parameter names and values from. 166 | Returns: 167 | Dict of parameter names that map to their values. 168 | """ 169 | param_dict = {} 170 | if self.PATH_DELIM not in url: 171 | return param_dict 172 | 173 | params_pos = url.find(self.PATH_DELIM) + 1 174 | for token in url[params_pos:].split(self.PARAM_DELIM): 175 | if not token: 176 | continue 177 | if '=' not in token: 178 | token_key = token 179 | token_value = '' 180 | else: 181 | partitioned_param = token.partition(self.NAME_VAL_DELIM) 182 | token_key = partitioned_param[0] 183 | token_value = partitioned_param[2] 184 | 185 | if self._url_decode_params: 186 | token_key = self._url_decode(token_key) 187 | token_value = self._url_decode(token_value) 188 | 189 | value_list = param_dict.get(token_key, []) 190 | value_list.append(token_value) 191 | param_dict[token_key] = value_list 192 | 193 | return param_dict 194 | 195 | def _diff_params(self, left_params, right_params): 196 | """Returns a list of the diffence between dicts on key/values. 197 | 198 | First all keys that exist in both URLs are compared, then keys only in the 199 | left, followed by keys only in the right. 200 | 201 | Args: 202 | left_param: dict; param name -> values dict of the left URL. 203 | right_param: dict; param name -> values dict of the right URL. 204 | 205 | Returns: 206 | List of ParamDiffEntry of differences between the left and right params. 207 | """ 208 | diffs = [] 209 | left_key_set = frozenset(left_params.keys()) 210 | right_key_set = frozenset(right_params.keys()) 211 | left_key_diff = left_key_set.difference(right_key_set) 212 | right_key_diff = right_key_set.difference(left_key_set) 213 | key_intersection = left_key_set.intersection(right_key_set) 214 | 215 | for common_key in key_intersection: 216 | left_val_set = set(left_params[common_key]) 217 | right_val_set = set(right_params[common_key]) 218 | left_diff = left_val_set.difference(right_val_set) 219 | right_diff = right_val_set.difference(left_val_set) 220 | if left_diff and right_diff: 221 | diff_type = ParamDiffEntry.BOTH_DIFFER 222 | elif left_diff: 223 | diff_type = ParamDiffEntry.LEFT_ONLY 224 | elif right_diff: 225 | diff_type = ParamDiffEntry.RIGHT_ONLY 226 | else: 227 | # if no diff skip to next iteration 228 | continue 229 | diffs.append( 230 | ParamDiffEntry( 231 | common_key, 232 | left_val_set.difference(right_val_set), 233 | right_val_set.difference(left_val_set), 234 | diff_type)) 235 | 236 | for left_key in left_key_diff: 237 | diffs.append(ParamDiffEntry( 238 | left_key, left_params[left_key], None, ParamDiffEntry.LEFT_ONLY)) 239 | 240 | for right_key in right_key_diff: 241 | diffs.append(ParamDiffEntry( 242 | right_key, None, right_params[right_key], ParamDiffEntry.RIGHT_ONLY)) 243 | 244 | return diffs 245 | 246 | def _do_diff(self): 247 | """Performs all appropriate diffing operations.""" 248 | if self._case_insensitive: 249 | self._left_url, self._right_url = self._left_url.lower(), self._right_url.lower() 250 | if self._wants_hostname_diff: 251 | self._left_hostname = self._get_hostname(self._left_url) 252 | self._right_hostname = self._get_hostname(self._right_url) 253 | self._diff_hostnames(self._left_hostname, self._right_hostname) 254 | self._left_params_dict = self._get_params(self._left_url) 255 | self._right_params_dict = self._get_params(self._right_url) 256 | if not self._left_params_dict == self._right_params_dict: 257 | self._diffs.extend(self._diff_params( 258 | self._left_params_dict, self._right_params_dict)) 259 | 260 | def _url_decode(self, token): 261 | """URL decodes provided string. 262 | 263 | Replaces all instances of %NN with the ascii value of hex(NN). 264 | 265 | Args: 266 | token: String to be decoded. 267 | Returns: 268 | String; deocded string. 269 | """ 270 | if self.URL_ESCAPE_CHAR not in token: 271 | return token 272 | new_token = [] 273 | cur = prev = 0 274 | cur = token.find(self.URL_ESCAPE_CHAR, prev) 275 | while cur != -1: 276 | new_token.append(token[prev:cur]) 277 | decoded_hex_as_bytes = base64.b16decode( 278 | token[cur+1:cur+self.URL_ESCAPE_SEQ_LEN], casefold=True) 279 | new_token.append(decoded_hex_as_bytes.decode()) 280 | prev = cur + self.URL_ESCAPE_SEQ_LEN 281 | cur = token.find(self.URL_ESCAPE_CHAR, prev) 282 | 283 | new_token.append(token[prev:]) 284 | return ''.join(new_token) 285 | 286 | def left_params(self): 287 | """Returns a deep coy of the left params dict.""" 288 | return copy.deepcopy(self._left_params_dict) 289 | 290 | def right_params(self): 291 | """Returns a deep coy of the left params dict.""" 292 | return copy.deepcopy(self._right_params_dict) 293 | 294 | def are_different(self): 295 | """Returns True if URLs differ, else false.""" 296 | return len(self._diffs) != 0 297 | 298 | @property 299 | def diff(self): 300 | return copy.deepcopy(self._diffs) 301 | 302 | 303 | def main(): 304 | """Parses args, inits and prints differ, and exits with appropriate value.""" 305 | # TODO(macpd): provide option for second diff delimeter. This would allow one 306 | # to diff multivalued param values. 307 | # TODO(macpd): provide verbosity option 308 | arg_parser = argparse.ArgumentParser( 309 | description='show the difference between 2 urls. Inspired by the unix utility diff', 310 | epilog='Currenty this tool discards everything after # if present. see https://github.com/google/url_diff for more information.') 311 | arg_parser.add_argument('--hostname', default=False, required=False, 312 | help='also diff URL hostname', action='store_true', dest='diff_hostname') 313 | arg_parser.add_argument('--names', '-n', default=False, required=False, 314 | help='only diff URL parameter names.', action='store_true', dest='names_only') 315 | arg_parser.add_argument('--decode', '-d', default=False, required=False, 316 | help='URL decode parameter names and values (if applicable). Decoded params will be used for comparison and printing.', 317 | action='store_true', dest='decode_params') 318 | arg_parser.add_argument('left_url', type=str, help='URL to diff against. Logically handled as the left argument of diff.', metavar='') 319 | arg_parser.add_argument('right_url', type=str, help='URL to diff against. Logically handled as the right argument of diff.', metavar='', nargs='?', default='') 320 | arg_parser.add_argument('--quiet', '-q', action='store_true', help='suppress output and return non-zero if URLs differ.', 321 | default=False, required=False) 322 | arg_parser.add_argument('--case_insensitive', '-i', action='store_true', help='Perform case insensitive diff. NOTE: this converts all input to lowercase.', default=False, required=False) 323 | args = arg_parser.parse_args() 324 | 325 | differ = UrlDiffer(args.left_url, 326 | args.right_url, 327 | names_only=args.names_only, 328 | hostnames=args.diff_hostname, 329 | url_decode_params=args.decode_params, 330 | case_insensitive=args.case_insensitive) 331 | 332 | if not args.quiet: 333 | sys.stdout.write('%s\n' % differ) 334 | 335 | sys.exit(1 if differ.are_different() else 0) 336 | 337 | if __name__ == '__main__': 338 | main() 339 | -------------------------------------------------------------------------------- /url_diff_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Copyright 2014 Google Inc. All Rights Reserved. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | """ 17 | 18 | """ 19 | Tests for url_diff 20 | """ 21 | 22 | import unittest 23 | import url_diff 24 | 25 | class TestUrlDiffer(unittest.TestCase): 26 | NORMALIZED_URL_WITHOUT_PARAMS = 'http://localhost/' 27 | NORMALIZED_URL_WITH_PARMAS = ('%s?key=val&aperture=science&cake=lie' % 28 | NORMALIZED_URL_WITHOUT_PARAMS) 29 | NORMALIZED_URLS = [NORMALIZED_URL_WITHOUT_PARAMS, NORMALIZED_URL_WITH_PARMAS] 30 | sample_urls = { 31 | 'http://www.nytimes.com/2013/12/31/science/viewing-where-the-internet-goes.html?_r=0': 32 | 'www.nytimes.com', 33 | 'https://twitter.com': 34 | 'twitter.com', 35 | 'https://mail.google.com/mail/u/0/?ui=2&shva=1#inbox': 36 | 'mail.google.com', 37 | 'http://something.localdomain/search?site=default_collection&client=default_frontend&output=xml_no_dtd&proxystylesheet=default_frontend&proxycustom=%3CHOME/%3E': 38 | 'something.localdomain', 39 | '/~macpd/url_diff/': 40 | '', 41 | '/2/library/unittest.html#assert-methods': 42 | ''} 43 | 44 | def setUp(self): 45 | self.empty_differ = url_diff.UrlDiffer('', '') 46 | 47 | def testGetHostname(self): 48 | """Test hostname correctly parsed from URL.""" 49 | for url in self.sample_urls: 50 | self.assertEquals(self.empty_differ._get_hostname(url), 51 | self.sample_urls.get(url)) 52 | 53 | def testNormalizeUrlWithoutParams(self): 54 | """Tests url whitespace trimmed, and truncated at hash.""" 55 | for normalized_url in self.NORMALIZED_URLS: 56 | spaces_on_each_end = ' %s ' % normalized_url 57 | hash_at_end = '%s#' % normalized_url 58 | hash_with_trailing_chars = ('%s#to%%20be%%20removed' % 59 | normalized_url) 60 | self.assertEqual(self.empty_differ._normalize_url(spaces_on_each_end), 61 | normalized_url) 62 | self.assertEqual(self.empty_differ._normalize_url(hash_at_end), 63 | normalized_url) 64 | self.assertEqual( 65 | self.empty_differ._normalize_url(hash_with_trailing_chars), 66 | normalized_url) 67 | # alse confirm normalized URL not changed 68 | self.assertEqual( 69 | self.empty_differ._normalize_url(normalized_url), 70 | normalized_url) 71 | 72 | def testEmptyURLsAreEqual(self): 73 | """Tests empty URLs are considered equal.""" 74 | self.assertFalse(self.empty_differ.are_different()) 75 | 76 | def testUrlDecode(self): 77 | """Tests percent encoded strings are correctly decoded to ASCII.""" 78 | self.assertEqual('', self.empty_differ._url_decode('%3CHOME/%3E')) 79 | --------------------------------------------------------------------------------