дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
13
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1438876254 | ||
|
|
7279f515db | ||
|
|
710d120689 | ||
|
|
38709947fe | ||
|
|
d9fbb19787 | ||
|
|
6aa613d4ec | ||
|
|
60ef498deb | ||
|
|
719b73ecd9 | ||
|
|
6c3284c300 | ||
|
|
69cec11761 | ||
|
|
6c76cfd316 | ||
|
|
66496221b9 | ||
|
|
e9f3aef5ae |
No files matched your search
@@ -21,6 +21,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
|
||||
@@ -23,6 +23,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
|
||||
@@ -34,6 +34,7 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -106,9 +107,9 @@ jobs:
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -19,6 +19,7 @@ env:
|
||||
jobs:
|
||||
plugin-keys:
|
||||
permissions: {}
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
keys: ${{ steps.keys.outputs.keys }}
|
||||
@@ -43,6 +44,7 @@ jobs:
|
||||
contents: write
|
||||
needs: plugin-keys
|
||||
name: Build (${{ matrix.name }})
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
strategy:
|
||||
@@ -227,6 +229,7 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: server
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Signing configured
|
||||
|
||||
@@ -20,6 +20,8 @@ env:
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
# the `release` environment, which holds those secrets.
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
@@ -96,6 +98,7 @@ jobs:
|
||||
contents: write
|
||||
needs: create-release
|
||||
name: Official plugins
|
||||
environment: release
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -1080,6 +1081,9 @@ impl DebugManager {
|
||||
.await?;
|
||||
arguments["program"] = json!(program);
|
||||
}
|
||||
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
|
||||
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
|
||||
}
|
||||
// Attach to a Node process started without `--inspect`: open its inspector first.
|
||||
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
|
||||
let pid = arguments.get("processId").and_then(|p| match p {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! SwiftPM launch integration: a launch request may carry
|
||||
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
|
||||
//! The run configuration's before launch task has built the product; this asks
|
||||
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
|
||||
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
|
||||
|
||||
use crate::adapter::find_binary;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
/// `swift build` arguments that print the bin path for `buildArgs` without building.
|
||||
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
|
||||
let mut args = vec!["build".to_owned()];
|
||||
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
|
||||
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
|
||||
}
|
||||
args.push("--show-bin-path".into());
|
||||
args
|
||||
}
|
||||
|
||||
/// The built product of `swiftpm` (see the module docs).
|
||||
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
|
||||
let product = swiftpm
|
||||
.get("product")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
|
||||
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
|
||||
let args = bin_path_args(swiftpm);
|
||||
let mut cmd = tokio::process::Command::new(swift);
|
||||
cmd.current_dir(cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let out = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
|
||||
};
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
|
||||
}
|
||||
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
|
||||
if dir.is_empty() {
|
||||
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
|
||||
}
|
||||
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
|
||||
Ok(cwd.join(dir).join(exe))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
|
||||
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
|
||||
assert_eq!(
|
||||
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
|
||||
["build", "-c", "release", "--show-bin-path"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
|
||||
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Flutter submenu.
|
||||
pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
|
||||
/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has
|
||||
/// Xcode schemes. A submenu after Build › Flutter when it has items, like it.
|
||||
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Xcode submenu.
|
||||
pub const XCODE_BUILD_MENU: &str = "build.xcode";
|
||||
|
||||
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
|
||||
/// separator; `None`: its items are listed in place.
|
||||
pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
|
||||
match slot {
|
||||
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
|
||||
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
|
||||
/// them with `menu.<id>` strings from the active locale catalog.
|
||||
@@ -622,6 +637,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Build",
|
||||
vec![
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
|
||||
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
|
||||
act("build.buildProject", "Build Project"),
|
||||
act("build.buildModule", "Build Module"),
|
||||
act("build.compileFile", "Recompile"),
|
||||
@@ -1298,12 +1314,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
|
||||
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
|
||||
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
|
||||
let items = config.dynamic_items(slot);
|
||||
if !items.is_empty() {
|
||||
out.push(MenuNode::Submenu {
|
||||
id: FLUTTER_BUILD_MENU.into(),
|
||||
label: "Flutter".into(),
|
||||
id: id.into(),
|
||||
label: label.into(),
|
||||
current: None,
|
||||
children: items.iter().map(DynamicItem::model).collect(),
|
||||
});
|
||||
|
||||
@@ -52,6 +52,8 @@ pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
pub mod xcode_bsp;
|
||||
pub mod xcode_clean;
|
||||
pub mod xcode_files;
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -140,6 +142,8 @@ ide_command::domains!(
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
xcode_bsp: crate::ops::xcode_bsp,
|
||||
xcode_clean: crate::ops::xcode_clean,
|
||||
xcode_files: crate::ops::xcode_files,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
|
||||
@@ -552,6 +552,15 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
|
||||
let root = project.root.clone();
|
||||
config = host
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Deleting an Xcode project's DerivedData (#6665 C6). Clean Build Folder is a run of
|
||||
//! `ide_run::xcode_clean::KIND`; this is the part a run can't do: moving folders to the Trash.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
async fn dirs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let project = host.project(window)?;
|
||||
let dir = project.root.join(cwd.unwrap_or_default());
|
||||
let cache = project.cache_dir.clone();
|
||||
super::blocking(move || ide_run::xcode_clean::derived_data_dirs(&dir, &cache, ¶ms)).await
|
||||
}
|
||||
|
||||
/// The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode`
|
||||
/// configuration (its `cwd` and `params`), for the user to confirm.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
Ok(dirs(host, window, cwd, params).await?.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
/// Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a
|
||||
/// build server config (xcode-build-server's `build_root`) reads build logs and the index there.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_delete_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let found = dirs(host, window, cwd, params).await?;
|
||||
let deleted = found.clone();
|
||||
super::blocking(move || found.iter().try_for_each(|d| ide_vfs::delete(d))).await?;
|
||||
let project = host.project(window)?;
|
||||
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
|
||||
project.lsp.restart(server.id).await?;
|
||||
}
|
||||
Ok(deleted.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_clean: xcode_derived_data, xcode_delete_derived_data);
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Source files created, renamed or deleted in an Xcode project (#6665 C7). `xcodebuild` compiles
|
||||
//! only the files a target lists, so a new file in a classic `.xcodeproj` group is silently left
|
||||
//! out. The IDE does not edit `project.pbxproj`: for XcodeGen / Tuist projects it offers to
|
||||
//! regenerate the project, and for a classic project it says which new files the project doesn't
|
||||
//! name, unless the project uses Xcode 16 synchronized folders, which pick new files up themselves.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Source files a target compiles; other files don't make `xcodebuild` miss code.
|
||||
const SOURCE_EXTENSIONS: [&str; 9] = ["swift", "m", "mm", "h", "c", "cc", "cpp", "hpp", "metal"];
|
||||
|
||||
/// What the changed files need in their Xcode project.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum XcodeFileSync {
|
||||
/// The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Generated { dir: PathBuf, tool: String },
|
||||
/// `files` (file names) are not named in `project`, a classic `.xcodeproj`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
NotInProject { project: PathBuf, files: Vec<String> },
|
||||
}
|
||||
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e))
|
||||
}
|
||||
|
||||
/// Hidden folders and the bundles themselves are not project sources.
|
||||
fn is_project_file(path: &Path, root: &Path) -> bool {
|
||||
path.strip_prefix(root).is_ok_and(|rel| {
|
||||
rel.components().all(|c| {
|
||||
let name = c.as_os_str().to_string_lossy();
|
||||
!name.starts_with('.') && !name.ends_with(".xcodeproj") && !name.ends_with(".xcworkspace")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
enum Owner {
|
||||
Generated(PathBuf, &'static str),
|
||||
Classic(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// The nearest folder from `path` up to `root` with a project spec or `.xcodeproj` bundles.
|
||||
fn owner(path: &Path, root: &Path) -> Option<Owner> {
|
||||
let mut dir = path.parent()?;
|
||||
loop {
|
||||
if dir.join("project.yml").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "xcodegen"));
|
||||
}
|
||||
if dir.join("Project.swift").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "tuist"));
|
||||
}
|
||||
// A local Swift package builds its files from the folder layout, not from a project.
|
||||
if dir.join("Package.swift").is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut projects: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "xcodeproj") && p.is_dir())
|
||||
.collect();
|
||||
if !projects.is_empty() {
|
||||
projects.sort();
|
||||
return Some(Owner::Classic(projects));
|
||||
}
|
||||
if dir == root {
|
||||
return None;
|
||||
}
|
||||
dir = dir.parent()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `text` names `file` as a whole name (`/* View.swift */`, `path = View.swift;`,
|
||||
/// `"My View.swift"`), not as the end of another one (`AppView.swift`).
|
||||
fn names(text: &str, file: &str) -> bool {
|
||||
let part_of_name = |c: char| c.is_alphanumeric() || "_-.+".contains(c);
|
||||
text.match_indices(file).any(|(at, _)| {
|
||||
!text[..at].chars().next_back().is_some_and(part_of_name)
|
||||
&& !text[at + file.len()..].chars().next().is_some_and(part_of_name)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `created` (created or renamed to) and `removed` source files under `root` need; the
|
||||
/// first Xcode project they belong to wins.
|
||||
pub fn file_sync(root: &Path, created: &[PathBuf], removed: &[PathBuf]) -> Option<XcodeFileSync> {
|
||||
let relevant = |p: &&PathBuf| is_source(p) && is_project_file(p, root);
|
||||
let mut classic: Option<(Vec<PathBuf>, Vec<String>)> = None;
|
||||
for (path, is_new) in
|
||||
created.iter().filter(relevant).map(|p| (p, true)).chain(removed.iter().filter(relevant).map(|p| (p, false)))
|
||||
{
|
||||
match owner(path, root) {
|
||||
Some(Owner::Generated(dir, tool)) => return Some(XcodeFileSync::Generated { dir, tool: tool.into() }),
|
||||
// A deleted file is still named in the project; Xcode shows it in red.
|
||||
Some(Owner::Classic(projects)) if is_new => {
|
||||
let (owner_projects, files) = classic.get_or_insert_with(|| (projects.clone(), Vec::new()));
|
||||
if *owner_projects == projects {
|
||||
files.push(path.file_name()?.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (projects, files) = classic?;
|
||||
// Plain string checks on project.pbxproj, no parsing; a project mixing groups and
|
||||
// synchronized folders counts as synchronized, as does a name that's taken by another file.
|
||||
let texts: Vec<String> =
|
||||
projects.iter().filter_map(|p| std::fs::read_to_string(p.join("project.pbxproj")).ok()).collect();
|
||||
if texts.is_empty() || texts.iter().any(|t| t.contains("PBXFileSystemSynchronizedRootGroup")) {
|
||||
return None;
|
||||
}
|
||||
let mut files: Vec<String> = files.into_iter().filter(|f| !texts.iter().any(|t| names(t, f))).collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
(!files.is_empty()).then(|| XcodeFileSync::NotInProject { project: projects[0].clone(), files })
|
||||
}
|
||||
|
||||
/// What source files created, renamed or deleted in the project need in their Xcode project;
|
||||
/// `None` when they are in none, or it picks them up itself.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_file_sync(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
created: Vec<PathBuf>,
|
||||
removed: Vec<PathBuf>,
|
||||
) -> IdeResult<Option<XcodeFileSync>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || Ok(file_sync(&root, &created, &removed))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_files: xcode_file_sync);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project(files: &[(&str, &str)]) -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (path, text) in files {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
const CLASSIC: &str = "/* Begin PBXFileReference section */ AppView.swift /* End */";
|
||||
|
||||
#[test]
|
||||
fn names_new_sources_a_classic_project_does_not_mention() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("App/AppView.swift", "")]);
|
||||
let root = dir.path();
|
||||
let created = [
|
||||
root.join("App/AppView.swift"),
|
||||
root.join("App/New.swift"),
|
||||
root.join("App/View.swift"),
|
||||
root.join("App/notes.md"),
|
||||
];
|
||||
assert_eq!(
|
||||
file_sync(root, &created, &[]),
|
||||
Some(XcodeFileSync::NotInProject {
|
||||
project: root.join("App.xcodeproj"),
|
||||
files: vec!["New.swift".into(), "View.swift".into()]
|
||||
})
|
||||
);
|
||||
// Deleting a file needs nothing in a classic project.
|
||||
assert_eq!(file_sync(root, &[], &[root.join("App/AppView.swift")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusts_synchronized_folders() {
|
||||
let text = "/* Begin PBXFileSystemSynchronizedRootGroup section */";
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", text)]);
|
||||
assert_eq!(file_sync(dir.path(), &[dir.path().join("App/New.swift")], &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offers_the_generator_of_the_nearest_spec() {
|
||||
let dir =
|
||||
project(&[("project.yml", ""), ("App.xcodeproj/project.pbxproj", CLASSIC), ("Mod/Project.swift", "")]);
|
||||
let root = dir.path();
|
||||
let generated = |dir: PathBuf, tool: &str| Some(XcodeFileSync::Generated { dir, tool: tool.into() });
|
||||
assert_eq!(file_sync(root, &[], &[root.join("Sources/Old.swift")]), generated(root.into(), "xcodegen"));
|
||||
assert_eq!(file_sync(root, &[root.join("Mod/A.m")], &[]), generated(root.join("Mod"), "tuist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_of_a_local_package_next_to_the_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("Packages/Feature/Package.swift", "")]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(root, &[root.join("Packages/Feature/Sources/Feature/New.swift")], &[]), None);
|
||||
// Files of the app itself are still checked.
|
||||
assert!(file_sync(root, &[root.join("App/New.swift")], &[]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_outside_any_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC)]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(&root.join("Sub"), &[root.join("Sub/A.swift")], &[]), None);
|
||||
assert_eq!(file_sync(root, &[root.join(".build/A.swift"), PathBuf::from("/elsewhere/A.swift")], &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -414,7 +414,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
});
|
||||
|
||||
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Always, |c| async move {
|
||||
let current = c.host.local_data_dir.to_string_lossy().into_owned();
|
||||
Ok(LocalDataInfo {
|
||||
default_dir: current.clone(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Swift packages (`Package.swift`): one `swift run <product>` per executable product, built
|
||||
//! first by `swift build --product <product>` and debuggable with lldb-dap on the built
|
||||
//! `.build/debug/<product>`. Read from the manifest's source: `swift package describe` would
|
||||
//! product (found by `swift build --show-bin-path` when debugging). Read from the manifest's source: `swift package describe` would
|
||||
//! compile and run the manifest, and detection never runs the project's build code.
|
||||
|
||||
use super::zig::{call_body, code_only, string_at};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
|
||||
//! Simulator (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! so its schemes and theirs are built through it.
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod tomcat;
|
||||
mod utf8;
|
||||
pub mod wrap;
|
||||
pub mod xcode;
|
||||
pub mod xcode_clean;
|
||||
|
||||
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
|
||||
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! projects without any, but it takes a second or two, too slow for detection.
|
||||
//!
|
||||
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
|
||||
//! `simctl`; [`prepare`] turns the configuration into that process when it starts.
|
||||
//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable;
|
||||
//! [`prepare`] turns the configuration into that process when it starts.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
@@ -208,15 +209,24 @@ fn pick_simulator(json: &str) -> Option<String> {
|
||||
|
||||
/// The run configuration parameter that holds the simulator's UDID. Empty means
|
||||
/// [`default_simulator`]: the one place a device selector can feed its choice into.
|
||||
/// [`MAC`] runs an app that supports both on the Mac instead.
|
||||
pub const SIMULATOR_PARAM: &str = "simulator";
|
||||
|
||||
/// Set (to anything but empty) by Debug: the app is launched suspended
|
||||
/// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints.
|
||||
pub const WAIT_FOR_DEBUGGER_PARAM: &str = "waitForDebugger";
|
||||
|
||||
/// The [`SIMULATOR_PARAM`] value that runs a multiplatform app on the Mac.
|
||||
pub const MAC: &str = "macos";
|
||||
|
||||
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the simulator.
|
||||
pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &Path) -> Result<Vec<String>, String> {
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the `-destination`
|
||||
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme).
|
||||
pub fn build_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: Option<&str>,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
@@ -225,30 +235,50 @@ pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend([
|
||||
"-destination".to_owned(),
|
||||
format!("id={udid}"),
|
||||
"-derivedDataPath".to_owned(),
|
||||
derived_data.to_string_lossy().into_owned(),
|
||||
]);
|
||||
if let Some(destination) = destination {
|
||||
args.extend(["-destination".to_owned(), destination.to_owned()]);
|
||||
}
|
||||
args.extend(["-derivedDataPath".to_owned(), derived_data.to_string_lossy().into_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The application targets' build settings in `xcodebuild -showBuildSettings -json` output.
|
||||
fn app_settings(settings: &str) -> Result<Vec<serde_json::Value>, String> {
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
|
||||
let targets = json.as_array().cloned().unwrap_or_default();
|
||||
Ok(targets
|
||||
.into_iter()
|
||||
.map(|mut t| t["buildSettings"].take())
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Whether the scheme's first application runs on the Mac, from its `SUPPORTED_PLATFORMS` in
|
||||
/// build settings read without a destination: it supports macOS but not the iOS Simulator, or
|
||||
/// both and `simulator` is [`MAC`].
|
||||
pub fn runs_on_mac(settings: &str, simulator: &str) -> Result<bool, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.first().ok_or("The scheme builds no application")?;
|
||||
let platforms: Vec<&str> = app["SUPPORTED_PLATFORMS"].as_str().unwrap_or_default().split_whitespace().collect();
|
||||
Ok(platforms.contains(&"macosx") && (simulator.trim() == MAC || !platforms.contains(&"iphonesimulator")))
|
||||
}
|
||||
|
||||
/// The executable inside the built macOS `.app`: `TARGET_BUILD_DIR/EXECUTABLE_PATH`.
|
||||
pub fn mac_executable(settings: &str) -> Result<PathBuf, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.iter().find(|b| b["PLATFORM_NAME"] == "macosx").ok_or("The scheme builds no macOS application")?;
|
||||
let get =
|
||||
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
|
||||
Ok(Path::new(get("TARGET_BUILD_DIR")?).join(get("EXECUTABLE_PATH")?))
|
||||
}
|
||||
|
||||
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
|
||||
/// scheme's first application target.
|
||||
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
|
||||
let targets = json.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let apps = || {
|
||||
targets
|
||||
.iter()
|
||||
.map(|t| &t["buildSettings"])
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
};
|
||||
let Some(app) = apps().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
return Err(match apps().next().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some("macosx") => "Running macOS apps is not supported yet; only iOS apps run on the Simulator".to_owned(),
|
||||
let apps = app_settings(settings)?;
|
||||
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
|
||||
None => "The scheme builds no application".to_owned(),
|
||||
});
|
||||
@@ -311,33 +341,79 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The script a macOS run executes: build, then become the app's executable, so its output
|
||||
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
|
||||
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
|
||||
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
|
||||
format!("set -e\nxcodebuild {} build\nexec {} \"$@\"\n", build.join(" "), sh_quote(&executable.to_string_lossy()))
|
||||
}
|
||||
|
||||
/// The `-destination` of a run of `params` on a Mac.
|
||||
pub const MAC_DESTINATION: &str = "platform=macOS";
|
||||
|
||||
/// Runs `program` in `dir` and returns its stdout; a failure carries its stderr.
|
||||
fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// Where a run of `params` builds: [`MAC_DESTINATION`] when the scheme's app runs on the Mac
|
||||
/// ([`runs_on_mac`]), else `id=<udid>` of the configured simulator or the default one. A Clean
|
||||
/// Build Folder of the configuration uses the same destination.
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data: &Path) -> IdeResult<String> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
let args = [
|
||||
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
|
||||
vec!["-showBuildSettings".into(), "-json".into()],
|
||||
]
|
||||
.concat();
|
||||
if runs_on_mac(&output(dir, "xcodebuild", &args)?, simulator).map_err(IdeError::invalid)? {
|
||||
return Ok(MAC_DESTINATION.to_owned());
|
||||
}
|
||||
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
Ok(format!("id={udid}"))
|
||||
}
|
||||
|
||||
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
|
||||
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches the app as `SIMCTL_CHILD_*`.
|
||||
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
|
||||
}
|
||||
let output = |program: &str, args: &[String]| -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
};
|
||||
let params = &config.extras.params;
|
||||
let udid = match params.get(SIMULATOR_PARAM).map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
let derived_data = cache_dir.join("xcode/DerivedData");
|
||||
let args = build_args(params, &udid, &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = output("xcodebuild", &[args.as_slice(), &["-showBuildSettings".into(), "-json".into()]].concat())?;
|
||||
let derived_data = crate::xcode_clean::ide_derived_data(cache_dir);
|
||||
let show =
|
||||
|args: &[String]| output(dir, "xcodebuild", &[args, &["-showBuildSettings".into(), "-json".into()]].concat());
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
if destination == MAC_DESTINATION {
|
||||
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), mac_launch_script(&args, &executable), "xcode-run".to_owned()]
|
||||
.into_iter()
|
||||
.chain(app_args)
|
||||
.collect();
|
||||
// Foundation buffers a GUI app's stdout when it is not a terminal; Xcode sets this too.
|
||||
config.env.entry("NSUnbufferedIO".to_owned()).or_insert_with(|| "YES".to_owned());
|
||||
return Ok(());
|
||||
}
|
||||
let udid = destination.trim_start_matches("id=").to_owned();
|
||||
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = show(&args)?;
|
||||
let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
@@ -477,7 +553,7 @@ mod tests {
|
||||
.into();
|
||||
let dd = Path::new("/cache/DerivedData");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap(),
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
@@ -494,11 +570,11 @@ mod tests {
|
||||
params.insert("container".into(), "App.xcodeproj".into());
|
||||
params.remove("configuration");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap()[..5],
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap()[..5],
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
|
||||
);
|
||||
params.remove("scheme");
|
||||
assert_eq!(build_args(¶ms, "U1", dd).unwrap_err(), "No scheme is set");
|
||||
assert_eq!(build_args(¶ms, Some("id=U1"), dd).unwrap_err(), "No scheme is set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -517,10 +593,101 @@ mod tests {
|
||||
built_app(&settings("iphonesimulator")).unwrap(),
|
||||
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
assert!(built_app(&settings("macosx")).unwrap_err().contains("macOS apps is not supported"));
|
||||
assert_eq!(
|
||||
built_app(&settings("macosx")).unwrap_err(),
|
||||
"The scheme builds an app for macosx, not the iOS Simulator"
|
||||
);
|
||||
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mac_only_app_or_a_multiplatform_one_pinned_to_the_mac_runs_on_the_mac() {
|
||||
let settings = |platforms: &str| {
|
||||
format!(
|
||||
r#"[{{"target": "Kit", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.framework", "SUPPORTED_PLATFORMS": "macosx"}}}},
|
||||
{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", "SUPPORTED_PLATFORMS": "{platforms}"}}}}]"#
|
||||
)
|
||||
};
|
||||
assert!(runs_on_mac(&settings("macosx"), "").unwrap());
|
||||
assert!(runs_on_mac(&settings("macosx"), "SOME-UDID").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), "").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), MAC).unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator macosx"), "SOME-UDID").unwrap());
|
||||
assert!(runs_on_mac(&settings("iphoneos iphonesimulator macosx"), " macos ").unwrap());
|
||||
assert_eq!(runs_on_mac("[]", "").unwrap_err(), "The scheme builds no application");
|
||||
|
||||
let mac = r#"[{"target": "App", "buildSettings": {"PRODUCT_TYPE": "com.apple.product-type.application",
|
||||
"PLATFORM_NAME": "macosx", "TARGET_BUILD_DIR": "/dd/Build/Products/Debug", "EXECUTABLE_PATH": "My App.app/Contents/MacOS/My App"}}]"#;
|
||||
assert_eq!(
|
||||
mac_executable(mac).unwrap(),
|
||||
PathBuf::from("/dd/Build/Products/Debug/My App.app/Contents/MacOS/My App")
|
||||
);
|
||||
assert_eq!(mac_executable(&settings("macosx")).unwrap_err(), "The scheme builds no macOS application");
|
||||
let dd = Path::new("/dd");
|
||||
let params: BTreeMap<String, String> =
|
||||
[("container", "App.xcodeproj"), ("scheme", "App")].map(|(k, v)| (k.to_owned(), v.to_owned())).into();
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("platform=macOS"), dd).unwrap(),
|
||||
[
|
||||
"-project",
|
||||
"App.xcodeproj",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-destination",
|
||||
"platform=macOS",
|
||||
"-derivedDataPath",
|
||||
"/dd"
|
||||
]
|
||||
);
|
||||
assert!(!build_args(¶ms, None, dd).unwrap().iter().any(|a| a == "-destination"));
|
||||
}
|
||||
|
||||
/// The script builds, then runs the executable in its place: the stub app logs its arguments
|
||||
/// and environment and exits on the SIGINT a Stop sends.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn mac_launch_script_builds_then_runs_the_executable_until_stopped() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |path: &Path, then: &str| {
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '%s' \"${{0##*/}}\" >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(path, body).unwrap();
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub(&dir.path().join("xcodebuild"), "");
|
||||
let exe = dir.path().join("My App");
|
||||
stub(
|
||||
&exe,
|
||||
"echo \"GREETING=$GREETING\" >> \"$LOG\"\ntrap 'echo stopped >> \"$LOG\"; exit 0' INT\nwhile :; do sleep 0.05; done\n",
|
||||
);
|
||||
let build = ["-scheme".to_owned(), "It's".to_owned(), "-destination".to_owned(), "platform=macOS".to_owned()];
|
||||
let mut child = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &mac_launch_script(&build, &exe), "xcode-run", "--greeting", "hi there"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.env("GREETING", "hello")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !fs::read_to_string(&log).unwrap_or_default().contains("GREETING") && std::time::Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
assert!(child.wait().unwrap().success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(&log).unwrap(),
|
||||
"xcodebuild [-scheme] [It's] [-destination] [platform=macOS] [build]\n\
|
||||
My App [--greeting] [hi there]\n\
|
||||
GREETING=hello\n\
|
||||
stopped\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs the script against stub `xcodebuild`, `xcrun` and `open` that log their arguments; the
|
||||
/// stub `simctl launch` runs until it gets SIGTERM, which a Stop's SIGINT must turn into.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Product › Clean Build Folder and deleting a project's DerivedData, for the `kind = "xcode"`
|
||||
//! configurations of `crate::detect::xcode`.
|
||||
use crate::xcode::{build_args, destination};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's.
|
||||
pub const KIND: &str = "xcode-clean";
|
||||
|
||||
/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache.
|
||||
pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
|
||||
cache_dir.join("xcode/DerivedData")
|
||||
}
|
||||
|
||||
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
|
||||
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
|
||||
/// macOS app) and DerivedData. `dir` is the configuration's working directory.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
let params = &config.extras.params;
|
||||
let derived_data = ide_derived_data(cache_dir);
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
config.args = clean_args(params, &destination, &derived_data).map_err(IdeError::invalid)?;
|
||||
config.command = "xcodebuild".into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: &str,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut args = build_args(params, Some(destination), derived_data)?;
|
||||
args.push("clean".into());
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// `xcodebuild -showBuildSettings -json` of the scheme as Xcode builds it: no destination and no
|
||||
/// `-derivedDataPath`, so the build folder is the one in Xcode's DerivedData location.
|
||||
fn settings_args(params: &BTreeMap<String, String>) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
let mut args = vec![flag.to_owned(), container.to_owned(), "-scheme".to_owned(), scheme.to_owned()];
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend(["-showBuildSettings".to_owned(), "-json".to_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's `<Name>-<hash>` folder in Xcode's DerivedData: the ancestor of the build
|
||||
/// settings' `BUILD_DIR` (else `OBJROOT`) that sits directly in a `DerivedData` folder. `None`
|
||||
/// when the build folder is elsewhere (a custom DerivedData location or a legacy `build/`).
|
||||
pub fn derived_data_of(settings: &str) -> Option<PathBuf> {
|
||||
let json: serde_json::Value = serde_json::from_str(settings).ok()?;
|
||||
let build = json.as_array()?.iter().find_map(|t| {
|
||||
let s = &t["buildSettings"];
|
||||
s["BUILD_DIR"].as_str().or(s["OBJROOT"].as_str()).filter(|v| !v.is_empty())
|
||||
})?;
|
||||
Path::new(build)
|
||||
.ancestors()
|
||||
.find(|dir| dir.parent().and_then(Path::file_name).is_some_and(|name| name == "DerivedData"))
|
||||
.map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's
|
||||
/// `<Name>-<hash>` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one.
|
||||
/// `dir` is the configuration's working directory.
|
||||
pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<Vec<PathBuf>> {
|
||||
let args = settings_args(params).map_err(IdeError::invalid)?;
|
||||
let mut cmd = std::process::Command::new("xcodebuild");
|
||||
cmd.args(&args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run xcodebuild: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("xcodebuild {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
let xcode = derived_data_of(&String::from_utf8_lossy(&out.stdout));
|
||||
Ok(xcode.into_iter().chain([ide_derived_data(cache_dir)]).filter(|d| d.is_dir()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn params(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_cleans_the_build_a_run_makes() {
|
||||
let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]);
|
||||
assert_eq!(
|
||||
clean_args(&p, "id=UDID", Path::new("/cache/xcode/DerivedData")).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-configuration",
|
||||
"Debug",
|
||||
"-destination",
|
||||
"id=UDID",
|
||||
"-derivedDataPath",
|
||||
"/cache/xcode/DerivedData",
|
||||
"clean"
|
||||
]
|
||||
);
|
||||
assert_eq!(ide_derived_data(Path::new("/cache")), Path::new("/cache/xcode/DerivedData"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_settings_are_read_where_xcode_builds() {
|
||||
let p = params(&[("container", "App.xcodeproj"), ("scheme", "App")]);
|
||||
assert_eq!(
|
||||
settings_args(&p).unwrap(),
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-showBuildSettings", "-json"]
|
||||
);
|
||||
assert!(settings_args(¶ms(&[("container", "App.xcodeproj")])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_data_is_the_folder_in_derived_data_that_holds_the_build() {
|
||||
let settings = |key: &str, dir: &str| format!(r#"[{{"target":"App","buildSettings":{{"{key}":"{dir}"}}}}]"#);
|
||||
let dd = "/Users/me/Library/Developer/Xcode/DerivedData/App-abcdef";
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", &format!("{dd}/Build/Products"))), Some(dd.into()));
|
||||
assert_eq!(
|
||||
derived_data_of(&settings("OBJROOT", &format!("{dd}/Build/Intermediates.noindex"))),
|
||||
Some(dd.into())
|
||||
);
|
||||
// A custom location or a legacy build folder: nothing to delete.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/Volumes/Builds/App-abcdef/Build/Products")), None);
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/src/App/build")), None);
|
||||
// The DerivedData folder itself is never the answer.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/x/DerivedData")), None);
|
||||
assert_eq!(derived_data_of("not json"), None);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
/// Exclude globs from settings (`files.exclude`), e.g. `**/node_modules`.
|
||||
@@ -97,6 +98,11 @@ pub(crate) struct GitignoreStack {
|
||||
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
|
||||
repo_level: RwLock<Vec<Gitignore>>,
|
||||
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
|
||||
/// Bumped (under the `cache` lock) by every invalidation. A lookup that read the ignore
|
||||
/// files before an invalidation doesn't store what it read: the watcher thread may be
|
||||
/// matching a new file while a command rewrites `.gitignore` and invalidates, and its
|
||||
/// older rules must not land in the cache after that.
|
||||
generation: AtomicU64,
|
||||
nested: Mutex<NestedRepos>,
|
||||
}
|
||||
|
||||
@@ -127,7 +133,7 @@ impl GitignoreStack {
|
||||
pub fn new(near: &Path) -> Self {
|
||||
let repo_root = find_repo_root(near);
|
||||
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
|
||||
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
|
||||
Self { repo_root, repo_level, cache: Mutex::default(), generation: AtomicU64::new(0), nested: Mutex::default() }
|
||||
}
|
||||
|
||||
/// [`new`](Self::new) for listing a directory over and over (expanding a tree, a slow share):
|
||||
@@ -163,6 +169,7 @@ impl GitignoreStack {
|
||||
repo_root: entry.repo_root.clone(),
|
||||
repo_level: RwLock::new(entry.rules.clone()),
|
||||
cache: Mutex::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
nested: Mutex::default(),
|
||||
}
|
||||
}
|
||||
@@ -217,6 +224,7 @@ impl GitignoreStack {
|
||||
}
|
||||
}
|
||||
let mut cache = self.cache.lock();
|
||||
self.generation.fetch_add(1, Ordering::Relaxed);
|
||||
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
|
||||
if cache.contains_key(dir) {
|
||||
cache.retain(|k, _| !k.starts_with(dir));
|
||||
@@ -232,7 +240,9 @@ impl GitignoreStack {
|
||||
for stack in self.nested.lock().by_root.values() {
|
||||
stack.invalidate(dir);
|
||||
}
|
||||
self.cache.lock().remove(dir);
|
||||
let mut cache = self.cache.lock();
|
||||
self.generation.fetch_add(1, Ordering::Relaxed);
|
||||
cache.remove(dir);
|
||||
}
|
||||
|
||||
/// Returns the shared `GitignoreStack` of the nested repository enclosing `dir`, if any.
|
||||
@@ -273,6 +283,7 @@ impl GitignoreStack {
|
||||
repo_root: Some(root),
|
||||
repo_level,
|
||||
cache: Mutex::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
nested: Mutex::default(),
|
||||
})
|
||||
})
|
||||
@@ -281,9 +292,13 @@ impl GitignoreStack {
|
||||
}
|
||||
|
||||
fn matcher_for(&self, dir: &Path) -> Option<Arc<Gitignore>> {
|
||||
if let Some(cached) = self.cache.lock().get(dir) {
|
||||
return cached.clone();
|
||||
}
|
||||
let generation = {
|
||||
let cache = self.cache.lock();
|
||||
if let Some(cached) = cache.get(dir) {
|
||||
return cached.clone();
|
||||
}
|
||||
self.generation.load(Ordering::Relaxed)
|
||||
};
|
||||
let mut builder = GitignoreBuilder::new(dir);
|
||||
let mut any = false;
|
||||
for name in [".gitignore", ".ignore"] {
|
||||
@@ -307,7 +322,10 @@ impl GitignoreStack {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.cache.lock().insert(dir.to_path_buf(), matcher.clone());
|
||||
let mut cache = self.cache.lock();
|
||||
if self.generation.load(Ordering::Relaxed) == generation {
|
||||
cache.insert(dir.to_path_buf(), matcher.clone());
|
||||
}
|
||||
matcher
|
||||
}
|
||||
|
||||
@@ -476,6 +494,38 @@ mod tests {
|
||||
assert!(Arc::ptr_eq(&nested, stack.nested.lock().by_root.get(&repo).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_racing_an_invalidation_does_not_cache_the_older_rules() {
|
||||
// The watcher thread matches new files while a command rewrites `.gitignore` and
|
||||
// invalidates; whatever it read before the rewrite must not outlive the invalidation.
|
||||
// A long file keeps the reader busy building its matcher, widening the window.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join(".git")).unwrap();
|
||||
let filler: String = (0..20_000).map(|n| format!("generated-{n}/\n")).collect();
|
||||
let stack = Arc::new(GitignoreStack::new(&root));
|
||||
for i in 0..20 {
|
||||
let name = format!("f{i}.tmp-ignore");
|
||||
std::fs::write(root.join(".gitignore"), &filler).unwrap();
|
||||
stack.invalidate(&root);
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (stack, stop, path) = (stack.clone(), stop.clone(), root.join(&name));
|
||||
std::thread::spawn(move || {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
stack.is_ignored(&path, false);
|
||||
}
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
std::fs::write(root.join(".gitignore"), format!("{filler}{name}\n")).unwrap();
|
||||
stack.invalidate(&root);
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
reader.join().unwrap();
|
||||
assert!(stack.is_ignored(&root.join(&name), false), "round {i} kept the older rules");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repository_created_inside_the_workspace_becomes_a_boundary() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -57,6 +57,16 @@ Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or
|
||||
|
||||
<Tip>`buildServer.json` holds absolute paths for your machine. Add it to `.gitignore` instead of committing it.</Tip>
|
||||
|
||||
**Clean Build Folder** (**Build › Xcode**, Find Action, or right-click the `.xcodeproj` / `.xcworkspace`) runs `xcodebuild clean` for the selected Xcode scheme in the Run tool window, with the same flags a run uses. **Delete DerivedData** moves this project's DerivedData folder (the one `xcodebuild -showBuildSettings` reports, plus the IDE's own run builds) to the Trash after asking, then restarts sourcekit-lsp. Other projects' DerivedData is left alone.
|
||||
|
||||
### New files in Xcode projects
|
||||
|
||||
`xcodebuild` compiles only the files a target lists, and the IDE does not edit `project.pbxproj`. What happens to a source file you create, rename or delete depends on how the project lists its files:
|
||||
|
||||
- **Synchronized folders** (Xcode 16 and newer): files in a folder shown with a blue folder icon in Xcode's navigator belong to the folder's targets as soon as they are on disk. To turn a classic group into one, right-click it in Xcode and choose **Convert to Folder**. New Xcode 16 projects use synchronized folders.
|
||||
- **Classic groups**: a new file must be added to a target in Xcode (**File › Add Files to…**, or drag it into the group). When a new `.swift`, `.m`, `.h` or other source file isn't named in `project.pbxproj`, the IDE says so, with **Open in Xcode**.
|
||||
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen) (`project.yml`) and [Tuist](https://tuist.dev) (`Project.swift`)**: the project is generated from the spec, so after files change the IDE offers to regenerate it (`xcodegen generate` or `tuist generate --no-open`) in the Run tool window. **Regenerate Xcode Project** in **Find Action** (`⌘⇧A` / `Ctrl+Shift+A`), or in the context menu of `project.yml` and `Project.swift`, runs it any time.
|
||||
|
||||
### Several Xcode versions
|
||||
|
||||
To run sourcekit-lsp from a specific Xcode, set `DEVELOPER_DIR` in the server's environment: in **Settings › Languages & Frameworks › Language Servers**, select sourcekit-lsp and add it under **Startup › Environment variables**, or in `settings.toml`:
|
||||
@@ -80,30 +90,27 @@ A `.swift` file can be run with **Run Context Configuration** (`⌃⇧R` / `Ctrl
|
||||
|
||||
### SwiftPM packages
|
||||
|
||||
There are no SwiftPM run or test configurations yet. Run `swift build`, `swift run` and `swift test` in the terminal, or create a **Shell Script** configuration for them (see [Run configurations](/en/guide/run)).
|
||||
Each executable product in `Package.swift` gets a **swift run <product>** run configuration. Its before launch task runs `swift build --product <product>`, then **Run** starts `swift run --skip-build <product>` in the package folder. Tests under `Tests/` get gutter icons that run `swift test --filter`.
|
||||
|
||||
### Xcode schemes
|
||||
|
||||
Each scheme of a `.xcodeproj` or `.xcworkspace` in the project root gets an **Xcode App** run configuration, with the scheme's launch arguments and environment variables. Run builds the scheme with `xcodebuild` and then:
|
||||
|
||||
- **iOS apps** are installed and launched on the simulator chosen in the toolbar, or on the one the configuration's **Simulator** field pins.
|
||||
- **macOS apps** are built with `-destination 'platform=macOS'`, and the app's executable (`<App>.app/Contents/MacOS/<App>`) runs directly: its output shows in the Run console, and **Stop** quits it. No simulator is booted.
|
||||
- **Apps that support both** run on the simulator. Set **Simulator** to `macos` to run them on the Mac instead.
|
||||
|
||||
### Debugging
|
||||
|
||||
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`. To debug a SwiftPM executable:
|
||||
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`.
|
||||
|
||||
<Steps>
|
||||
<Step title="Build it">
|
||||
Run `swift build`. The executable is written to `.build/debug/<product>`.
|
||||
</Step>
|
||||
<Step title="Create a Program configuration">
|
||||
In **Run › Edit Configurations…**, add a **Program** configuration with **Executable** set to
|
||||
`.build/debug/<product>` and **Debug adapter** set to **lldb-dap (C, C++, Swift)**.
|
||||
</Step>
|
||||
<Step title="Debug">
|
||||
Start it with **Debug** (`⌃D` / `Shift+F9`).
|
||||
</Step>
|
||||
</Steps>
|
||||
Start a **swift run <product>** configuration with **Debug** (`⌃D` / `Shift+F9`). The before launch task builds the product as for **Run**, the IDE asks `swift build --show-bin-path` where it was written (with the configuration's build options, such as `-c release`), and lldb-dap launches it with the configuration's arguments, environment and working folder. Program output goes to the **Debug** console. Debugging `swift test` runs is not supported yet.
|
||||
|
||||
Rebuild with `swift build` after editing, as the configuration does not build first. **Attach to Process…** also attaches to a running Swift program with lldb-dap when CodeLLDB is not installed. See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||||
To debug another Swift executable, add a **Program** configuration with **Executable** set to its path and **Debug adapter** set to **lldb-dap (C, C++, Swift)**. **Attach to Process…** also attaches to a running Swift program with lldb-dap when CodeLLDB is not installed. See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||||
|
||||
## Limitations
|
||||
|
||||
- There are no run, test or debug configurations for SwiftPM targets or Xcode schemes, and no test tree for XCTest or Swift Testing.
|
||||
- `swift test` runs cannot be debugged yet.
|
||||
- Xcode projects need a `buildServer.json` that you generate yourself (see [Xcode projects](#xcode-projects)).
|
||||
- **Expand Macro** does nothing: sourcekit-lsp shows the expansion in a new document, which the IDE does not open yet.
|
||||
- There is no SwiftUI Preview, Interface Builder, asset catalog editor or simulator integration. Use Xcode for those.
|
||||
|
||||
@@ -57,6 +57,16 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器
|
||||
|
||||
<Tip>`buildServer.json` 里是本机的绝对路径。把它加入 `.gitignore`,不要提交。</Tip>
|
||||
|
||||
**清理构建文件夹**(**构建 › Xcode**、Find Action,或在 `.xcodeproj` / `.xcworkspace` 上右键)会在 Run 工具窗口中对所选 Xcode scheme 运行 `xcodebuild clean`,参数与运行时相同。**删除 DerivedData** 会先询问,再把本项目的 DerivedData 文件夹(`xcodebuild -showBuildSettings` 报告的那个,以及 IDE 自己运行时的构建)移到废纸篓,然后重启 sourcekit-lsp。其他项目的 DerivedData 不受影响。
|
||||
|
||||
### Xcode 项目中的新文件
|
||||
|
||||
`xcodebuild` 只编译 target 中列出的文件,而 IDE 不会修改 `project.pbxproj`。新建、重命名或删除的源文件会怎样,取决于项目如何列出文件:
|
||||
|
||||
- **同步文件夹**(Xcode 16 及以上):在 Xcode 导航器中显示为蓝色文件夹图标的文件夹,其中的文件一写入磁盘就属于该文件夹的 target。要把传统的组转换成同步文件夹,在 Xcode 中右键点击它并选择 **Convert to Folder**。Xcode 16 新建的项目默认使用同步文件夹。
|
||||
- **传统的组**:新文件需要在 Xcode 中加入 target(**File › Add Files to…**,或拖进对应的组)。新建的 `.swift`、`.m`、`.h` 等源文件没有出现在 `project.pbxproj` 中时,IDE 会提示,并提供 **在 Xcode 中打开**。
|
||||
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen)(`project.yml`)和 [Tuist](https://tuist.dev)(`Project.swift`)**:项目由配置文件生成,所以文件变更后 IDE 会提示重新生成(`xcodegen generate` 或 `tuist generate --no-open`),在运行工具窗口中执行。也可以随时通过 **查找操作**(`⌘⇧A` / `Ctrl+Shift+A`)或 `project.yml`、`Project.swift` 的右键菜单中的 **重新生成 Xcode 项目** 来运行。
|
||||
|
||||
### 多个 Xcode 版本
|
||||
|
||||
要让 sourcekit-lsp 使用某个特定的 Xcode,在服务器的环境中设置 `DEVELOPER_DIR`:在 **设置 › 语言和框架 › 语言服务器** 中选中 sourcekit-lsp,在 **启动 › 环境变量** 中添加;或者写在 `settings.toml` 中:
|
||||
@@ -80,30 +90,27 @@ env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
|
||||
|
||||
### SwiftPM 包
|
||||
|
||||
目前还没有 SwiftPM 的运行或测试配置。在终端里执行 `swift build`、`swift run` 和 `swift test`,或者为它们新建 **Shell 脚本** 配置(见[运行配置](/zh/guide/run))。
|
||||
`Package.swift` 中的每个可执行产品都有一个 **swift run <product>** 运行配置。它的启动前任务执行 `swift build --product <product>`,然后 **运行** 在包所在文件夹中启动 `swift run --skip-build <product>`。`Tests/` 下的测试有装订区图标,点击执行 `swift test --filter`。
|
||||
|
||||
### Xcode scheme
|
||||
|
||||
项目根目录下 `.xcodeproj` 或 `.xcworkspace` 的每个 scheme 都会生成一个 **Xcode App** 运行配置,带上 scheme 的启动参数和环境变量。运行时先用 `xcodebuild` 构建 scheme,然后:
|
||||
|
||||
- **iOS App** 安装到工具栏选中的模拟器上启动,或者装到配置的 **模拟器** 字段固定的模拟器上。
|
||||
- **macOS App** 用 `-destination 'platform=macOS'` 构建,然后直接运行 App 的可执行文件(`<App>.app/Contents/MacOS/<App>`):输出显示在运行控制台里,**停止** 会退出 App。不会启动模拟器。
|
||||
- **同时支持两者的 App** 在模拟器上运行。把 **模拟器** 设为 `macos` 就改在 Mac 上运行。
|
||||
|
||||
### 调试
|
||||
|
||||
调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。调试一个 SwiftPM 可执行程序:
|
||||
调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。
|
||||
|
||||
<Steps>
|
||||
<Step title="构建">
|
||||
执行 `swift build`,可执行文件会写到 `.build/debug/<product>`。
|
||||
</Step>
|
||||
<Step title="新建程序配置">
|
||||
在 **运行 › 编辑配置…** 中添加一个 **程序** 配置,把 **可执行文件** 设为 `.build/debug/<product>`,**调试适配器** 设为
|
||||
**lldb-dap (C, C++, Swift)**。
|
||||
</Step>
|
||||
<Step title="调试">
|
||||
用 **调试**(`⌃D` / `Shift+F9`)启动。
|
||||
</Step>
|
||||
</Steps>
|
||||
用 **调试**(`⌃D` / `Shift+F9`)启动 **swift run <product>** 配置。启动前任务像 **运行** 一样构建产品,IDE 用 `swift build --show-bin-path`(带上配置中的构建选项,例如 `-c release`)找到产物所在位置,再由 lldb-dap 按配置的参数、环境变量和工作目录启动它。程序输出显示在 **调试** 控制台中。目前还不能调试 `swift test`。
|
||||
|
||||
这个配置不会先构建,修改代码后要重新执行 `swift build`。未安装 CodeLLDB 时,**附加到进程…** 也会用 lldb-dap 附加到正在运行的 Swift 程序。断点、单步和变量视图见[调试](/zh/guide/debugging)。
|
||||
要调试其他 Swift 可执行文件,添加一个 **程序** 配置,把 **可执行文件** 设为它的路径,**调试适配器** 设为 **lldb-dap (C, C++, Swift)**。未安装 CodeLLDB 时,**附加到进程…** 也会用 lldb-dap 附加到正在运行的 Swift 程序。断点、单步和变量视图见[调试](/zh/guide/debugging)。
|
||||
|
||||
## 限制
|
||||
|
||||
- 还没有针对 SwiftPM 目标或 Xcode scheme 的运行、测试和调试配置,也没有 XCTest 或 Swift Testing 的测试树。
|
||||
- 还不能调试 `swift test`。
|
||||
- Xcode 项目需要你自己生成 `buildServer.json`(见 [Xcode 项目](#xcode-项目))。
|
||||
- **Expand Macro** 不起作用:sourcekit-lsp 会在新文档中显示展开结果,而 IDE 目前还不会打开它。
|
||||
- 没有 SwiftUI 预览、Interface Builder、资源目录编辑器和模拟器集成,这些请使用 Xcode。
|
||||
|
||||
@@ -48,7 +48,8 @@ pub struct LocalDataInfo {
|
||||
pub env_override: bool,
|
||||
}
|
||||
|
||||
#[desktop_command(trust = trusted)]
|
||||
/// Read-only, and the welcome window shows it too: no project needed.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn caches_local_data_info(app: AppHandle, state: State<'_, AppState>) -> IdeResult<LocalDataInfo> {
|
||||
@@ -65,8 +66,9 @@ pub fn caches_local_data_info(app: AppHandle, state: State<'_, AppState>) -> Ide
|
||||
/// Stores (`Some`) or clears (`None`, an empty string counts) the custom
|
||||
/// local-data root; with `migrate`, the current tree moves at the next start.
|
||||
/// Returns the directory that takes effect after a restart. The caller
|
||||
/// restarts the IDE (see `app_restart`).
|
||||
#[desktop_command(trust = trusted)]
|
||||
/// restarts the IDE (see `app_restart`). An app-wide setting, so it works from
|
||||
/// the welcome window too; a Restricted Mode project window can't change it.
|
||||
#[desktop_command(trust = outside_restricted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn caches_set_local_data_dir(
|
||||
|
||||
@@ -33,8 +33,9 @@ pub struct GtkPickOptions {
|
||||
}
|
||||
|
||||
/// True when the plugin's dialogs can't be shown here: Linux with no portal service on the session
|
||||
/// bus (running or activatable) and no `zenity`.
|
||||
#[desktop_command(trust = trusted)]
|
||||
/// bus (running or activatable) and no `zenity`. Every window picks files (the welcome
|
||||
/// window opens projects with it), so no trust check.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn file_dialog_needs_gtk() -> bool {
|
||||
@@ -51,7 +52,7 @@ pub async fn file_dialog_needs_gtk() -> bool {
|
||||
}
|
||||
|
||||
/// Shows a GTK file chooser attached to `window`. `None` when the user cancels.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn gtk_pick_paths(window: tauri::Window, options: GtkPickOptions) -> IdeResult<Option<Vec<IpcPath>>> {
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_core::IdeResult;
|
||||
|
||||
/// Reports which of `combos` (single-stroke `Alt+Shift+R`-style bindings) are
|
||||
/// already registered to another app. Empty everywhere but Windows.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn system_probe_hotkeys(combos: Vec<String>) -> IdeResult<Vec<String>> {
|
||||
|
||||
@@ -230,12 +230,12 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
|
||||
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
|
||||
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
|
||||
let items = config.dynamic_items(slot);
|
||||
if !items.is_empty() {
|
||||
out.push(RenderedItem::Submenu {
|
||||
id: FLUTTER_BUILD_MENU.into(),
|
||||
title: config.label(FLUTTER_BUILD_MENU, "Flutter"),
|
||||
id: id.into(),
|
||||
title: config.label(id, label),
|
||||
current: false,
|
||||
items: items.iter().map(|item| render_dynamic(item, config)).collect(),
|
||||
});
|
||||
@@ -1402,6 +1402,7 @@ mod tests {
|
||||
DYNAMIC_TOOL_WINDOWS,
|
||||
DYNAMIC_STATUS_BAR_WIDGETS,
|
||||
DYNAMIC_FLUTTER_BUILD,
|
||||
DYNAMIC_XCODE_BUILD,
|
||||
DYNAMIC_PLUGIN_TOOLS,
|
||||
DYNAMIC_LAYOUTS
|
||||
],
|
||||
@@ -1595,6 +1596,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcode_build_submenu_follows_flutter_when_filled() {
|
||||
let mut config = MenuConfig::default();
|
||||
config.dynamic.insert(
|
||||
DYNAMIC_XCODE_BUILD.into(),
|
||||
vec![
|
||||
dynamic_item("xcode.cleanBuildFolder", None, "Clean Build Folder"),
|
||||
dynamic_item("xcode.deleteDerivedData", None, "Delete DerivedData"),
|
||||
],
|
||||
);
|
||||
config.dynamic.insert(DYNAMIC_FLUTTER_BUILD.into(), vec![dynamic_item("flutter.build.ios", None, "Build iOS")]);
|
||||
let build = render_bar(&spec(Os::Mac), &config, &[]).into_iter().find(|m| m.id == "build").unwrap().items;
|
||||
let ids: Vec<_> = build
|
||||
.iter()
|
||||
.take(4)
|
||||
.map(|i| match i {
|
||||
RenderedItem::Submenu { id, title, items, .. } => format!("{id}:{title}:{}", items.len()),
|
||||
RenderedItem::Separator => "-".into(),
|
||||
_ => "?".into(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ids, ["build.flutter:Flutter:1", "-", "build.xcode:Xcode:2", "-"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_menu_lists_recompile_and_patches_its_label() {
|
||||
for os in ALL_OS {
|
||||
|
||||
@@ -103,9 +103,9 @@ build_compile_file trusted project_host bin
|
||||
build_model trusted project_host bindings async
|
||||
build_run trusted project_host bindings async
|
||||
build_sync trusted project_host bindings async
|
||||
caches_local_data_info trusted desktop bindings sync
|
||||
caches_local_data_info always desktop bindings sync
|
||||
caches_schedule_invalidation always desktop bindings sync
|
||||
caches_set_local_data_dir trusted desktop bindings sync
|
||||
caches_set_local_data_dir outside_restricted desktop bindings sync
|
||||
cancel_request always project_host bindings sync
|
||||
cancel_task always project_host bindings sync
|
||||
clear_caches always desktop bindings async
|
||||
@@ -307,7 +307,7 @@ docker_snapshot trusted project_host bin
|
||||
docker_volume_sizes trusted project_host bindings async
|
||||
end_process trusted desktop bindings async
|
||||
env_reload always project_host bindings async
|
||||
file_dialog_needs_gtk trusted desktop bindings async
|
||||
file_dialog_needs_gtk always desktop bindings async
|
||||
find_dirs always project_host bindings async
|
||||
find_files always project_host bindings async
|
||||
find_files_named always project_host bindings async
|
||||
@@ -359,7 +359,7 @@ gradle_dependencies trusted project_host bin
|
||||
gradle_link_projects trusted project_host bindings async
|
||||
gradle_published_catalog trusted project_host bindings async
|
||||
gradle_unlink_projects trusted project_host bindings async
|
||||
gtk_pick_paths trusted desktop bindings async
|
||||
gtk_pick_paths always desktop bindings async
|
||||
history_content always project_host bindings async
|
||||
history_list always project_host bindings async
|
||||
history_list_dir always project_host bindings async
|
||||
@@ -749,7 +749,7 @@ syntax_node_at always project_host bin
|
||||
syntax_structural_ranges always project_host bindings async
|
||||
syntax_support always project_host bindings sync
|
||||
system_font_families always desktop bindings async
|
||||
system_probe_hotkeys trusted desktop bindings sync
|
||||
system_probe_hotkeys always desktop bindings sync
|
||||
term_attach always project_host bindings async
|
||||
term_available_shells always project_host bindings sync
|
||||
term_default_shell always project_host bindings sync
|
||||
@@ -965,3 +965,6 @@ wsl_distros always desktop bin
|
||||
wsl_resolve always desktop bindings sync
|
||||
xcode_bsp_generate trusted project_host bindings async
|
||||
xcode_bsp_setup trusted project_host bindings sync
|
||||
xcode_delete_derived_data trusted project_host bindings async
|
||||
xcode_derived_data trusted project_host bindings async
|
||||
xcode_file_sync trusted project_host bindings async
|
||||
+31
-2
@@ -329,6 +329,7 @@ export const commands = {
|
||||
* Returns the refreshed model; a failed build is reported in its `syncError`.
|
||||
*/
|
||||
buildSync: (tool: BuildTool, request: RequestId, offline: boolean, profiles: string[], buildDir: string | null, onProgress: Channel<SyncProgress>) => typedError<BuildModel, IdeError>(__TAURI_INVOKE("build_sync", { tool, request, offline, profiles, buildDir, onProgress })),
|
||||
/** Read-only, and the welcome window shows it too: no project needed. */
|
||||
cachesLocalDataInfo: () => typedError<LocalDataInfo, IdeError>(__TAURI_INVOKE("caches_local_data_info")),
|
||||
/** Schedules the invalidation for the next start (`None` cancels a pending one). */
|
||||
cachesScheduleInvalidation: (options: {
|
||||
@@ -343,7 +344,8 @@ export const commands = {
|
||||
* Stores (`Some`) or clears (`None`, an empty string counts) the custom
|
||||
* local-data root; with `migrate`, the current tree moves at the next start.
|
||||
* Returns the directory that takes effect after a restart. The caller
|
||||
* restarts the IDE (see `app_restart`).
|
||||
* restarts the IDE (see `app_restart`). An app-wide setting, so it works from
|
||||
* the welcome window too; a Restricted Mode project window can't change it.
|
||||
*/
|
||||
cachesSetLocalDataDir: (path: string | null, migrate: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("caches_set_local_data_dir", { path, migrate })),
|
||||
cancelRequest: (id: RequestId) => __TAURI_INVOKE<void>("cancel_request", { id }),
|
||||
@@ -782,7 +784,8 @@ export const commands = {
|
||||
envReload: () => typedError<EnvReloaded, IdeError>(__TAURI_INVOKE("env_reload")),
|
||||
/**
|
||||
* True when the plugin's dialogs can't be shown here: Linux with no portal service on the session
|
||||
* bus (running or activatable) and no `zenity`.
|
||||
* bus (running or activatable) and no `zenity`. Every window picks files (the welcome
|
||||
* window opens projects with it), so no trust check.
|
||||
*/
|
||||
fileDialogNeedsGtk: () => __TAURI_INVOKE<boolean>("file_dialog_needs_gtk"),
|
||||
/** Folders holding indexed files, for `@` references. */
|
||||
@@ -2795,6 +2798,25 @@ export const commands = {
|
||||
/** The generator found on `PATH`; `None`: neither is installed. */
|
||||
tool: string | null,
|
||||
} | null, IdeError>(__TAURI_INVOKE("xcode_bsp_setup")),
|
||||
/**
|
||||
* Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a
|
||||
* build server config (xcode-build-server's `build_root`) reads build logs and the index there.
|
||||
*/
|
||||
xcodeDeleteDerivedData: (cwd: string | null, params: { [key in string]: string }) => typedError<string[], IdeError>(__TAURI_INVOKE("xcode_delete_derived_data", { cwd, params })),
|
||||
/**
|
||||
* The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode`
|
||||
* configuration (its `cwd` and `params`), for the user to confirm.
|
||||
*/
|
||||
xcodeDerivedData: (cwd: string | null, params: { [key in string]: string }) => typedError<string[], IdeError>(__TAURI_INVOKE("xcode_derived_data", { cwd, params })),
|
||||
/**
|
||||
* What source files created, renamed or deleted in the project need in their Xcode project;
|
||||
* `None` when they are in none, or it picks them up itself.
|
||||
*/
|
||||
xcodeFileSync: (created: string[], removed: string[]) => typedError<
|
||||
/** The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`. */
|
||||
{ kind: "generated"; dir: string; tool: string } |
|
||||
/** `files` (file names) are not named in `project`, a classic `.xcodeproj`. */
|
||||
{ kind: "notInProject"; project: string; files: string[] } | null, IdeError>(__TAURI_INVOKE("xcode_file_sync", { created, removed })),
|
||||
};
|
||||
|
||||
/* Types */
|
||||
@@ -16473,6 +16495,13 @@ export type XcodeBspSetup = {
|
||||
tool: string | null,
|
||||
};
|
||||
|
||||
/** What the changed files need in their Xcode project. */
|
||||
export type XcodeFileSync =
|
||||
/** The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`. */
|
||||
{ kind: "generated"; dir: string; tool: string } |
|
||||
/** `files` (file names) are not named in `project`, a classic `.xcodeproj`. */
|
||||
{ kind: "notInProject"; project: string; files: string[] };
|
||||
|
||||
export type ZigSettings = {
|
||||
/** Directory holding the `zig` executable; empty = the one on `PATH`. */
|
||||
zig?: string,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Gutter icon groups and an editor's local appearance overrides, apart from the editor
|
||||
* preferences so gutter providers can read them without loading the editor setup.
|
||||
*/
|
||||
import { StateEffect, StateField, type EditorState } from "@codemirror/state";
|
||||
import { editorPrefs, type EditorExtras } from "@/platform/editorSettings";
|
||||
|
||||
/**
|
||||
* Gutter icon groups of Settings › Editor › General › Gutter Icons. A hidden group sets
|
||||
* `cm-openidea-hideGutter-<id>` on the editor (the theme hides the bookmark, color and
|
||||
* script/compose run columns by it); the icon area's run and inheritance icons read the
|
||||
* setting themselves.
|
||||
*/
|
||||
export const GUTTER_ICON_GROUPS = [
|
||||
{ id: "run" },
|
||||
{ id: "bookmarks" },
|
||||
{ id: "inheritors" },
|
||||
{ id: "supers" },
|
||||
{ id: "colors" },
|
||||
] as const;
|
||||
|
||||
export type GutterIconGroup = (typeof GUTTER_ICON_GROUPS)[number]["id"];
|
||||
|
||||
/** The four IDEA decoration switches that can be overridden on one editor. */
|
||||
export interface EffectiveAppearance {
|
||||
lineNumbers: boolean;
|
||||
whitespaces: boolean;
|
||||
gutterIcons: boolean;
|
||||
indentGuides: boolean;
|
||||
}
|
||||
|
||||
export type LocalAppearanceKey = keyof EffectiveAppearance;
|
||||
export type LocalAppearanceOverride = Partial<EffectiveAppearance>;
|
||||
|
||||
/** Per-editor decoration overrides live in EditorState, outside the reconfigurable compartments. */
|
||||
export const setLocalAppearance = StateEffect.define<LocalAppearanceOverride | null>();
|
||||
export const localAppearanceField = StateField.define<LocalAppearanceOverride | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
for (const effect of tr.effects) if (effect.is(setLocalAppearance)) value = effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
/** Gutter providers use the editor's effective value, including a local override. */
|
||||
export function gutterIconsOn(
|
||||
state: EditorState | undefined,
|
||||
group?: GutterIconGroup,
|
||||
prefs: Pick<EditorExtras, "showGutterIcons" | "gutterIconsDisabled"> = editorPrefs(),
|
||||
): boolean {
|
||||
const local = state?.field(localAppearanceField, false)?.gutterIcons;
|
||||
return (local ?? prefs.showGutterIcons) && (!group || !prefs.gutterIconsDisabled.includes(group));
|
||||
}
|
||||
@@ -72,6 +72,15 @@ import { LINE_INSET } from "./lineInset";
|
||||
import { codeLensPositions } from "./codeLens";
|
||||
import { stickyMove } from "./stickySelection";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
export {
|
||||
gutterIconsOn,
|
||||
localAppearanceField,
|
||||
setLocalAppearance,
|
||||
type EffectiveAppearance,
|
||||
type LocalAppearanceKey,
|
||||
type LocalAppearanceOverride,
|
||||
} from "./localAppearance";
|
||||
import { GUTTER_ICON_GROUPS, type EffectiveAppearance, type LocalAppearanceOverride } from "./localAppearance";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
|
||||
@@ -586,22 +595,6 @@ const noSurround = EditorView.inputHandler.of((view, from, to, text) => {
|
||||
return true;
|
||||
});
|
||||
|
||||
/**
|
||||
* Gutter icon groups of Settings › Editor › General › Gutter Icons. A hidden group sets
|
||||
* `cm-openidea-hideGutter-<id>` on the editor (the theme hides the bookmark, color and
|
||||
* script/compose run columns by it); the icon area's run and inheritance icons read the
|
||||
* setting themselves.
|
||||
*/
|
||||
export const GUTTER_ICON_GROUPS = [
|
||||
{ id: "run" },
|
||||
{ id: "bookmarks" },
|
||||
{ id: "inheritors" },
|
||||
{ id: "supers" },
|
||||
{ id: "colors" },
|
||||
] as const;
|
||||
|
||||
export type GutterIconGroup = (typeof GUTTER_ICON_GROUPS)[number]["id"];
|
||||
|
||||
/**
|
||||
* Languages whose outer parser is `@lezer/html`, plus JSX / TSX, where
|
||||
* simultaneous `<tag></tag>` editing works from the syntax tree. Angular
|
||||
@@ -619,37 +612,6 @@ const LINKED_TAG_LANGUAGES = new Set([
|
||||
"javascriptreact",
|
||||
]);
|
||||
|
||||
/** The four IDEA decoration switches that can be overridden on one editor. */
|
||||
export interface EffectiveAppearance {
|
||||
lineNumbers: boolean;
|
||||
whitespaces: boolean;
|
||||
gutterIcons: boolean;
|
||||
indentGuides: boolean;
|
||||
}
|
||||
|
||||
export type LocalAppearanceKey = keyof EffectiveAppearance;
|
||||
export type LocalAppearanceOverride = Partial<EffectiveAppearance>;
|
||||
|
||||
/** Per-editor decoration overrides live in EditorState, outside the reconfigurable compartments. */
|
||||
export const setLocalAppearance = StateEffect.define<LocalAppearanceOverride | null>();
|
||||
export const localAppearanceField = StateField.define<LocalAppearanceOverride | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
for (const effect of tr.effects) if (effect.is(setLocalAppearance)) value = effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
/** Gutter providers use the editor's effective value, including a local override. */
|
||||
export function gutterIconsOn(
|
||||
state: EditorState | undefined,
|
||||
group?: GutterIconGroup,
|
||||
prefs: Pick<EditorExtras, "showGutterIcons" | "gutterIconsDisabled"> = editorPrefs(),
|
||||
): boolean {
|
||||
const local = state?.field(localAppearanceField, false)?.gutterIcons;
|
||||
return (local ?? prefs.showGutterIcons) && (!group || !prefs.gutterIconsDisabled.includes(group));
|
||||
}
|
||||
|
||||
/** Editor settings values after applying this editor's optional local overrides. */
|
||||
export function effectiveAppearance(
|
||||
prefs: EditorExtras,
|
||||
|
||||
@@ -282,6 +282,16 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
|
||||
}
|
||||
}
|
||||
|
||||
/** A kind's tab tint; `undefined` when it has none (the tab falls back to file colours). */
|
||||
export function tabTint(input: EditorInput, kinds: EditorKinds): string | undefined {
|
||||
const kind = kinds.get(input.kind);
|
||||
try {
|
||||
return kind?.tabTint?.(input);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
|
||||
function tabModified(tab: Tab): boolean {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { EditorKindContribution } from "@/workbench/contributions";
|
||||
import { tabTint } from "./controller";
|
||||
|
||||
/** `kinds` as the editor reads it: only the registered contributions matter here. */
|
||||
const kindsOf = (...contributions: EditorKindContribution[]) => new Map(contributions.map((c) => [c.kind, c]));
|
||||
|
||||
describe("tabTint", () => {
|
||||
it("returns no tint for a kind that does not supply one", () => {
|
||||
// A file tab is tinted through `setFileDecorations` and its path; nothing kind-level.
|
||||
const kinds = kindsOf({ kind: "plain", title: (i) => i.key, component: () => null });
|
||||
expect(tabTint({ kind: "plain", key: "k" }, kinds)).toBeUndefined();
|
||||
expect(tabTint({ kind: "unregistered", key: "k" }, kinds)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("asks the kind for a tint, and reads it from the input", () => {
|
||||
// A table's tab carries its data source's colour, which lives in the input's data.
|
||||
const kinds = kindsOf({
|
||||
kind: "table-probe",
|
||||
title: (i) => i.key,
|
||||
component: () => null,
|
||||
tabTint: (i) => `var(--db-color-${(i.data as { color: string }).color})`,
|
||||
});
|
||||
const input = { kind: "table-probe", key: "k", data: { color: "red" } };
|
||||
expect(tabTint(input, kinds)).toBe("var(--db-color-red)");
|
||||
});
|
||||
|
||||
it("re-reads the tint on every call, so a changed colour reaches the tab", () => {
|
||||
// The colour is not part of the tab state, so nothing else would re-render the row.
|
||||
let color = "red";
|
||||
const kinds = kindsOf({
|
||||
kind: "table-probe",
|
||||
title: (i) => i.key,
|
||||
component: () => null,
|
||||
tabTint: () => `var(--db-color-${color})`,
|
||||
});
|
||||
const input = { kind: "table-probe", key: "k" };
|
||||
expect(tabTint(input, kinds)).toBe("var(--db-color-red)");
|
||||
color = "blue";
|
||||
expect(tabTint(input, kinds)).toBe("var(--db-color-blue)");
|
||||
});
|
||||
|
||||
it("survives a kind whose tabTint throws", () => {
|
||||
// A broken contribution must not take the tab row down with it.
|
||||
const kinds = kindsOf({
|
||||
kind: "throwing",
|
||||
title: (i) => i.key,
|
||||
component: () => null,
|
||||
tabTint: () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
});
|
||||
expect(tabTint({ kind: "throwing", key: "k" }, kinds)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
useEditorGroupPanels,
|
||||
useFileDecorations,
|
||||
useEditorDocumentRevision,
|
||||
useEditorTabTints,
|
||||
useEditorTabTitles,
|
||||
useTextEditorWrappers,
|
||||
type EditorInput,
|
||||
@@ -67,6 +68,7 @@ import {
|
||||
isTextInput,
|
||||
tabIcon,
|
||||
tabTitle,
|
||||
tabTint,
|
||||
tabTrailing,
|
||||
useTabs,
|
||||
type VirtualInputData,
|
||||
@@ -190,6 +192,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const kinds = useContributions((s) => s.editorKinds);
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
const titleRevision = useEditorTabTitles((s) => s.revision);
|
||||
const tintRevision = useEditorTabTints((s) => s.revision);
|
||||
const tabs = useMemo(() => pane?.tabs ?? [], [pane]);
|
||||
const paths = tabs.map((t) => t.input.path ?? "");
|
||||
const textDirty = useDocMeta(useShallow((s) => paths.map((p) => !!s[p]?.dirty)));
|
||||
@@ -215,10 +218,18 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const items: TabItem[] = useMemo(() => {
|
||||
// A kind's title may change without the tab state (a renamed agent task).
|
||||
void titleRevision;
|
||||
// A kind's tab tint comes from its own store (a data source's colour), which the tab
|
||||
// state knows nothing about: `tintRevision` says it moved.
|
||||
void tintRevision;
|
||||
const names = tabs.map((t) => tabTitle(t.input, kinds));
|
||||
return tabs.map((t, i) => {
|
||||
const full = names[i]!;
|
||||
const dot = full.lastIndexOf(".");
|
||||
const kindTint = tabTint(t.input, kinds);
|
||||
const tint =
|
||||
tints[i] ||
|
||||
kindTint ||
|
||||
(fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined);
|
||||
const name = tabLabels[i] ?? (t.input.kind === "file" && !showExtension && dot > 0 ? full.slice(0, dot) : full);
|
||||
const dupe = !showDirectoryForNonUnique
|
||||
? null
|
||||
@@ -261,9 +272,10 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
// (middle click, Shift+click, Delete) alive when its position is None.
|
||||
showCloseButton,
|
||||
color: colors[i] || undefined,
|
||||
tint:
|
||||
tints[i] || (fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined),
|
||||
tintStrength: tints[i] ? undefined : "var(--file-tint-strength)",
|
||||
tint,
|
||||
// A decoration-tinted tab keeps the full `--tint-strength`; only the softer file
|
||||
// colour drops to `--file-tint-strength`, so a table matches its console.
|
||||
tintStrength: tints[i] || kindTint ? undefined : "var(--file-tint-strength)",
|
||||
tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined),
|
||||
trailing: kindMark,
|
||||
};
|
||||
@@ -273,6 +285,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
tabs,
|
||||
kinds,
|
||||
titleRevision,
|
||||
tintRevision,
|
||||
dirty,
|
||||
colors,
|
||||
errors,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/prefs";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance";
|
||||
import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api";
|
||||
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
|
||||
import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from "@/editor/api";
|
||||
import { onServerSettled } from "@/editor/lsp/availability";
|
||||
import { comparePos } from "@/editor/lsp/positions";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/prefs";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { call, commands, type DocumentColor } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
@@ -183,6 +183,10 @@
|
||||
flex: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
/* A table's toolbar carries its data source's colour, as IDEA tints it. */
|
||||
.sourceTinted {
|
||||
background: color-mix(in srgb, var(--db-source-tint) var(--tint-strength, 22%), transparent);
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* together in one transaction. Tables without a primary key are read-only.
|
||||
*/
|
||||
import { canModifyTable } from "./objects";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
@@ -14,7 +15,7 @@ import {
|
||||
type DbTablePage,
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { EmptyState, Icon, IconButton, Select, Spinner, Toolbar, showContextMenu } from "@/ui";
|
||||
import { Button, EmptyState, Icon, IconButton, Select, Spinner, Toolbar, showContextMenu } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { SqlFilterInput } from "./SqlFilterInput";
|
||||
import { ColumnsPopup } from "./ColumnsPopup";
|
||||
@@ -22,6 +23,7 @@ import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type
|
||||
import type { ExportFormat } from "./export";
|
||||
import {
|
||||
buildRowEdits,
|
||||
colorVar,
|
||||
emptyEdits,
|
||||
formatOrderBy,
|
||||
hasEdits,
|
||||
@@ -31,7 +33,7 @@ import {
|
||||
type Cell,
|
||||
type PendingEdits,
|
||||
} from "./model";
|
||||
import { openDialog, sourceById, withConnection } from "./store";
|
||||
import { openDialog, openDdl, sourceById, withConnection } from "./store";
|
||||
import type { TableRef } from "./tableInput";
|
||||
import styles from "./Database.module.css";
|
||||
import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus";
|
||||
@@ -98,6 +100,9 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
[input.key],
|
||||
);
|
||||
const [nonce, setNonce] = useState(0);
|
||||
// The DDL travels to the backend and back, so the button shows it is working instead of
|
||||
// leaving a click with nothing on screen for a few hundred milliseconds.
|
||||
const [ddlBusy, setDdlBusy] = useState(false);
|
||||
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
|
||||
const [panel, setPanel] = useState<DataPanel | null>(null);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
@@ -282,6 +287,14 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
|
||||
};
|
||||
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
|
||||
const showDdl = async () => {
|
||||
setDdlBusy(true);
|
||||
try {
|
||||
await openDdl(ref.id, ref.schema, ref.table);
|
||||
} finally {
|
||||
setDdlBusy(false);
|
||||
}
|
||||
};
|
||||
const restoreRows = (rows: number[]) =>
|
||||
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
|
||||
const showExport = (at: { x: number; y: number }) =>
|
||||
@@ -333,9 +346,15 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
total: null,
|
||||
});
|
||||
const singlePage = offset === 0 && !hasMore;
|
||||
const tint = colorVar(source?.color);
|
||||
return (
|
||||
<div className={styles.view} ref={viewRef} data-db-table-editor="">
|
||||
<Toolbar className={styles.toolbar} aria-label="Table actions">
|
||||
<div
|
||||
className={styles.view}
|
||||
ref={viewRef}
|
||||
data-db-table-editor=""
|
||||
style={tint ? ({ "--db-source-tint": tint } as CSSProperties) : undefined}
|
||||
>
|
||||
<Toolbar className={clsx(styles.toolbar, tint && styles.sourceTinted)} aria-label="Table actions">
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Reload Page"
|
||||
@@ -350,6 +369,15 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
aria-pressed={searchOpen}
|
||||
onClick={() => setSearchOpen(!searchOpen)}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="small"
|
||||
title="Show DDL"
|
||||
disabled={ddlBusy || ref.catalog !== undefined || source?.driver === "jdbc"}
|
||||
onClick={() => void showDdl()}
|
||||
>
|
||||
DDL
|
||||
</Button>
|
||||
{editable && (
|
||||
<>
|
||||
<span className={styles.toolbarSeparator} />
|
||||
|
||||
@@ -32,13 +32,14 @@ import {
|
||||
useActiveServiceView,
|
||||
setFileDecorations,
|
||||
toolWindowService,
|
||||
notifyTabTintsChanged,
|
||||
} from "@/workbench/contributions";
|
||||
import { installCellActions } from "./cellActions";
|
||||
import { installValueEditorActions } from "./valueEditorActions";
|
||||
import { registerResultTabActions } from "./resultTabActions";
|
||||
import { supportsExplain } from "./model";
|
||||
import { colorVar, supportsExplain } from "./model";
|
||||
import { SQL_LANGUAGE } from "./sqlLanguage";
|
||||
import { TABLE_KIND, tableTitle } from "./tableInput";
|
||||
import { TABLE_KIND, tableTitle, type TableRef } from "./tableInput";
|
||||
import { DIAGRAM_KIND, diagramTitle } from "./erDiagram";
|
||||
import { isCsvPath } from "./csv";
|
||||
import { registerCsvLiveSource, useCsvSourceHidden } from "./csvModes";
|
||||
@@ -260,6 +261,8 @@ export function activate(): () => void {
|
||||
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
|
||||
title: tableTitle,
|
||||
icon: () => "database",
|
||||
// A table's tab carries its data source's colour, the way its console tab does.
|
||||
tabTint: (input) => colorVar(sourceById((input.data as TableRef).id)?.color),
|
||||
// Switching tabs keeps the rows, filters, page and unsubmitted edits without querying again.
|
||||
keepAlive: true,
|
||||
}),
|
||||
@@ -334,8 +337,12 @@ export function activate(): () => void {
|
||||
});
|
||||
}),
|
||||
useDatabase.subscribe((s, prev) => {
|
||||
if (s.consoles !== prev.consoles || s.sources !== prev.sources)
|
||||
if (s.consoles !== prev.consoles || s.sources !== prev.sources) {
|
||||
setFileDecorations("database", consoleDecorations(s));
|
||||
// A table's tab tint is read from its data source, so editing that colour has to
|
||||
// reach the tab row even though no tab state changed.
|
||||
if (s.sources !== prev.sources) notifyTabTintsChanged();
|
||||
}
|
||||
}),
|
||||
() => setFileDecorations("database", new Map()),
|
||||
watchConsoleSessions(),
|
||||
|
||||
@@ -13,6 +13,7 @@ const backend = vi.hoisted(() => ({
|
||||
page: vi.fn(),
|
||||
catalogPage: vi.fn(),
|
||||
applyEdits: vi.fn(),
|
||||
openDdl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
@@ -32,6 +33,7 @@ vi.mock("./store", () => ({
|
||||
sourceById: () => ({ driver: backend.driver, readOnly: false }),
|
||||
withConnection: (_id: string, run: () => unknown) => run(),
|
||||
openDialog: vi.fn(),
|
||||
openDdl: backend.openDdl,
|
||||
}));
|
||||
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
@@ -126,6 +128,27 @@ describe("table editor capabilities", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("opens the table's DDL from the data view's toolbar", async () => {
|
||||
backend.driver = "postgres";
|
||||
await act(async () => {
|
||||
render(<TableEditor input={tableInput("source", "public", "users")} />);
|
||||
});
|
||||
const button = await screen.findByRole("button", { name: "DDL" });
|
||||
fireEvent.click(button);
|
||||
expect(backend.openDdl).toHaveBeenCalledWith("source", "public", "users");
|
||||
});
|
||||
|
||||
it("does not offer DDL where the source cannot report it", async () => {
|
||||
// A custom JDBC source answers no vendor DDL, and a catalog-qualified table is not the
|
||||
// connection's own database, so neither can ask `db_ddl` for a definition.
|
||||
backend.driver = "jdbc";
|
||||
await act(async () => {
|
||||
render(<TableEditor input={tableInput("source", "public", "users")} />);
|
||||
});
|
||||
await screen.findByRole("gridcell", { name: "Ann" });
|
||||
expect(screen.getByRole("button", { name: "DDL" })).toHaveProperty("disabled", true);
|
||||
});
|
||||
|
||||
it("keeps keyed PostgreSQL rows editable", async () => {
|
||||
backend.driver = "postgres";
|
||||
await act(async () => {
|
||||
|
||||
@@ -566,11 +566,12 @@ describe("run config → launch config", () => {
|
||||
debugAdapter: "lldb-dap",
|
||||
params: { product: "greet", program: ".build/debug/greet" },
|
||||
});
|
||||
expect(launchConfigFor(run, "/p")).toMatchObject({
|
||||
program: "/p/pkg/.build/debug/greet",
|
||||
args: ["--loud"],
|
||||
cwd: "/p/pkg",
|
||||
});
|
||||
const launch = launchConfigFor(run, "/p")!;
|
||||
expect(launch).toMatchObject({ args: ["--loud"], cwd: "/p/pkg" });
|
||||
// The backend replaces `program` with `<swift build --show-bin-path>/greet`.
|
||||
expect(extra(launch)).toEqual({ env: [], swiftpm: { product: "greet", buildArgs: [] } });
|
||||
const release = { ...run, args: ["run", "--skip-build", "-c", "release", "greet", "--loud"] };
|
||||
expect(extra(launchConfigFor(release, "/p")!).swiftpm).toEqual({ product: "greet", buildArgs: ["-c", "release"] });
|
||||
});
|
||||
|
||||
it.each(["native", "cmake-application"])(
|
||||
|
||||
@@ -398,10 +398,15 @@ function godotLaunch(rc: RunConfig, cwd: string): LaunchConfig {
|
||||
/** A native program under CodeLLDB, lldb-dap or GDB: program, args, cwd, env. */
|
||||
function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig {
|
||||
const out: LaunchConfig = { ...base(rc, adapter, cwd), program: resolveCommand(rc.command, cwd), args: [...rc.args] };
|
||||
// `swift run <product> <args…>`: debug the product its before launch build left behind.
|
||||
if (rc.kind === "swiftpm" && rc.params?.program && rc.params.product) {
|
||||
out.program = join(cwd, rc.params.program);
|
||||
out.args = rc.args.slice(rc.args.indexOf(rc.params.product) + 1);
|
||||
// `swift run [flags] <product> <args…>`: debug the product its before launch build left behind,
|
||||
// found by the backend with `swift build [flags] --show-bin-path`.
|
||||
let swiftpm: { product: string; buildArgs: string[] } | undefined;
|
||||
const product = rc.kind === "swiftpm" ? rc.params?.product : undefined;
|
||||
if (product && rc.args.includes(product)) {
|
||||
const at = rc.args.indexOf(product);
|
||||
out.program = join(cwd, rc.params?.program || product);
|
||||
out.args = rc.args.slice(at + 1);
|
||||
swiftpm = { product, buildArgs: rc.args.slice(1, at).filter((a) => a !== "--skip-build") };
|
||||
}
|
||||
// lldb-dap takes the environment as `KEY=VALUE` strings.
|
||||
if (adapter === "lldb-dap") {
|
||||
@@ -409,6 +414,7 @@ function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
|
||||
const to = rc.params?.cmakeCanonicalSourceRoot;
|
||||
out.extraJson = JSON.stringify({
|
||||
env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`),
|
||||
...(swiftpm ? { swiftpm } : {}),
|
||||
...(from && to && from !== to ? { sourceMap: [[from, to]] } : {}),
|
||||
});
|
||||
} else if (rc.kind === "zig-application" || rc.params?.language === "zig") {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { iconAreaSource, rangeToOffsets, registerEditorContribution } from "@/editor/api";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/prefs";
|
||||
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { FileMarkers, IndexedMarker, Location } from "@/platform/ipc";
|
||||
import { markerIcon } from "./lineMarkerGutter";
|
||||
|
||||
@@ -50,6 +50,7 @@ import { registerExternalTools } from "./externalTools";
|
||||
import { openImport } from "./importConfigs";
|
||||
import { registerComposerInstall } from "./composerInstall";
|
||||
import { registerNpmInstall } from "./npmInstall";
|
||||
import { registerXcodeFiles } from "./xcodeFiles";
|
||||
import { registerPubspecCommands } from "./pubspec";
|
||||
import { registerGoActions } from "./goActions";
|
||||
import { registerSwiftPackageActions } from "./swiftpmActions";
|
||||
@@ -86,6 +87,7 @@ import {
|
||||
} from "./applicationUpdate";
|
||||
import { hotReload, hotReloadSession, hotRestart, syncFlutterRunApps } from "./flutterHotReload";
|
||||
import { registerFlutterBuildActions } from "./flutterBuild";
|
||||
import { registerXcodeCleanActions } from "./xcodeClean";
|
||||
import { npmGutter } from "./npmGutter";
|
||||
import { launchSettingsGutter } from "./launchSettingsGutter";
|
||||
import { runGutter } from "./runGutter";
|
||||
@@ -484,9 +486,11 @@ export function activate(): () => void {
|
||||
registerGoActions(),
|
||||
registerSwiftPackageActions(),
|
||||
registerFlutterBuildActions(),
|
||||
registerXcodeCleanActions(),
|
||||
registerRunTabActions(),
|
||||
registerComposerInstall(),
|
||||
registerNpmInstall(),
|
||||
registerXcodeFiles(),
|
||||
registerPubspecCommands(),
|
||||
registerOverlay({ id: "run.chooser", component: ConfigChooserOverlay }),
|
||||
registerOverlay({
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { iconAreaSource, mapLineStart, type EditorDocContext } from "@/editor/api";
|
||||
import { gutterIconsOn } from "@/editor/core/cm/prefs";
|
||||
import { gutterIconsOn } from "@/editor/core/cm/localAppearance";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useMenuSlotItems } from "@/workbench/contributions";
|
||||
import { useRun } from "./store";
|
||||
import { cleanConfig, registerXcodeCleanActions, xcodeConfigFor } from "./xcodeClean";
|
||||
|
||||
const config = (id: string, kind: string, container: string, scheme = id): RunConfig => ({
|
||||
id,
|
||||
name: scheme,
|
||||
kind,
|
||||
command: "xcodebuild",
|
||||
args: ["-project", container, "-scheme", scheme],
|
||||
cwd: null,
|
||||
env: { A: "1" },
|
||||
params: { container, scheme, configuration: "Debug" },
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
});
|
||||
|
||||
describe("xcode clean", () => {
|
||||
const configs = [
|
||||
config("node", "node", ""),
|
||||
config("a", "xcode", "App.xcodeproj"),
|
||||
config("b", "xcode", "App.xcodeproj"),
|
||||
config("w", "xcode", "Other.xcworkspace"),
|
||||
];
|
||||
|
||||
it("acts on the selected Xcode configuration, else the first", () => {
|
||||
expect(xcodeConfigFor(configs, "b")?.id).toBe("b");
|
||||
expect(xcodeConfigFor(configs, "node")?.id).toBe("a");
|
||||
expect(xcodeConfigFor([configs[0]!], "node")).toBeNull();
|
||||
});
|
||||
|
||||
it("acts on a scheme of the right-clicked container", () => {
|
||||
expect(xcodeConfigFor(configs, "b", "/p/Other.xcworkspace")?.id).toBe("w");
|
||||
expect(xcodeConfigFor(configs, "w", "/p/App.xcodeproj/")?.id).toBe("a");
|
||||
expect(xcodeConfigFor(configs, "a", "/p/Missing.xcodeproj")).toBeNull();
|
||||
});
|
||||
|
||||
it("cleans with the configuration's params on the chosen simulator", () => {
|
||||
const clean = cleanConfig(configs[1]!, "UDID");
|
||||
expect(clean).toMatchObject({
|
||||
id: "xcode:clean:App.xcodeproj:a",
|
||||
kind: "xcode-clean",
|
||||
args: [],
|
||||
env: {},
|
||||
params: { container: "App.xcodeproj", scheme: "a", configuration: "Debug", simulator: "UDID" },
|
||||
});
|
||||
});
|
||||
|
||||
it("lists Build › Xcode only while the project has an Xcode configuration", () => {
|
||||
const listed = () => (useMenuSlotItems.getState().slots.xcodeBuild ?? []).map((i) => i.label);
|
||||
useRun.setState({ configs: [configs[0]!] });
|
||||
const dispose = registerXcodeCleanActions();
|
||||
expect(listed()).toEqual([]);
|
||||
useRun.setState({ configs });
|
||||
expect(listed()).toEqual(["Clean Build Folder", "Delete DerivedData"]);
|
||||
useRun.setState({ configs: [configs[0]!] });
|
||||
expect(listed()).toEqual([]);
|
||||
useRun.setState({ configs });
|
||||
dispose();
|
||||
expect(listed()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Xcode's Product › Clean Build Folder and deleting the project's DerivedData (#6665 C6), for the
|
||||
* selected `xcode` configuration (else the first one), or the right-clicked `.xcodeproj` /
|
||||
* `.xcworkspace`; in Build › Xcode, Find Action and the Project view's context menu. Clean runs
|
||||
* `xcodebuild clean` in the Run tool window with the build flags a run uses (host:
|
||||
* `ide_run::xcode_clean`); Delete DerivedData asks first, then moves Xcode's `<Name>-<hash>`
|
||||
* folder and the IDE's run builds to the Trash.
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { notifications, registerMenuGroup, registerMenuSlotItem } from "@/workbench/contributions";
|
||||
import { iosSimulatorFor } from "@/workbench/iosSimulators";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { startRun, useRun } from "./store";
|
||||
|
||||
const CLEAN = "xcode.cleanBuildFolder";
|
||||
const DERIVED_DATA = "xcode.deleteDerivedData";
|
||||
|
||||
const baseName = (path: string) => path.replace(/\/+$/, "").split("/").pop() ?? "";
|
||||
|
||||
/** The `xcode` configuration to act on: of the right-clicked container (`arg`), else the selected one, else the first. */
|
||||
export function xcodeConfigFor(
|
||||
configs: readonly RunConfig[],
|
||||
selectedId: string | null,
|
||||
arg?: unknown,
|
||||
): RunConfig | null {
|
||||
const container = typeof arg === "string" ? baseName(arg) : null;
|
||||
const xcode = configs.filter(
|
||||
(c) => c.kind === "xcode" && (!container || baseName(c.params?.container ?? "") === container),
|
||||
);
|
||||
return xcode.find((c) => c.id === selectedId) ?? xcode[0] ?? null;
|
||||
}
|
||||
|
||||
function target(arg?: unknown): RunConfig | null {
|
||||
const { configs, selectedId } = useRun.getState();
|
||||
return xcodeConfigFor(configs, selectedId, arg);
|
||||
}
|
||||
|
||||
/** The transient `xcode-clean` run of `config`: its scheme and build flags, on the toolbar's simulator. */
|
||||
export function cleanConfig(config: RunConfig, simulator: string | null): RunConfig {
|
||||
return {
|
||||
...config,
|
||||
id: `xcode:clean:${config.params?.container ?? ""}:${config.params?.scheme ?? ""}`,
|
||||
name: tx`Clean ${config.name}`,
|
||||
kind: "xcode-clean",
|
||||
// The host fills in `xcodebuild … clean`.
|
||||
args: [],
|
||||
env: {},
|
||||
params: { ...config.params, simulator: simulator ?? "" },
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function cleanBuildFolder(arg?: unknown) {
|
||||
const config = target(arg);
|
||||
if (!config) return;
|
||||
const clean = cleanConfig(config, iosSimulatorFor(config));
|
||||
const [applied] = await call(commands.runApplySettings([clean]));
|
||||
await startRun(applied ?? clean);
|
||||
}
|
||||
|
||||
function notify(level: "info" | "error", title: string, body?: string) {
|
||||
notifications().notify({ group: "run", level, key: DERIVED_DATA, title, body });
|
||||
}
|
||||
|
||||
async function deleteDerivedData(arg?: unknown) {
|
||||
const config = target(arg);
|
||||
if (!config) return;
|
||||
const at = { cwd: config.cwd ?? null, params: config.params ?? {} };
|
||||
try {
|
||||
const dirs = await call(commands.xcodeDerivedData(at.cwd, at.params));
|
||||
if (!dirs.length) return notify("info", tx`No DerivedData to delete`);
|
||||
const ok = await confirm({
|
||||
title: tx`Delete DerivedData`,
|
||||
message: `${tx`Move the DerivedData of ${config.params?.container ?? config.name} to the Trash? The next build starts from scratch.`}\n\n${dirs.join("\n")}`,
|
||||
ok: tx`Move to Trash`,
|
||||
icon: "warning",
|
||||
});
|
||||
if (!ok) return;
|
||||
const deleted = await call(commands.xcodeDeleteDerivedData(at.cwd, at.params));
|
||||
notify("info", tx`DerivedData moved to the Trash`, deleted.join("\n"));
|
||||
} catch (e) {
|
||||
notify("error", tx`Could not delete DerivedData`, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
/** The native Build menu's Xcode submenu (`ide_host::menu::DYNAMIC_XCODE_BUILD`). */
|
||||
const XCODE_BUILD_SLOT = "xcodeBuild";
|
||||
|
||||
/** Lists the actions in Build › Xcode while the project has an `xcode` configuration. */
|
||||
function syncBuildMenu(): () => void {
|
||||
let inMenu: (() => void)[] = [];
|
||||
const sync = () => {
|
||||
const xcode = !!target();
|
||||
if (xcode === inMenu.length > 0) return;
|
||||
inMenu.forEach((d) => d());
|
||||
inMenu = xcode
|
||||
? [
|
||||
registerMenuSlotItem(XCODE_BUILD_SLOT, { action: CLEAN, label: "Clean Build Folder" }),
|
||||
registerMenuSlotItem(XCODE_BUILD_SLOT, { action: DERIVED_DATA, label: "Delete DerivedData" }),
|
||||
]
|
||||
: [];
|
||||
};
|
||||
sync();
|
||||
const off = useRun.subscribe((s, old) => {
|
||||
if (s.configs !== old.configs) sync();
|
||||
});
|
||||
return () => {
|
||||
off();
|
||||
inMenu.forEach((d) => d());
|
||||
};
|
||||
}
|
||||
|
||||
const isContainer = (path: string) => /\.(xcodeproj|xcworkspace)\/?$/.test(path);
|
||||
|
||||
export function registerXcodeCleanActions(): () => void {
|
||||
const disposers = [
|
||||
syncBuildMenu(),
|
||||
registerActions([
|
||||
{
|
||||
id: CLEAN,
|
||||
title: "Clean Build Folder",
|
||||
category: "Build",
|
||||
keywords: ["xcode", "xcodebuild clean"],
|
||||
when: "projectOpen",
|
||||
enabled: () => !!target(),
|
||||
run: ({ arg }) => cleanBuildFolder(arg),
|
||||
},
|
||||
{
|
||||
id: DERIVED_DATA,
|
||||
title: "Delete DerivedData",
|
||||
category: "Build",
|
||||
keywords: ["xcode", "derived data"],
|
||||
when: "projectOpen",
|
||||
enabled: () => !!target(),
|
||||
run: ({ arg }) => deleteDerivedData(arg),
|
||||
},
|
||||
]),
|
||||
registerMenuGroup({
|
||||
id: "xcode.clean",
|
||||
menus: ["projectView"],
|
||||
order: 45,
|
||||
items: (_menu, { paths }) => {
|
||||
const path = paths.length === 1 ? paths[0]! : null;
|
||||
if (!path || !isContainer(path) || !target(path)) return [];
|
||||
return [
|
||||
{ kind: "action", action: CLEAN, arg: path },
|
||||
{ kind: "action", action: DERIVED_DATA, arg: path },
|
||||
];
|
||||
},
|
||||
}),
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
const ipc = vi.hoisted(() => ({ xcodeFileSync: vi.fn(), runApplySettings: vi.fn() }));
|
||||
const run = vi.hoisted(() => ({ startRun: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
isTauri: () => true,
|
||||
commands: ipc,
|
||||
}));
|
||||
vi.mock("@/platform/keymap", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/keymap")>()),
|
||||
isMacHost: () => true,
|
||||
}));
|
||||
vi.mock("./store", () => run);
|
||||
|
||||
import { notifyFileOperation, notifyFilesMoved } from "@/platform/fileOps";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import { registerXcodeFiles } from "./xcodeFiles";
|
||||
|
||||
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
|
||||
const notify = vi.fn();
|
||||
provideNotificationService({ notify, expire: vi.fn() });
|
||||
const act = (label: string) =>
|
||||
notify.mock.calls
|
||||
.at(-1)![0]
|
||||
.actions.find((a: { label: string }) => a.label === label)
|
||||
.run();
|
||||
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
useProject.setState({ project: { root: "/p", trusted: true } as never });
|
||||
ipc.runApplySettings.mockImplementation((configs: RunConfig[]) => ok(configs));
|
||||
run.startRun.mockResolvedValue(null);
|
||||
dispose = registerXcodeFiles();
|
||||
});
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
it("checks a burst of file operations once and names the files a classic project misses", async () => {
|
||||
ipc.xcodeFileSync.mockReturnValue(ok({ kind: "notInProject", project: "/p/App.xcodeproj", files: ["New.swift"] }));
|
||||
notifyFileOperation({ kind: "created", paths: ["/p/App/New.swift"] });
|
||||
notifyFileOperation({ kind: "deleted", paths: ["/p/App/Old.swift"] });
|
||||
await notifyFilesMoved([{ from: "/p/App/A.swift", to: "/p/App/B.swift" }]);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(ipc.xcodeFileSync).toHaveBeenCalledTimes(1);
|
||||
expect(ipc.xcodeFileSync).toHaveBeenCalledWith(
|
||||
["/p/App/New.swift", "/p/App/B.swift"],
|
||||
["/p/App/Old.swift", "/p/App/A.swift"],
|
||||
);
|
||||
expect(notify).toHaveBeenCalledTimes(1);
|
||||
expect(notify.mock.calls[0]![0].title).toBe("New.swift isn't in the Xcode project");
|
||||
|
||||
act("Open in Xcode");
|
||||
await vi.waitFor(() => expect(run.startRun).toHaveBeenCalled());
|
||||
expect(run.startRun.mock.calls[0]![0]).toMatchObject({
|
||||
command: "open",
|
||||
args: ["-a", "Xcode", "App.xcodeproj"],
|
||||
cwd: "/p",
|
||||
});
|
||||
});
|
||||
|
||||
it("offers to regenerate a generated project", async () => {
|
||||
ipc.xcodeFileSync.mockReturnValue(ok({ kind: "generated", dir: "/p", tool: "tuist" }));
|
||||
notifyFileOperation({ kind: "created", paths: ["/p/Sources/New.swift"] });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(notify.mock.calls[0]![0].body).toBe(
|
||||
"Files changed in a project generated by tuist. Run 'tuist generate --no-open' so Xcode builds them.",
|
||||
);
|
||||
act("Regenerate");
|
||||
await vi.waitFor(() => expect(run.startRun).toHaveBeenCalled());
|
||||
expect(run.startRun.mock.calls[0]![0]).toMatchObject({
|
||||
command: "tuist",
|
||||
args: ["generate", "--no-open"],
|
||||
cwd: "/p",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays quiet when the project picks the files up itself", async () => {
|
||||
ipc.xcodeFileSync.mockReturnValue(ok(null));
|
||||
notifyFileOperation({ kind: "created", paths: ["/p/App/New.swift"] });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(ipc.xcodeFileSync).toHaveBeenCalled();
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* New source files in an Xcode project (#6665 C7): `xcodebuild` compiles only the files a target
|
||||
* lists. After files are created, renamed or deleted in the IDE (one check per burst), an XcodeGen
|
||||
* (`project.yml`) or Tuist (`Project.swift`) project gets an offer to regenerate it; a classic
|
||||
* `.xcodeproj` without synchronized folders says which new files it doesn't name, with Open in
|
||||
* Xcode. The IDE never edits `project.pbxproj`.
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { onFileOperation, onFilesMoved } from "@/platform/fileOps";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, isTauri, type RunConfig } from "@/platform/ipc";
|
||||
import { isMacHost } from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { maybeEditorService, notifications, registerMenuGroup } from "@/workbench/contributions";
|
||||
import { startRun } from "./store";
|
||||
|
||||
const BURST_MS = 800;
|
||||
const KEY = "xcode-files";
|
||||
const SPEC = /\/(project\.yml|Project\.swift)$/;
|
||||
/** Same list as the backend: only these make `xcodebuild` miss code. */
|
||||
const SOURCE = /\.(swift|m|mm|h|c|cc|cpp|hpp|metal)$/;
|
||||
|
||||
function regenerateCommand(tool: string): string[] {
|
||||
return tool === "tuist" ? ["tuist", "generate", "--no-open"] : ["xcodegen", "generate"];
|
||||
}
|
||||
|
||||
function commandConfig(dir: string, [command, ...args]: string[], name: string): RunConfig {
|
||||
return {
|
||||
id: `xcode-files:${command}:${dir}`,
|
||||
name,
|
||||
kind: "external",
|
||||
command: command!,
|
||||
args,
|
||||
cwd: dir,
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function run(config: RunConfig) {
|
||||
const [applied] = await call(commands.runApplySettings([config]));
|
||||
await startRun(applied ?? config);
|
||||
}
|
||||
|
||||
const parentOf = (path: string) => path.slice(0, path.lastIndexOf("/"));
|
||||
|
||||
async function regenerate(dir: string, tool: string) {
|
||||
notifications().expire?.(KEY);
|
||||
const command = regenerateCommand(tool);
|
||||
await run(commandConfig(dir, command, command.join(" ")));
|
||||
}
|
||||
|
||||
/** Regenerates the project of `arg` (a `project.yml` / `Project.swift` path), else of the active file or the root. */
|
||||
async function regenerateFor(arg: unknown) {
|
||||
const root = useProject.getState().project?.root;
|
||||
const path = typeof arg === "string" ? arg : (maybeEditorService()?.activePath() ?? `${root}/_`);
|
||||
if (SPEC.test(path)) return regenerate(parentOf(path), path.endsWith("/Project.swift") ? "tuist" : "xcodegen");
|
||||
// A removed source file next to the active one: the backend finds the spec above it.
|
||||
const sync = root ? await call(commands.xcodeFileSync([], [`${parentOf(path)}/_.swift`])) : null;
|
||||
if (sync?.kind === "generated") return regenerate(sync.dir, sync.tool);
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "info",
|
||||
key: KEY,
|
||||
title: "No XcodeGen or Tuist project found",
|
||||
body: "Open a file of a project with project.yml or Project.swift.",
|
||||
});
|
||||
}
|
||||
|
||||
async function check(created: string[], removed: string[]) {
|
||||
const project = useProject.getState().project;
|
||||
if (!isTauri() || !project?.trusted) return;
|
||||
if (![...created, ...removed].some((p) => SOURCE.test(p))) return;
|
||||
const sync = await call(commands.xcodeFileSync(created, removed));
|
||||
if (!sync || useProject.getState().project?.root !== project.root) return;
|
||||
if (sync.kind === "generated") {
|
||||
const { tool } = sync;
|
||||
const command = regenerateCommand(tool).join(" ");
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "info",
|
||||
key: KEY,
|
||||
title: "Xcode project may be out of date",
|
||||
body: tx`Files changed in a project generated by ${tool}. Run '${command}' so Xcode builds them.`,
|
||||
actions: [{ label: "Regenerate", run: () => void regenerate(sync.dir, sync.tool) }],
|
||||
});
|
||||
return;
|
||||
}
|
||||
const name = sync.project.slice(sync.project.lastIndexOf("/") + 1);
|
||||
const [file] = sync.files;
|
||||
const count = sync.files.length;
|
||||
const files = sync.files.join(", ");
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "warning",
|
||||
key: KEY,
|
||||
title: count === 1 ? tx`${file} isn't in the Xcode project` : tx`${count} files aren't in the Xcode project`,
|
||||
body:
|
||||
count === 1
|
||||
? tx`xcodebuild doesn't compile it until it's in a target of ${name}. Add it in Xcode or convert the group to a folder.`
|
||||
: tx`xcodebuild doesn't compile ${files} until they're in a target of ${name}. Add them in Xcode or convert the group to a folder.`,
|
||||
actions: isMacHost()
|
||||
? [
|
||||
{
|
||||
label: "Open in Xcode",
|
||||
run: () => void run(commandConfig(parentOf(sync.project), ["open", "-a", "Xcode", name], "Open in Xcode")),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
});
|
||||
}
|
||||
|
||||
export function registerXcodeFiles(): () => void {
|
||||
let created = new Set<string>();
|
||||
let removed = new Set<string>();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const queue = (add: readonly string[], gone: readonly string[]) => {
|
||||
add.forEach((p) => created.add(p));
|
||||
gone.forEach((p) => removed.add(p));
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
const paths = [...created];
|
||||
const gonePaths = [...removed];
|
||||
created = new Set();
|
||||
removed = new Set();
|
||||
void check(paths, gonePaths).catch(() => {});
|
||||
}, BURST_MS);
|
||||
};
|
||||
const disposers = [
|
||||
onFileOperation((op) => (op.kind === "created" ? queue(op.paths, []) : queue([], op.paths))),
|
||||
onFilesMoved((moves) =>
|
||||
queue(
|
||||
moves.map((m) => m.to),
|
||||
moves.map((m) => m.from),
|
||||
),
|
||||
),
|
||||
registerActions([
|
||||
{
|
||||
id: "xcode.regenerateProject",
|
||||
title: "Regenerate Xcode Project",
|
||||
category: "Run",
|
||||
keywords: ["xcodegen generate", "tuist generate"],
|
||||
when: "projectOpen",
|
||||
run: ({ arg }) => regenerateFor(arg),
|
||||
},
|
||||
]),
|
||||
// project.yml / Project.swift in the editor, its tab and the project view.
|
||||
registerMenuGroup({
|
||||
id: "xcode.regenerateProject",
|
||||
menus: ["editor", "editorTab", "projectView"],
|
||||
order: 30,
|
||||
items: (_menu, { paths, dirs }) => {
|
||||
const path = paths.length === 1 && !dirs?.[0] ? paths[0]! : null;
|
||||
if (!path || !SPEC.test(path)) return [];
|
||||
return [{ kind: "action", action: "xcode.regenerateProject", arg: path, label: "Regenerate Xcode Project" }];
|
||||
},
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
disposers.forEach((d) => d());
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Xcode schemes run on the iOS Simulator. The host builds, installs and launches the app at
|
||||
* Xcode schemes run on the iOS Simulator, or on the Mac for a macOS app. The host builds, installs and launches the app at
|
||||
* launch (`ide_run::xcode::prepare`); the command line here names what is built.
|
||||
*/
|
||||
import type { RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
@@ -9,7 +9,7 @@ export const xcodeType: RunConfigTypeContribution = {
|
||||
id: "xcode",
|
||||
label: "Xcode App",
|
||||
icon: "file-swift",
|
||||
description: "Build an Xcode scheme and run it on the iOS Simulator",
|
||||
description: "Build an Xcode scheme and run it on the iOS Simulator or the Mac",
|
||||
// Debug launches the app suspended and attaches lldb-dap to it (`debugXcodeApp`).
|
||||
debugAdapter: "lldb-dap",
|
||||
fields: [
|
||||
@@ -28,7 +28,7 @@ export const xcodeType: RunConfigTypeContribution = {
|
||||
label: "Simulator",
|
||||
mono: true,
|
||||
placeholder: "A booted simulator, else the newest iPhone",
|
||||
hint: "A simulator UDID (xcrun simctl list devices) pins this configuration to it",
|
||||
hint: "A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there",
|
||||
},
|
||||
{ key: "arguments", label: "Launch arguments", mono: true },
|
||||
],
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { iconAreaSource, mapLineStart, type EditorDocContext } from "@/editor/api";
|
||||
import { gutterIconsOn } from "@/editor/core/cm/prefs";
|
||||
import { gutterIconsOn } from "@/editor/core/cm/localAppearance";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
|
||||
|
||||
@@ -440,6 +440,7 @@
|
||||
"menu.build.rebuildProject": "Rebuild Project",
|
||||
"menu.build.buildArtifacts": "Build Artifacts",
|
||||
"menu.build.flutter": "Flutter",
|
||||
"menu.build.xcode": "Xcode",
|
||||
"menu.toolwindow.build": "Build",
|
||||
"menu.find.structural": "Search Structurally…",
|
||||
"menu.find.replaceStructural": "Replace Structurally…",
|
||||
|
||||
@@ -4785,5 +4785,24 @@
|
||||
"No matching memories.": "No matching memories.",
|
||||
"Focus Text Filter": "Focus Text Filter",
|
||||
"Maximize Commit Message": "Maximize Commit Message",
|
||||
"Commit Messages": "Commit Messages"
|
||||
"Commit Messages": "Commit Messages",
|
||||
"Clean Build Folder": "Clean Build Folder",
|
||||
"Delete DerivedData": "Delete DerivedData",
|
||||
"Clean {name}": "Clean {name}",
|
||||
"No DerivedData to delete": "No DerivedData to delete",
|
||||
"Move the DerivedData of {container} to the Trash? The next build starts from scratch.": "Move the DerivedData of {container} to the Trash? The next build starts from scratch.",
|
||||
"Move to Trash": "Move to Trash",
|
||||
"DerivedData moved to the Trash": "DerivedData moved to the Trash",
|
||||
"Could not delete DerivedData": "Could not delete DerivedData",
|
||||
"Regenerate Xcode Project": "Regenerate Xcode Project",
|
||||
"No XcodeGen or Tuist project found": "No XcodeGen or Tuist project found",
|
||||
"Open a file of a project with project.yml or Project.swift.": "Open a file of a project with project.yml or Project.swift.",
|
||||
"Xcode project may be out of date": "Xcode project may be out of date",
|
||||
"Files changed in a project generated by {tool}. Run '{command}' so Xcode builds them.": "Files changed in a project generated by {tool}. Run '{command}' so Xcode builds them.",
|
||||
"Regenerate": "Regenerate",
|
||||
"{file} isn't in the Xcode project": "{file} isn't in the Xcode project",
|
||||
"{count} files aren't in the Xcode project": "{count} files aren't in the Xcode project",
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
|
||||
"Open in Xcode": "Open in Xcode"
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"{name} ({runtime} Simulator)": "{name}({runtime} 模擬器)",
|
||||
"Xcode App": "Xcode 應用程式",
|
||||
"Build an Xcode scheme and run it on the iOS Simulator": "建置 Xcode 方案並在 iOS 模擬器上執行",
|
||||
"Build an Xcode scheme and run it on the iOS Simulator or the Mac": "建置 Xcode 方案並在 iOS 模擬器或 Mac 上執行",
|
||||
"Project or workspace": "專案或工作區",
|
||||
"Build configuration": "建置組態",
|
||||
"The scheme's": "方案自身的",
|
||||
"Simulator": "模擬器",
|
||||
"A booted simulator, else the newest iPhone": "已啟動的模擬器,否則為最新的 iPhone",
|
||||
"A simulator UDID (xcrun simctl list devices) pins this configuration to it": "填寫模擬器 UDID(xcrun simctl list devices)可將此組態固定到該模擬器",
|
||||
"A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填寫模擬器 UDID(xcrun simctl list devices)可將此組態固定到該模擬器;填寫 macos 則讓同時支援 Mac 的 App 在 Mac 上執行",
|
||||
"Launch arguments": "啟動引數",
|
||||
"Quick Preview": "快速預覽",
|
||||
"Build and Run": "建置和執行",
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"{name} ({runtime} Simulator)": "{name}({runtime} 模拟器)",
|
||||
"App.xcodeproj": "App.xcodeproj",
|
||||
"Xcode App": "Xcode 应用",
|
||||
"Build an Xcode scheme and run it on the iOS Simulator": "构建 Xcode 方案并在 iOS 模拟器上运行",
|
||||
"Build an Xcode scheme and run it on the iOS Simulator or the Mac": "构建 Xcode 方案并在 iOS 模拟器或 Mac 上运行",
|
||||
"Project or workspace": "项目或工作区",
|
||||
"Build configuration": "构建配置",
|
||||
"The scheme's": "方案自身的",
|
||||
"Simulator": "模拟器",
|
||||
"A booted simulator, else the newest iPhone": "已启动的模拟器,否则为最新的 iPhone",
|
||||
"A simulator UDID (xcrun simctl list devices) pins this configuration to it": "填写模拟器 UDID(xcrun simctl list devices)可将此配置固定到该模拟器",
|
||||
"A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填写模拟器 UDID(xcrun simctl list devices)可将此配置固定到该模拟器;填写 macos 则让同时支持 Mac 的 App 在 Mac 上运行",
|
||||
"Launch arguments": "启动参数",
|
||||
"Enable Git integration": "启用 Git 集成",
|
||||
"Off, the IDE runs no git: repositories are not detected, and Git actions, menus and tool windows are hidden. Applies to all projects.": "关闭后 IDE 不运行 git:不检测仓库,并隐藏 Git 操作、菜单和工具窗口。对所有项目生效。",
|
||||
@@ -2217,6 +2217,7 @@
|
||||
"Go to Child Commit": "转到子提交",
|
||||
"Go to Class…": "转到类…",
|
||||
"Go to DDL": "转到 DDL",
|
||||
"Show DDL": "显示 DDL",
|
||||
"Go to File": "转到文件",
|
||||
"Go to File…": "转到文件…",
|
||||
"Go to Line:Column": "转到行:列",
|
||||
@@ -11436,5 +11437,24 @@
|
||||
"No matching memories.": "没有匹配的记忆。",
|
||||
"Focus Text Filter": "聚焦文本过滤器",
|
||||
"Maximize Commit Message": "最大化提交消息",
|
||||
"Commit Messages": "提交消息"
|
||||
"Commit Messages": "提交消息",
|
||||
"Clean Build Folder": "清理构建文件夹",
|
||||
"Delete DerivedData": "删除 DerivedData",
|
||||
"Clean {name}": "清理 {name}",
|
||||
"No DerivedData to delete": "没有可删除的 DerivedData",
|
||||
"Move the DerivedData of {container} to the Trash? The next build starts from scratch.": "将 {container} 的 DerivedData 移到废纸篓?下次构建将从头开始。",
|
||||
"Move to Trash": "移到废纸篓",
|
||||
"DerivedData moved to the Trash": "DerivedData 已移到废纸篓",
|
||||
"Could not delete DerivedData": "无法删除 DerivedData",
|
||||
"Regenerate Xcode Project": "重新生成 Xcode 项目",
|
||||
"No XcodeGen or Tuist project found": "未找到 XcodeGen 或 Tuist 项目",
|
||||
"Open a file of a project with project.yml or Project.swift.": "请打开含 project.yml 或 Project.swift 的项目中的文件。",
|
||||
"Xcode project may be out of date": "Xcode 项目可能已过期",
|
||||
"Files changed in a project generated by {tool}. Run '{command}' so Xcode builds them.": "由 {tool} 生成的项目中有文件变更。运行 '{command}',Xcode 才会编译它们。",
|
||||
"Regenerate": "重新生成",
|
||||
"{file} isn't in the Xcode project": "{file} 不在 Xcode 项目中",
|
||||
"{count} files aren't in the Xcode project": "{count} 个文件不在 Xcode 项目中",
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"Open in Xcode": "在 Xcode 中打开"
|
||||
}
|
||||
@@ -440,6 +440,7 @@
|
||||
"menu.build.rebuildProject": "重新构建项目",
|
||||
"menu.build.buildArtifacts": "构建工件",
|
||||
"menu.build.flutter": "Flutter",
|
||||
"menu.build.xcode": "Xcode",
|
||||
"menu.toolwindow.build": "构建",
|
||||
"menu.find.structural": "结构化搜索…",
|
||||
"menu.find.replaceStructural": "结构化替换…",
|
||||
|
||||
@@ -60,7 +60,17 @@
|
||||
background: var(--tab-selected-bg);
|
||||
box-shadow: inset 0 0 0 1px var(--tab-selected-border);
|
||||
}
|
||||
/* IDEA marks a coloured data source by how strong the tint is, not by an extra highlight:
|
||||
an inactive tab is dimmed, the selected one shows the colour at full strength. */
|
||||
.tinted {
|
||||
--tab-tint-mix: color-mix(
|
||||
in srgb,
|
||||
var(--tab-tint) calc(var(--tab-tint-strength, var(--tint-strength, 22%)) * 0.55),
|
||||
transparent
|
||||
);
|
||||
background: var(--tab-tint-mix);
|
||||
}
|
||||
.tinted.selected {
|
||||
--tab-tint-mix: color-mix(in srgb, var(--tab-tint) var(--tab-tint-strength, var(--tint-strength, 22%)), transparent);
|
||||
background: var(--tab-tint-mix);
|
||||
}
|
||||
@@ -68,13 +78,6 @@
|
||||
.tinted:where([data-context-menu-open]) {
|
||||
background: linear-gradient(var(--bg-toolbar-hover), var(--bg-toolbar-hover)), var(--tab-tint-mix);
|
||||
}
|
||||
.tinted.selected {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--tab-tint) var(--tab-tint-strength, var(--tint-strength, 22%)),
|
||||
var(--tab-selected-bg)
|
||||
);
|
||||
}
|
||||
.tabButton {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -145,6 +145,11 @@ export interface EditorKindContribution {
|
||||
icon?: (input: EditorInput) => string;
|
||||
/** Small marker rendered in the tab's trailing slot (a status dot for live state). */
|
||||
trailing?: (input: EditorInput) => ReactNode;
|
||||
/**
|
||||
* CSS colour tinting the tab, for kinds that are not files and so have no path for
|
||||
* `setFileDecorations` to hang a decoration on (a table shows its data source's colour).
|
||||
*/
|
||||
tabTint?: (input: EditorInput) => string | undefined;
|
||||
/**
|
||||
* Its tabs are saved with the editor session and reopened with the project (their
|
||||
* `data` must be plain JSON). The editor closes tabs whose target is gone itself.
|
||||
@@ -237,6 +242,18 @@ export function notifyTabTitlesChanged() {
|
||||
useEditorTabTitles.setState((s) => ({ revision: s.revision + 1 }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bumped by `notifyTabTintsChanged`; tabs whose kind supplies `tabTint` re-render. The tint
|
||||
* lives in the kind's own store (a data source's colour), not in the contributions state, so
|
||||
* nothing else would tell the tab row it changed.
|
||||
*/
|
||||
export const useEditorTabTints = create<{ revision: number }>(() => ({ revision: 0 }));
|
||||
|
||||
/** A `tabTint` kind's colour may have changed (a data source's colour was edited). */
|
||||
export function notifyTabTintsChanged() {
|
||||
useEditorTabTints.setState((s) => ({ revision: s.revision + 1 }));
|
||||
}
|
||||
|
||||
/** Bumped by `notifyEditorDocumentChanged`; selectors reading `isDirty` re-run on it. */
|
||||
export const useEditorDocuments = create<{ revision: number }>(() => ({ revision: 0 }));
|
||||
export const useStandaloneEditor = create<{ title: string | null }>(() => ({ title: null }));
|
||||
|
||||
Reference in new issue
Заблокувати користувача