дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
feat(swift): resolve and update Swift packages from the IDE (#6899)
Resolve Swift Packages and Update Swift Packages run swift package resolve / update in the Run tool window from the folder of Package.swift, like Go Mod Tidy, using the swiftpm run kind. They are in Find Action (category Swift) and on a single Package.swift in the Project view, editor and tab menus; when the run ends, run configurations and external libraries reload. sourcekit-lsp already reloads on Package.resolved changes through its file watcher, so no restart is added. Documented on the Swift page. Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
7be55e4eec
коміт
5229e44a9c
7 files changed
+165
No files matched your search
@@ -28,6 +28,15 @@ sourcekit-lsp then reads the build settings for that root:
|
||||
- **Build server**: a `.bsp/*.json` file or a `buildServer.json` in the root points sourcekit-lsp at a Build Server Protocol server. Xcode projects use this (see [Xcode projects](#xcode-projects)).
|
||||
- **`compile_commands.json`**: a compilation database, for example from CMake.
|
||||
|
||||
### Package dependencies
|
||||
|
||||
Right-click `Package.swift` in the Project view or the editor, or use **Find Action** (`⇧⌘A` / `Ctrl+Shift+A`):
|
||||
|
||||
- **Resolve Swift Packages** runs `swift package resolve`: it fetches the dependencies and writes `Package.resolved`.
|
||||
- **Update Swift Packages** runs `swift package update`: it moves the dependencies to the newest versions `Package.swift` allows.
|
||||
|
||||
Both run in the **Run** tool window in the folder of `Package.swift`. sourcekit-lsp watches `Package.swift` and `Package.resolved` and reloads the package when either changes, including after `git pull`, so completion for a new dependency works without restarting the server.
|
||||
|
||||
`.sourcekit-lsp/config.json` holds sourcekit-lsp's own options; see the [sourcekit-lsp configuration reference](https://github.com/swiftlang/sourcekit-lsp/blob/main/Documentation/Configuration%20File.md).
|
||||
|
||||
### Xcode projects
|
||||
|
||||
@@ -28,6 +28,15 @@ sourcekit-lsp 从当前文件向上查找以下文件来确定工作区根目录
|
||||
- **构建服务器**:根目录中的 `.bsp/*.json` 或 `buildServer.json` 让 sourcekit-lsp 连接一个 Build Server Protocol 服务器。Xcode 项目就用这种方式(见 [Xcode 项目](#xcode-项目))。
|
||||
- **`compile_commands.json`**:编译数据库,例如由 CMake 生成。
|
||||
|
||||
### 包依赖
|
||||
|
||||
在项目视图或编辑器里右键 `Package.swift`,或者在查找操作(`⇧⌘A` / `Ctrl+Shift+A`)中执行:
|
||||
|
||||
- **解析 Swift 包依赖**执行 `swift package resolve`:拉取依赖并写入 `Package.resolved`。
|
||||
- **更新 Swift 包依赖**执行 `swift package update`:把依赖升级到 `Package.swift` 允许的最新版本。
|
||||
|
||||
两者都在 `Package.swift` 所在目录执行,输出显示在运行工具窗口。sourcekit-lsp 会监听 `Package.swift` 和 `Package.resolved`,任一变化(包括 `git pull` 之后)都会重新加载包,所以新依赖的补全不用重启语言服务器就能用。
|
||||
|
||||
`.sourcekit-lsp/config.json` 存放 sourcekit-lsp 自己的选项,见 [sourcekit-lsp 配置文件说明](https://github.com/swiftlang/sourcekit-lsp/blob/main/Documentation/Configuration%20File.md)。
|
||||
|
||||
### Xcode 项目
|
||||
|
||||
@@ -51,6 +51,7 @@ import { registerComposerInstall } from "./composerInstall";
|
||||
import { registerNpmInstall } from "./npmInstall";
|
||||
import { registerPubspecCommands } from "./pubspec";
|
||||
import { registerGoActions } from "./goActions";
|
||||
import { registerSwiftPackageActions } from "./swiftpmActions";
|
||||
import { registerRunTabActions } from "./runTabs";
|
||||
import { invalidateGoModules } from "./goModules";
|
||||
import { invalidatePythonPackages } from "./pythonPackages";
|
||||
@@ -475,6 +476,7 @@ export function activate(): () => void {
|
||||
registerBuiltinTypes(),
|
||||
registerRunConfigType(junitType),
|
||||
registerGoActions(),
|
||||
registerSwiftPackageActions(),
|
||||
registerFlutterBuildActions(),
|
||||
registerRunTabActions(),
|
||||
registerComposerInstall(),
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { swiftPackageCommand, swiftPackageManifest, swiftPackageMenu } from "./swiftpmActions";
|
||||
|
||||
describe("SwiftPM package commands", () => {
|
||||
it("runs resolve and update in the manifest's folder", () => {
|
||||
for (const operation of ["resolve", "update"] as const) {
|
||||
expect(swiftPackageCommand(operation, "/work/app/Package.swift")).toMatchObject({
|
||||
kind: "swiftpm",
|
||||
command: "swift",
|
||||
args: ["package", operation],
|
||||
cwd: "/work/app",
|
||||
isTest: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
it("rejects other files and NULs", () => {
|
||||
expect(swiftPackageCommand("resolve", "/work/app/main.swift")).toBeNull();
|
||||
expect(swiftPackageCommand("resolve", "/work/app/Package.resolved")).toBeNull();
|
||||
expect(swiftPackageCommand("update", "/work/a\0b/Package.swift")).toBeNull();
|
||||
});
|
||||
it("offers the actions only on a single Package.swift", () => {
|
||||
expect(swiftPackageMenu({ paths: ["/p/Package.swift"] }).map((m) => m.action)).toEqual([
|
||||
"swift.package.resolve",
|
||||
"swift.package.update",
|
||||
]);
|
||||
expect(swiftPackageMenu({ paths: ["/p/Package.swift", "/q/Package.swift"] })).toEqual([]);
|
||||
expect(swiftPackageMenu({ paths: ["/p/Sources/main.swift"] })).toEqual([]);
|
||||
});
|
||||
it("falls back to the project root's Package.swift when another file is active", async () => {
|
||||
const has = (paths: string[]) => async (p: string) => paths.includes(p);
|
||||
expect(await swiftPackageManifest("/p/sub/Package.swift", "/p", has([]))).toBe("/p/sub/Package.swift");
|
||||
expect(await swiftPackageManifest("/p/Sources/main.swift", "/p", has(["/p/Package.swift"]))).toBe(
|
||||
"/p/Package.swift",
|
||||
);
|
||||
expect(await swiftPackageManifest("/p/Sources/main.swift", "/p", has([]))).toBeNull();
|
||||
expect(await swiftPackageManifest("", undefined, has(["/Package.swift"]))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { executeAction, getAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerMenuGroup, maybeEditorService, notifications, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { loadConfigs, startRun } from "./store";
|
||||
|
||||
export type SwiftPackageOperation = "resolve" | "update";
|
||||
const ACTIONS = {
|
||||
resolve: { id: "swift.package.resolve", title: "Resolve Swift Packages" },
|
||||
update: { id: "swift.package.update", title: "Update Swift Packages" },
|
||||
} as const;
|
||||
|
||||
/** `swift package resolve|update` in the folder of a `Package.swift`. */
|
||||
export function swiftPackageCommand(operation: SwiftPackageOperation, path: string): RunConfig | null {
|
||||
if (!path.endsWith("/Package.swift") || path.includes("\0")) return null;
|
||||
return {
|
||||
id: `swiftpm:${operation}:${path}`,
|
||||
name: `swift package ${operation}`,
|
||||
kind: "swiftpm",
|
||||
command: "swift",
|
||||
args: ["package", operation],
|
||||
cwd: path.slice(0, path.lastIndexOf("/")),
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
}
|
||||
|
||||
const MANIFEST = "/Package.swift";
|
||||
|
||||
/**
|
||||
* The manifest an action runs on: the given or active `Package.swift`, else the project root's
|
||||
* one if `exists` finds it (Find Action from a source file).
|
||||
*/
|
||||
export async function swiftPackageManifest(
|
||||
path: string,
|
||||
root: string | undefined,
|
||||
exists: (path: string) => Promise<boolean>,
|
||||
): Promise<string | null> {
|
||||
if (path.endsWith(MANIFEST)) return path;
|
||||
const fallback = root ? `${root}${MANIFEST}` : "";
|
||||
return fallback && (await exists(fallback)) ? fallback : null;
|
||||
}
|
||||
|
||||
const fileExists = (path: string) =>
|
||||
call(commands.fsReadDir(path.slice(0, path.lastIndexOf("/"))))
|
||||
.then((entries) => entries.some((e) => e.name === "Package.swift"))
|
||||
.catch(() => false);
|
||||
|
||||
export function swiftPackageMenu(ctx: MenuGroupContext) {
|
||||
const path = ctx.paths.length === 1 ? ctx.paths[0]! : "";
|
||||
if (!path.endsWith("/Package.swift")) return [];
|
||||
return Object.values(ACTIONS).map((a) => ({ kind: "action" as const, action: a.id, arg: { path } }));
|
||||
}
|
||||
|
||||
export function registerSwiftPackageActions(): () => void {
|
||||
const actions = registerActions(
|
||||
Object.entries(ACTIONS).map(([operation, spec]) => ({
|
||||
...spec,
|
||||
category: "Swift",
|
||||
when: "projectOpen",
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
const path =
|
||||
typeof arg === "string"
|
||||
? arg
|
||||
: arg && typeof arg === "object" && "path" in arg && typeof arg.path === "string"
|
||||
? arg.path
|
||||
: (maybeEditorService()?.activePath() ?? "");
|
||||
const root = useProject.getState().project?.root;
|
||||
const manifest = await swiftPackageManifest(path, root, fileExists);
|
||||
const config = manifest && swiftPackageCommand(operation as SwiftPackageOperation, manifest);
|
||||
if (!config) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "warning",
|
||||
title: "No Package.swift found",
|
||||
body: "Open a Package.swift, or a project with one in its root folder.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
await startRun(config, undefined, undefined, {
|
||||
onExit: () => {
|
||||
// New products in resolved dependencies can change the detected run configurations.
|
||||
void loadConfigs();
|
||||
if (getAction("libraries.reload")) void executeAction("libraries.reload");
|
||||
},
|
||||
});
|
||||
},
|
||||
})),
|
||||
);
|
||||
const menu = registerMenuGroup({
|
||||
id: "swift.packages",
|
||||
menus: ["projectView", "editorTab", "editor"],
|
||||
items: (_menu, ctx) => swiftPackageMenu(ctx),
|
||||
});
|
||||
return () => {
|
||||
menu();
|
||||
actions();
|
||||
};
|
||||
}
|
||||
@@ -331,6 +331,7 @@ describe("catalogs", () => {
|
||||
"Go",
|
||||
"Rust",
|
||||
"Kotlin",
|
||||
"Swift",
|
||||
"Claude Code",
|
||||
"GitHub Copilot",
|
||||
"Codex",
|
||||
|
||||
@@ -7423,6 +7423,11 @@
|
||||
"Open a project to configure Go modules.": "打开项目以配置 Go 模块。",
|
||||
"Go Mod Tidy": "整理 Go 模块依赖",
|
||||
"Download Go Modules": "下载 Go 模块",
|
||||
"Resolve Swift Packages": "解析 Swift 包依赖",
|
||||
"Update Swift Packages": "更新 Swift 包依赖",
|
||||
"No Package.swift found": "找不到 Package.swift",
|
||||
"Open a Package.swift, or a project with one in its root folder.": "请打开一个 Package.swift,或打开根目录里有 Package.swift 的项目。",
|
||||
"Swift": "Swift",
|
||||
"Sync Go Workspace": "同步 Go 工作区",
|
||||
"Add Directory to Go Workspace…": "添加目录到 Go 工作区…",
|
||||
"Add Directory to Go Workspace": "添加目录到 Go 工作区",
|
||||
|
||||
Reference in new issue
Заблокувати користувача