get_pr_ut.py 8.2 KB
Newer Older
C
chalsliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
""" For the PR that only modified the unit test, get cases in pull request. """

import os
import json
18 19 20
import re
import sys
import requests
C
chalsliu 已提交
21 22 23
from github import Github

PADDLE_ROOT = os.getenv('PADDLE_ROOT', '/paddle/')
C
chalsliu 已提交
24 25
PADDLE_ROOT += '/'
PADDLE_ROOT = PADDLE_ROOT.replace('//', '/')
C
chalsliu 已提交
26 27 28 29 30 31 32 33


class PRChecker(object):
    """ PR Checker. """

    def __init__(self):
        self.github = Github(os.getenv('GITHUB_API_TOKEN'), timeout=60)
        self.repo = self.github.get_repo('PaddlePaddle/Paddle')
34
        self.py_prog_oneline = re.compile('\d+\|\s*#.*')
C
chalsliu 已提交
35 36
        self.py_prog_multiline_a = re.compile('\d+\|\s*r?""".*?"""', re.DOTALL)
        self.py_prog_multiline_b = re.compile("\d+\|\s*r?'''.*?'''", re.DOTALL)
37 38 39
        self.cc_prog_online = re.compile('\d+\|\s*//.*')
        self.cc_prog_multiline = re.compile('\d+\|\s*/\*.*?\*/', re.DOTALL)
        self.lineno_prog = re.compile('@@ \-\d+,\d+ \+(\d+),(\d+) @@')
C
chalsliu 已提交
40
        self.pr = None
41
        self.suffix = ''
C
chalsliu 已提交
42
        self.full_case = False
C
chalsliu 已提交
43 44 45 46 47 48 49

    def init(self):
        """ Get pull request. """
        pr_id = os.getenv('GIT_PR_ID')
        if not pr_id:
            print('No PR ID')
            exit(0)
50 51 52
        suffix = os.getenv('PREC_SUFFIX')
        if suffix:
            self.suffix = suffix
C
chalsliu 已提交
53
        self.pr = self.repo.get_pull(int(pr_id))
C
chalsliu 已提交
54 55 56 57 58 59 60 61 62 63 64
        last_commit = None
        ix = 0
        while True:
            commits = self.pr.get_commits().get_page(ix)
            for c in commits:
                last_commit = c.commit
            else:
                break
            ix = ix + 1
        if last_commit.message.find('test=full_case') != -1:
            self.full_case = True
C
chalsliu 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78

    def get_pr_files(self):
        """ Get files in pull request. """
        page = 0
        file_list = []
        while True:
            files = self.pr.get_files().get_page(page)
            if not files:
                break
            for f in files:
                file_list.append(PADDLE_ROOT + f.filename)
            page += 1
        return file_list

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    def __get_comment_by_filetype(self, content, filetype):
        result = []
        if filetype == 'py':
            result = self.__get_comment_by_prog(content, self.py_prog_oneline)
            result.extend(
                self.__get_comment_by_prog(content, self.py_prog_multiline_a))
            result.extend(
                self.__get_comment_by_prog(content, self.py_prog_multiline_b))
        if filetype == 'cc':
            result = self.__get_comment_by_prog(content, self.cc_prog_oneline)
            result.extend(
                self.__get_comment_by_prog(content, self.cc_prog_multiline))
        return result

    def __get_comment_by_prog(self, content, prog):
        result_list = prog.findall(content)
        if not result_list:
C
chalsliu 已提交
96 97
            return []
        result = []
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        for u in result_list:
            result.extend(u.split('\n'))
        return result

    def get_comment_of_file(self, f):
        #content = self.repo.get_contents(f.replace(PADDLE_ROOT, ''), 'pull/').decoded_content
        with open(f) as fd:
            lines = fd.readlines()
        lineno = 1
        inputs = ''
        for line in lines:
            #for line in content.split('\n'):
            #input += str(lineno) + '|' + line + '\n'
            inputs += str(lineno) + '|' + line
            lineno += 1
        fietype = ''
        if f.endswith('.h') or f.endswith('.cc') or f.endswith('.cu'):
            filetype = 'cc'
        if f.endswith('.py'):
            filetype = 'py'
        else:
