3 # Copyright 2009 the Melange authors.
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from __future__
import with_statement
19 """User prompting and file access utilities."""
22 # alphabetical order by last name, please
23 '"David Anderson" <dave@natulte.net>',
30 class Error(error
.Error
):
34 class FileAccessError(Error
):
35 """An error occured while accessing a file."""
39 def getString(prompt
):
40 """Prompt for and return a string."""
42 log
.stdout
.write(prompt
)
45 response
= sys
.stdin
.readline()
46 log
.terminal_echo(prompt
+ response
.strip())
48 raise error
.AbortedByUser('Aborted by ctrl+D')
50 return response
.strip()
53 def confirm(prompt
, default
=False):
54 """Ask a yes/no question and return the answer.
56 Will reprompt the user until one of "yes", "no", "y" or "n" is
57 entered. The input is case insensitive.
60 prompt: The question to ask the user.
61 default: The answer to return if the user just hits enter.
64 True if the user answered affirmatively, False otherwise.
67 question
= prompt
+ ' [Yn]'
69 question
= prompt
+ ' [yN]'
71 answer
= getString(question
)
74 elif answer
in ('y', 'yes'):
76 elif answer
in ('n', 'no'):
79 log
.error('Please answer yes or no.')
82 def getNumber(prompt
):
83 """Prompt for and return a number.
85 Will reprompt the user until a number is entered.
88 value_str
= getString(prompt
)
92 log
.error('Please enter a number. You entered "%s".' % value_str
)
95 def getChoice(intro
, prompt
, choices
, done
=None, suggest
=None):
96 """Prompt for and return a choice from a menu.
98 Will reprompt the user until a valid menu entry is chosen.
101 intro: Text to print verbatim before the choice menu.
102 prompt: The prompt to print right before accepting input.
103 choices: The list of string choices to display.
104 done: If not None, the list of indices of previously
105 selected/completed choices.
106 suggest: If not None, the index of the choice to highlight as
107 the suggested choice.
110 The index in the choices list of the selection the user made.
112 done
= set(done
or [])
116 for i
, entry
in enumerate(choices
):
117 done_text
= ' (done)' if i
in done
else ''
118 indent
= '--> ' if i
== suggest
else ' '
119 print '%s%2d. %s%s' % (indent
, i
+1, entry
, done_text
)
121 choice
= getNumber(prompt
)
122 if 0 < choice
<= len(choices
):
124 log
.error('%d is not a valid choice between %d and %d' %
125 (choice
, 1, len(choices
)))
129 def fileToLines(path
):
130 """Read a file and return it as a list of lines."""
132 with
file(path
) as f
:
133 return f
.read().split('\n')
134 except (IOError, OSError), e
:
135 raise FileAccessError(str(e
))
138 def linesToFile(path
, lines
):
139 """Write a list of lines to a file."""
141 with
file(path
, 'w') as f
:
142 f
.write('\n'.join(lines
))
143 except (IOError, OSError), e
:
144 raise FileAccessError(str(e
))