Added simple listing (no score, rank) for Student Proposals you are a mentor for.
[Melange.git] / scripts / release / io.py
blobdf798fcea32dd1755b9a619fc461ff80146fd872
1 #!/usr/bin/python2.5
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."""
21 __authors__ = [
22 # alphabetical order by last name, please
23 '"David Anderson" <dave@natulte.net>',
26 import error
27 import log
30 class Error(error.Error):
31 pass
34 class FileAccessError(Error):
35 """An error occured while accessing a file."""
36 pass
39 def getString(prompt):
40 """Prompt for and return a string."""
41 prompt += ' '
42 log.stdout.write(prompt)
43 log.stdout.flush()
45 response = sys.stdin.readline()
46 log.terminal_echo(prompt + response.strip())
47 if not response:
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.
59 Args:
60 prompt: The question to ask the user.
61 default: The answer to return if the user just hits enter.
63 Returns:
64 True if the user answered affirmatively, False otherwise.
65 """
66 if default:
67 question = prompt + ' [Yn]'
68 else:
69 question = prompt + ' [yN]'
70 while True:
71 answer = getString(question)
72 if not answer:
73 return default
74 elif answer in ('y', 'yes'):
75 return True
76 elif answer in ('n', 'no'):
77 return False
78 else:
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.
86 """
87 while True:
88 value_str = getString(prompt)
89 try:
90 return int(value_str)
91 except ValueError:
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.
100 Args:
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.
109 Returns:
110 The index in the choices list of the selection the user made.
112 done = set(done or [])
113 while True:
114 print intro
115 print
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)
120 print
121 choice = getNumber(prompt)
122 if 0 < choice <= len(choices):
123 return choice-1
124 log.error('%d is not a valid choice between %d and %d' %
125 (choice, 1, len(choices)))
126 print
129 def fileToLines(path):
130 """Read a file and return it as a list of lines."""
131 try:
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."""
140 try:
141 with file(path, 'w') as f:
142 f.write('\n'.join(lines))
143 except (IOError, OSError), e:
144 raise FileAccessError(str(e))