multi-lang-build 0.2.8__py3-none-any.whl → 0.2.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. multi_lang_build/__init__.py +4 -4
  2. multi_lang_build/cli.py +3 -2
  3. multi_lang_build/compiler/__init__.py +1 -1
  4. multi_lang_build/compiler/go_compiler.py +388 -0
  5. multi_lang_build/compiler/go_support/__init__.py +19 -0
  6. multi_lang_build/compiler/go_support/binary.py +117 -0
  7. multi_lang_build/compiler/go_support/builder.py +228 -0
  8. multi_lang_build/compiler/go_support/cleaner.py +40 -0
  9. multi_lang_build/compiler/go_support/env.py +41 -0
  10. multi_lang_build/compiler/go_support/mirror.py +111 -0
  11. multi_lang_build/compiler/go_support/module.py +77 -0
  12. multi_lang_build/compiler/go_support/tester.py +199 -0
  13. multi_lang_build/compiler/pnpm.py +61 -209
  14. multi_lang_build/compiler/pnpm_support/__init__.py +6 -0
  15. multi_lang_build/compiler/pnpm_support/executor.py +148 -0
  16. multi_lang_build/compiler/pnpm_support/project.py +53 -0
  17. multi_lang_build/compiler/python.py +65 -222
  18. multi_lang_build/compiler/python_support/__init__.py +13 -0
  19. multi_lang_build/compiler/python_support/cleaner.py +56 -0
  20. multi_lang_build/compiler/python_support/cli.py +46 -0
  21. multi_lang_build/compiler/python_support/detector.py +64 -0
  22. multi_lang_build/compiler/python_support/installer.py +162 -0
  23. multi_lang_build/compiler/python_support/venv.py +63 -0
  24. multi_lang_build/ide_register.py +97 -0
  25. multi_lang_build/mirror/config.py +19 -0
  26. multi_lang_build/register/support/__init__.py +13 -0
  27. multi_lang_build/register/support/claude.py +94 -0
  28. multi_lang_build/register/support/codebuddy.py +100 -0
  29. multi_lang_build/register/support/opencode.py +62 -0
  30. multi_lang_build/register/support/trae.py +72 -0
  31. {multi_lang_build-0.2.8.dist-info → multi_lang_build-0.2.10.dist-info}/METADATA +1 -1
  32. multi_lang_build-0.2.10.dist-info/RECORD +40 -0
  33. multi_lang_build/compiler/go.py +0 -564
  34. multi_lang_build/register.py +0 -412
  35. multi_lang_build-0.2.8.dist-info/RECORD +0 -18
  36. {multi_lang_build-0.2.8.dist-info → multi_lang_build-0.2.10.dist-info}/WHEEL +0 -0
  37. {multi_lang_build-0.2.8.dist-info → multi_lang_build-0.2.10.dist-info}/entry_points.txt +0 -0
  38. {multi_lang_build-0.2.8.dist-info → multi_lang_build-0.2.10.dist-info}/licenses/LICENSE +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multi-lang-build
3
- Version: 0.2.8
3
+ Version: 0.2.10
4
4
  Summary: Multi-language automated build tool with domestic mirror acceleration support
5
5
  Project-URL: Homepage, https://github.com/example/multi-lang-build
6
6
  Project-URL: Repository, https://github.com/example/multi-lang-build
