streamlit

Форк
0
/
run_in_subdirectory.py 
121 строка · 3.6 Кб
1
#!/usr/bin/env python
2
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15

16
import subprocess
17
import sys
18
import textwrap
19
from pathlib import Path
20
from typing import List, Tuple
21

22
if __name__ not in ("__main__", "__mp_main__"):
23
    raise SystemExit(
24
        "This file is intended to be executed as an executable program. You cannot use "
25
        "it as a module.To run this script, run the ./{__file__} command"
26
    )
27

28

29
def is_relative_to(path: Path, *other):
30
    """Return True if the path is relative to another path or False.
31

32
    This function is backported from Python 3.9 - Path.relativeto.
33
    """
34
    try:
35
        path.relative_to(*other)
36
        return True
37
    except ValueError:
38
        return False
39

40

41
def display_usage():
42
    prog = Path(__file__).name
43
    print(
44
        textwrap.dedent(
45
            f"""\
46
    usage: {prog} [-h] SUBDIRECTORY ARGS [ARGS ...]
47

48
    Runs the program in a subdirectory and fix paths in arguments.
49

50
    example:
51

52
    When this program is executed with the following command:
53
       {prog} frontend/ yarn eslint frontend/src/index.ts
54
    Then the command will be executed:
55
        yarn eslint src/index.ts
56
    and the current working directory will be set to frontend/
57

58
    positional arguments:
59
      SUBDIRECTORY  subdirectory within which the subprocess will be executed
60
      ARGS  sequence of program arguments
61

62
    optional arguments:
63
      -h, --help    show this help message and exit\
64
    """
65
        )
66
    )
67

68

69
def parse_args() -> Tuple[str, List[str]]:
70
    if len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help"):
71
        display_usage()
72
        sys.exit(0)
73
    if len(sys.argv) < 3:
74
        print("Missing arguments")
75
        display_usage()
76
        sys.exit(1)
77
    print(sys.argv)
78

79
    return sys.argv[1], sys.argv[2:]
80

81

82
def fix_arg(subdirectory: str, arg: str) -> str:
83
    arg_path = Path(arg)
84
    if not (arg_path.exists() and is_relative_to(arg_path, subdirectory)):
85
        return arg
86
    return str(arg_path.relative_to(subdirectory))
87

88

89
def try_as_shell(fixed_args: List[str], subdirectory: str):
90
    # Windows doesn't know how to run "yarn" using the CreateProcess
91
    # WINAPI because it's looking for an executable, and yarn is a node script.
92
    # Yarn happens to be the only thing currently run with this patching script,
93
    # so add a fall-back which tries to run the requested command in a shell
94
    # if directly calling the process doesn't work.
95
    import shlex
96

97
    print("Direct call failed, trying as shell command:")
98
    shell_cmd = shlex.join(fixed_args)
99
    print(shell_cmd)
100
    try:
101
        subprocess.run(shell_cmd, cwd=subdirectory, check=True, shell=True)
102
    except subprocess.CalledProcessError as ex:
103
        sys.exit(ex.returncode)
104

105

106
def main():
107
    subdirectory, subprocess_args = parse_args()
108

109
    fixed_args = [fix_arg(subdirectory, arg) for arg in subprocess_args]
110
    try:
111
        subprocess.run(fixed_args, cwd=subdirectory, check=True)
112
    except subprocess.CalledProcessError as ex:
113
        sys.exit(ex.returncode)
114
    except FileNotFoundError:
115
        if "win32" in sys.platform:
116
            try_as_shell(fixed_args, subdirectory)
117
        else:
118
            sys.exit(1)
119

120

121
main()
122

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.