Debian Codegraph @

src/CedarBackup3/extend/subversion.py

raw
1 # vim: set ft=python ts=4 sw=4 expandtab:
2 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3 #
4 # C E D A R
5 # S O L U T I O N S "Software done right."
6 # S O F T W A R E
7 #
8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
9 #
10 # Copyright (c) 2005,2007,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Official Cedar Backup Extensions
29 # Purpose : Provides an extension to back up Subversion repositories.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to back up Subversion repositories.
39
40 This is a Cedar Backup extension used to back up Subversion repositories via
41 the Cedar Backup command line. Each Subversion repository can be backed using
42 the same collect modes allowed for filesystems in the standard Cedar Backup
43 collect action: weekly, daily, incremental.
44
45 This extension requires a new configuration section <subversion> and is
46 intended to be run either immediately before or immediately after the standard
47 collect action. Aside from its own configuration, it requires the options and
48 collect configuration sections in the standard Cedar Backup configuration file.
49
50 There are two different kinds of Subversion repositories at this writing: BDB
51 (Berkeley Database) and FSFS (a "filesystem within a filesystem"). Although
52 the repository type can be specified in configuration, that information is just
53 kept around for reference. It doesn't affect the backup. Both kinds of
54 repositories are backed up in the same way, using ``svnadmin dump`` in an
55 incremental mode.
56
57 It turns out that FSFS repositories can also be backed up just like any
58 other filesystem directory. If you would rather do that, then use the normal
59 collect action. This is probably simpler, although it carries its own
60 advantages and disadvantages (plus you will have to be careful to exclude
61 the working directories Subversion uses when building an update to commit).
62 Check the Subversion documentation for more information.
63
64 :author: Kenneth J. Pronovici <[email protected]>
65 """
66
67 ########################################################################
68 # Imported modules
69 ########################################################################
70
71 import logging
72 import os
73 import pickle # ruff: ignore[suspicious-pickle-import] # we operate on trusted data, so pickle is ok
74 import posixpath
75 from bz2 import BZ2File
76 from functools import total_ordering
77 from gzip import GzipFile
78
79 from CedarBackup3.config import VALID_COLLECT_MODES, VALID_COMPRESS_MODES
80 from CedarBackup3.filesystem import FilesystemList
81 from CedarBackup3.util import (
82 ObjectTypeList,
83 RegexList,
84 UnorderedList,
85 buildNormalizedPath,
86 changeOwnership,
87 encodePath,
88 executeCommand,
89 isStartOfWeek,
90 pathJoin,
91 resolveCommand,
92 )
93 from CedarBackup3.xmlutil import (
94 addContainerNode,
95 addStringNode,
96 createInputDom,
97 isElement,
98 readChildren,
99 readFirstChild,
100 readString,
101 readStringList,
102 )
103
104 ########################################################################
105 # Module-wide constants and variables
106 ########################################################################
107
108 logger = logging.getLogger("CedarBackup3.log.extend.subversion")
109
110 SVNLOOK_COMMAND = ["svnlook"]
111 SVNADMIN_COMMAND = ["svnadmin"]
112
113 REVISION_PATH_EXTENSION = "svnlast"
114
115
116 ########################################################################
117 # RepositoryDir class definition
118 ########################################################################
119
120
121 @total_ordering
122 class RepositoryDir:
123 """
124 Class representing Subversion repository directory.
125
126 A repository directory is a directory that contains one or more Subversion
127 repositories.
128
129 The following restrictions exist on data in this class:
130
131 - The directory path must be absolute.
132 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
133 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
134
135 The repository type value is kept around just for reference. It doesn't
136 affect the behavior of the backup.
137
138 Relative exclusions are allowed here. However, there is no configured
139 ignore file, because repository dir backups are not recursive.
140
141 """
142
143 def __init__(
144 self,
145 repositoryType=None,
146 directoryPath=None,
147 collectMode=None,
148 compressMode=None,
149 relativeExcludePaths=None,
150 excludePatterns=None,
151 ):
152 """
153 Constructor for the ``RepositoryDir`` class.
154
155 Args:
156 repositoryType: Type of repository, for reference
157 directoryPath: Absolute path of the Subversion parent directory
158 collectMode: Overridden collect mode for this directory
159 compressMode: Overridden compression mode for this directory
160 relativeExcludePaths: List of relative paths to exclude
161 excludePatterns: List of regular expression patterns to exclude
162 """
163 self._repositoryType = None
164 self._directoryPath = None
165 self._collectMode = None
166 self._compressMode = None
167 self._relativeExcludePaths = None
168 self._excludePatterns = None
169 self.repositoryType = repositoryType
170 self.directoryPath = directoryPath
171 self.collectMode = collectMode
172 self.compressMode = compressMode
173 self.relativeExcludePaths = relativeExcludePaths
174 self.excludePatterns = excludePatterns
175
176 def __repr__(self):
177 """
178 Official string representation for class instance.
179 """
180 return "RepositoryDir(%s, %s, %s, %s, %s, %s)" % (
181 self.repositoryType,
182 self.directoryPath,
183 self.collectMode,
184 self.compressMode,
185 self.relativeExcludePaths,
186 self.excludePatterns,
187 )
188
189 def __str__(self):
190 """
191 Informal string representation for class instance.
192 """
193 return self.__repr__()
194
195 def __eq__(self, other):
196 """Equals operator, iplemented in terms of original Python 2 compare operator."""
197 return self.__cmp__(other) == 0
198
199 def __lt__(self, other):
200 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
201 return self.__cmp__(other) < 0
202
203 def __gt__(self, other):
204 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
205 return self.__cmp__(other) > 0
206
207 def __cmp__(self, other):
208 """
209 Original Python 2 comparison operator.
210 Args:
211 other: Other object to compare to
212 Returns:
213 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
214 """
215 if other is None:
216 return 1
217 if self.repositoryType != other.repositoryType:
218 if str(self.repositoryType or "") < str(other.repositoryType or ""):
219 return -1
220 else:
221 return 1
222 if self.directoryPath != other.directoryPath:
223 if str(self.directoryPath or "") < str(other.directoryPath or ""):
224 return -1
225 else:
226 return 1
227 if self.collectMode != other.collectMode:
228 if str(self.collectMode or "") < str(other.collectMode or ""):
229 return -1
230 else:
231 return 1
232 if self.compressMode != other.compressMode:
233 if str(self.compressMode or "") < str(other.compressMode or ""):
234 return -1
235 else:
236 return 1
237 if self.relativeExcludePaths != other.relativeExcludePaths:
238 if self.relativeExcludePaths < other.relativeExcludePaths:
239 return -1
240 else:
241 return 1
242 if self.excludePatterns != other.excludePatterns:
243 if self.excludePatterns < other.excludePatterns:
244 return -1
245 else:
246 return 1
247 return 0
248
249 def _setRepositoryType(self, value):
250 """
251 Property target used to set the repository type.
252 There is no validation; this value is kept around just for reference.
253 """
254 self._repositoryType = value
255
256 def _getRepositoryType(self):
257 """
258 Property target used to get the repository type.
259 """
260 return self._repositoryType
261
262 def _setDirectoryPath(self, value):
263 """
264 Property target used to set the directory path.
265 The value must be an absolute path if it is not ``None``.
266 It does not have to exist on disk at the time of assignment.
267 Raises:
268 ValueError: If the value is not an absolute path
269 ValueError: If the value cannot be encoded properly
270 """
271 if value is not None:
272 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
273 raise ValueError("Repository path must be an absolute path.")
274 self._directoryPath = encodePath(value)
275
276 def _getDirectoryPath(self):
277 """
278 Property target used to get the repository path.
279 """
280 return self._directoryPath
281
282 def _setCollectMode(self, value):
283 """
284 Property target used to set the collect mode.
285 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
286 Raises:
287 ValueError: If the value is not valid
288 """
289 if value is not None:
290 if value not in VALID_COLLECT_MODES:
291 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
292 self._collectMode = value
293
294 def _getCollectMode(self):
295 """
296 Property target used to get the collect mode.
297 """
298 return self._collectMode
299
300 def _setCompressMode(self, value):
301 """
302 Property target used to set the compress mode.
303 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
304 Raises:
305 ValueError: If the value is not valid
306 """
307 if value is not None:
308 if value not in VALID_COMPRESS_MODES:
309 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
310 self._compressMode = value
311
312 def _getCompressMode(self):
313 """
314 Property target used to get the compress mode.
315 """
316 return self._compressMode
317
318 def _setRelativeExcludePaths(self, value):
319 """
320 Property target used to set the relative exclude paths list.
321 Elements do not have to exist on disk at the time of assignment.
322 """
323 if value is None:
324 self._relativeExcludePaths = None
325 else:
326 try:
327 saved = self._relativeExcludePaths
328 self._relativeExcludePaths = UnorderedList()
329 self._relativeExcludePaths.extend(value)
330 except Exception as e:
331 self._relativeExcludePaths = saved
332 raise e
333
334 def _getRelativeExcludePaths(self):
335 """
336 Property target used to get the relative exclude paths list.
337 """
338 return self._relativeExcludePaths
339
340 def _setExcludePatterns(self, value):
341 """
342 Property target used to set the exclude patterns list.
343 """
344 if value is None:
345 self._excludePatterns = None
346 else:
347 try:
348 saved = self._excludePatterns
349 self._excludePatterns = RegexList()
350 self._excludePatterns.extend(value)
351 except Exception as e:
352 self._excludePatterns = saved
353 raise e
354
355 def _getExcludePatterns(self):
356 """
357 Property target used to get the exclude patterns list.
358 """
359 return self._excludePatterns
360
361 repositoryType = property(_getRepositoryType, _setRepositoryType, None, doc="Type of this repository, for reference.")
362 directoryPath = property(_getDirectoryPath, _setDirectoryPath, None, doc="Absolute path of the Subversion parent directory.")
363 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this repository.")
364 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Overridden compress mode for this repository.")
365 relativeExcludePaths = property(_getRelativeExcludePaths, _setRelativeExcludePaths, None, "List of relative paths to exclude.")
366 excludePatterns = property(_getExcludePatterns, _setExcludePatterns, None, "List of regular expression patterns to exclude.")
367
368
369 ########################################################################
370 # Repository class definition
371 ########################################################################
372
373
374 @total_ordering
375 class Repository:
376 """
377 Class representing generic Subversion repository configuration..
378
379 The following restrictions exist on data in this class:
380
381 - The respository path must be absolute.
382 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
383 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
384
385 The repository type value is kept around just for reference. It doesn't
386 affect the behavior of the backup.
387
388 """
389
390 def __init__(self, repositoryType=None, repositoryPath=None, collectMode=None, compressMode=None):
391 """
392 Constructor for the ``Repository`` class.
393
394 Args:
395 repositoryType: Type of repository, for reference
396 repositoryPath: Absolute path to a Subversion repository on disk
397 collectMode: Overridden collect mode for this directory
398 compressMode: Overridden compression mode for this directory
399 """
400 self._repositoryType = None
401 self._repositoryPath = None
402 self._collectMode = None
403 self._compressMode = None
404 self.repositoryType = repositoryType
405 self.repositoryPath = repositoryPath
406 self.collectMode = collectMode
407 self.compressMode = compressMode
408
409 def __repr__(self):
410 """
411 Official string representation for class instance.
412 """
413 return "Repository(%s, %s, %s, %s)" % (self.repositoryType, self.repositoryPath, self.collectMode, self.compressMode)
414
415 def __str__(self):
416 """
417 Informal string representation for class instance.
418 """
419 return self.__repr__()
420
421 def __eq__(self, other):
422 """Equals operator, iplemented in terms of original Python 2 compare operator."""
423 return self.__cmp__(other) == 0
424
425 def __lt__(self, other):
426 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
427 return self.__cmp__(other) < 0
428
429 def __gt__(self, other):
430 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
431 return self.__cmp__(other) > 0
432
433 def __cmp__(self, other):
434 """
435 Original Python 2 comparison operator.
436 Args:
437 other: Other object to compare to
438 Returns:
439 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
440 """
441 if other is None:
442 return 1
443 if self.repositoryType != other.repositoryType:
444 if str(self.repositoryType or "") < str(other.repositoryType or ""):
445 return -1
446 else:
447 return 1
448 if self.repositoryPath != other.repositoryPath:
449 if str(self.repositoryPath or "") < str(other.repositoryPath or ""):
450 return -1
451 else:
452 return 1
453 if self.collectMode != other.collectMode:
454 if str(self.collectMode or "") < str(other.collectMode or ""):
455 return -1
456 else:
457 return 1
458 if self.compressMode != other.compressMode:
459 if str(self.compressMode or "") < str(other.compressMode or ""):
460 return -1
461 else:
462 return 1
463 return 0
464
465 def _setRepositoryType(self, value):
466 """
467 Property target used to set the repository type.
468 There is no validation; this value is kept around just for reference.
469 """
470 self._repositoryType = value
471
472 def _getRepositoryType(self):
473 """
474 Property target used to get the repository type.
475 """
476 return self._repositoryType
477
478 def _setRepositoryPath(self, value):
479 """
480 Property target used to set the repository path.
481 The value must be an absolute path if it is not ``None``.
482 It does not have to exist on disk at the time of assignment.
483 Raises:
484 ValueError: If the value is not an absolute path
485 ValueError: If the value cannot be encoded properly
486 """
487 if value is not None:
488 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
489 raise ValueError("Repository path must be an absolute path.")
490 self._repositoryPath = encodePath(value)
491
492 def _getRepositoryPath(self):
493 """
494 Property target used to get the repository path.
495 """
496 return self._repositoryPath
497
498 def _setCollectMode(self, value):
499 """
500 Property target used to set the collect mode.
501 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
502 Raises:
503 ValueError: If the value is not valid
504 """
505 if value is not None:
506 if value not in VALID_COLLECT_MODES:
507 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
508 self._collectMode = value
509
510 def _getCollectMode(self):
511 """
512 Property target used to get the collect mode.
513 """
514 return self._collectMode
515
516 def _setCompressMode(self, value):
517 """
518 Property target used to set the compress mode.
519 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
520 Raises:
521 ValueError: If the value is not valid
522 """
523 if value is not None:
524 if value not in VALID_COMPRESS_MODES:
525 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
526 self._compressMode = value
527
528 def _getCompressMode(self):
529 """
530 Property target used to get the compress mode.
531 """
532 return self._compressMode
533
534 repositoryType = property(_getRepositoryType, _setRepositoryType, None, doc="Type of this repository, for reference.")
535 repositoryPath = property(_getRepositoryPath, _setRepositoryPath, None, doc="Path to the repository to collect.")
536 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this repository.")
537 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Overridden compress mode for this repository.")
538
539
540 ########################################################################
541 # SubversionConfig class definition
542 ########################################################################
543
544
545 @total_ordering
546 class SubversionConfig:
547 """
548 Class representing Subversion configuration.
549
550 Subversion configuration is used for backing up Subversion repositories.
551
552 The following restrictions exist on data in this class:
553
554 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
555 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
556 - The repositories list must be a list of ``Repository`` objects.
557 - The repositoryDirs list must be a list of ``RepositoryDir`` objects.
558
559 For the two lists, validation is accomplished through the
560 :any:`util.ObjectTypeList` list implementation that overrides common list
561 methods and transparently ensures that each element has the correct type.
562
563 *Note:* Lists within this class are "unordered" for equality comparisons.
564
565 """
566
567 def __init__(self, collectMode=None, compressMode=None, repositories=None, repositoryDirs=None):
568 """
569 Constructor for the ``SubversionConfig`` class.
570
571 Args:
572 collectMode: Default collect mode
573 compressMode: Default compress mode
574 repositories: List of Subversion repositories to back up
575 repositoryDirs: List of Subversion parent directories to back up
576
577 Raises:
578 ValueError: If one of the values is invalid
579 """
580 self._collectMode = None
581 self._compressMode = None
582 self._repositories = None
583 self._repositoryDirs = None
584 self.collectMode = collectMode
585 self.compressMode = compressMode
586 self.repositories = repositories
587 self.repositoryDirs = repositoryDirs
588
589 def __repr__(self):
590 """
591 Official string representation for class instance.
592 """
593 return "SubversionConfig(%s, %s, %s, %s)" % (self.collectMode, self.compressMode, self.repositories, self.repositoryDirs)
594
595 def __str__(self):
596 """
597 Informal string representation for class instance.
598 """
599 return self.__repr__()
600
601 def __eq__(self, other):
602 """Equals operator, iplemented in terms of original Python 2 compare operator."""
603 return self.__cmp__(other) == 0
604
605 def __lt__(self, other):
606 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
607 return self.__cmp__(other) < 0
608
609 def __gt__(self, other):
610 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
611 return self.__cmp__(other) > 0
612
613 def __cmp__(self, other):
614 """
615 Original Python 2 comparison operator.
616 Lists within this class are "unordered" for equality comparisons.
617 Args:
618 other: Other object to compare to
619 Returns:
620 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
621 """
622 if other is None:
623 return 1
624 if self.collectMode != other.collectMode:
625 if str(self.collectMode or "") < str(other.collectMode or ""):
626 return -1
627 else:
628 return 1
629 if self.compressMode != other.compressMode:
630 if str(self.compressMode or "") < str(other.compressMode or ""):
631 return -1
632 else:
633 return 1
634 if self.repositories != other.repositories:
635 if self.repositories < other.repositories:
636 return -1
637 else:
638 return 1
639 if self.repositoryDirs != other.repositoryDirs:
640 if self.repositoryDirs < other.repositoryDirs:
641 return -1
642 else:
643 return 1
644 return 0
645
646 def _setCollectMode(self, value):
647 """
648 Property target used to set the collect mode.
649 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
650 Raises:
651 ValueError: If the value is not valid
652 """
653 if value is not None:
654 if value not in VALID_COLLECT_MODES:
655 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
656 self._collectMode = value
657
658 def _getCollectMode(self):
659 """
660 Property target used to get the collect mode.
661 """
662 return self._collectMode
663
664 def _setCompressMode(self, value):
665 """
666 Property target used to set the compress mode.
667 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
668 Raises:
669 ValueError: If the value is not valid
670 """
671 if value is not None:
672 if value not in VALID_COMPRESS_MODES:
673 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
674 self._compressMode = value
675
676 def _getCompressMode(self):
677 """
678 Property target used to get the compress mode.
679 """
680 return self._compressMode
681
682 def _setRepositories(self, value):
683 """
684 Property target used to set the repositories list.
685 Either the value must be ``None`` or each element must be a ``Repository``.
686 Raises:
687 ValueError: If the value is not a ``Repository``
688 """
689 if value is None:
690 self._repositories = None
691 else:
692 try:
693 saved = self._repositories
694 self._repositories = ObjectTypeList(Repository, "Repository")
695 self._repositories.extend(value)
696 except Exception as e:
697 self._repositories = saved
698 raise e
699
700 def _getRepositories(self):
701 """
702 Property target used to get the repositories list.
703 """
704 return self._repositories
705
706 def _setRepositoryDirs(self, value):
707 """
708 Property target used to set the repositoryDirs list.
709 Either the value must be ``None`` or each element must be a ``Repository``.
710 Raises:
711 ValueError: If the value is not a ``Repository``
712 """
713 if value is None:
714 self._repositoryDirs = None
715 else:
716 try:
717 saved = self._repositoryDirs
718 self._repositoryDirs = ObjectTypeList(RepositoryDir, "RepositoryDir")
719 self._repositoryDirs.extend(value)
720 except Exception as e:
721 self._repositoryDirs = saved
722 raise e
723
724 def _getRepositoryDirs(self):
725 """
726 Property target used to get the repositoryDirs list.
727 """
728 return self._repositoryDirs
729
730 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Default collect mode.")
731 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Default compress mode.")
732 repositories = property(_getRepositories, _setRepositories, None, doc="List of Subversion repositories to back up.")
733 repositoryDirs = property(_getRepositoryDirs, _setRepositoryDirs, None, doc="List of Subversion parent directories to back up.")
734
735
736 ########################################################################
737 # LocalConfig class definition
738 ########################################################################
739
740
741 @total_ordering
742 class LocalConfig:
743 """
744 Class representing this extension's configuration document.
745
746 This is not a general-purpose configuration object like the main Cedar
747 Backup configuration object. Instead, it just knows how to parse and emit
748 Subversion-specific configuration values. Third parties who need to read
749 and write configuration related to this extension should access it through
750 the constructor, ``validate`` and ``addConfig`` methods.
751
752 *Note:* Lists within this class are "unordered" for equality comparisons.
753
754 """
755
756 def __init__(self, xmlData=None, xmlPath=None, validate=True):
757 """
758 Initializes a configuration object.
759
760 If you initialize the object without passing either ``xmlData`` or
761 ``xmlPath`` then configuration will be empty and will be invalid until it
762 is filled in properly.
763
764 No reference to the original XML data or original path is saved off by
765 this class. Once the data has been parsed (successfully or not) this
766 original information is discarded.
767
768 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
769 method will be called (with its default arguments) against configuration
770 after successfully parsing any passed-in XML. Keep in mind that even if
771 ``validate`` is ``False``, it might not be possible to parse the passed-in
772 XML document if lower-level validations fail.
773
774 *Note:* It is strongly suggested that the ``validate`` option always be set
775 to ``True`` (the default) unless there is a specific need to read in
776 invalid configuration from disk.
777
778 Args:
779 xmlData (String data): XML data representing configuration
780 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
781 validate (Boolean true/false): Validate the document after parsing it
782 Raises:
783 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
784 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
785 ValueError: If the parsed configuration document is not valid
786 """
787 self._subversion = None
788 self.subversion = None
789 if xmlData is not None and xmlPath is not None:
790 raise ValueError("Use either xmlData or xmlPath, but not both.")
791 if xmlData is not None:
792 self._parseXmlData(xmlData)
793 if validate:
794 self.validate()
795 elif xmlPath is not None:
796 with open(xmlPath) as f:
797 xmlData = f.read()
798 self._parseXmlData(xmlData)
799 if validate:
800 self.validate()
801
802 def __repr__(self):
803 """
804 Official string representation for class instance.
805 """
806 return "LocalConfig(%s)" % (self.subversion)
807
808 def __str__(self):
809 """
810 Informal string representation for class instance.
811 """
812 return self.__repr__()
813
814 def __eq__(self, other):
815 """Equals operator, iplemented in terms of original Python 2 compare operator."""
816 return self.__cmp__(other) == 0
817
818 def __lt__(self, other):
819 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
820 return self.__cmp__(other) < 0
821
822 def __gt__(self, other):
823 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
824 return self.__cmp__(other) > 0
825
826 def __cmp__(self, other):
827 """
828 Original Python 2 comparison operator.
829 Lists within this class are "unordered" for equality comparisons.
830 Args:
831 other: Other object to compare to
832 Returns:
833 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
834 """
835 if other is None:
836 return 1
837 if self.subversion != other.subversion:
838 if self.subversion < other.subversion:
839 return -1
840 else:
841 return 1
842 return 0
843
844 def _setSubversion(self, value):
845 """
846 Property target used to set the subversion configuration value.
847 If not ``None``, the value must be a ``SubversionConfig`` object.
848 Raises:
849 ValueError: If the value is not a ``SubversionConfig``
850 """
851 if value is None:
852 self._subversion = None
853 else:
854 if not isinstance(value, SubversionConfig):
855 raise ValueError("Value must be a ``SubversionConfig`` object.")
856 self._subversion = value
857
858 def _getSubversion(self):
859 """
860 Property target used to get the subversion configuration value.
861 """
862 return self._subversion
863
864 subversion = property(
865 _getSubversion, _setSubversion, None, "Subversion configuration in terms of a ``SubversionConfig`` object."
866 )
867
868 def validate(self):
869 """
870 Validates configuration represented by the object.
871
872 Subversion configuration must be filled in. Within that, the collect
873 mode and compress mode are both optional, but the list of repositories
874 must contain at least one entry.
875
876 Each repository must contain a repository path, and then must be either
877 able to take collect mode and compress mode configuration from the parent
878 ``SubversionConfig`` object, or must set each value on its own.
879
880 Raises:
881 ValueError: If one of the validations fails
882 """
883 if self.subversion is None:
884 raise ValueError("Subversion section is required.")
885 if (self.subversion.repositories is None or len(self.subversion.repositories) < 1) and (
886 self.subversion.repositoryDirs is None or len(self.subversion.repositoryDirs) < 1
887 ):
888 raise ValueError("At least one Subversion repository must be configured.")
889 if self.subversion.repositories is not None:
890 for repository in self.subversion.repositories:
891 if repository.repositoryPath is None:
892 raise ValueError("Each repository must set a repository path.")
893 if self.subversion.collectMode is None and repository.collectMode is None:
894 raise ValueError("Collect mode must either be set in parent section or individual repository.")
895 if self.subversion.compressMode is None and repository.compressMode is None:
896 raise ValueError("Compress mode must either be set in parent section or individual repository.")
897 if self.subversion.repositoryDirs is not None:
898 for repositoryDir in self.subversion.repositoryDirs:
899 if repositoryDir.directoryPath is None:
900 raise ValueError("Each repository directory must set a directory path.")
901 if self.subversion.collectMode is None and repositoryDir.collectMode is None:
902 raise ValueError("Collect mode must either be set in parent section or repository directory.")
903 if self.subversion.compressMode is None and repositoryDir.compressMode is None:
904 raise ValueError("Compress mode must either be set in parent section or repository directory.")
905
906 def addConfig(self, xmlDom, parentNode):
907 """
908 Adds a <subversion> configuration section as the next child of a parent.
909
910 Third parties should use this function to write configuration related to
911 this extension.
912
913 We add the following fields to the document::
914
915 collectMode //cb_config/subversion/collectMode
916 compressMode //cb_config/subversion/compressMode
917
918 We also add groups of the following items, one list element per
919 item::
920
921 repository //cb_config/subversion/repository
922 repository_dir //cb_config/subversion/repository_dir
923
924 Args:
925 xmlDom: DOM tree as from ``impl.createDocument()``
926 parentNode: Parent that the section should be appended to
927 """
928 if self.subversion is not None:
929 sectionNode = addContainerNode(xmlDom, parentNode, "subversion")
930 addStringNode(xmlDom, sectionNode, "collect_mode", self.subversion.collectMode)
931 addStringNode(xmlDom, sectionNode, "compress_mode", self.subversion.compressMode)
932 if self.subversion.repositories is not None:
933 for repository in self.subversion.repositories:
934 LocalConfig._addRepository(xmlDom, sectionNode, repository)
935 if self.subversion.repositoryDirs is not None:
936 for repositoryDir in self.subversion.repositoryDirs:
937 LocalConfig._addRepositoryDir(xmlDom, sectionNode, repositoryDir)
938
939 def _parseXmlData(self, xmlData):
940 """
941 Internal method to parse an XML string into the object.
942
943 This method parses the XML document into a DOM tree (``xmlDom``) and then
944 calls a static method to parse the subversion configuration section.
945
946 Args:
947 xmlData (String data): XML data to be parsed
948 Raises:
949 ValueError: If the XML cannot be successfully parsed
950 """
951 (_, parentNode) = createInputDom(xmlData)
952 self._subversion = LocalConfig._parseSubversion(parentNode)
953
954 @staticmethod
955 def _parseSubversion(parent):
956 """
957 Parses a subversion configuration section.
958
959 We read the following individual fields::
960
961 collectMode //cb_config/subversion/collect_mode
962 compressMode //cb_config/subversion/compress_mode
963
964 We also read groups of the following item, one list element per
965 item::
966
967 repositories //cb_config/subversion/repository
968 repository_dirs //cb_config/subversion/repository_dir
969
970 The repositories are parsed by :any:`_parseRepositories`, and the repository
971 dirs are parsed by :any:`_parseRepositoryDirs`.
972
973 Args:
974 parent: Parent node to search beneath
975
976 Returns:
977 ``SubversionConfig`` object or ``None`` if the section does not exist
978 Raises:
979 ValueError: If some filled-in value is invalid
980 """
981 subversion = None
982 section = readFirstChild(parent, "subversion")
983 if section is not None:
984 subversion = SubversionConfig()
985 subversion.collectMode = readString(section, "collect_mode")
986 subversion.compressMode = readString(section, "compress_mode")
987 subversion.repositories = LocalConfig._parseRepositories(section)
988 subversion.repositoryDirs = LocalConfig._parseRepositoryDirs(section)
989 return subversion
990
991 @staticmethod
992 def _parseRepositories(parent):
993 """
994 Reads a list of ``Repository`` objects from immediately beneath the parent.
995
996 We read the following individual fields::
997
998 repositoryType type
999 repositoryPath abs_path
1000 collectMode collect_mode
1001 compressMode compess_mode
1002
1003 The type field is optional, and its value is kept around only for
1004 reference.
1005
1006 Args:
1007 parent: Parent node to search beneath
1008
1009 Returns:
1010 List of ``Repository`` objects or ``None`` if none are found
1011 Raises:
1012 ValueError: If some filled-in value is invalid
1013 """
1014 lst = []
1015 for entry in readChildren(parent, "repository"):
1016 if isElement(entry):
1017 repository = Repository()
1018 repository.repositoryType = readString(entry, "type")
1019 repository.repositoryPath = readString(entry, "abs_path")
1020 repository.collectMode = readString(entry, "collect_mode")
1021 repository.compressMode = readString(entry, "compress_mode")
1022 lst.append(repository)
1023 if not lst:
1024 lst = None
1025 return lst
1026
1027 @staticmethod
1028 def _addRepository(xmlDom, parentNode, repository):
1029 """
1030 Adds a repository container as the next child of a parent.
1031
1032 We add the following fields to the document::
1033
1034 repositoryType repository/type
1035 repositoryPath repository/abs_path
1036 collectMode repository/collect_mode
1037 compressMode repository/compress_mode
1038
1039 The <repository> node itself is created as the next child of the parent
1040 node. This method only adds one repository node. The parent must loop
1041 for each repository in the ``SubversionConfig`` object.
1042
1043 If ``repository`` is ``None``, this method call will be a no-op.
1044
1045 Args:
1046 xmlDom: DOM tree as from ``impl.createDocument()``
1047 parentNode: Parent that the section should be appended to
1048 repository: Repository to be added to the document
1049 """
1050 if repository is not None:
1051 sectionNode = addContainerNode(xmlDom, parentNode, "repository")
1052 addStringNode(xmlDom, sectionNode, "type", repository.repositoryType)
1053 addStringNode(xmlDom, sectionNode, "abs_path", repository.repositoryPath)
1054 addStringNode(xmlDom, sectionNode, "collect_mode", repository.collectMode)
1055 addStringNode(xmlDom, sectionNode, "compress_mode", repository.compressMode)
1056
1057 @staticmethod
1058 def _parseRepositoryDirs(parent):
1059 """
1060 Reads a list of ``RepositoryDir`` objects from immediately beneath the parent.
1061
1062 We read the following individual fields::
1063
1064 repositoryType type
1065 directoryPath abs_path
1066 collectMode collect_mode
1067 compressMode compess_mode
1068
1069 We also read groups of the following items, one list element per
1070 item::
1071
1072 relativeExcludePaths exclude/rel_path
1073 excludePatterns exclude/pattern
1074
1075 The exclusions are parsed by :any:`_parseExclusions`.
1076
1077 The type field is optional, and its value is kept around only for
1078 reference.
1079
1080 Args:
1081 parent: Parent node to search beneath
1082
1083 Returns:
1084 List of ``RepositoryDir`` objects or ``None`` if none are found
1085 Raises:
1086 ValueError: If some filled-in value is invalid
1087 """
1088 lst = []
1089 for entry in readChildren(parent, "repository_dir"):
1090 if isElement(entry):
1091 repositoryDir = RepositoryDir()
1092 repositoryDir.repositoryType = readString(entry, "type")
1093 repositoryDir.directoryPath = readString(entry, "abs_path")
1094 repositoryDir.collectMode = readString(entry, "collect_mode")
1095 repositoryDir.compressMode = readString(entry, "compress_mode")
1096 (repositoryDir.relativeExcludePaths, repositoryDir.excludePatterns) = LocalConfig._parseExclusions(entry)
1097 lst.append(repositoryDir)
1098 if not lst:
1099 lst = None
1100 return lst
1101
1102 @staticmethod
1103 def _parseExclusions(parentNode):
1104 """
1105 Reads exclusions data from immediately beneath the parent.
1106
1107 We read groups of the following items, one list element per item::
1108
1109 relative exclude/rel_path
1110 patterns exclude/pattern
1111
1112 If there are none of some pattern (i.e. no relative path items) then
1113 ``None`` will be returned for that item in the tuple.
1114
1115 Args:
1116 parentNode: Parent node to search beneath
1117
1118 Returns:
1119 Tuple of (relative, patterns) exclusions
1120 """
1121 section = readFirstChild(parentNode, "exclude")
1122 if section is None:
1123 return (None, None)
1124 else:
1125 relative = readStringList(section, "rel_path")
1126 patterns = readStringList(section, "pattern")
1127 return (relative, patterns)
1128
1129 @staticmethod
1130 def _addRepositoryDir(xmlDom, parentNode, repositoryDir):
1131 """
1132 Adds a repository dir container as the next child of a parent.
1133
1134 We add the following fields to the document::
1135
1136 repositoryType repository_dir/type
1137 directoryPath repository_dir/abs_path
1138 collectMode repository_dir/collect_mode
1139 compressMode repository_dir/compress_mode
1140
1141 We also add groups of the following items, one list element per item::
1142
1143 relativeExcludePaths dir/exclude/rel_path
1144 excludePatterns dir/exclude/pattern
1145
1146 The <repository_dir> node itself is created as the next child of the
1147 parent node. This method only adds one repository node. The parent must
1148 loop for each repository dir in the ``SubversionConfig`` object.
1149
1150 If ``repositoryDir`` is ``None``, this method call will be a no-op.
1151
1152 Args:
1153 xmlDom: DOM tree as from ``impl.createDocument()``
1154 parentNode: Parent that the section should be appended to
1155 repositoryDir: Repository dir to be added to the document
1156 """
1157 if repositoryDir is not None:
1158 sectionNode = addContainerNode(xmlDom, parentNode, "repository_dir")
1159 addStringNode(xmlDom, sectionNode, "type", repositoryDir.repositoryType)
1160 addStringNode(xmlDom, sectionNode, "abs_path", repositoryDir.directoryPath)
1161 addStringNode(xmlDom, sectionNode, "collect_mode", repositoryDir.collectMode)
1162 addStringNode(xmlDom, sectionNode, "compress_mode", repositoryDir.compressMode)
1163 if (repositoryDir.relativeExcludePaths is not None and repositoryDir.relativeExcludePaths != []) or (
1164 repositoryDir.excludePatterns is not None and repositoryDir.excludePatterns != []
1165 ):
1166 excludeNode = addContainerNode(xmlDom, sectionNode, "exclude")
1167 if repositoryDir.relativeExcludePaths is not None:
1168 for relativePath in repositoryDir.relativeExcludePaths:
1169 addStringNode(xmlDom, excludeNode, "rel_path", relativePath)
1170 if repositoryDir.excludePatterns is not None:
1171 for pattern in repositoryDir.excludePatterns:
1172 addStringNode(xmlDom, excludeNode, "pattern", pattern)
1173
1174
1175 ########################################################################
1176 # Public functions
1177 ########################################################################
1178
1179 ###########################
1180 # executeAction() function
1181 ###########################
1182
1183
1184 def executeAction(configPath, options, config):
1185 """
1186 Executes the Subversion backup action.
1187
1188 Args:
1189 configPath (String representing a path on disk): Path to configuration file on disk
1190 options (Options object): Program command-line options
1191 config (Config object): Program configuration
1192 Raises:
1193 ValueError: Under many generic error conditions
1194 IOError: If a backup could not be written for some reason
1195 """
1196 logger.debug("Executing Subversion extended action.")
1197 if config.options is None or config.collect is None:
1198 raise ValueError("Cedar Backup configuration is not properly filled in.")
1199 local = LocalConfig(xmlPath=configPath)
1200 todayIsStart = isStartOfWeek(config.options.startingDay)
1201 fullBackup = options.full or todayIsStart
1202 logger.debug("Full backup flag is [%s]", fullBackup)
1203 if local.subversion.repositories is not None:
1204 for repository in local.subversion.repositories:
1205 _backupRepository(config, local, todayIsStart, fullBackup, repository)
1206 if local.subversion.repositoryDirs is not None:
1207 for repositoryDir in local.subversion.repositoryDirs:
1208 logger.debug("Working with repository directory [%s].", repositoryDir.directoryPath)
1209 for repositoryPath in _getRepositoryPaths(repositoryDir):
1210 repository = Repository(
1211 repositoryDir.repositoryType, repositoryPath, repositoryDir.collectMode, repositoryDir.compressMode
1212 )
1213 _backupRepository(config, local, todayIsStart, fullBackup, repository)
1214 logger.info("Completed backing up Subversion repository directory [%s].", repositoryDir.directoryPath)
1215 logger.info("Executed the Subversion extended action successfully.")
1216
1217
1218 def _getCollectMode(local, repository):
1219 """
1220 Gets the collect mode that should be used for a repository.
1221 Use repository's if possible, otherwise take from subversion section.
1222 Args:
1223 repository: Repository object
1224 Returns:
1225 Collect mode to use
1226 """
1227 if repository.collectMode is None:
1228 collectMode = local.subversion.collectMode
1229 else:
1230 collectMode = repository.collectMode
1231 logger.debug("Collect mode is [%s]", collectMode)
1232 return collectMode
1233
1234
1235 def _getCompressMode(local, repository):
1236 """
1237 Gets the compress mode that should be used for a repository.
1238 Use repository's if possible, otherwise take from subversion section.
1239 Args:
1240 local: LocalConfig object
1241 repository: Repository object
1242 Returns:
1243 Compress mode to use
1244 """
1245 if repository.compressMode is None:
1246 compressMode = local.subversion.compressMode
1247 else:
1248 compressMode = repository.compressMode
1249 logger.debug("Compress mode is [%s]", compressMode)
1250 return compressMode
1251
1252
1253 def _getRevisionPath(config, repository):
1254 """
1255 Gets the path to the revision file associated with a repository.
1256 Args:
1257 config: Config object
1258 repository: Repository object
1259 Returns:
1260 Absolute path to the revision file associated with the repository
1261 """
1262 normalized = buildNormalizedPath(repository.repositoryPath)
1263 filename = "%s.%s" % (normalized, REVISION_PATH_EXTENSION)
1264 revisionPath = pathJoin(config.options.workingDir, filename)
1265 logger.debug("Revision file path is [%s]", revisionPath)
1266 return revisionPath
1267
1268
1269 def _getBackupPath(config, repositoryPath, compressMode, startRevision, endRevision):
1270 """
1271 Gets the backup file path (including correct extension) associated with a repository.
1272 Args:
1273 config: Config object
1274 repositoryPath: Path to the indicated repository
1275 compressMode: Compress mode to use for this repository
1276 startRevision: Starting repository revision
1277 endRevision: Ending repository revision
1278 Returns:
1279 Absolute path to the backup file associated with the repository
1280 """
1281 normalizedPath = buildNormalizedPath(repositoryPath)
1282 filename = "svndump-%d:%d-%s.txt" % (startRevision, endRevision, normalizedPath)
1283 if compressMode == "gzip":
1284 filename = "%s.gz" % filename
1285 elif compressMode == "bzip2":
1286 filename = "%s.bz2" % filename
1287 backupPath = pathJoin(config.collect.targetDir, filename)
1288 logger.debug("Backup file path is [%s]", backupPath)
1289 return backupPath
1290
1291
1292 def _getRepositoryPaths(repositoryDir):
1293 """
1294 Gets a list of child repository paths within a repository directory.
1295 Args:
1296 repositoryDir: RepositoryDirectory
1297 """
1298 (excludePaths, excludePatterns) = _getExclusions(repositoryDir)
1299 fsList = FilesystemList()
1300 fsList.excludeFiles = True
1301 fsList.excludeLinks = True
1302 fsList.excludePaths = excludePaths
1303 fsList.excludePatterns = excludePatterns
1304 fsList.addDirContents(path=repositoryDir.directoryPath, recursive=False, addSelf=False)
1305 return fsList
1306
1307
1308 def _getExclusions(repositoryDir):
1309 """
1310 Gets exclusions (file and patterns) associated with an repository directory.
1311
1312 The returned files value is a list of absolute paths to be excluded from the
1313 backup for a given directory. It is derived from the repository directory's
1314 relative exclude paths.
1315
1316 The returned patterns value is a list of patterns to be excluded from the
1317 backup for a given directory. It is derived from the repository directory's
1318 list of patterns.
1319
1320 Args:
1321 repositoryDir: Repository directory object
1322
1323 Returns:
1324 Tuple (files, patterns) indicating what to exclude
1325 """
1326 paths = []
1327 if repositoryDir.relativeExcludePaths is not None:
1328 for relativePath in repositoryDir.relativeExcludePaths:
1329 paths.append(pathJoin(repositoryDir.directoryPath, relativePath))
1330 patterns = []
1331 if repositoryDir.excludePatterns is not None:
1332 patterns.extend(repositoryDir.excludePatterns)
1333 logger.debug("Exclude paths: %s", paths)
1334 logger.debug("Exclude patterns: %s", patterns)
1335 return (paths, patterns)
1336
1337
1338 def _backupRepository(config, local, todayIsStart, fullBackup, repository):
1339 """
1340 Backs up an individual Subversion repository.
1341
1342 This internal method wraps the public methods and adds some functionality
1343 to work better with the extended action itself.
1344
1345 Args:
1346 config: Cedar Backup configuration
1347 local: Local configuration
1348 todayIsStart: Indicates whether today is start of week
1349 fullBackup: Full backup flag
1350 repository: Repository to operate on
1351
1352 Raises:
1353 ValueError: If some value is missing or invalid
1354 IOError: If there is a problem executing the Subversion dump
1355 """
1356 logger.debug("Working with repository [%s]", repository.repositoryPath)
1357 logger.debug("Repository type is [%s]", repository.repositoryType)
1358 collectMode = _getCollectMode(local, repository)
1359 compressMode = _getCompressMode(local, repository)
1360 revisionPath = _getRevisionPath(config, repository)
1361 if not (fullBackup or (collectMode in ["daily", "incr"]) or (collectMode == "weekly" and todayIsStart)):
1362 logger.debug("Repository will not be backed up, per collect mode.")
1363 return
1364 logger.debug("Repository meets criteria to be backed up today.")
1365 if collectMode != "incr" or fullBackup:
1366 startRevision = 0
1367 endRevision = getYoungestRevision(repository.repositoryPath)
1368 logger.debug("Using full backup, revision: (%d, %d).", startRevision, endRevision)
1369 else:
1370 if fullBackup:
1371 startRevision = 0
1372 endRevision = getYoungestRevision(repository.repositoryPath)
1373 else:
1374 startRevision = _loadLastRevision(revisionPath) + 1
1375 endRevision = getYoungestRevision(repository.repositoryPath)
1376 if startRevision > endRevision:
1377 logger.info("No need to back up repository [%s]; no new revisions.", repository.repositoryPath)
1378 return
1379 logger.debug("Using incremental backup, revision: (%d, %d).", startRevision, endRevision)
1380 backupPath = _getBackupPath(config, repository.repositoryPath, compressMode, startRevision, endRevision)
1381 with _getOutputFile(backupPath, compressMode) as outputFile:
1382 backupRepository(repository.repositoryPath, outputFile, startRevision, endRevision)
1383 if not os.path.exists(backupPath):
1384 raise OSError("Dump file [%s] does not seem to exist after backup completed." % backupPath)
1385 changeOwnership(backupPath, config.options.backupUser, config.options.backupGroup)
1386 if collectMode == "incr":
1387 _writeLastRevision(config, revisionPath, endRevision)
1388 logger.info("Completed backing up Subversion repository [%s].", repository.repositoryPath)
1389
1390
1391 def _getOutputFile(backupPath, compressMode):
1392 """
1393 Opens the output file used for saving the Subversion dump.
1394
1395 If the compress mode is "gzip", we'll open a ``GzipFile``, and if the
1396 compress mode is "bzip2", we'll open a ``BZ2File``. Otherwise, we'll just
1397 return an object from the normal ``open()`` method.
1398
1399 Args:
1400 backupPath: Path to file to open
1401 compressMode: Compress mode of file ("none", "gzip", "bzip")
1402
1403 Returns:
1404 Output file object, opened in binary mode for use with executeCommand()
1405 """
1406 if compressMode == "gzip":
1407 return GzipFile(backupPath, "wb")
1408 elif compressMode == "bzip2":
1409 return BZ2File(backupPath, "wb")
1410 else:
1411 return open(backupPath, "wb")
1412
1413
1414 def _loadLastRevision(revisionPath):
1415 """
1416 Loads the indicated revision file from disk into an integer.
1417
1418 If we can't load the revision file successfully (either because it doesn't
1419 exist or for some other reason), then a revision of -1 will be returned -
1420 but the condition will be logged. This way, we err on the side of backing
1421 up too much, because anyone using this will presumably be adding 1 to the
1422 revision, so they don't duplicate any backups.
1423
1424 Args:
1425 revisionPath: Path to the revision file on disk
1426
1427 Returns:
1428 Integer representing last backed-up revision, -1 on error or if none can be read
1429 """
1430 if not os.path.isfile(revisionPath):
1431 startRevision = -1
1432 logger.debug("Revision file [%s] does not exist on disk.", revisionPath)
1433 else:
1434 try:
1435 with open(revisionPath, "rb") as f:
1436 startRevision = pickle.load(f, fix_imports=True) # ruff: ignore[suspicious-pickle-usage] # this is trusted data, so pickle is ok
1437 logger.debug("Loaded revision file [%s] from disk: %d.", revisionPath, startRevision)
1438 except Exception as e:
1439 startRevision = -1
1440 logger.error("Failed loading revision file [%s] from disk: %s", revisionPath, e)
1441 return startRevision
1442
1443
1444 def _writeLastRevision(config, revisionPath, endRevision):
1445 """
1446 Writes the end revision to the indicated revision file on disk.
1447
1448 If we can't write the revision file successfully for any reason, we'll log
1449 the condition but won't throw an exception.
1450
1451 Args:
1452 config: Config object
1453 revisionPath: Path to the revision file on disk
1454 endRevision: Last revision backed up on this run
1455 """
1456 try:
1457 with open(revisionPath, "wb") as f:
1458 pickle.dump(endRevision, f, 0, fix_imports=True)
1459 changeOwnership(revisionPath, config.options.backupUser, config.options.backupGroup)
1460 logger.debug("Wrote new revision file [%s] to disk: %d.", revisionPath, endRevision)
1461 except Exception as e:
1462 logger.error("Failed to write revision file [%s] to disk: %s", revisionPath, e)
1463
1464
1465 ##############################
1466 # backupRepository() function
1467 ##############################
1468
1469
1470 def backupRepository(repositoryPath, backupFile, startRevision=None, endRevision=None):
1471 """
1472 Backs up an individual Subversion repository.
1473
1474 The starting and ending revision values control an incremental backup. If
1475 the starting revision is not passed in, then revision zero (the start of the
1476 repository) is assumed. If the ending revision is not passed in, then the
1477 youngest revision in the database will be used as the endpoint.
1478
1479 The backup data will be written into the passed-in back file. Normally,
1480 this would be an object as returned from ``open``, but it is possible to use
1481 something like a ``GzipFile`` to write compressed output. The caller is
1482 responsible for closing the passed-in backup file.
1483
1484 *Note:* This function should either be run as root or as the owner of the
1485 Subversion repository.
1486
1487 *Note:* It is apparently *not* a good idea to interrupt this function.
1488 Sometimes, this leaves the repository in a "wedged" state, which requires
1489 recovery using ``svnadmin recover``.
1490
1491 Args:
1492 repositoryPath (String path representing Subversion repository on disk): Path to Subversion repository to back up
1493 backupFile (Python file object as from ``open`` or ``file``): Python file object to use for writing backup
1494 startRevision (Integer value >= 0): Starting repository revision to back up (for incremental backups)
1495 endRevision (Integer value >= 0): Ending repository revision to back up (for incremental backups)
1496 Raises:
1497 ValueError: If some value is missing or invalid
1498 IOError: If there is a problem executing the Subversion dump
1499 """
1500 if startRevision is None:
1501 startRevision = 0
1502 if endRevision is None:
1503 endRevision = getYoungestRevision(repositoryPath)
1504 if int(startRevision) < 0:
1505 raise ValueError("Start revision must be >= 0.")
1506 if int(endRevision) < 0:
1507 raise ValueError("End revision must be >= 0.")
1508 if startRevision > endRevision:
1509 raise ValueError("Start revision must be <= end revision.")
1510 args = ["dump", "--quiet", "-r%s:%s" % (startRevision, endRevision), "--incremental", repositoryPath]
1511 command = resolveCommand(SVNADMIN_COMMAND)
1512 result = executeCommand(command, args, returnOutput=False, ignoreStderr=True, doNotLog=True, outputFile=backupFile)[0]
1513 if result != 0:
1514 raise OSError("Error [%d] executing Subversion dump for repository [%s]." % (result, repositoryPath))
1515 logger.debug("Completed dumping subversion repository [%s].", repositoryPath)
1516
1517
1518 #################################
1519 # getYoungestRevision() function
1520 #################################
1521
1522
1523 def getYoungestRevision(repositoryPath):
1524 """
1525 Gets the youngest (newest) revision in a Subversion repository using ``svnlook``.
1526
1527 *Note:* This function should either be run as root or as the owner of the
1528 Subversion repository.
1529
1530 Args:
1531 repositoryPath (String path representing Subversion repository on disk): Path to Subversion repository to look in
1532 Returns:
1533 Youngest revision as an integer
1534
1535 Raises:
1536 ValueError: If there is a problem parsing the ``svnlook`` output
1537 IOError: If there is a problem executing the ``svnlook`` command
1538 """
1539 args = ["youngest", repositoryPath]
1540 command = resolveCommand(SVNLOOK_COMMAND)
1541 (result, output) = executeCommand(command, args, returnOutput=True, ignoreStderr=True)
1542 if result != 0:
1543 raise OSError("Error [%d] executing 'svnlook youngest' for repository [%s]." % (result, repositoryPath))
1544 if len(output) != 1:
1545 raise ValueError("Unable to parse 'svnlook youngest' output.")
1546 return int(output[0])
1547
1548
1549 ########################################################################
1550 # Deprecated functionality
1551 ########################################################################
1552
1553
1554 class BDBRepository(Repository):
1555 """
1556 Class representing Subversion BDB (Berkeley Database) repository configuration.
1557 This object is deprecated. Use a simple :any:`Repository` instead.
1558 """
1559
1560 def __init__(self, repositoryPath=None, collectMode=None, compressMode=None):
1561 """
1562 Constructor for the ``BDBRepository`` class.
1563 """
1564 super().__init__("BDB", repositoryPath, collectMode, compressMode)
1565
1566 def __repr__(self):
1567 """
1568 Official string representation for class instance.
1569 """
1570 return "BDBRepository(%s, %s, %s)" % (self.repositoryPath, self.collectMode, self.compressMode)
1571
1572
1573 class FSFSRepository(Repository):
1574 """
1575 Class representing Subversion FSFS repository configuration.
1576 This object is deprecated. Use a simple :any:`Repository` instead.
1577 """
1578
1579 def __init__(self, repositoryPath=None, collectMode=None, compressMode=None):
1580 """
1581 Constructor for the ``FSFSRepository`` class.
1582 """
1583 super().__init__("FSFS", repositoryPath, collectMode, compressMode)
1584
1585 def __repr__(self):
1586 """
1587 Official string representation for class instance.
1588 """
1589 return "FSFSRepository(%s, %s, %s)" % (self.repositoryPath, self.collectMode, self.compressMode)
1590
1591
1592 def backupBDBRepository(repositoryPath, backupFile, startRevision=None, endRevision=None):
1593 """
1594 Backs up an individual Subversion BDB repository.
1595 This function is deprecated. Use :any:`backupRepository` instead.
1596 """
1597 return backupRepository(repositoryPath, backupFile, startRevision, endRevision)
1598
1599
1600 def backupFSFSRepository(repositoryPath, backupFile, startRevision=None, endRevision=None):
1601 """
1602 Backs up an individual Subversion FSFS repository.
1603 This function is deprecated. Use :any:`backupRepository` instead.
1604 """
1605 return backupRepository(repositoryPath, backupFile, startRevision, endRevision)