p4_validate_submitted_changelists.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. #
  8. import argparse
  9. import os
  10. import sys
  11. from typing import Dict, List
  12. from commit_validation.commit_validation import Commit, validate_commit
  13. from p4 import run_p4_command
  14. class P4SubmittedChangelists(Commit):
  15. """An implementation of the :class:`Commit` interface for accessing details about Perforce submitted changelists"""
  16. def __init__(self, from_change: str, to_change: str, client: str = None) -> None:
  17. """Creates a new instance of :class:`P4SubmittedChangelists`
  18. :param from_change: The oldest Perforce changelist to include
  19. :param to_change: The newest Perforce changelist to include
  20. :param client: The Perforce client
  21. """
  22. self.from_change = from_change
  23. self.to_change = to_change
  24. self.client = client
  25. self.files: List[str] = []
  26. self.removed_files: List[str] = []
  27. self.file_diffs: Dict[str, str] = {}
  28. self._load_files()
  29. def _load_files(self):
  30. self.files = []
  31. self.removed_files = []
  32. depot_root = None
  33. client_root = run_p4_command(f'client -o', client=self.client)[0]['Root']
  34. files = run_p4_command(f'files {client_root}{os.sep}...@{self.from_change},{self.to_change}',
  35. client=self.client)
  36. for f in files:
  37. # The following code optimizes for the specific use case where all files are mapped the same way on the
  38. # client. The reason for this is to avoid calling 'p4 where' on thousands of files. So instead, it only calls
  39. # 'p4 where' on the first file and applies the same mapping to the rest of the files.
  40. if depot_root is None:
  41. file_path = run_p4_command(f'where {f["depotFile"]}', client=self.client)[0]['path']
  42. relative_path = file_path.replace(client_root, '')
  43. relative_path = relative_path.replace('\\', '/')
  44. depot_root = f['depotFile'].replace(relative_path, '')
  45. else:
  46. file_path = os.path.abspath(f['depotFile'].replace(depot_root, client_root))
  47. if 'delete' in f['action']:
  48. self.removed_files.append(file_path)
  49. else:
  50. self.files.append(file_path)
  51. pass
  52. def get_file_diff(self, file) -> str:
  53. if file in self.file_diffs:
  54. return self.file_diffs[file]
  55. if file not in self.files:
  56. raise RuntimeError(f"Cannot compute diff for file not in change set: {file}")
  57. # the diff2 command does not behave like normal diff command, in that it only
  58. # returns the actual diff if you do not use '-G' mode. So we ask it for the raw output:
  59. diff = run_p4_command(f'diff2 -du {file}@{self.from_change} {file}@{self.to_change}', client=self.client, raw_output=True)
  60. self.file_diffs[file] = diff
  61. # note that if you feed the same changelist as the 'before' and 'after' on the command line
  62. # you will get no diffs, because there is no difference between a changelist and itself.
  63. # In addition, if you are diffing across changelists, but the file only existed
  64. # in one changelist, it will also not indicate a diff (due to how the p4 diff2 command operates)
  65. # This means that this validator is blind to branch integrates. This is not the case
  66. # for the 'live' or 'shelved' validator as those files show up as additions.
  67. return diff
  68. def get_files(self) -> List[str]:
  69. return self.files
  70. def get_removed_files(self) -> List[str]:
  71. return self.removed_files
  72. def get_description(self) -> str:
  73. raise NotImplementedError
  74. def get_author(self) -> str:
  75. raise NotImplementedError
  76. def init_parser():
  77. """Prepares the command line parser"""
  78. parser = argparse.ArgumentParser()
  79. parser.add_argument('from_change', help='The oldest changelist to include')
  80. parser.add_argument('to_change', help='The newest changelist to include')
  81. parser.add_argument('--client', help='The Perforce client')
  82. return parser
  83. def main():
  84. parser = init_parser()
  85. args = parser.parse_args()
  86. change = P4SubmittedChangelists(client=args.client, from_change=args.from_change, to_change=args.to_change)
  87. if not validate_commit(commit=change, ignore_validators=["NewlineValidator", "WhitespaceValidator"]):
  88. sys.exit(1)
  89. sys.exit(0)
  90. if __name__ == '__main__':
  91. main()