p4_validate_changelist.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. import difflib
  13. from commit_validation.commit_validation import Commit, validate_commit
  14. from p4 import run_p4_command
  15. class P4Changelist(Commit):
  16. """An implementation of the :class:`Commit` interface for accessing details about a Perforce changelist"""
  17. def __init__(self, client: str = None, change: str = 'default') -> None:
  18. """Creates a new instance of :class:`P4Changelist`
  19. :param client: the Perforce client
  20. :param change: the Perforce changelist
  21. """
  22. self.client = client
  23. self.change = change
  24. self.files: List[str] = []
  25. self.removed_files: List[str] = []
  26. self.file_diffs: Dict[str, str] = {}
  27. self._load_files()
  28. def _load_files(self):
  29. self.files = []
  30. self.removed_files = []
  31. self.added_files = []
  32. client_spec = run_p4_command(f'client -o', client=self.client)[0]
  33. files = run_p4_command(f'opened -c {self.change}', client=self.client)
  34. for f in files:
  35. file_path = os.path.abspath(f['clientFile'].replace(f'//{client_spec["Client"]}', client_spec['Root']))
  36. if 'delete' in f['action']:
  37. self.removed_files.append(file_path)
  38. elif 'add' in f['action']:
  39. self.added_files.append(file_path)
  40. elif 'branch' in f['action']:
  41. self.added_files.append(file_path)
  42. else:
  43. self.files.append(file_path)
  44. def get_file_diff(self, file) -> str:
  45. if file in self.file_diffs: # allow caching
  46. return self.file_diffs[file]
  47. if file in self.added_files: # added files return the entire file as a diff.
  48. with open(file, "rt", encoding='utf8', errors='replace') as opened_file:
  49. data = opened_file.readlines()
  50. diffs = difflib.unified_diff([], data, fromfile=file, tofile=file)
  51. diff_being_built = ''.join(diffs)
  52. self.file_diffs[file] = diff_being_built
  53. return diff_being_built
  54. if file not in self.files:
  55. raise RuntimeError(f"Cannot calculate a diff for a file not in the changelist: {file}")
  56. try:
  57. result = run_p4_command(f'diff -du {file}', client=self.client)
  58. if len(result) > 1:
  59. diff = result[1]['data'] # p4 returns a normal code but with no result if theres no diff
  60. else:
  61. diff = ''
  62. print(f'Warning: File being committed contains no changes {file}')
  63. # note that the p4 command handles the data and errors internally, no need to check.
  64. self.file_diffs[file] = diff
  65. return diff
  66. except RuntimeError as e:
  67. print(f'error during p4 operation, unable to get a diff: {e}')
  68. return ''
  69. def get_files(self) -> List[str]:
  70. # this is just files relevant to the operation
  71. return self.files + self.added_files
  72. def get_removed_files(self) -> List[str]:
  73. return self.removed_files
  74. def get_description(self) -> str:
  75. raise NotImplementedError
  76. def get_author(self) -> str:
  77. raise NotImplementedError
  78. def init_parser():
  79. """Prepares the command line parser"""
  80. parser = argparse.ArgumentParser()
  81. parser.add_argument('--client', help='Perforce client')
  82. parser.add_argument('--change', default='default', help='Perforce changelist')
  83. return parser
  84. def main():
  85. parser = init_parser()
  86. args = parser.parse_args()
  87. change = P4Changelist(client=args.client, change=args.change)
  88. if not validate_commit(commit=change, ignore_validators=["NewlineValidator", "WhitespaceValidator"]):
  89. sys.exit(1)
  90. sys.exit(0)
  91. if __name__ == '__main__':
  92. main()