File: PRESUBMIT.py

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (127 lines) | stat: -rw-r--r-- 5,454 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# Copyright 2022 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for //ui/file_manager/base/gn.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""

import sys

PRESUBMIT_VERSION = '2.0.0'


def _load_json_data(input_api, file_path):
    """ Loads json data from the file |file_path| via json5 module.
    Args:
        input_api: InputApi instance from depot_tools's presumbit_support.py
        file_path: the full file path string.
    Returns:
        The loaded json data.
    """
    try:
        json5_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
                                            '..', '..', '..', '..',
                                            'third_party', 'pyjson5', 'src')
        sys.path.append(json5_path)
        import json5
        return json5.load(open(file_path, encoding='utf-8'))
    finally:
        # Restore sys.path to what it was before.
        sys.path.remove(json5_path)


def _validate_json_schema(json_data, file_path, output_api):
    """ Validates the json schema for the json data |json_data|.
    Args:
        json_data: The json data to be validated.
        file_path: the full file path string.
        output_api: OutputApi instance from depot_tools's presumbit_support.py
    Returns:
        The validation result array which contains various presubmit error
        messages. Empty array will return if the json data passes the
        validation.
    """
    validation_results = []
    if not isinstance(json_data, list):
        validation_results.append(
            output_api.PresubmitError(f'{file_path}: must be a json array.'))
    else:
        required_str_fields = ['translationKey', 'type', 'subtype']
        for item in json_data:
            for field in required_str_fields:
                if not isinstance(item.get(field), str):
                    validation_results.append(
                        output_api.PresubmitError(
                            f'{file_path}: field "{field}" must be a string for'
                            ' each file type.'))
            # Field "icon" is optional.
            if 'icon' in item and not isinstance(item['icon'], str):
                validation_results.append(
                    output_api.PresubmitError(
                        f'{file_path}: field "icon" must be a string for each'
                        ' file type.'))
            # Field "mime" is optional.
            if 'mime' in item and not isinstance(item['mime'], str):
                validation_results.append(
                    output_api.PresubmitError(
                        f'{file_path}: field "mime" must be a string for each'
                        ' file type.'))
            if isinstance(item.get('extensions'), list):
                if not item['extensions']:
                    validation_results.append(
                        output_api.PresubmitError(
                            f'{file_path}: "extensions" array needs to include'
                            ' at least 1 file extension.'))
                else:
                    missing_dots = [
                        ext for ext in item['extensions']
                        if not (ext and ext.startswith('.'))
                    ]
                    if missing_dots:
                        validation_results.append(
                            output_api.PresubmitError(
                                f'{file_path}: the following extension(s)'
                                ' should start with dot'
                                ' "{", ".join(missing_dots)}"'))
                    unique_ext_keys = len(set(item['extensions']))
                    if unique_ext_keys != len(item['extensions']):
                        validation_results.append(
                            output_api.PresubmitError(
                                f'{file_path}: "extensions" array should not'
                                ' include duplicate extensions.'))
            else:
                validation_results.append(
                    output_api.PresubmitError(
                        f'{file_path}: field "extensions" must be an array for'
                        ' each file type.'))

    return validation_results


def CheckFileTypesJSONSchema(input_api, output_api):
    """ Main check function during PreSubmit.
    Args:
        input_api: InputApi instance from depot_tools's presumbit_support.py
        output_api: OutputApi instance from depot_tools's presumbit_support.py
    Returns:
        The result array which contains various presubmit error messages.
    """
    file_name = 'file_types.json5'
    file_path = input_api.os_path.relpath(
        input_api.os_path.join(input_api.PresubmitLocalPath(), file_name),
        input_api.change.RepositoryRoot())
    file_types_json = input_api.AffectedSourceFiles(lambda x: x.LocalPath() ==
                                                    file_path)
    if not file_types_json:
        return []

    results = []
    try:
        data = _load_json_data(input_api, file_name)
        results.extend(_validate_json_schema(data, file_path, output_api))
    except ValueError as err:
        results.append(
            output_api.PresubmitError(f'{file_path}: must be a valid json.'))
    return results