1 """Common utility functions
4 import errno
, os
, os
.path
, re
, sys
5 from stgit
.config
import config
8 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License version 2 as
12 published by the Free Software Foundation.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 def mkdir_file(filename
, mode
):
25 """Opens filename with the given mode, creating the directory it's
26 in if it doesn't already exist."""
27 create_dirs(os
.path
.dirname(filename
))
28 return file(filename
, mode
)
30 def read_string(filename
, multiline
= False):
31 """Reads the first line from a file
33 f
= file(filename
, 'r')
37 result
= f
.readline().strip()
41 def write_string(filename
, line
, multiline
= False):
42 """Writes 'line' to file and truncates it
44 f
= mkdir_file(filename
, 'w+')
51 def append_strings(filename
, lines
):
52 """Appends 'lines' sequence to file
54 f
= mkdir_file(filename
, 'a+')
59 def append_string(filename
, line
):
60 """Appends 'line' to file
62 f
= mkdir_file(filename
, 'a+')
66 def insert_string(filename
, line
):
67 """Inserts 'line' at the beginning of the file
69 f
= mkdir_file(filename
, 'r+')
71 f
.seek(0); f
.truncate()
76 def create_empty_file(name
):
77 """Creates an empty file
79 mkdir_file(name
, 'w+').close()
81 def list_files_and_dirs(path
):
82 """Return the sets of filenames and directory names in a
85 for fd
in os
.listdir(path
):
86 full_fd
= os
.path
.join(path
, fd
)
87 if os
.path
.isfile(full_fd
):
89 elif os
.path
.isdir(full_fd
):
93 def walk_tree(basedir
):
94 """Starting in the given directory, iterate through all its
95 subdirectories. For each subdirectory, yield the name of the
96 subdirectory (relative to the base directory), the list of
97 filenames in the subdirectory, and the list of directory names in
101 subdir
= subdirs
.pop()
102 files
, dirs
= list_files_and_dirs(os
.path
.join(basedir
, subdir
))
104 subdirs
.append(os
.path
.join(subdir
, d
))
105 yield subdir
, files
, dirs
107 def strip_prefix(prefix
, string
):
108 """Return string, without the prefix. Blow up if string doesn't
109 start with prefix."""
110 assert string
.startswith(prefix
)
111 return string
[len(prefix
):]
113 def strip_suffix(suffix
, string
):
114 """Return string, without the suffix. Blow up if string doesn't
116 assert string
.endswith(suffix
)
117 return string
[:-len(suffix
)]
119 def remove_file_and_dirs(basedir
, file):
120 """Remove join(basedir, file), and then remove the directory it
121 was in if empty, and try the same with its parent, until we find a
122 nonempty directory or reach basedir."""
123 os
.remove(os
.path
.join(basedir
, file))
125 os
.removedirs(os
.path
.join(basedir
, os
.path
.dirname(file)))
127 # file's parent dir may not be empty after removal
130 def create_dirs(directory
):
131 """Create the given directory, if the path doesn't already exist."""
132 if directory
and not os
.path
.isdir(directory
):
133 create_dirs(os
.path
.dirname(directory
))
137 if e
.errno
!= errno
.EEXIST
:
140 def rename(basedir
, file1
, file2
):
141 """Rename join(basedir, file1) to join(basedir, file2), not
142 leaving any empty directories behind and creating any directories
144 full_file2
= os
.path
.join(basedir
, file2
)
145 create_dirs(os
.path
.dirname(full_file2
))
146 os
.rename(os
.path
.join(basedir
, file1
), full_file2
)
148 os
.removedirs(os
.path
.join(basedir
, os
.path
.dirname(file1
)))
150 # file1's parent dir may not be empty after move
153 class EditorException(Exception):
156 def call_editor(filename
):
157 """Run the editor on the specified filename."""
160 editor
= config
.get('stgit.editor')
163 elif 'EDITOR' in os
.environ
:
164 editor
= os
.environ
['EDITOR']
167 editor
+= ' %s' % filename
169 print 'Invoking the editor: "%s"...' % editor
,
171 err
= os
.system(editor
)
173 raise EditorException
, 'editor failed, exit code: %d' % err
176 def patch_name_from_msg(msg
):
177 """Return a string to be used as a patch name. This is generated
178 from the top line of the string passed as argument, and is at most
179 30 characters long."""
183 subject_line
= msg
.split('\n', 1)[0].lstrip().lower()
184 return re
.sub('[\W]+', '-', subject_line
).strip('-')[:30]
186 def make_patch_name(msg
, unacceptable
, default_name
= 'patch',
188 """Return a patch name generated from the given commit message,
189 guaranteed to make unacceptable(name) be false. If the commit
190 message is empty, base the name on default_name instead."""
191 patchname
= patch_name_from_msg(msg
)
193 patchname
= default_name
194 if alternative
and unacceptable(patchname
):
196 while unacceptable('%s-%d' % (patchname
, suffix
)):
198 patchname
= '%s-%d' % (patchname
, suffix
)