1#!/usr/bin/env python
2#
3# Copyright (C) 2021 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18"""CLI script for linting .proto files inside update_engine."""
19
20import sys
21import re
22import subprocess
23
24def check_proto_file(commit_hash, filename):
25  """Check if |filename| is consistnet with our protobuf guidelines
26
27    Args:
28      commit_hash: Hash of the git commit to look
29      filename: A filesystem path to a .proto file
30    Returns:
31      True if this file passes linting check, False otherwise
32  """
33  output = subprocess.check_output(
34      ["git", "diff", commit_hash+"~", commit_hash, "--", filename])
35  output = output.decode()
36  p = re.compile(r"^[+]?\s*required .*$", re.M)
37  m = p.search(output)
38  if m:
39    print("File", filename,
40          "contains 'required' keyword. Usage of required",
41          "is strongly discouraged in protobuf", m.group())
42    return False
43  return True
44
45def main():
46  if len(sys.argv) < 2:
47    print("Usage:", sys.argv[0], "commit_hash", "<file1>", "<file2>", "...")
48    sys.exit(1)
49  commit_hash = sys.argv[1]
50  for filename in sys.argv[2:]:
51    if filename.endswith(".proto"):
52      if not check_proto_file(commit_hash, filename):
53        sys.exit(1)
54
55if __name__ == "__main__":
56  main()
57