Debian Codegraph @

mesonbuild/minit.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2017 The Meson development team
3
4 """Code that creates simple startup projects."""
5
6 from __future__ import annotations
7
8 from pathlib import Path
9 from enum import Enum
10 import subprocess
11 import shutil
12 import sys
13 import os
14 import re
15 from glob import glob
16 import typing as T
17
18 from mesonbuild import build, mesonlib, mlog
19 from mesonbuild.coredata import FORBIDDEN_TARGET_NAMES
20 from mesonbuild.tooldetect import detect_ninja
21 from mesonbuild.templates.mesontemplates import create_meson_build
22 from mesonbuild.templates.samplefactory import sample_generator
23 from mesonbuild.options import OptionKey
24
25 if T.TYPE_CHECKING:
26 import argparse
27
28 from typing_extensions import Protocol, Literal
29
30 class Arguments(Protocol):
31
32 srcfiles: T.List[Path]
33 wd: str
34 name: str
35 executable: str
36 deps: str
37 language: Literal['c', 'cpp', 'cs', 'cuda', 'd', 'fortran', 'java', 'rust', 'objc', 'objcpp', 'vala']
38 build: bool
39 builddir: str
40 force: bool
41 type: Literal['executable', 'library']
42 version: str
43
44
45 FORTRAN_SUFFIXES = {'.f', '.for', '.F', '.f90', '.F90'}
46 LANG_SUFFIXES = {'.c', '.cc', '.cpp', '.cs', '.cu', '.d', '.m', '.mm', '.rs', '.java', '.vala'} | FORTRAN_SUFFIXES
47 LANG_SUPPORTED = {'c', 'cpp', 'cs', 'cuda', 'd', 'fortran', 'java', 'rust', 'objc', 'objcpp', 'vala'}
48
49 DEFAULT_PROJECT = 'executable'
50 DEFAULT_VERSION = '0.1'
51 class DEFAULT_TYPES(Enum):
52 EXE = 'executable'
53 LIB = 'library'
54
55 INFO_MESSAGE = '''Sample project created. To build it run the
56 following commands:
57
58 meson setup builddir
59 meson compile -C builddir
60 '''
61
62
63 def create_sample(options: Arguments) -> None:
64 '''
65 Based on what arguments are passed we check for a match in language
66 then check for project type and create new Meson samples project.
67 '''
68 sample_gen = sample_generator(options)
69 if options.type == DEFAULT_TYPES['EXE'].value:
70 sample_gen.create_executable()
71 elif options.type == DEFAULT_TYPES['LIB'].value:
72 sample_gen.create_library()
73 else:
74 raise RuntimeError('Unreachable code')
75 print(INFO_MESSAGE)
76
77 def autodetect_options(options: Arguments, sample: bool = False) -> None:
78 '''
79 Here we autodetect options for args not passed in so don't have to
80 think about it.
81 '''
82 if not options.name:
83 options.name = Path().resolve().stem
84 if not re.match('[a-zA-Z_][a-zA-Z0-9]*', options.name) and sample:
85 raise SystemExit(f'Name of current directory "{options.name}" is not usable as a sample project name.\n'
86 'Specify a project name with --name.')
87 print(f'Using "{options.name}" (name of current directory) as project name.')
88 if not options.executable:
89 options.executable = options.name
90 print(f'Using "{options.executable}" (project name) as name of executable to build.')
91 if options.executable in FORBIDDEN_TARGET_NAMES:
92 raise mesonlib.MesonException(f'Executable name {options.executable!r} is reserved for Meson internal use. '
93 'Refusing to init an invalid project.')
94 if sample:
95 # The rest of the autodetection is not applicable to generating sample projects.
96 return
97 if not options.srcfiles:
98 srcfiles: T.List[Path] = []
99 for f in (f for f in Path().iterdir() if f.is_file()):
100 if f.suffix in LANG_SUFFIXES:
101 srcfiles.append(f)
102 if not srcfiles:
103 raise SystemExit('No recognizable source files found.\n'
104 'Run meson init in an empty directory to create a sample project.')
105 options.srcfiles = srcfiles
106 print("Detected source files: " + ' '.join(str(s) for s in srcfiles))
107 if not options.language:
108 for f in options.srcfiles:
109 if f.suffix == '.c':
110 options.language = 'c'
111 break
112 if f.suffix in {'.cc', '.cpp'}:
113 options.language = 'cpp'
114 break
115 if f.suffix == '.cs':
116 options.language = 'cs'
117 break
118 if f.suffix == '.cu':
119 options.language = 'cuda'
120 break
121 if f.suffix == '.d':
122 options.language = 'd'
123 break
124 if f.suffix in FORTRAN_SUFFIXES:
125 options.language = 'fortran'
126 break
127 if f.suffix == '.rs':
128 options.language = 'rust'
129 break
130 if f.suffix == '.m':
131 options.language = 'objc'
132 break
133 if f.suffix == '.mm':
134 options.language = 'objcpp'
135 break
136 if f.suffix == '.java':
137 options.language = 'java'
138 break
139 if f.suffix == '.vala':
140 options.language = 'vala'
141 break
142 if not options.language:
143 raise SystemExit("Can't autodetect language, please specify it with -l.")
144 print("Detected language: " + options.language)
145
146 # Note: when adding arguments, please also add them to the completion
147 # scripts in $MESONSRC/data/shell-completions/
148 def add_arguments(parser: 'argparse.ArgumentParser') -> None:
149 '''
150 Here we add args for that the user can passed when making a new
151 Meson project.
152 '''
153 parser.add_argument("srcfiles", metavar="sourcefile", nargs="*", type=Path, help="source files. default: all recognized files in current directory")
154 parser.add_argument('-C', dest='wd', action=mesonlib.RealPathAction,
155 help='directory to cd into before running')
156 parser.add_argument("-n", "--name", help="project name. default: name of current directory")
157 parser.add_argument("-e", "--executable", help="executable name. default: project name")
158 parser.add_argument("-d", "--deps", help="dependencies, comma-separated")
159 parser.add_argument("-l", "--language", choices=sorted(LANG_SUPPORTED), help="project language. default: autodetected based on source files")
160 parser.add_argument("-b", "--build", action='store_true', help="build after generation")
161 parser.add_argument("--builddir", default='build', help="directory for build")
162 parser.add_argument("-f", "--force", action="store_true", help="force overwrite of existing files and directories.")
163 parser.add_argument('--type', default=DEFAULT_PROJECT, choices=('executable', 'library'), help=f"project type. default: {DEFAULT_PROJECT} based project")
164 parser.add_argument('--version', default=DEFAULT_VERSION, help=f"project version. default: {DEFAULT_VERSION}")
165
166 def run(options: Arguments) -> int:
167 '''
168 Here we generate the new Meson sample project.
169 '''
170 if not Path(options.wd).exists():
171 sys.exit('Project source root directory not found. Run this command in source directory root.')
172 os.chdir(options.wd)
173
174 if not glob('*'):
175 autodetect_options(options, sample=True)
176 if not options.language:
177 print('Defaulting to generating a C language project.')
178 options.language = 'c'
179 create_sample(options)
180 else:
181 autodetect_options(options)
182 if Path('meson.build').is_file() and not options.force:
183 raise SystemExit('meson.build already exists. Use --force to overwrite.')
184 create_meson_build(options)
185 if options.build:
186 if Path(options.builddir).is_dir() and options.force:
187 print('Build directory already exists, deleting it.')
188 shutil.rmtree(options.builddir)
189 print('Building...')
190 cmd = mesonlib.get_meson_command() + ['setup', options.builddir]
191 ret = subprocess.run(cmd)
192 if ret.returncode:
193 raise SystemExit
194
195 b = build.load(options.builddir)
196 need_vsenv = T.cast('bool', b.environment.coredata.optstore.get_value_for(OptionKey('vsenv')))
197 vsenv_active = mesonlib.setup_vsenv(need_vsenv)
198 if vsenv_active:
199 mlog.log(mlog.green('INFO:'), 'automatically activated MSVC compiler environment')
200
201 ninja = mesonlib.unwrap_err(detect_ninja(), 'Could not detect ninja and it is required')
202 cmd = ninja + ['-C', options.builddir]
203 ret = subprocess.run(cmd)
204 if ret.returncode:
205 raise SystemExit
206 return 0