@@ -0,0 +1,40 @@
1
+ multi_lang_build/__init__.py,sha256=HFLjChxI1v6o36HTscv8X8p0WQMEuwXHVt9FzYZE4x8,1795
2
+ multi_lang_build/cli.py,sha256=SSj7f_auQ0qmjiY65aU0xEIW56w0xgA-8PgI9ICj04I,13100
3
+ multi_lang_build/ide_register.py,sha256=lz345IOs9S6-neh7t_6txJhz7XLypEiNzwvSl3ouVo8,3028
4
+ multi_lang_build/py.typed,sha256=c8jtFarMovqA5DdwhEzKPH4WrX85xaoiWilIlvuc6KU,84
5
+ multi_lang_build/types.py,sha256=iCyz_6KmEBU4xwpCtfJnpzXoiSsmOcOKOhzHJVx8Z4Q,1043
6
+ multi_lang_build/compiler/__init__.py,sha256=7cfE3n7ATXZ8JabON_Qg0npxd7EY2jEU4tC6FxDupIs,493
7
+ multi_lang_build/compiler/base.py,sha256=crtDW9bthfV-FSpp96O2Hi0DrViNqcIt4TjAVK2lPXE,9391
8
+ multi_lang_build/compiler/go_compiler.py,sha256=HPNp6UQD_umjlV5ewqsYmRET3rfegqFaHOtOWy_cCIM,13234
9
+ multi_lang_build/compiler/pnpm.py,sha256=0dwcf5LoPdzqlpkjEBVy8YNZNjd6CnUTOxIdonckwjo,10463
10
+ multi_lang_build/compiler/python.py,sha256=P-4ydqoUerMFkupVISu7j_KGSJVsZfmxeAZzCy36WWo,11797
11
+ multi_lang_build/compiler/go_support/__init__.py,sha256=UGsWdG_RdbjgLGYtvbftjzLjPwHF9tmb-pmezKvEWMQ,675
12
+ multi_lang_build/compiler/go_support/binary.py,sha256=XGt9jzRaCl2tykaHy8iqF1KrLHa3eW4hiolDozMMtaI,3698
13
+ multi_lang_build/compiler/go_support/builder.py,sha256=NtavFLgEtZ5zFvygvudzylJ5AMo2wuRxCMJCDxHTmQA,6531
14
+ multi_lang_build/compiler/go_support/cleaner.py,sha256=UW5YQhzJtgypBpG0BQusmguxl7C8T3TLxlt58Krgvmg,1046
15
+ multi_lang_build/compiler/go_support/env.py,sha256=GPXFkePQb2QHaiiJuLXXVnSE9VtHjjPiZx82oYuVx3k,1270
16
+ multi_lang_build/compiler/go_support/mirror.py,sha256=BWT8mhLEshSVCFZa2D0amIvR366ZSXJCvP8djAqP11Q,3786
17
+ multi_lang_build/compiler/go_support/module.py,sha256=5ubgiMJu0P8UeiutV3tIIifO30IBhbktDfJB4orWgvk,2204
18
+ multi_lang_build/compiler/go_support/tester.py,sha256=r6DVL4EtNUYQB_Jm84MGmZ1sDl9QsV6JqanZwHj-XyM,5428
19
+ multi_lang_build/compiler/pnpm_support/__init__.py,sha256=_bPoy8XWGykiijpC8xwGMfJK3H4iBzIOYlcZUStwb9A,225
20
+ multi_lang_build/compiler/pnpm_support/executor.py,sha256=w52GN4fCGqbt90yEPq_LyaaWcGhoRbhudI_RJ38OkZY,4352
21
+ multi_lang_build/compiler/pnpm_support/project.py,sha256=JPHAxK0z1FOtNsAgJUUlp70wPGP4bq5pSB5o0FK44Co,1531
22
+ multi_lang_build/compiler/python_support/__init__.py,sha256=YjLyDtSvFy9VnhD9f0Mr9saMk98FnsKOe5O1L5pOAVc,459
23
+ multi_lang_build/compiler/python_support/cleaner.py,sha256=AT1KdRRX5vTGdtVLAgml2SuAUNEz0MzeuEgaHzBrAJo,1526
24
+ multi_lang_build/compiler/python_support/cli.py,sha256=q3guZAST1Rs2gy79BOb9GAWvShy7LBcdl1R1p8nfNXY,1642
25
+ multi_lang_build/compiler/python_support/detector.py,sha256=eMHSLsU--a_LbyeXlgFuqwN_CHM8MeSbE8rNX8fe35E,1804
26
+ multi_lang_build/compiler/python_support/installer.py,sha256=1gDqQPZRhYB6DIVlCxdRuIwJ_i5WpO4B5j2cG-VWVHI,4575
27
+ multi_lang_build/compiler/python_support/venv.py,sha256=It6tppc7BFToJBzFxR9hPfpYeteVpNIw-mHjF3pwdr4,1957
28
+ multi_lang_build/mirror/__init__.py,sha256=RrZOQ83bxImAR275zeAUKyyCgwqdGt5xH8tF_-UShJo,489
29
+ multi_lang_build/mirror/cli.py,sha256=qv6RI6izxUIsfMCIDOtTK3avcNSJpAaUF3NPiK1W49A,9820
30
+ multi_lang_build/mirror/config.py,sha256=ZQo9upkE29vw0QFuBT6sYw85DhOhHQg59RSYu-OcdQg,9067
31
+ multi_lang_build/register/support/__init__.py,sha256=Hg5oKJn5KhJ-qikzpDtFf0CO9WVnMvJVhExf20-PC10,443
32
+ multi_lang_build/register/support/claude.py,sha256=YgXdU0--1wr6QIDL6rojY_zLKnlb-nu6fDqvpKywzd4,3370
33
+ multi_lang_build/register/support/codebuddy.py,sha256=6ZPj0bs6erkSvok5lHueLbqxjIOCqml98zJoVTuBKj4,3356
34
+ multi_lang_build/register/support/opencode.py,sha256=zGrTREyCNUX8RZgTbv9p2KV0ZcQjB68jZQqIClFbD1k,2394
35
+ multi_lang_build/register/support/trae.py,sha256=nkiQRCWp8in3cI3BLuWHMMLzQwiQQv3crxAU06sXOuk,2527
36
+ multi_lang_build-0.2.10.dist-info/METADATA,sha256=1UZ3bhhQbW4AXA8fR-M6nF6ZU29gl18OIRuFEa_EucA,10074
37
+ multi_lang_build-0.2.10.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
38
+ multi_lang_build-0.2.10.dist-info/entry_points.txt,sha256=0vd5maQH5aZoqnpbr2Yr_IWB_-ncWX1rO3jGBCW3pHY,319
39
+ multi_lang_build-0.2.10.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
40
+ multi_lang_build-0.2.10.dist-info/RECORD,,
@@ -1,564 +0,0 @@
1
- """Go compiler with mirror acceleration support."""
2
-
3
- from pathlib import Path
4
- from typing import Final, Literal
5
- import shutil
6
- import subprocess
7
- import os
8
- import tempfile
9
-
10
- from multi_lang_build.compiler.base import CompilerBase, BuildResult, CompilerInfo
11
- from multi_lang_build.mirror.config import (
12
- get_mirror_config,
13
- apply_mirror_environment,
14
- GO_PROXY_GOPROXY_CN,
15
- GO_PROXY_GOPROXY_IO,
16
- GO_PROXY_GOVIP_CN,
17
- DEFAULT_GO_MIRROR,
18
- )
19
-
20
-
21
- class GoCompiler(CompilerBase):
22
- """Compiler for Go projects with module support."""
23
-
24
- NAME: Final[str] = "go"
25
- DEFAULT_MIRROR: Final[str] = DEFAULT_GO_MIRROR
26
-
27
- def __init__(
28
- self,
29
- go_path: str | None = None,
30
- mirror: str | None = None,
31
- ) -> None:
32
- """Initialize the Go compiler.
33
-
34
- Args:
35
- go_path: Optional path to go executable. If None, uses system PATH.
36
- mirror: Mirror configuration name (e.g., "go", "go_qiniu", "go_vip").
37
- Defaults to DEFAULT_GO_MIRROR (goproxy.cn).
38
- """
39
- self._go_path = go_path
40
- self._mirror = mirror
41
- self._version_cache: str | None = None
42
-
43
- @property
44
- def name(self) -> str:
45
- """Get the compiler name."""
46
- return self.NAME
47
-
48
- @property
49
- def version(self) -> str:
50
- """Get the Go version."""
51
- if self._version_cache:
52
- return self._version_cache
53
-
54
- go_executable = self._get_executable_path()
55
-
56
- try:
57
- result = subprocess.run(
58
- [go_executable, "version"],
59
- capture_output=True,
60
- text=True,
61
- timeout=10,
62
- )
63
- output = result.stdout.strip()
64
- if output:
65
- parts = output.split()
66
- if len(parts) >= 3:
67
- self._version_cache = parts[2]
68
- else:
69
- self._version_cache = output
70
- else:
71
- self._version_cache = "unknown"
72
- except Exception:
73
- self._version_cache = "unknown"
74
-
75
- return self._version_cache
76
-
77
- @property
78
- def supported_mirrors(self) -> list[str]:
79
- """Get list of supported mirror configurations."""
80
- return ["go", "go_qiniu", "go_vip"]
81
-
82
- @property
83
- def current_mirror(self) -> str:
84
- """Get the current mirror configuration name."""
85
- return self._mirror or "go"
86
-
87
- def get_info(self) -> CompilerInfo:
88
- """Get compiler information."""
89
- return {
90
- "name": self.name,
91
- "version": self.version,
92
- "supported_mirrors": self.supported_mirrors,
93
- "default_mirror": self.DEFAULT_MIRROR,
94
- "executable": self._get_executable_path(),
95
- }
96
-
97
- def set_mirror(self, mirror: str) -> None:
98
- """Set the mirror configuration.
99
-
100
- Args:
101
- mirror: Mirror configuration name (e.g., "go", "go_qiniu", "go_vip")
102
- """
103
- self._mirror = mirror
104
-
105
- def build(
106
- self,
107
- source_dir: Path,
108
- output_dir: Path,
109
- *,
110
- environment: dict[str, str] | None = None,
111
- mirror_enabled: bool = True,
112
- extra_args: list[str] | None = None,
113
- stream_output: bool = True,
114
- ) -> BuildResult:
115
- """Execute the Go build process.
116
-
117
- Args:
118
- source_dir: Source code directory
119
- output_dir: Build output directory (for binary)
120
- environment: Additional environment variables
121
- mirror_enabled: Whether to use Go proxy mirror
122
- extra_args: Additional arguments to pass to go build
123
- stream_output: Whether to stream output in real-time (default: True)
124
-
125
- Returns:
126
- BuildResult containing success status and output information.
127
- """
128
- from loguru import logger
129
-
130
- go_executable = self._get_executable_path()
131
-
132
- # Validate directories
133
- source_dir = self._validate_directory(source_dir, create_if_not_exists=False)
134
- output_dir = self._validate_directory(output_dir, create_if_not_exists=True)
135
-
136
- # Print current working directory
137
- cwd = Path.cwd().resolve()
138
- logger.info(f"当前工作目录: {cwd}")
139
-
140
- # Prepare environment
141
- env = environment.copy() if environment else {}
142
-
143
- # Ensure GOMODCACHE is set
144
- if "GOMODCACHE" not in env and "GOPATH" not in env:
145
- default_cache = Path.home() / "go" / "pkg" / "mod"
146
- env["GOMODCACHE"] = str(default_cache)
147
- logger.info(f"Go模块缓存: {default_cache}")
148
-
149
- if mirror_enabled:
150
- mirror_key = self._mirror or "go"
151
- env = apply_mirror_environment(mirror_key, env)
152
-
153
- # Check for go.mod
154
- go_mod = source_dir / "go.mod"
155
- has_go_mod = go_mod.exists()
156
-
157
- # Download dependencies if go.mod exists
158
- if has_go_mod:
159
- logger.info("⬇️ 下载Go依赖...")
160
- deps_result = self._run_build(
161
- [go_executable, "mod", "download"],
162
- source_dir,
163
- output_dir,
164
- environment=env,
165
- stream_output=stream_output,
166
- )
167
- logger.info("✅ 依赖下载完成")
168
-
169
- if not deps_result["success"]:
170
- return deps_result
171
-
172
- # Build the project
173
- logger.info("🔨 开始构建...")
174
- build_args = [go_executable, "build", "-o", str(output_dir)]
175
-
176
- if extra_args:
177
- build_args.extend(extra_args)
178
-
179
- build_result = self._run_build(
180
- build_args,
181
- source_dir,
182
- output_dir,
183
- environment=env,
184
- stream_output=stream_output,
185
- )
186
-
187
- if build_result["success"]:
188
- logger.info("✅ 构建成功")
189
-
190
- return build_result
191
-
192
- def build_binary(
193
- self,
194
- source_dir: Path,
195
- output_path: Path,
196
- *,
197
- target: str | Path | None = None,
198
- environment: dict[str, str] | None = None,
199
- mirror_enabled: bool = True,
200
- ldflags: str | None = None,
201
- tags: list[str] | None = None,
202
- stream_output: bool = True,
203
- ) -> BuildResult:
204
- """Build a specific Go binary.
205
-
206
- Args:
207
- source_dir: Source code directory (working directory for build)
208
- output_path: Output path for the binary
209
- target: Build target - can be a .go file (e.g., "server.go", "cmd/server/main.go")
210
- or a directory (e.g., "./cmd/server"). If None, builds current directory.
211
- environment: Additional environment variables
212
- mirror_enabled: Whether to use Go proxy mirror
213
- ldflags: Linker flags to pass to the compiler
214
- tags: Build tags to pass to the compiler
215
- stream_output: Whether to stream output in real-time (default: True)
216
-
217
- Returns:
218
- BuildResult containing success status and output information.
219
- """
220
- from loguru import logger
221
-
222
- go_executable = self._get_executable_path()
223
-
224
- source_dir = self._validate_directory(source_dir, create_if_not_exists=False)
225
-
226
- # Ensure output directory exists
227
- output_path.parent.mkdir(parents=True, exist_ok=True)
228
-
229
- # Print current working directory
230
- cwd = Path.cwd().resolve()
231
- logger.info(f"当前工作目录: {cwd}")
232
-
233
- # Prepare environment
234
- env = environment.copy() if environment else {}
235
-
236
- # Ensure GOMODCACHE is set
237
- if "GOMODCACHE" not in env and "GOPATH" not in env:
238
- default_cache = Path.home() / "go" / "pkg" / "mod"
239
- env["GOMODCACHE"] = str(default_cache)
240
- logger.info(f"Go模块缓存: {default_cache}")
241
-
242
- if mirror_enabled:
243
- mirror_key = self._mirror or "go"
244
- env = apply_mirror_environment(mirror_key, env)
245
-
246
- build_args = [go_executable, "build", "-o", str(output_path)]
247
-
248
- if ldflags:
249
- build_args.extend(["-ldflags", ldflags])
250
-
251
- if tags:
252
- build_args.extend(["-tags", ",".join(tags)])
253
-
254
- # Add target if specified (target is relative to source_dir)
255
- if target:
256
- build_args.append(str(target))
257
-
258
- logger.info("🔨 开始构建...")
259
- build_result = self._run_build(
260
- build_args,
261
- source_dir,
262
- output_path.parent,
263
- environment=env,
264
- stream_output=stream_output,
265
- )
266
-
267
- if build_result["success"]:
268
- logger.info("✅ 构建成功")
269
-
270
- return build_result
271
-
272
- def build_all(
273
- self,
274
- source_dir: Path,
275
- output_dir: Path,
276
- *,
277
- environment: dict[str, str] | None = None,
278
- mirror_enabled: bool = True,
279
- platform: str | None = None,
280
- stream_output: bool = True,
281
- ) -> BuildResult:
282
- """Build all binaries defined in a Makefile or build script.
283
-
284
- Args:
285
- source_dir: Source code directory
286
- output_dir: Output directory for all binaries
287
- environment: Additional environment variables
288
- mirror_enabled: Whether to use Go proxy mirror
289
- platform: Target platform (e.g., "linux/amd64", "windows/amd64")
290
- stream_output: Whether to stream output in real-time (default: True)
291
-
292
- Returns:
293
- BuildResult containing success status and output information.
294
- """
295
- from loguru import logger
296
-
297
- go_executable = self._get_executable_path()
298
-
299
- source_dir = self._validate_directory(source_dir, create_if_not_exists=False)
300
- output_dir = self._validate_directory(output_dir, create_if_not_exists=True)
301
-
302
- # Print current working directory
303
- cwd = Path.cwd().resolve()
304
- logger.info(f"当前工作目录: {cwd}")
305
-
306
- # Prepare environment
307
- env = environment.copy() if environment else {}
308
-
309
- # Ensure GOMODCACHE is set
310
- if "GOMODCACHE" not in env and "GOPATH" not in env:
311
- default_cache = Path.home() / "go" / "pkg" / "mod"
312
- env["GOMODCACHE"] = str(default_cache)
313
- logger.info(f"Go模块缓存: {default_cache}")
314
-
315
- if mirror_enabled:
316
- mirror_key = self._mirror or "go"
317
- env = apply_mirror_environment(mirror_key, env)
318
-
319
- build_args = [go_executable, "build", "-o", str(output_dir), "./..."]
320
-
321
- if platform:
322
- env["GOOS"], env["GOARCH"] = platform.split("/")
323
-
324
- logger.info("🔨 开始构建...")
325
- build_result = self._run_build(
326
- build_args,
327
- source_dir,
328
- output_dir,
329
- environment=env,
330
- stream_output=stream_output,
331
- )
332
-
333
- if build_result["success"]:
334
- logger.info("✅ 构建成功")
335
-
336
- return build_result
337
-
338
- def run_tests(
339
- self,
340
- source_dir: Path,
341
- *,
342
- environment: dict[str, str] | None = None,
343
- mirror_enabled: bool = True,
344
- verbose: bool = True,
345
- race: bool = False,
346
- stream_output: bool = True,
347
- ) -> BuildResult:
348
- """Run Go tests.
349
-
350
- Args:
351
- source_dir: Source code directory
352
- environment: Additional environment variables
353
- mirror_enabled: Whether to use Go proxy mirror
354
- verbose: Enable verbose test output
355
- race: Enable race detector
356
- stream_output: Whether to stream output in real-time (default: True)
357
-
358
- Returns:
359
- BuildResult containing success status and output information.
360
- """
361
- from loguru import logger
362
-
363
- go_executable = self._get_executable_path()
364
-
365
- source_dir = self._validate_directory(source_dir, create_if_not_exists=False)
366
-
367
- # Print current working directory
368
- cwd = Path.cwd().resolve()
369
- logger.info(f"当前工作目录: {cwd}")
370
-
371
- # Prepare environment
372
- env = environment.copy() if environment else {}
373
-
374
- # Ensure GOMODCACHE is set
375
- if "GOMODCACHE" not in env and "GOPATH" not in env:
376
- default_cache = Path.home() / "go" / "pkg" / "mod"
377
- env["GOMODCACHE"] = str(default_cache)
378
- logger.info(f"Go模块缓存: {default_cache}")
379
-
380
- if mirror_enabled:
381
- mirror_key = self._mirror or "go"
382
- env = apply_mirror_environment(mirror_key, env)
383
-
384
- test_args = [go_executable, "test"]
385
-
386
- if verbose:
387
- test_args.append("-v")
388
-
389
- if race:
390
- test_args.append("-race")
391
-
392
- logger.info("🧪 开始运行测试...")
393
- test_result = self._run_build(
394
- test_args,
395
- source_dir,
396
- source_dir,
397
- environment=env,
398
- stream_output=stream_output,
399
- )
400
-
401
- if test_result["success"]:
402
- logger.info("✅ 测试完成")
403
-
404
- return test_result
405
-
406
- def tidy_modules(
407
- self,
408
- source_dir: Path,
409
- *,
410
- environment: dict[str, str] | None = None,
411
- mirror_enabled: bool = True,
412
- stream_output: bool = True,
413
- ) -> BuildResult:
414
- """Run go mod tidy to clean up dependencies.
415
-
416
- Args:
417
- source_dir: Source code directory
418
- environment: Additional environment variables
419
- mirror_enabled: Whether to use Go proxy mirror
420
- stream_output: Whether to stream output in real-time (default: True)
421
-
422
- Returns:
423
- BuildResult containing success status and output information.
424
- """
425
- from loguru import logger
426
-
427
- go_executable = self._get_executable_path()
428
-
429
- source_dir = self._validate_directory(source_dir, create_if_not_exists=False)
430
-
431
- # Print current working directory
432
- cwd = Path.cwd().resolve()
433
- logger.info(f"当前工作目录: {cwd}")
434
-
435
- # Prepare environment
436
- env = environment.copy() if environment else {}
437
-
438
- # Ensure GOMODCACHE is set
439
- if "GOMODCACHE" not in env and "GOPATH" not in env:
440
- default_cache = Path.home() / "go" / "pkg" / "mod"
441
- env["GOMODCACHE"] = str(default_cache)
442
- logger.info(f"Go模块缓存: {default_cache}")
443
-
444
- if mirror_enabled:
445
- mirror_key = self._mirror or "go"
446
- env = apply_mirror_environment(mirror_key, env)
447
-
448
- logger.info("📦 执行 go mod tidy...")
449
- tidy_result = self._run_build(
450
- [go_executable, "mod", "tidy"],
451
- source_dir,
452
- source_dir,
453
- environment=env,
454
- stream_output=stream_output,
455
- )
456
-
457
- if tidy_result["success"]:
458
- logger.info("✅ 依赖整理完成")
459
-
460
- return tidy_result
461
-
462
- def clean(self, directory: Path) -> bool:
463
- """Clean Go build artifacts in the specified directory.
464
-
465
- Args:
466
- directory: Directory to clean
467
-
468
- Returns:
469
- True if successful, False otherwise.
470
- """
471
- import shutil
472
-
473
- try:
474
- directory = self._validate_directory(directory, create_if_not_exists=False)
475
-
476
- # Remove go.sum
477
- go_sum = directory / "go.sum"
478
- if go_sum.exists():
479
- go_sum.unlink()
480
-
481
- # Remove vendor directory
482
- vendor = directory / "vendor"
483
- if vendor.exists():
484
- shutil.rmtree(vendor)
485
-
486
- # Remove bin directory
487
- bin_dir = directory / "bin"
488
- if bin_dir.exists():
489
- shutil.rmtree(bin_dir)
490
-
491
- return True
492
-
493
- except Exception:
494
- return False
495
-
496
- def _get_executable_path(self) -> str:
497
- """Get the go executable path."""
498
- if self._go_path:
499
- return self._go_path
500
-
501
- go_path = shutil.which("go")
502
- if go_path is None:
503
- raise RuntimeError("go not found in PATH. Please install Go or provide go_path.")
504
-
505
- return go_path
506
-
507
- @staticmethod
508
- def create(source_dir: Path, *, mirror_enabled: bool = True) -> "GoCompiler":
509
- """Factory method to create a GoCompiler instance.
510
-
511
- Args:
512
- source_dir: Source directory for the project
513
- mirror_enabled: Whether to enable mirror acceleration by default
514
-
515
- Returns:
516
- Configured GoCompiler instance
517
- """
518
- compiler = GoCompiler()
519
- return compiler
520
-
521
-
522
- def main() -> None:
523
- """Go compiler CLI entry point."""
524
- import argparse
525
- import sys
526
-
527
- parser = argparse.ArgumentParser(description="Go Build Compiler")
528
- parser.add_argument("source_dir", type=Path, help="Source directory (working directory)")
529
- parser.add_argument("-o", "--output", type=Path, required=True, help="Output binary path")
530
- parser.add_argument("-t", "--target", type=str, help="Build target: .go file (e.g., server.go, cmd/main.go) or directory (e.g., ./cmd/server)")
531
- parser.add_argument("--mirror", action="store_true", default=True, help="Enable Go proxy mirror")
532
- parser.add_argument("--no-mirror", dest="mirror", action="store_false", help="Disable Go proxy mirror")
533
- parser.add_argument("--ldflags", type=str, help="Linker flags")
534
- parser.add_argument("--tags", type=str, help="Build tags (comma-separated)")
535
- parser.add_argument("--test", action="store_true", help="Run tests instead of building")
536
- parser.add_argument("--tidy", action="store_true", help="Run go mod tidy")
537
- parser.add_argument("--all", action="store_true", help="Build all packages")
538
-
539
- args = parser.parse_args()
540
-
541
- compiler = GoCompiler()
542
-
543
- if args.test:
544
- result = compiler.run_tests(args.source_dir, mirror_enabled=args.mirror)
545
- elif args.tidy:
546
- result = compiler.tidy_modules(args.source_dir, mirror_enabled=args.mirror)
547
- elif args.all:
548
- result = compiler.build_all(
549
- args.source_dir,
550
- args.output,
551
- mirror_enabled=args.mirror,
552
- )
553
- else:
554
- tags = args.tags.split(",") if args.tags else None
555
- result = compiler.build_binary(
556
- args.source_dir,
557
- args.output,
558
- target=args.target,
559
- mirror_enabled=args.mirror,
560
- ldflags=args.ldflags,
561
- tags=tags,
562
- )
563
-
564
- sys.exit(0 if result["success"] else 1)