git-p4: convert descriptive class and function comments into docstrings

Previously, a small number of functions, methods and classes were documented using comments. This patch improves consistency by converting these into docstrings similar to those that already exist in the script. Signed-off-by: Joel Holdsworth <jholdsworth@nvidia.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Joel Holdsworth committed Apr 1, 2022 at 15:24 UTC 522e914f65da504f6b485dd8a89f49f7f176bbd0
1 file changed +94 -70
git-p4.py
+94 -70
@@ -458,7 +458,7 @@ def p4_sync(f, *options):
458
459
460 def p4_add(f):
461 - # forcibly add file names with wildcards
461 + """Forcibly add file names with wildcards."""
462 if wildcard_present(f):
463 p4_system(["add", "-f", f])
464 else:
@@ -526,12 +526,10 @@ def p4_describe(change, shelved=False):
526 return d
527
528
529 -#
530 -# Canonicalize the p4 type and return a tuple of the
531 -# base type, plus any modifiers. See "p4 help filetypes"
532 -# for a list and explanation.
533 -#
529 def split_p4_type(p4type):
530 + """Canonicalize the p4 type and return a tuple of the base type, plus any
531 + modifiers. See "p4 help filetypes" for a list and explanation.
532 + """
533
534 p4_filetypes_historical = {
535 "ctempobj": "binary+Sw",
@@ -562,19 +560,18 @@ def split_p4_type(p4type):
560 return (base, mods)
561
562
565 -#
566 -# return the raw p4 type of a file (text, text+ko, etc)
567 -#
563 def p4_type(f):
564 + """Return the raw p4 type of a file (text, text+ko, etc)."""
565 +
566 results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
567 return results[0]['headType']
568
569
573 -#
574 -# Given a type base and modifier, return a regexp matching
575 -# the keywords that can be expanded in the file
576 -#
570 def p4_keywords_regexp_for_type(base, type_mods):
571 + """Given a type base and modifier, return a regexp matching the keywords
572 + that can be expanded in the file.
573 + """
574 +
575 if base in ("text", "unicode", "binary"):
576 if "ko" in type_mods:
577 return re_ko_keywords
@@ -586,12 +583,11 @@ def p4_keywords_regexp_for_type(base, type_mods):
583 return None
584
585
589 -#
590 -# Given a file, return a regexp matching the possible
591 -# RCS keywords that will be expanded, or None for files
592 -# with kw expansion turned off.
593 -#
586 def p4_keywords_regexp_for_file(file):
587 + """Given a file, return a regexp matching the possible RCS keywords that
588 + will be expanded, or None for files with kw expansion turned off.
589 + """
590 +
591 if not os.path.exists(file):
592 return None
593 else:
@@ -600,8 +596,9 @@ def p4_keywords_regexp_for_file(file):
596
597
598 def setP4ExecBit(file, mode):
603 - # Reopens an already open file and changes the execute bit to match
604 - # the execute bit setting in the passed in mode.
599 + """Reopens an already open file and changes the execute bit to match the
600 + execute bit setting in the passed in mode.
601 + """
602
603 p4Type = "+x"
604
@@ -616,7 +613,7 @@ def setP4ExecBit(file, mode):
613
614
615 def getP4OpenedType(file):
619 - # Returns the perforce file type for the given file.
616 + """Returns the perforce file type for the given file."""
617
618 result = p4_read_pipe(["opened", wildcard_encode(file)])
619 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
@@ -626,8 +623,9 @@ def getP4OpenedType(file):
623 die("Could not determine file type for %s (result: '%s')" % (file, result))
624
625
629 -# Return the set of all p4 labels
626 def getP4Labels(depotPaths):
627 + """Return the set of all p4 labels."""
628 +
629 labels = set()
630 if not isinstance(depotPaths, list):
631 depotPaths = [depotPaths]
@@ -639,8 +637,9 @@ def getP4Labels(depotPaths):
637 return labels
638
639
642 -# Return the set of all git tags
640 def getGitTags():
641 + """Return the set of all git tags."""
642 +
643 gitTags = set()
644 for line in read_pipe_lines(["git", "tag"]):
645 tag = line.strip()
@@ -691,8 +690,9 @@ def parseDiffTreeEntry(entry):
690
691
692 def isModeExec(mode):
694 - # Returns True if the given git mode represents an executable file,
695 - # otherwise False.
693 + """Returns True if the given git mode represents an executable file,
694 + otherwise False.
695 + """
696 return mode[-3:] == "755"
697
698
@@ -1201,13 +1201,14 @@ def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
1201
1202
1203 def p4PathStartsWith(path, prefix):
1204 - # This method tries to remedy a potential mixed-case issue:
1205 - #
1206 - # If UserA adds //depot/DirA/file1
1207 - # and UserB adds //depot/dira/file2
1208 - #
1209 - # we may or may not have a problem. If you have core.ignorecase=true,
1210 - # we treat DirA and dira as the same directory
1204 + """This method tries to remedy a potential mixed-case issue:
1205 +
1206 + If UserA adds //depot/DirA/file1
1207 + and UserB adds //depot/dira/file2
1208 +
1209 + we may or may not have a problem. If you have core.ignorecase=true,
1210 + we treat DirA and dira as the same directory.
1211 + """
1212 if gitConfigBool("core.ignorecase"):
1213 return path.lower().startswith(prefix.lower())
1214 return path.startswith(prefix)
@@ -1259,12 +1260,14 @@ def getClientRoot():
1260 return entry["Root"]
1261
1262
1262 -#
1263 -# P4 wildcards are not allowed in filenames. P4 complains
1264 -# if you simply add them, but you can force it with "-f", in
1265 -# which case it translates them into %xx encoding internally.
1266 -#
1263 def wildcard_decode(path):
1264 + """Decode P4 wildcards into %xx encoding
1265 +
1266 + P4 wildcards are not allowed in filenames. P4 complains if you simply
1267 + add them, but you can force it with "-f", in which case it translates
1268 + them into %xx encoding internally.
1269 + """
1270 +
1271 # Search for and fix just these four characters. Do % last so
1272 # that fixing it does not inadvertently create new %-escapes.
1273 # Cannot have * in a filename in windows; untested as to
@@ -1278,6 +1281,8 @@ def wildcard_decode(path):
1281
1282
1283 def wildcard_encode(path):
1284 + """Encode %xx coded wildcards into P4 coding."""
1285 +
1286 # do % first to avoid double-encoding the %s introduced here
1287 path = path.replace("%", "%25") \
1288 .replace("*", "%2A") \
@@ -1524,7 +1529,7 @@ class P4UserMap:
1529 die("Could not find your p4 user id")
1530
1531 def p4UserIsMe(self, p4User):
1527 - # return True if the given p4 user is actually me
1532 + """Return True if the given p4 user is actually me."""
1533 me = self.p4UserId()
1534 if not p4User or p4User != me:
1535 return False
@@ -1727,7 +1732,9 @@ class P4Submit(Command, P4UserMap):
1732 return result
1733
1734 def patchRCSKeywords(self, file, regexp):
1730 - # Attempt to zap the RCS keywords in a p4 controlled file matching the given regex
1735 + """Attempt to zap the RCS keywords in a p4 controlled file matching the
1736 + given regex.
1737 + """
1738 (handle, outFileName) = tempfile.mkstemp(dir='.')
1739 try:
1740 with os.fdopen(handle, "wb") as outFile, open(file, "rb") as inFile:
@@ -1745,7 +1752,9 @@ class P4Submit(Command, P4UserMap):
1752 print("Patched up RCS keywords in %s" % file)
1753
1754 def p4UserForCommit(self,id):
1748 - # Return the tuple (perforce user,git email) for a given git commit id
1755 + """Return the tuple (perforce user,git email) for a given git commit
1756 + id.
1757 + """
1758 self.getUserMapFromPerforceServer()
1759 gitEmail = read_pipe(["git", "log", "--max-count=1",
1760 "--format=%ae", id])
@@ -1756,7 +1765,7 @@ class P4Submit(Command, P4UserMap):
1765 return (self.emails[gitEmail],gitEmail)
1766
1767 def checkValidP4Users(self,commits):
1759 - # check if any git authors cannot be mapped to p4 users
1768 + """Check if any git authors cannot be mapped to p4 users."""
1769 for id in commits:
1770 (user,email) = self.p4UserForCommit(id)
1771 if not user:
@@ -1767,10 +1776,12 @@ class P4Submit(Command, P4UserMap):
1776 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
1777
1778 def lastP4Changelist(self):
1770 - # Get back the last changelist number submitted in this client spec. This
1771 - # then gets used to patch up the username in the change. If the same
1772 - # client spec is being used by multiple processes then this might go
1773 - # wrong.
1779 + """Get back the last changelist number submitted in this client spec.
1780 +
1781 + This then gets used to patch up the username in the change. If the
1782 + same client spec is being used by multiple processes then this might
1783 + go wrong.
1784 + """
1785 results = p4CmdList(["client", "-o"]) # find the current client
1786 client = None
1787 for r in results:
@@ -1786,7 +1797,7 @@ class P4Submit(Command, P4UserMap):
1797 die("Could not get changelist number for last submit - cannot patch up user details")
1798
1799 def modifyChangelistUser(self, changelist, newUser):
1789 - # fixup the user field of a changelist after it has been submitted.
1800 + """Fixup the user field of a changelist after it has been submitted."""
1801 changes = p4CmdList(["change", "-o", changelist])
1802 if len(changes) != 1:
1803 die("Bad output from p4 change modifying %s to user %s" %
@@ -1809,8 +1820,9 @@ class P4Submit(Command, P4UserMap):
1820 die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
1821
1822 def canChangeChangelists(self):
1812 - # check to see if we have p4 admin or super-user permissions, either of
1813 - # which are required to modify changelists.
1823 + """Check to see if we have p4 admin or super-user permissions, either
1824 + of which are required to modify changelists.
1825 + """
1826 results = p4CmdList(["protects", self.depotPath])
1827 for r in results:
1828 if 'perm' in r:
@@ -2262,9 +2274,11 @@ class P4Submit(Command, P4UserMap):
2274 os.remove(fileName)
2275 return submitted
2276
2265 - # Export git tags as p4 labels. Create a p4 label and then tag
2266 - # with that.
2277 def exportGitTags(self, gitTags):
2278 + """Export git tags as p4 labels. Create a p4 label and then tag with
2279 + that.
2280 + """
2281 +
2282 validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
2283 if len(validLabelRegexp) == 0:
2284 validLabelRegexp = defaultLabelRegexp
@@ -2787,8 +2801,8 @@ class P4Sync(Command, P4UserMap):
2801 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
2802 self.labels = {}
2803
2790 - # Force a checkpoint in fast-import and wait for it to finish
2804 def checkpoint(self):
2805 + """Force a checkpoint in fast-import and wait for it to finish."""
2806 self.gitStream.write("checkpoint\n\n")
2807 self.gitStream.write("progress checkpoint\n\n")
2808 self.gitStream.flush()
@@ -2934,10 +2948,12 @@ class P4Sync(Command, P4UserMap):
2948 print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
2949 return path
2950
2937 - # output one file from the P4 stream
2938 - # - helper for streamP4Files
2939 -
2951 def streamOneP4File(self, file, contents):
2952 + """Output one file from the P4 stream.
2953 +
2954 + This is a helper for streamP4Files().
2955 + """
2956 +
2957 file_path = file['depotFile']
2958 relPath = self.stripRepoPath(decode_path(file_path), self.branchPrefixes)
2959
@@ -3029,8 +3045,8 @@ class P4Sync(Command, P4UserMap):
3045 if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
3046 self.largeFileSystem.removeLargeFile(relPath)
3047
3032 - # handle another chunk of streaming data
3048 def streamP4FilesCb(self, marshalled):
3049 + """Handle another chunk of streaming data."""
3050
3051 # catch p4 errors and complain
3052 err = None
@@ -3094,8 +3110,9 @@ class P4Sync(Command, P4UserMap):
3110
3111 self.stream_have_file_info = True
3112
3097 - # Stream directly from "p4 files" into "git fast-import"
3113 def streamP4Files(self, files):
3114 + """Stream directly from "p4 files" into "git fast-import."""
3115 +
3116 filesForCommit = []
3117 filesToRead = []
3118 filesToDelete = []
@@ -3199,15 +3216,18 @@ class P4Sync(Command, P4UserMap):
3216 return hasPrefix
3217
3218 def findShadowedFiles(self, files, change):
3202 - # Perforce allows you commit files and directories with the same name,
3203 - # so you could have files //depot/foo and //depot/foo/bar both checked
3204 - # in. A p4 sync of a repository in this state fails. Deleting one of
3205 - # the files recovers the repository.
3206 - #
3207 - # Git will not allow the broken state to exist and only the most recent
3208 - # of the conflicting names is left in the repository. When one of the
3209 - # conflicting files is deleted we need to re-add the other one to make
3210 - # sure the git repository recovers in the same way as perforce.
3219 + """Perforce allows you commit files and directories with the same name,
3220 + so you could have files //depot/foo and //depot/foo/bar both checked
3221 + in. A p4 sync of a repository in this state fails. Deleting one of
3222 + the files recovers the repository.
3223 +
3224 + Git will not allow the broken state to exist and only the most
3225 + recent of the conflicting names is left in the repository. When one
3226 + of the conflicting files is deleted we need to re-add the other one
3227 + to make sure the git repository recovers in the same way as
3228 + perforce.
3229 + """
3230 +
3231 deleted = [f for f in files if f['action'] in self.delete_actions]
3232 to_check = set()
3233 for f in deleted:
@@ -3324,8 +3344,11 @@ class P4Sync(Command, P4UserMap):
3344 print("Tag %s does not match with change %s: file count is different."
3345 % (labelDetails["label"], change))
3346
3327 - # Build a dictionary of changelists and labels, for "detect-labels" option.
3347 def getLabels(self):
3348 + """Build a dictionary of changelists and labels, for "detect-labels"
3349 + option.
3350 + """
3351 +
3352 self.labels = {}
3353
3354 l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
@@ -3351,11 +3374,12 @@ class P4Sync(Command, P4UserMap):
3374 if self.verbose:
3375 print("Label changes: %s" % self.labels.keys())
3376
3354 - # Import p4 labels as git tags. A direct mapping does not
3355 - # exist, so assume that if all the files are at the same revision
3356 - # then we can use that, or it's something more complicated we should
3357 - # just ignore.
3377 def importP4Labels(self, stream, p4Labels):
3378 + """Import p4 labels as git tags. A direct mapping does not exist, so
3379 + assume that if all the files are at the same revision then we can
3380 + use that, or it's something more complicated we should just ignore.
3381 + """
3382 +
3383 if verbose:
3384 print("import p4 labels: " + ' '.join(p4Labels))
3385