C
chalsliu 已提交
119
            return []
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        return self.__get_comment_by_filetype(inputs, filetype)

    def get_pr_diff_lines(self):
        file_to_diff_lines = {}
        r = requests.get(self.pr.diff_url)
        data = r.text
        data = data.split('\n')
        ix = 0
        while ix < len(data):
            if data[ix].startswith('+++'):
                if data[ix].rstrip('\r\n') == '+++ /dev/null':
                    ix += 1
                    continue
                filename = data[ix][6:]
                ix += 1
                while ix < len(data):
                    result = self.lineno_prog.match(data[ix])
                    if not result:
                        break
                    lineno = int(result.group(1))
                    length = int(result.group(2))
                    ix += 1
                    end = ix + length
                    while ix < end:
                        if data[ix][0] == '-':
                            end += 1
                        if data[ix][0] == '+':
                            line_list = file_to_diff_lines.get(filename)
C
chalsliu 已提交
148 149
                            line = '{}{}'.format(lineno,
                                                 data[ix].replace('+', '|', 1))
150 151 152 153 154 155 156 157 158 159 160 161 162
                            if line_list:
                                line_list.append(line)
                            else:
                                file_to_diff_lines[filename] = [line, ]
                        if data[ix][0] != '-':
                            lineno += 1
                        ix += 1
            ix += 1
        return file_to_diff_lines

    def is_only_comment(self, f):
        file_to_diff_lines = self.get_pr_diff_lines()
        comment_lines = self.get_comment_of_file(f)
C
chalsliu 已提交
163 164 165
        diff_lines = file_to_diff_lines.get(f.replace(PADDLE_ROOT, '', 1))
        if not diff_lines:
            return False
166 167 168 169 170
        for l in diff_lines:
            if l not in comment_lines:
                return False
        return True

C
chalsliu 已提交
171 172
    def get_pr_ut(self):
        """ Get unit tests in pull request. """
C
chalsliu 已提交
173 174
        if self.full_case:
            return ''
C
chalsliu 已提交
175
        check_added_ut = False
C
chalsliu 已提交
176 177
        ut_list = []
        file_ut_map = None
C
chalsliu 已提交
178
        cmd = 'wget -q --no-proxy --no-check-certificate https://sys-p0.bj.bcebos.com/prec/file_ut.json' + self.suffix
C
chalsliu 已提交
179
        os.system(cmd)
180
        with open('file_ut.json' + self.suffix) as jsonfile:
C
chalsliu 已提交
181 182
            file_ut_map = json.load(jsonfile)
        for f in self.get_pr_files():
C
chalsliu 已提交
183
            if f not in file_ut_map:
184 185 186 187 188 189 190
                if f.endswith('.md'):
                    ut_list.append('md_placeholder')
                elif f.endswith('.h') or f.endswith('.cu'):
                    if self.is_only_comment(f):
                        ut_list.append('h_cu_comment_placeholder')
                    else:
                        return ''
C
chalsliu 已提交
191 192
                elif f.endswith('.cc') or f.endswith('.py') or f.endswith(
                        '.cu'):
193 194 195
                    if f.find('test_') != -1 or f.find('_test') != -1:
                        check_added_ut = True
                    elif self.is_only_comment(f):
C
chalsliu 已提交
196
                        ut_list.append('nomap_comment_placeholder')
197 198
                    else:
                        return ''
C
chalsliu 已提交
199 200
                else:
                    return ''
C
chalsliu 已提交
201
            else:
202
                if self.is_only_comment(f):
C
chalsliu 已提交
203
                    ut_list.append('map_comment_placeholder')
204 205
                else:
                    ut_list.extend(file_ut_map.get(f))
C
chalsliu 已提交
206
        ut_list = list(set(ut_list))
C
chalsliu 已提交
207
        cmd = 'wget -q --no-proxy --no-check-certificate https://sys-p0.bj.bcebos.com/prec/prec_delta' + self.suffix
C
chalsliu 已提交
208
        os.system(cmd)
209
        with open('prec_delta' + self.suffix) as delta:
C
chalsliu 已提交
210 211 212
            for ut in delta:
                ut_list.append(ut.rstrip('\r\n'))

C
chalsliu 已提交
213
        if check_added_ut:
C
chalsliu 已提交
214 215
            cmd = 'bash {}/tools/check_added_ut.sh >/tmp/pre_ut 2>&1'.format(
                PADDLE_ROOT)
C
chalsliu 已提交
216
            os.system(cmd)
C
chalsliu 已提交
217 218 219
            with open('{}/added_ut'.format(PADDLE_ROOT)) as utfile:
                for ut in utfile:
                    ut_list.append(ut.rstrip('\r\n'))
C
chalsliu 已提交
220

C
chalsliu 已提交
221 222 223 224 225 226 227
        return ' '.join(ut_list)


if __name__ == '__main__':
    pr_checker = PRChecker()
    pr_checker.init()
    print(pr_checker.get_pr_ut())