1# SPDX-License-Identifier: GPL-2.0+
2# Copyright (c) 2012 The Chromium OS Authors.
3# Copyright (c) 2022 Maxim Cournoyer <maxim.cournoyer@savoirfairelinux.com>
4#
5
6import os
7import shlex
8import shutil
9
10from patman import gitutil
11from u_boot_pylib import command
12
13
14def find_get_maintainer(script_file_name):
15    """Try to find where `script_file_name` is.
16
17    It searches in PATH and falls back to a path relative to the top
18    of the current git repository.
19    """
20    get_maintainer = shutil.which(script_file_name)
21    if get_maintainer:
22        return get_maintainer
23
24    git_relative_script = os.path.join(gitutil.get_top_level(),
25                                       script_file_name)
26    if os.path.exists(git_relative_script):
27        return git_relative_script
28
29
30def get_maintainer(script_file_name, fname, verbose=False):
31    """Run `script_file_name` on a file.
32
33    `script_file_name` should be a get_maintainer.pl-like script that
34    takes a patch file name as an input and return the email addresses
35    of the associated maintainers to standard output, one per line.
36
37    If `script_file_name` does not exist we fail silently.
38
39    Args:
40        script_file_name: The file name of the get_maintainer.pl script
41            (or compatible).
42        fname: File name of the patch to process with get_maintainer.pl.
43
44    Returns:
45        A list of email addresses to CC to.
46    """
47    # Expand `script_file_name` into a file name and its arguments, if
48    # any.
49    cmd_args = shlex.split(script_file_name)
50    file_name = cmd_args[0]
51    arguments = cmd_args[1:]
52
53    get_maintainer = find_get_maintainer(file_name)
54    if not get_maintainer:
55        if verbose:
56            print("WARNING: Couldn't find get_maintainer.pl")
57        return []
58
59    stdout = command.output(get_maintainer, *arguments, fname)
60    lines = stdout.splitlines()
61    return [x.replace('"', '') for x in lines]
62