#!/usr/bin/env python3
# Copyright (C) 2020 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This tool checks for inline comments in proto files

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import re
import sys

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def main():
  errors = 0
  # Don't want to check protos/third_party:
  protos_root = os.path.join(ROOT_DIR, 'protos', 'perfetto')
  for root, _, files in os.walk(protos_root):
    for fname in files:
      fpath = os.path.join(root, fname)
      if not os.path.isfile(fpath):
        continue
      if not fpath.endswith('.proto'):
        continue
      with open(fpath, encoding='UTF-8') as f:
        lines = f.readlines()
      for line in lines:
        comm = line.find('//')
        alt_comm = re.search(r'^\s*\*', line)
        only_comm = re.search(r'^\s*//', line)

        # Allow comments only if not inline
        if comm == -1 or alt_comm or only_comm:
          continue

        rel_path = os.path.relpath(fpath, ROOT_DIR)
        sys.stderr.write(('Proto file %s has inline comment, please move to ' +
                          'the previous line:\t%s') % (rel_path, line))
        errors += 1

  return 0 if errors == 0 else 1


if __name__ == '__main__':
  sys.exit(main())
