Extract a method, DumpfileDelegate._string_for_props().
[cvs2svn.git] / cvs2svn_lib / dvcs_common.py
blob0b819b5c72c3b975a7d904560bd2060c021e0eb9
1 # (Be in -*- python -*- mode.)
3 # ====================================================================
4 # Copyright (c) 2007-2009 CollabNet. All rights reserved.
6 # This software is licensed as described in the file COPYING, which
7 # you should have received as part of this distribution. The terms
8 # are also available at http://subversion.tigris.org/license-1.html.
9 # If newer versions of this license are posted there, you may use a
10 # newer version instead, at your option.
12 # This software consists of voluntary contributions made by many
13 # individuals. For exact contribution history, see the revision
14 # history and logs, available at http://cvs2svn.tigris.org/.
15 # ====================================================================
17 """Miscellaneous utility code common to DVCS backends (like
18 Git, Mercurial, or Bazaar).
19 """
21 import sys
23 from cvs2svn_lib import config
24 from cvs2svn_lib.common import FatalError
25 from cvs2svn_lib.common import InternalError
26 from cvs2svn_lib.run_options import RunOptions
27 from cvs2svn_lib.log import Log
28 from cvs2svn_lib.common import error_prefix
29 from cvs2svn_lib.context import Ctx
30 from cvs2svn_lib.artifact_manager import artifact_manager
31 from cvs2svn_lib.project import Project
32 from cvs2svn_lib.cvs_item import CVSRevisionAdd
33 from cvs2svn_lib.cvs_item import CVSRevisionChange
34 from cvs2svn_lib.cvs_item import CVSRevisionDelete
35 from cvs2svn_lib.cvs_item import CVSRevisionNoop
36 from cvs2svn_lib.svn_revision_range import RevisionScores
37 from cvs2svn_lib.openings_closings import SymbolingsReader
38 from cvs2svn_lib.repository_mirror import RepositoryMirror
39 from cvs2svn_lib.output_option import OutputOption
42 class DVCSRunOptions(RunOptions):
43 """Dumping ground for whatever is common to GitRunOptions and
44 HgRunOptions."""
45 def __init__(self, progname, cmd_args, pass_manager):
46 Ctx().cross_project_commits = False
47 Ctx().cross_branch_commits = False
48 RunOptions.__init__(self, progname, cmd_args, pass_manager)
50 def set_project(
51 self,
52 project_cvs_repos_path,
53 symbol_transforms=None,
54 symbol_strategy_rules=[],
56 """Set the project to be converted.
58 If a project had already been set, overwrite it.
60 Most arguments are passed straight through to the Project
61 constructor. SYMBOL_STRATEGY_RULES is an iterable of
62 SymbolStrategyRules that will be applied to symbols in this
63 project."""
65 symbol_strategy_rules = list(symbol_strategy_rules)
67 project = Project(
69 project_cvs_repos_path,
70 symbol_transforms=symbol_transforms,
73 self.projects = [project]
74 self.project_symbol_strategy_rules = [symbol_strategy_rules]
76 def process_options(self):
77 # Consistency check for options and arguments.
78 if len(self.args) == 0:
79 self.usage()
80 sys.exit(1)
82 if len(self.args) > 1:
83 Log().error(error_prefix + ": must pass only one CVS repository.\n")
84 self.usage()
85 sys.exit(1)
87 cvsroot = self.args[0]
89 self.process_extraction_options()
90 self.process_output_options()
91 self.process_symbol_strategy_options()
92 self.process_property_setter_options()
94 # Create the project:
95 self.set_project(
96 cvsroot,
97 symbol_transforms=self.options.symbol_transforms,
98 symbol_strategy_rules=self.options.symbol_strategy_rules,
102 class DVCSOutputOption(OutputOption):
103 # name of output format (for error messages); must be set by
104 # subclasses
105 name = None
107 def __init__(self):
108 self._mirror = RepositoryMirror()
109 self._symbolings_reader = None
111 def normalize_author_transforms(self, author_transforms):
112 """Convert AUTHOR_TRANSFORMS into author strings.
114 AUTHOR_TRANSFORMS is a dict { CVSAUTHOR : DVCSAUTHOR } where
115 CVSAUTHOR is the CVS author and DVCSAUTHOR is either:
117 * a tuple (NAME, EMAIL) where NAME and EMAIL are strings. Such
118 entries are converted into a UTF-8 string of the form 'name
119 <email>'.
121 * a string already in the form 'name <email>'.
123 Return a similar dict { CVSAUTHOR : DVCSAUTHOR } where all keys
124 and values are UTF-8-encoded strings.
126 Any of the input strings may be Unicode strings (in which case
127 they are encoded to UTF-8) or 8-bit strings (in which case they
128 are used as-is). Also turns None into the empty dict."""
130 result = {}
131 if author_transforms is not None:
132 for (cvsauthor, dvcsauthor) in author_transforms.iteritems():
133 cvsauthor = to_utf8(cvsauthor)
134 if isinstance(dvcsauthor, basestring):
135 dvcsauthor = to_utf8(dvcsauthor)
136 else:
137 (name, email,) = dvcsauthor
138 name = to_utf8(name)
139 email = to_utf8(email)
140 dvcsauthor = "%s <%s>" % (name, email,)
141 result[cvsauthor] = dvcsauthor
142 return result
144 def register_artifacts(self, which_pass):
145 # These artifacts are needed for SymbolingsReader:
146 artifact_manager.register_temp_file_needed(
147 config.SYMBOL_OPENINGS_CLOSINGS_SORTED, which_pass
149 artifact_manager.register_temp_file_needed(
150 config.SYMBOL_OFFSETS_DB, which_pass
152 self._mirror.register_artifacts(which_pass)
154 def check(self):
155 if Ctx().cross_project_commits:
156 raise FatalError(
157 '%s output is not supported with cross-project commits' % self.name
159 if Ctx().cross_branch_commits:
160 raise FatalError(
161 '%s output is not supported with cross-branch commits' % self.name
163 if Ctx().username is None:
164 raise FatalError(
165 '%s output requires a default commit username' % self.name
168 def setup(self, svn_rev_count):
169 self._symbolings_reader = SymbolingsReader()
170 self._mirror.open()
172 def cleanup(self):
173 self._mirror.close()
174 self._symbolings_reader.close()
175 del self._symbolings_reader
177 def _get_source_groups(self, svn_commit):
178 """Return groups of sources for SVN_COMMIT.
180 SVN_COMMIT is an instance of SVNSymbolCommit. Yield tuples
181 (source_lod, svn_revnum, cvs_symbols) where source_lod is the line
182 of development and svn_revnum is the revision that should serve as
183 a source, and cvs_symbols is a list of CVSSymbolItems that can be
184 copied from that source. The groups are returned in arbitrary
185 order."""
187 # Get a map {CVSSymbol : SVNRevisionRange}:
188 range_map = self._symbolings_reader.get_range_map(svn_commit)
190 # range_map, split up into one map per LOD; i.e., {LOD :
191 # {CVSSymbol : SVNRevisionRange}}:
192 lod_range_maps = {}
194 for (cvs_symbol, range) in range_map.iteritems():
195 lod_range_map = lod_range_maps.get(range.source_lod)
196 if lod_range_map is None:
197 lod_range_map = {}
198 lod_range_maps[range.source_lod] = lod_range_map
199 lod_range_map[cvs_symbol] = range
201 # Sort the sources so that the branch that serves most often as
202 # parent is processed first:
203 lod_ranges = lod_range_maps.items()
204 lod_ranges.sort(
205 lambda (lod1,lod_range_map1),(lod2,lod_range_map2):
206 -cmp(len(lod_range_map1), len(lod_range_map2)) or cmp(lod1, lod2)
209 for (lod, lod_range_map) in lod_ranges:
210 while lod_range_map:
211 revision_scores = RevisionScores(lod_range_map.values())
212 (source_lod, revnum, score) = revision_scores.get_best_revnum()
213 assert source_lod == lod
214 cvs_symbols = []
215 for (cvs_symbol, range) in lod_range_map.items():
216 if revnum in range:
217 cvs_symbols.append(cvs_symbol)
218 del lod_range_map[cvs_symbol]
219 yield (lod, revnum, cvs_symbols)
221 def _is_simple_copy(self, svn_commit, source_groups):
222 """Return True iff SVN_COMMIT can be created as a simple copy.
224 SVN_COMMIT is an SVNTagCommit. Return True iff it can be created
225 as a simple copy from an existing revision (i.e., if the fixup
226 branch can be avoided for this tag creation)."""
228 # The first requirement is that there be exactly one source:
229 if len(source_groups) != 1:
230 return False
232 (source_lod, svn_revnum, cvs_symbols) = source_groups[0]
234 # The second requirement is that the destination LOD not already
235 # exist:
236 try:
237 self._mirror.get_current_lod_directory(svn_commit.symbol)
238 except KeyError:
239 # The LOD doesn't already exist. This is good.
240 pass
241 else:
242 # The LOD already exists. It cannot be created by a copy.
243 return False
245 # The third requirement is that the source LOD contains exactly
246 # the same files as we need to add to the symbol:
247 try:
248 source_node = self._mirror.get_old_lod_directory(source_lod, svn_revnum)
249 except KeyError:
250 raise InternalError('Source %r does not exist' % (source_lod,))
251 return (
252 set([cvs_symbol.cvs_file for cvs_symbol in cvs_symbols])
253 == set(self._get_all_files(source_node))
256 def _get_all_files(self, node):
257 """Generate all of the CVSFiles under NODE."""
259 for cvs_path in node:
260 subnode = node[cvs_path]
261 if subnode is None:
262 yield cvs_path
263 else:
264 for sub_cvs_path in self._get_all_files(subnode):
265 yield sub_cvs_path
268 class MirrorUpdater(object):
269 def register_artifacts(self, which_pass):
270 pass
272 def start(self, mirror):
273 self._mirror = mirror
275 def _mkdir_p(self, cvs_directory, lod):
276 """Make sure that CVS_DIRECTORY exists in LOD.
278 If not, create it. Return the node for CVS_DIRECTORY."""
280 try:
281 node = self._mirror.get_current_lod_directory(lod)
282 except KeyError:
283 node = self._mirror.add_lod(lod)
285 for sub_path in cvs_directory.get_ancestry()[1:]:
286 try:
287 node = node[sub_path]
288 except KeyError:
289 node = node.mkdir(sub_path)
290 if node is None:
291 raise ExpectedDirectoryError(
292 'File found at \'%s\' where directory was expected.' % (sub_path,)
295 return node
297 def add_file(self, cvs_rev, post_commit):
298 cvs_file = cvs_rev.cvs_file
299 if post_commit:
300 lod = cvs_file.project.get_trunk()
301 else:
302 lod = cvs_rev.lod
303 parent_node = self._mkdir_p(cvs_file.parent_directory, lod)
304 parent_node.add_file(cvs_file)
306 def modify_file(self, cvs_rev, post_commit):
307 cvs_file = cvs_rev.cvs_file
308 if post_commit:
309 lod = cvs_file.project.get_trunk()
310 else:
311 lod = cvs_rev.lod
312 if self._mirror.get_current_path(cvs_file, lod) is not None:
313 raise ExpectedFileError(
314 'Directory found at \'%s\' where file was expected.' % (cvs_file,)
317 def delete_file(self, cvs_rev, post_commit):
318 cvs_file = cvs_rev.cvs_file
319 if post_commit:
320 lod = cvs_file.project.get_trunk()
321 else:
322 lod = cvs_rev.lod
323 parent_node = self._mirror.get_current_path(
324 cvs_file.parent_directory, lod
326 if parent_node[cvs_file] is not None:
327 raise ExpectedFileError(
328 'Directory found at \'%s\' where file was expected.' % (cvs_file,)
330 del parent_node[cvs_file]
332 def process_revision(self, cvs_rev, post_commit):
333 if isinstance(cvs_rev, CVSRevisionAdd):
334 self.add_file(cvs_rev, post_commit)
335 elif isinstance(cvs_rev, CVSRevisionChange):
336 self.modify_file(cvs_rev, post_commit)
337 elif isinstance(cvs_rev, CVSRevisionDelete):
338 self.delete_file(cvs_rev, post_commit)
339 elif isinstance(cvs_rev, CVSRevisionNoop):
340 pass
341 else:
342 raise InternalError('Unexpected CVSRevision type: %s' % (cvs_rev,))
344 def branch_file(self, cvs_symbol):
345 cvs_file = cvs_symbol.cvs_file
346 parent_node = self._mkdir_p(cvs_file.parent_directory, cvs_symbol.symbol)
347 parent_node.add_file(cvs_file)
349 def finish(self):
350 del self._mirror
353 def to_utf8(s):
354 if isinstance(s, unicode):
355 return s.encode('utf8')
356 else:
357 return s