Debian Codegraph @

src/briefcase/commands/new.py

raw
1 from __future__ import annotations
2
3 import re
4 import unicodedata
5 from collections import OrderedDict
6 from email.utils import parseaddr
7 from importlib.metadata import entry_points
8
9 from briefcase.bootstraps import BaseGuiBootstrap
10 from briefcase.config import (
11 is_valid_app_name,
12 is_valid_bundle_identifier,
13 make_class_name,
14 validate_url,
15 )
16 from briefcase.exceptions import BriefcaseCommandError
17 from briefcase.integrations.git import Git
18
19 from .base import BaseCommand
20
21 LICENSE_OPTIONS = {
22 "BSD-3-Clause": 'BSD 3-Clause "New" or "Revised" License (BSD-3-Clause)',
23 "MIT": "MIT License (MIT)",
24 "Apache-2.0": "Apache License 2.0 (Apache-2.0)",
25 "GPL-2.0": "GNU General Public License v2.0 only (GPL-2.0)",
26 "GPL-2.0+": "GNU General Public License v2.0 or later (GPL-2.0+)",
27 "GPL-3.0": "GNU General Public License v3.0 only (GPL-3.0)",
28 "GPL-3.0+": "GNU General Public License v3.0 or later (GPL-3.0+)",
29 "Proprietary": "Proprietary",
30 "Other": "Other",
31 }
32 DEFAULT_LICENSE = "BSD-3-Clause"
33
34
35 def get_gui_bootstraps() -> dict[str, type[BaseGuiBootstrap]]:
36 """Loads built-in and third-party GUI bootstraps."""
37 return {
38 entry_point.name: entry_point.load()
39 for entry_point in entry_points(group="briefcase.bootstraps")
40 }
41
42
43 def parse_project_overrides(project_overrides: list[str]) -> dict[str, str]:
44 """Parse the command-line arguments to override new project defaults."""
45 overrides = {}
46
47 if project_overrides:
48 for override in project_overrides:
49 try:
50 key, value = override.split("=", 1)
51 except ValueError as e:
52 raise BriefcaseCommandError(
53 f"Unable to parse project configuration override {override!r}"
54 ) from e
55 else:
56 if not ((key := key.strip()) and (value := value.strip())):
57 raise BriefcaseCommandError(
58 f"Invalid Project configuration override {override!r}"
59 )
60 if key in overrides:
61 raise BriefcaseCommandError(
62 f"Project configuration override {key!r} specified multiple "
63 f"times"
64 )
65 overrides[key] = value
66 return overrides
67
68
69 class NewCommand(BaseCommand):
70 cmd_line = "briefcase new"
71 command = "new"
72 platform = "all"
73 output_format = ""
74 description = "Create a new Briefcase project."
75
76 def bundle_path(self, app):
77 """A placeholder; New command doesn't have a bundle path."""
78 raise NotImplementedError()
79
80 def binary_path(self, app):
81 """A placeholder; New command doesn't have a binary path."""
82 raise NotImplementedError()
83
84 def parse_config(self, filename, overrides):
85 """There is no configuration when starting a new project; this implementation
86 overrides the base so that no config is parsed."""
87
88 def add_options(self, parser):
89 parser.add_argument(
90 "-t",
91 "--template",
92 dest="template",
93 help="The cookiecutter template to use for the new project",
94 )
95
96 parser.add_argument(
97 "--template-branch",
98 dest="template_branch",
99 help="The branch of the cookiecutter template to use for the new project",
100 )
101
102 parser.add_argument(
103 "-Q",
104 dest="project_overrides",
105 action="append",
106 metavar="KEY=VALUE",
107 help="Override the value of the project configuration item KEY with VALUE",
108 )
109
110 def make_app_name(self, formal_name):
111 """Construct a candidate app name from a formal name.
112
113 :param formal_name: The formal name
114 :returns: The candidate app name
115 """
116 normalized = unicodedata.normalize("NFKD", formal_name)
117 stripped = re.sub("[^0-9a-zA-Z_]+", "", normalized).lstrip("_")
118 if stripped:
119 return stripped.lower()
120 else:
121 # If stripping removes all the content,
122 # use a dummy app name as the suggestion.
123 return "myapp"
124
125 def validate_formal_name(self, candidate):
126 """Determine if the formal name is valid.
127
128 A formal name is valid if it contains at least one identifier character.
129
130 :param candidate: The candidate name
131 :returns: True the formal name is valid.
132 :raises: ValueError if the name is not a valid formal name.
133 """
134 if not make_class_name(candidate): # Check whether a class name may be derived
135 raise ValueError(
136 self.console.textwrap(
137 f"{candidate!r} is not a valid formal name.\n"
138 "\n"
139 "Formal names must include at least one valid Python identifier "
140 "character."
141 )
142 )
143
144 return True
145
146 def _validate_existing_app_name(self, candidate):
147 """Perform internal validation preventing the use of pre-existing app names.
148
149 Invoked by validate_app_name; subclasses may override this behavior.
150 """
151 if (self.base_path / candidate).exists():
152 raise ValueError(
153 self.console.textwrap(
154 f"A {candidate!r} directory already exists.\n"
155 f"\n"
156 f"Select a different name, move to a different parent directory, "
157 f"or delete the existing folder."
158 )
159 )
160
161 def validate_app_name(self, candidate):
162 """Determine if the app name is valid.
163
164 :param candidate: The candidate name
165 :returns: True. If there are any validation problems, raises ValueError with a
166 diagnostic message.
167 """
168 if not is_valid_app_name(candidate):
169 raise ValueError(
170 self.console.textwrap(
171 f"{candidate!r} is not a valid app name.\n"
172 "\n"
173 "App names must not be reserved keywords such as 'and', 'for' and "
174 "'while'. They must also be PEP508 compliant (i.e., they can only "
175 "include letters, numbers, '-' and '_'; must start with a letter; "
176 "and cannot end with '-' or '_')."
177 )
178 )
179
180 # Validate if the existing app name
181 self._validate_existing_app_name(candidate)
182
183 return True
184
185 def make_module_name(self, app_name):
186 """Construct a valid module name from an app name.
187
188 :param app_name: The app name
189 :returns: The app's module name.
190 """
191 return app_name.replace("-", "_")
192
193 def validate_bundle(self, candidate):
194 """Determine if the bundle identifier is valid.
195
196 :param candidate: The candidate bundle identifier
197 :returns: True. If there are any validation problems, raises ValueError with a
198 diagnostic message.
199 """
200 if not is_valid_bundle_identifier(candidate):
201 raise ValueError(
202 self.console.textwrap(
203 f"{candidate!r} is not a valid bundle identifier.\n"
204 "\n"
205 "The bundle should be a reversed domain name. It must contain at "
206 "least 2 dot-separated sections; each section may only include "
207 "letters, numbers, and hyphens; and each section may not contain "
208 "any reserved words (like 'switch', or 'while')."
209 )
210 )
211
212 return True
213
214 def make_domain(self, bundle):
215 """Construct a candidate domain from a bundle identifier.
216
217 :param bundle: The bundle identifier
218 :returns: The candidate domain
219 """
220 return ".".join(bundle.split(".")[::-1])
221
222 def make_author_email(self, author, bundle):
223 """Construct a candidate email address from the authors name and the bundle
224 identifier.
225
226 The candidate is based on the assumption that the author's name is in
227 "first/last" format, or it a corporate name; the "first" part is split off, and
228 prepended to the domain extracted from the bundle.
229
230 It's not a perfect system, but it's better than putting up "[email protected]" as a
231 candidate default value.
232
233 :param author: The authors name.
234 :param bundle: The bundle identifier.
235 :returns: The candidate author's name
236 """
237 return f"{author.split(' ')[0].lower()}@{self.make_domain(bundle)}"
238
239 def validate_email(self, candidate):
240 """Determine if the email address is valid.
241
242 :param candidate: The candidate email address
243 :returns: True. If there are any validation problems, raises ValueError with a
244 diagnostic message.
245 """
246 if parseaddr(candidate)[1] != candidate:
247 raise ValueError("Not a valid email address")
248 return True
249
250 def make_project_url(self, bundle, app_name):
251 """Construct a candidate project URL from the bundle and app name.
252
253 It's not a perfect guess, but it's better than having
254 "https://example.com".
255
256 :param bundle: The bundle identifier.
257 :param app_name: The app name.
258 :returns: The candidate project URL
259 """
260 return f"https://{self.make_domain(bundle)}/{app_name}"
261
262 def input_project_name(self, formal_name, override_value):
263 return self.console.text_question(
264 intro=(
265 "Briefcase can manage projects that contain multiple applications, so "
266 "we need a Project name.\n"
267 "\n"
268 "If you're only planning to have one application in this project, you "
269 "can use the formal name as the project name."
270 ),
271 description="Project Name",
272 default=formal_name,
273 override_value=override_value,
274 )
275
276 def input_license(self, override_value: str | None) -> str:
277 return self.console.selection_question(
278 intro="What license do you want to use for this project's code?",
279 description="Project License",
280 options=LICENSE_OPTIONS,
281 default=DEFAULT_LICENSE,
282 override_value=override_value,
283 )
284
285 def build_app_context(self, project_overrides: dict[str, str]) -> dict[str, str]:
286 """Ask the user for details about the app to be created.
287
288 :returns: A context dictionary to be used in the cookiecutter project template.
289 """
290 formal_name = self.console.text_question(
291 intro=(
292 "First, we need a formal name for your application.\n"
293 "\n"
294 "This is the name that will be displayed to humans whenever the name "
295 "of the application is displayed. It can have spaces and punctuation "
296 "if you like, and any capitalization will be used as you type it."
297 ),
298 description="Formal Name",
299 default="Hello World",
300 validator=self.validate_formal_name,
301 override_value=project_overrides.pop("formal_name", None),
302 )
303
304 # The class name can be completely derived from the formal name.
305 class_name = make_class_name(formal_name)
306
307 default_app_name = self.make_app_name(formal_name)
308 app_name = self.console.text_question(
309 intro=(
310 "Next, we need a name that can serve as a machine-readable Python "
311 "package name for your application.\n"
312 "\n"
313 "This name must be PEP508-compliant - that means the name may only "
314 "contain letters, numbers, hyphens and underscores; it can't contain "
315 "spaces or punctuation, and it can't start with a hyphen or "
316 "underscore.\n"
317 "\n"
318 "Based on your formal name, we suggest an app name of "
319 f"{default_app_name!r}, but you can use another name if you want."
320 ),
321 description="App Name",
322 default=default_app_name,
323 validator=self.validate_app_name,
324 override_value=project_overrides.pop("app_name", None),
325 )
326
327 # The module name can be completely derived from the app name.
328 module_name = self.make_module_name(app_name)
329 source_dir = f"src/{module_name}"
330 test_source_dir = "tests"
331
332 bundle = self.console.text_question(
333 intro=(
334 "Now we need a bundle identifier for your application."
335 "\n\n"
336 "App stores need to protect against having multiple applications with "
337 "the same name; the bundle identifier is the namespace they use to "
338 "identify applications that come from you. The bundle identifier is "
339 "usually the domain name of your company or project, in reverse order."
340 "\n\n"
341 "For example, if you are writing an application for Example Corp, "
342 "whose website is example.com, your bundle would be 'com.example'. "
343 "The bundle will be combined with your application's machine readable "
344 "name to form a complete application identifier (e.g., "
345 f"com.example.{app_name})."
346 ),
347 description="Bundle Identifier",
348 default="com.example",
349 validator=self.validate_bundle,
350 override_value=project_overrides.pop("bundle", None),
351 )
352
353 project_name = self.input_project_name(
354 formal_name, project_overrides.pop("project_name", None)
355 )
356
357 description = self.console.text_question(
358 intro="Now, we need a one line description for your application.",
359 description="Description",
360 default="My first application",
361 override_value=project_overrides.pop("description", None),
362 )
363
364 author_intro = (
365 "Who do you want to be credited as the author of this application?\n"
366 "\n"
367 "This could be your own name, or the name of your company you work for."
368 )
369 default_author = "Jane Developer"
370 git_username = self.get_git_config_value("user", "name")
371 if git_username is not None:
372 default_author = git_username
373 author_intro = (
374 f"{author_intro}\n\n"
375 f"Based on your git configuration, "
376 f"we believe it could be '{git_username}'."
377 )
378 author = self.console.text_question(
379 intro=author_intro,
380 description="Author",
381 default=default_author,
382 override_value=project_overrides.pop("author", None),
383 )
384
385 author_email_intro = (
386 "What email address should people use to contact the developers of "
387 "this application?\n"
388 "\n"
389 "This might be your own email address, or a generic contact address "
390 "you set up specifically for this application."
391 )
392 git_email = self.get_git_config_value("user", "email")
393 if git_email is None:
394 default_author_email = self.make_author_email(author, bundle)
395 else:
396 default_author_email = git_email
397 author_email_intro = (
398 f"{author_email_intro}\n\n"
399 f"Based on your git configuration, "
400 f"we believe it could be '{git_email}'."
401 )
402 author_email = self.console.text_question(
403 intro=author_email_intro,
404 description="Author's Email",
405 default=default_author_email,
406 validator=self.validate_email,
407 override_value=project_overrides.pop("author_email", None),
408 )
409
410 url = self.console.text_question(
411 intro=(
412 "What is the website URL for this application?\n"
413 "\n"
414 "If you don't have a website set up yet, you can put in a dummy URL."
415 ),
416 description="Application URL",
417 default=self.make_project_url(bundle, app_name),
418 validator=validate_url,
419 override_value=project_overrides.pop("url", None),
420 )
421 project_license = self.input_license(
422 override_value=project_overrides.pop("license", None)
423 )
424
425 return {
426 "formal_name": formal_name,
427 "app_name": app_name,
428 "class_name": class_name,
429 "module_name": module_name,
430 "source_dir": source_dir,
431 "test_source_dir": test_source_dir,
432 "project_name": project_name,
433 "description": description,
434 "author": author,
435 "author_email": author_email,
436 "bundle": bundle,
437 "url": url,
438 "license": project_license,
439 }
440
441 def create_bootstrap(
442 self,
443 context: dict[str, str],
444 project_overrides: dict[str, str],
445 ) -> BaseGuiBootstrap:
446 """Select and instantiate a bootstrap for the new project.
447
448 :returns: An instance of the GUI bootstrap that the user has selected.
449 """
450 bootstraps = get_gui_bootstraps()
451 bootstrap_options = self._gui_bootstrap_choices(bootstraps)
452
453 selected_bootstrap = self.console.selection_question(
454 intro=(
455 "What GUI toolkit do you want to use for this project?\n"
456 "\n"
457 "Additional GUI bootstraps are available from the community.\n"
458 "\n"
459 "Check them out at https://beeware.org/bee/briefcase-bootstraps"
460 ),
461 description="GUI Framework",
462 default=next(iter(bootstrap_options.keys())),
463 options=bootstrap_options,
464 override_value=project_overrides.pop("bootstrap", None),
465 )
466
467 bootstrap_class = bootstraps[selected_bootstrap]
468
469 return bootstrap_class(console=self.console, context=context)
470
471 def build_gui_context(
472 self,
473 bootstrap: BaseGuiBootstrap,
474 project_overrides: dict[str, str],
475 ) -> dict[str, str]:
476 """Build context specific to the GUI toolkit."""
477
478 gui_context = {}
479
480 # Iterate over the Bootstrap interface to build the context.
481 # Returning ``None`` is a special case that means the field should not be
482 # included in the context and instead deferred to the template default.
483 if (
484 additional_context := bootstrap.extra_context(project_overrides)
485 ) is not None:
486 gui_context.update(additional_context)
487
488 for context_field in bootstrap.fields:
489 if (context_value := getattr(bootstrap, context_field)()) is not None:
490 gui_context[context_field] = context_value
491
492 return gui_context
493
494 def _gui_bootstrap_choices(self, bootstraps):
495 """Construct the list of available GUI bootstraps to display to the user."""
496 # Sort the options alphabetically first
497 ordered = OrderedDict(sorted(bootstraps.items()))
498
499 # Ensure the first 3 options are: Toga, PySide6, Pygame
500 ordered.move_to_end("Pygame", last=False)
501 ordered.move_to_end("PySide6", last=False)
502 ordered.move_to_end("Toga", last=False)
503
504 # Option None should always be last
505 ordered.move_to_end("None")
506
507 # Construct the bootstrap options as they should be presented to users.
508 # The name of the bootstrap is its registered entry point name. Along with the
509 # bootstrap's name, a short message important to a user's choice can be shown
510 # also; for instance, several show "does not support iOS/Android deployment".
511 bootstrap_choices = {}
512 max_len = max(map(len, ordered))
513 for name, klass in ordered.items():
514 if annotation := getattr(klass, "display_name_annotation", ""):
515 annotation = f"{' ' * (max_len - len(name))} ({annotation})"
516 bootstrap_choices[name] = f"{name}{annotation or ''}"
517
518 return bootstrap_choices
519
520 def warn_unused_overrides(self, project_overrides: dict[str, str] | None):
521 """Inform user of project configuration overrides that were not used."""
522 if project_overrides:
523 unused_overrides = "\n ".join(
524 f"{key} = {value}" for key, value in project_overrides.items()
525 )
526 self.console.warning()
527 self.console.warning(
528 "WARNING: These project configuration overrides were not used:\n\n"
529 f" {unused_overrides}"
530 )
531
532 def new_app(
533 self,
534 template: str | None = None,
535 template_branch: str | None = None,
536 project_overrides: dict[str, str] | None = None,
537 **options,
538 ):
539 """Ask questions to generate a new application, and generate a stub project from
540 the briefcase-template."""
541 self.console.prompt()
542 self.console.prompt("Let's build a new Briefcase app!")
543
544 context = self.build_app_context(project_overrides)
545 bootstrap = self.create_bootstrap(context, project_overrides)
546 context.update(self.build_gui_context(bootstrap, project_overrides))
547
548 self.console.divider() # close the prompting section of output
549
550 self.warn_unused_overrides(project_overrides)
551
552 self.console.info(
553 f"Generating a new application {context['formal_name']!r}",
554 prefix=context["app_name"],
555 )
556
557 # Make extra sure we won't clobber an existing application.
558 if (self.base_path / context["app_name"]).exists():
559 raise BriefcaseCommandError(
560 f"A directory named {context['app_name']!r} already exists."
561 )
562
563 # Create the project files
564 self.generate_template(
565 template=(template or "https://github.com/beeware/briefcase-template"),
566 branch=template_branch,
567 output_path=self.base_path,
568 extra_context=context,
569 )
570
571 # Perform any post-template processing required by the bootstrap.
572 bootstrap.post_generate(base_path=self.base_path / context["app_name"])
573
574 self.console.info(
575 f"Generated new application {context['formal_name']!r}",
576 prefix=context["app_name"],
577 )
578 self.console.info(
579 f"""
580 To run your application, type:
581
582 $ cd {context["app_name"]}
583 $ briefcase dev
584
585 """
586 )
587
588 def verify_tools(self):
589 """Verify that the tools needed to run this command exist.
590
591 Raises MissingToolException if a required system tool is missing.
592 """
593 super().verify_tools()
594 Git.verify(tools=self.tools)
595
596 def __call__(
597 self,
598 template: str | None = None,
599 template_branch: str | None = None,
600 project_overrides: list[str] | None = None,
601 **options,
602 ):
603 # Confirm host compatibility, and that all required tools are available.
604 # There are no apps, so finalize() is called with an empty list.
605 self.finalize(apps=[])
606
607 return self.new_app(
608 template=template,
609 template_branch=template_branch,
610 project_overrides=parse_project_overrides(project_overrides),
611 **options,
612 )