1#!/usr/bin/env bash
2
3# Copyright (C) 2016 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### Scan this directory for any testng classes
19### Outputs a testng.xml formatted list of classes
20###
21
22DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
23test_property_files="$(find "$DIR" -name TEST.properties)"
24
25function debug_print {
26  if [[ $DEBUG == "true" ]]; then
27    echo "DEBUG:" "$@" >& 2
28  fi
29}
30
31function error_print {
32  echo "ERROR:" "$@" >& 2
33  exit 1
34}
35
36function class_name_from_class_file {
37  # Reads a list of .java files from stdin, spits out their fully qualified class name.
38  local file_name
39  local package_string
40  local package_name
41  local class_name
42  while read file_name; do
43    package_string="$(grep "package" "$file_name")"
44    [[ $? -ne 0 ]] && error_print "File $file_name missing package declaration."
45    debug_print "File: $file_name"
46
47    # Parse the package name by looking inside of the file.
48    package_name=${package_string#package[[:space:]]*}  # remove package followed by any spaces
49    package_name=${package_name%;} # remove semicolon at the end
50
51    # Assumes class name == file name. Almost always the case.
52    class_name="$(basename "$file_name")"
53    class_name="${class_name%.java}" # remove ".java" from the end
54    debug_print "Package: <$package_name>"
55
56    echo "$package_name.$class_name"
57  done
58}
59
60function list_classes_in_dir {
61  find "$1" -name "*.java" | class_name_from_class_file
62}
63
64function list_all_classes {
65  local file
66  for file in $test_property_files; do
67    debug_print "File: $file"
68
69    if ! grep "TestNG.dirs" "$file" > /dev/null; then
70      continue
71    fi
72
73    debug_print "Has TestNG files"
74
75    list_classes_in_dir "$(dirname "$file")"
76  done
77}
78
79function class_name_to_testng_entry {
80  local class_name
81  while read class_name; do
82    echo "<class name=\"$class_name\" />"
83  done
84}
85
86list_all_classes | class_name_to_testng_entry
87