Debian Codegraph @

src/briefcase/integrations/visualstudio.py

raw
1 from __future__ import annotations
2
3 import subprocess
4 from collections.abc import Collection
5 from pathlib import Path
6
7 from briefcase.exceptions import BriefcaseCommandError, CommandOutputParseError
8 from briefcase.integrations.base import Tool, ToolCache
9 from briefcase.integrations.subprocess import json_parser
10
11
12 class VisualStudio(Tool):
13 name = "visualstudio"
14 full_name = "Visual Studio"
15 supported_host_os: Collection[str] = {"Windows"}
16 VSCODE_REQUIRED_COMPONENTS = """
17 * .NET Desktop Development
18 - Default packages
19 * Desktop Development with C++
20 - Default packages; plus
21 - C++/CLI support for v143 build tools
22 """
23
24 def __init__(
25 self,
26 tools: ToolCache,
27 msbuild_path: Path,
28 install_metadata: dict[str, str | int | bool] | None = None,
29 ):
30 super().__init__(tools=tools)
31 self._msbuild_path = msbuild_path
32 self._install_metadata = install_metadata
33
34 @property
35 def msbuild_path(self) -> Path:
36 """The path to the MSBuild executable."""
37 return self._msbuild_path
38
39 @property
40 def install_metadata(self) -> dict[str, str | int | bool] | None:
41 """Metadata about the Visual Studio install.
42
43 Will be ``None`` if MSBuild the path to MSBuild has been provided
44 explicitly, or is on the path.
45
46 Otherwise, a dictionary containing the install details from VSWhere.
47 """
48 return self._install_metadata
49
50 @classmethod
51 def verify_install(cls, tools: ToolCache, **kwargs) -> VisualStudio:
52 """Verify that Visual Studio is available.
53
54 :param tools: ToolCache of available tools
55 :returns: A Visual Studio tool wrapper. Raises an exception if Visual Studio is
56 not available.
57 """
58 # short circuit since already verified and available
59 if hasattr(tools, "visualstudio"):
60 return tools.visualstudio
61
62 visualstudio = None
63
64 try:
65 # Try running MSBuild, assuming it is on the PATH.
66 tools.subprocess.check_output(["MSBuild.exe", "--version"])
67 except FileNotFoundError:
68 # MSBuild isn't on the path
69 pass
70 except subprocess.CalledProcessError as e:
71 raise BriefcaseCommandError(
72 "MSBuild is on the path, but Briefcase cannot start it."
73 ) from e
74 else:
75 # Create an explicit VisualStudio, with no install metadata
76 visualstudio = VisualStudio(tools=tools, msbuild_path=Path("MSBuild.exe"))
77
78 # try to find Visual Studio
79 if visualstudio is None:
80 # Look for an %MSBUILD% environment variable
81 try:
82 msbuild_path = Path(tools.os.environ["MSBUILD"])
83 install_metadata: dict[str, str | int | bool] | None = None
84
85 if not msbuild_path.exists():
86 # The location referenced by %MSBUILD% doesn't exist
87 raise BriefcaseCommandError(
88 f"""\
89 The location referenced by the environment variable MSBUILD:
90
91 {msbuild_path}
92
93 does not appear to point to a MSBuild executable. Correct
94 or unset the environment variable; then re-run Briefcase.
95
96 """
97 )
98
99 except KeyError:
100 # No %MSBUILD% environment variable. Look for vswhere.exe
101 vswhere_path = None
102 if program_files := tools.os.environ.get("ProgramFiles(x86)"):
103 vswhere_path = (
104 Path(program_files)
105 / "Microsoft Visual Studio"
106 / "Installer"
107 / "vswhere.exe"
108 )
109 if vswhere_path is None or not vswhere_path.exists():
110 raise BriefcaseCommandError(
111 f"""\
112 Visual Studio does not appear to be installed. Visual Studio 2022 Community
113 Edition can be obtained as a free download from:
114
115 https://visualstudio.microsoft.com/vs/community/
116
117 When you install Visual Studio, ensure you install the following workloads
118 and additional components:
119 {cls.VSCODE_REQUIRED_COMPONENTS}
120 If you have Visual Studio installed in a non-default location, you must
121 either put MSBuild.exe in your path, or define an MSBUILD environment
122 variable that points at the MSBuild.exe provided by your Visual Studio
123 installation.
124
125 """
126 ) from None
127
128 # Retrieve metadata for Visual Studio install
129 try:
130 install_metadata = tools.subprocess.parse_output(
131 json_parser,
132 [
133 vswhere_path,
134 "-latest",
135 "-prerelease",
136 "-format",
137 "json",
138 ],
139 stderr=subprocess.STDOUT,
140 )[0]
141 except (
142 IndexError,
143 KeyError,
144 CommandOutputParseError,
145 subprocess.CalledProcessError,
146 OSError,
147 ) as e:
148 raise BriefcaseCommandError(
149 f"""\
150 Visual Studio appears to exist, but Briefcase can't retrieve installation metadata.
151 Please report this as a bug at:
152
153 https://github.com/beeware/briefcase/issues/new
154
155 In your report, please including the output from running:
156
157 {vswhere_path}
158
159 from the command prompt.
160
161 """
162 ) from e
163
164 msbuild_path = (
165 Path(install_metadata["installationPath"])
166 / "MSBuild"
167 / "Current"
168 / "Bin"
169 / "MSBuild.exe"
170 )
171 if not msbuild_path.exists():
172 raise BriefcaseCommandError(
173 f"""\
174 Your Visual Studio installation does not appear to provide MSBuild.
175 Ensure that Visual Studio following workloads and components installed:
176 {cls.VSCODE_REQUIRED_COMPONENTS}
177 Then restart Briefcase.
178 """
179 ) from None
180
181 # Try to invoke MSBuild at the established location
182 try:
183 tools.subprocess.check_output([msbuild_path, "--version"])
184 except (subprocess.CalledProcessError, OSError) as e:
185 raise BriefcaseCommandError(
186 "MSBuild appears to exist, but Briefcase can't start it."
187 ) from e
188
189 visualstudio = VisualStudio(
190 tools=tools,
191 msbuild_path=msbuild_path,
192 install_metadata=install_metadata,
193 )
194
195 tools.visualstudio = visualstudio
196 return visualstudio