Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / tools / metrics / common / diff_util.py
bloba4553df63aac2cc26200c853f8ffa771f699d9f3
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Utility functions for prompting user if changes automatically applied to some
6 user-managed files are correct.
7 """
9 import logging
10 import os
11 import webbrowser
13 from difflib import HtmlDiff
14 from tempfile import NamedTemporaryFile
17 def PromptUserToAcceptDiff(old_text, new_text, prompt):
18 """Displays a difference in two strings (old and new file contents) to the
19 user and asks whether the new version is acceptable.
21 Args:
22 old_text: A string containing old file contents.
23 new_text: A string containing new file contents.
24 prompt: Text that should be displayed to the user, asking whether the new
25 file contents should be accepted.
27 Returns:
28 True is user accepted the changes or there were no changes, False otherwise.
29 """
30 logging.info('Computing diff...')
31 if old_text == new_text:
32 logging.info('No changes detected')
33 return True
34 html_diff = HtmlDiff(wrapcolumn=80).make_file(
35 old_text.splitlines(), new_text.splitlines(), fromdesc='Original',
36 todesc='Updated', context=True, numlines=5)
37 temp = NamedTemporaryFile(suffix='.html', delete=False)
38 try:
39 temp.write(html_diff)
40 temp.close() # Close the file so the browser process can access it.
41 webbrowser.open('file://' + temp.name)
42 print prompt
43 response = raw_input('(Y/n): ').strip().lower()
44 finally:
45 temp.close() # May be called on already closed file.
46 os.remove(temp.name)
47 return response == 'y' or response == ''