Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 800434ee54 feat(build): Build Artifacts and Tomcat deployment for projects without a build tool
Build Artifacts on a Java project without Maven or Gradle compiles the
production classes with javac and lays out every Project Structure
artifact: an exploded WAR (the Web facet's web root, the classes in
WEB-INF/classes and the included libraries in WEB-INF/lib) in its output
folder (out/artifacts/<name> by default), a WAR packed from that layout,
and a JAR of the classes with a manifest naming the main class and the
included libraries copied next to it. A layout is rebuilt from scratch and
refuses an output folder that holds its own inputs.

The WAR and exploded WAR artifacts of such a project are offered to Tomcat
run configurations; Build before launch compiles and packs the WAR in the
IDE and records it for deployment like a build tool's archive.

Part of #3571, closes #2875
2026-11-16 09:54:39 +08:00
l0ng-ai 6df0087038 feat(build): build Java projects without a build tool from their Project Structure (#3627)
Build Project / Rebuild Project on a Java project without Maven or Gradle now compiles with javac from the Project Structure: source roots to <compiler output>/production/<module> (out by default) against the project libraries, module library dependencies and the Web facet's WEB-INF/lib; resources copied next to the classes; tests to the test output with the production classes. JDK: module or project SDK, else an installed JDK for the language level (--release from JDK 9, -source/-target before). Rebuild cleans first. BuildStep can carry in-IDE actions (clean, copy resources); BuildSystem gains javac.

Part of #3571
2026-11-16 09:47:30 +08:00
l0ng-ai bedd9d2fc9 feat(appearance): scopes and file colors for the project view and editor tabs (#3624)
Settings › Appearance & Behavior gets Scopes (named file sets as file:pattern expressions with ||, && and !, optionally limited to a module) and File Colors (a background colour per scope, first match wins, in the project view and on editor tabs; on by default with Tests green and Non-Project Files yellow). The project view's context menu gets File Color for a file or folder, kept as a scope of that path first in the project's File Colors, with Clear File Color.

Closes #3183
2026-11-16 09:36:14 +08:00
27 змінених файлів з 2170 додано та 23 видалено

No files matched your search

+54 -1
Переглянути файл
@@ -7,6 +7,7 @@ mod fingerprint;
mod launch_resources;
mod parse;
mod single;
mod structure;
mod up_to_date;
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
@@ -15,6 +16,10 @@ pub use single::{
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
use crate::process::{self, Stream};
@@ -55,6 +60,8 @@ pub enum BuildSystem {
CMake,
#[serde(rename = "dotnet")]
Dotnet,
/// A Java project without a build tool, compiled from its Project Structure.
Javac,
}
/// One command of a build.
@@ -65,6 +72,10 @@ pub struct BuildStep {
pub cwd: PathBuf,
pub env: BTreeMap<String, String>,
format: Format,
/// Folders created before the command runs (a compiler's output).
mkdirs: Vec<PathBuf>,
/// Work done in the IDE instead of a command, with its console title.
action: Option<(structure::Action, String)>,
}
impl BuildStep {
@@ -75,16 +86,26 @@ impl BuildStep {
cwd: cwd.to_path_buf(),
env: BTreeMap::new(),
format,
mkdirs: Vec::new(),
action: None,
}
}
fn action(action: structure::Action, root: &Path) -> Self {
let title = action.display(root);
BuildStep { action: Some((action, title)), ..Self::new("", &[], root, Format::Gradle) }
}
/// A CMake configure/build invocation, parsed as compiler output in the Build view.
pub fn cmake(program: &str, args: Vec<String>, cwd: PathBuf, env: BTreeMap<String, String>) -> Self {
Self { program: program.into(), args, cwd, env, format: Format::Gcc }
Self { program: program.into(), args, cwd, env, format: Format::Gcc, mkdirs: Vec::new(), action: None }
}
/// The command line as echoed in the console.
pub fn display(&self) -> String {
if let Some((_, title)) = &self.action {
return title.clone();
}
let program = Path::new(&self.program).file_name().map_or(self.program.clone(), |n| n.to_string_lossy().into());
std::iter::once(program)
.chain(self.args.iter().map(|a| if a.contains(' ') { format!("\"{a}\"") } else { a.clone() }))
@@ -249,6 +270,8 @@ pub fn plan(
BuildSystem::TypeScript => ts_steps(&dir, kind),
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
};
Ok(BuildPlan { system, title, steps })
}
@@ -650,6 +673,36 @@ pub fn run(
let command = step.display();
on_event(BuildEvent::Step { command: command.clone(), cwd: step.cwd.clone().into() });
on_event(BuildEvent::Progress { message: command.clone(), fraction: None });
if let Some((action, _)) = &step.action {
match action.run(cancel) {
Ok(text) => {
if !text.is_empty() {
on_event(BuildEvent::Output { text: format!("{text}\n"), stderr: false });
}
continue;
}
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
Err(e) => {
let m = BuildMessage {
severity: Severity::Error,
text: e.message.clone(),
path: None,
range: None,
code: None,
};
on_event(BuildEvent::Output { text: format!("{}\n", e.message), stderr: true });
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
success = false;
break;
}
}
}
for dir in &step.mkdirs {
if let Err(e) = std::fs::create_dir_all(dir) {
tracing::debug!(dir = %dir.display(), %e, "cannot create the build output folder");
}
}
let mut parser = OutputParser::new(step.format);
let mut emit = |raws: Vec<RawMessage>, messages: &mut Vec<BuildMessage>| {
for raw in raws {
+817
Переглянути файл
@@ -0,0 +1,817 @@
//! A Java project without a build tool, built from its Project Structure: `javac` compiles
//! the source roots to the module's output folder against the project libraries and the
//! Web facet's `WEB-INF/lib`, and the resources are copied next to the classes; tests the
//! same way into the test output, which also sees the production classes.
use super::*;
use ide_core::settings::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
};
use std::fs;
/// The roots of the project as the IDE resolved them (absolute folders).
#[derive(Clone, Debug, Default)]
pub struct StructureRoots {
pub sources: Vec<PathBuf>,
pub tests: Vec<PathBuf>,
pub resources: Vec<PathBuf>,
pub test_resources: Vec<PathBuf>,
pub excluded: Vec<PathBuf>,
}
/// The JDK compiling the project.
#[derive(Clone, Debug)]
pub struct StructureJdk {
pub home: PathBuf,
pub major: u32,
}
/// Where the project's classes go: `<compiler output>/production/<module>` and
/// `<compiler output>/test/<module>` (`out` by default), unless the module names its own.
pub fn structure_outputs(root: &Path, ps: &ProjectStructureSettings) -> (PathBuf, PathBuf) {
let module = root_module(root, ps);
let name = module_name(root);
let base = resolve_dir(root, &ps.compiler_output).unwrap_or_else(|| root.join("out"));
let main = module
.and_then(|m| resolve_dir(root, &m.compiler_output))
.unwrap_or_else(|| base.join("production").join(&name));
let test = module
.and_then(|m| resolve_dir(root, &m.test_compiler_output))
.unwrap_or_else(|| base.join("test").join(&name));
(main, test)
}
fn module_name(root: &Path) -> String {
root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned())
}
fn root_module<'a>(root: &Path, ps: &'a ProjectStructureSettings) -> Option<&'a ModuleStructureSettings> {
ps.modules.get(".").or_else(|| ps.module_settings(root, root))
}
fn resolve_dir(root: &Path, value: &str) -> Option<PathBuf> {
let value = value.trim();
(!value.is_empty()).then(|| root.join(value))
}
/// `.java` files below `dir`, not inside an excluded folder or another root of `skip`.
fn java_files(dir: &Path, excluded: &[PathBuf], out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
let path = e.path();
match e.file_type() {
Ok(t) if t.is_dir() => {
if !excluded.iter().any(|x| path.starts_with(x)) {
java_files(&path, excluded, out);
}
}
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x == "java") => out.push(path),
_ => {}
}
}
}
/// Folders and archives of the libraries a module compiles against, for `scope`.
fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Vec<String> {
let wanted = |scope: DependencyScope| match scope {
DependencyScope::Compile | DependencyScope::Provided => true,
DependencyScope::Test => test,
DependencyScope::Runtime => false,
};
let mut out: Vec<String> = Vec::new();
let mut add = |entry: String| {
if !out.contains(&entry) {
out.push(entry);
}
};
let module_deps = root_module(root, ps).map(|m| m.dependencies.as_slice()).unwrap_or_default();
for lib in &ps.libraries {
// A library a module dependency names takes that dependency's scope.
let scope =
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
add(class_entry(root, class));
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
add(class_entry(root, &dep.target));
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
let lib = web_root(root, facet).join("WEB-INF").join("lib");
if lib.is_dir() {
add(format!("{}{}*", lib.to_string_lossy(), std::path::MAIN_SEPARATOR));
}
}
out
}
/// The web resource folder of a Web facet: its own, else the folder holding `WEB-INF/web.xml`.
fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
let dir = facet.web_root.trim();
let dir = if dir.is_empty() {
facet.descriptor.trim().replace('\\', "/").strip_suffix("/WEB-INF/web.xml").unwrap_or("").to_owned()
} else {
dir.to_owned()
};
root.join(dir)
}
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
let entry = class_entry(root, value);
match entry.strip_suffix('*') {
Some(dir) => {
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
.unwrap_or_default();
jars.sort();
jars
}
None => vec![PathBuf::from(entry)],
}
}
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
fn class_entry(root: &Path, value: &str) -> String {
let path = root.join(value.trim());
let text = path.to_string_lossy().into_owned();
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
return text[..text.len() - 4].to_owned();
}
text
}
fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk.is_none_or(|j| j.major >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
let digits = digits.strip_prefix("1.").unwrap_or(&digits);
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
pub fn structure_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
kind: BuildKind,
cache: &Path,
) -> IdeResult<Option<BuildPlan>> {
let mut main_sources = Vec::new();
for dir in &roots.sources {
java_files(dir, &roots.excluded, &mut main_sources);
}
let mut test_sources = Vec::new();
for dir in &roots.tests {
java_files(dir, &roots.excluded, &mut test_sources);
}
if main_sources.is_empty() && test_sources.is_empty() {
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
let mut steps = Vec::new();
if kind == BuildKind::Rebuild {
steps.push(BuildStep::action(Action::Clean(vec![main_out.clone(), test_out.clone()]), root));
}
let main_cp = library_entries(root, ps, false);
let compile = |name: &str, sources: &[PathBuf], out: &Path, cp: &[String]| -> IdeResult<BuildStep> {
let args_file = args_dir.join(format!("{name}.args"));
// One quoted path per line: the sources outgrow a command line quickly.
let text: String = sources
.iter()
.map(|p| format!("\"{}\"\n", p.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"")))
.collect();
fs::write(&args_file, text)
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", args_file.display())))?;
let mut step = BuildStep::new(&javac, &[], root, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out.to_string_lossy().into_owned()]);
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
step.args.extend(release_args(level, jdk));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
Ok(step)
};
if !main_sources.is_empty() {
steps.push(compile("production", &main_sources, &main_out, &main_cp)?);
}
steps.push(BuildStep::action(
Action::CopyResources {
from: roots.sources.iter().chain(&roots.resources).cloned().collect(),
to: main_out.clone(),
},
root,
));
// Artifacts hold production classes only.
if !test_sources.is_empty() && kind != BuildKind::Artifacts {
let mut test_cp = vec![main_out.to_string_lossy().into_owned()];
test_cp.extend(library_entries(root, ps, true));
steps.push(compile("test", &test_sources, &test_out, &test_cp)?);
steps.push(BuildStep::action(
Action::CopyResources {
from: roots.tests.iter().chain(&roots.test_resources).cloned().collect(),
to: test_out.clone(),
},
root,
));
}
if kind == BuildKind::Artifacts {
if ps.artifacts.is_empty() {
return Err(IdeError::invalid("No artifacts are configured: add one in Project Structure › Artifacts"));
}
for artifact in &ps.artifacts {
steps.extend(artifact_steps(root, ps, artifact, &main_out, None, cache));
}
}
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
.unwrap_or_else(|| root.join("out").join("artifacts").join(file_name(&artifact.name)))
}
/// An artifact name as a file name (`shop:war exploded` → `shop_war_exploded`).
fn file_name(name: &str) -> String {
name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '.' { c } else { '_' }).collect()
}
/// The archive a `jar` / `war` artifact writes (`<output>/<name>.war`), or its folder (exploded).
pub fn artifact_file(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
let out = artifact_output(root, artifact);
let base = artifact.name.split(':').next().filter(|n| !n.trim().is_empty()).unwrap_or(&artifact.name);
match artifact.kind {
ArtifactKind::Jar => out.join(format!("{}.jar", file_name(base))),
ArtifactKind::War => out.join(format!("{}.war", file_name(base))),
ArtifactKind::WarExploded => out,
}
}
/// The steps laying out one artifact from the module output `classes`; `war`: write a
/// WAR there instead of the artifact's own output (an application server's deployment).
fn artifact_steps(
root: &Path,
ps: &ProjectStructureSettings,
artifact: &ArtifactConfig,
classes: &Path,
war: Option<&Path>,
cache: &Path,
) -> Vec<BuildStep> {
let libraries: Vec<PathBuf> = ps
.libraries
.iter()
.filter(|l| artifact.include_libraries.contains(&l.name))
.flat_map(|l| l.classes.iter().flat_map(|c| library_files(root, c)))
.collect();
let facet = ps
.facets
.iter()
.filter(|f| f.kind == "web")
.find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".")
.or_else(|| ps.facets.iter().find(|f| f.kind == "web"));
let staging = cache.join("artifacts").join(file_name(&artifact.name));
let mut steps = Vec::new();
match (artifact.kind, war) {
(ArtifactKind::Jar, None) => {
let out = artifact_output(root, artifact);
let mut manifest = String::from("Manifest-Version: 1.0\r\n");
if !artifact.main_class.trim().is_empty() {
manifest.push_str(&format!("Main-Class: {}\r\n", artifact.main_class.trim()));
}
let names: Vec<String> =
libraries.iter().filter_map(|l| l.file_name()).map(|n| n.to_string_lossy().into_owned()).collect();
if !names.is_empty() {
manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" ")));
}
steps.push(BuildStep::action(
Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] },
root,
));
// The jar's Class-Path names the libraries next to it.
steps.push(BuildStep::action(
Action::Layout {
into: out.clone(),
entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(),
},
root,
));
steps.push(BuildStep::action(
Action::Archive { from: staging, to: artifact_file(root, artifact), manifest: Some(manifest) },
root,
));
}
(kind, war) => {
let exploded = match (kind, war) {
(ArtifactKind::WarExploded, None) => artifact_output(root, artifact),
_ => staging.clone(),
};
let mut entries = Vec::new();
if let Some(facet) = facet {
entries.push((web_root(root, facet), PathBuf::new()));
}
entries.push((classes.to_path_buf(), PathBuf::from("WEB-INF/classes")));
for lib in &libraries {
entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib))));
}
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root));
let archive = war
.map(Path::to_path_buf)
.or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact)));
if let Some(to) = archive {
steps.push(BuildStep::action(Action::Archive { from: exploded, to, manifest: None }, root));
}
}
}
steps
}
fn file_of(path: &Path) -> PathBuf {
path.file_name().map(PathBuf::from).unwrap_or_default()
}
/// The WAR artifacts of a project without a build tool: an application server deploys them.
pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactConfig> {
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
}
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
#[allow(clippy::too_many_arguments)]
pub fn structure_war_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
artifact: &ArtifactConfig,
war: &Path,
cache: &Path,
) -> IdeResult<BuildPlan> {
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
.unwrap_or_else(|| BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps: Vec::new() });
let (main_out, _) = structure_outputs(root, ps);
// Tests are not part of a deployment.
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
plan.steps
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
plan.title = artifact.name.clone();
Ok(plan)
}
/// Work a build does in the IDE itself rather than through a tool.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Action {
/// Deletes these output folders (Rebuild).
Clean(Vec<PathBuf>),
/// Copies the files of these folders that are not Java sources into `to`, keeping their
/// relative paths; files that are already up to date are left alone.
CopyResources { from: Vec<PathBuf>, to: PathBuf },
/// Lays out an artifact in `into`: each folder's content or file goes to its relative
/// place (`""` = the top). What is no longer laid out is removed.
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> },
/// Zips the folder `from` into the archive `to`, with this manifest first.
Archive { from: PathBuf, to: PathBuf, manifest: Option<String> },
}
impl Action {
pub(crate) fn display(&self, root: &Path) -> String {
let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).to_string_lossy().into_owned();
match self {
Action::Clean(dirs) => format!("Clean {}", dirs.iter().map(|d| rel(d)).collect::<Vec<_>>().join(", ")),
Action::CopyResources { to, .. } => format!("Copy resources to {}", rel(to)),
Action::Layout { into, .. } => format!("Lay out {}", rel(into)),
Action::Archive { to, .. } => format!("Pack {}", rel(to)),
}
}
/// Runs the action; the text is a summary for the console.
pub(crate) fn run(&self, cancel: &CancellationToken) -> IdeResult<String> {
match self {
Action::Clean(dirs) => {
for dir in dirs.iter().filter(|d| d.exists()) {
fs::remove_dir_all(dir)
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", dir.display())))?;
}
Ok(String::new())
}
Action::CopyResources { from, to } => {
let mut copied = 0;
for dir in from {
copied += copy_resources(dir, dir, to, cancel)?;
}
Ok(format!("{copied} resource file(s) copied"))
}
Action::Layout { into, entries } => {
// A fresh layout: files dropped from the sources must not linger in the artifact.
if entries.iter().any(|(from, _)| from.starts_with(into)) {
return Err(IdeError::invalid(format!(
"The artifact output folder {} holds files the artifact is made of",
into.display()
)));
}
if into.exists() {
fs::remove_dir_all(into)
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
}
let mut copied = 0;
for (from, to) in entries {
let target = into.join(to);
if from.is_dir() {
copied += copy_tree(from, &target, cancel)?;
} else if from.is_file() {
copy_file(from, &target)?;
copied += 1;
}
}
Ok(format!("{copied} file(s) laid out"))
}
Action::Archive { from, to, manifest } => {
archive(from, to, manifest.as_deref(), cancel)?;
Ok(format!("Wrote {}", to.display()))
}
}
}
}
fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
fs::copy(from, to).map_err(|e| IdeError::internal(format!("cannot copy {} ({e})", from.display())))?;
Ok(())
}
fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(from) else { return Ok(0) };
let mut copied = 0;
for e in entries.flatten() {
let Ok(t) = e.file_type() else { continue };
let target = to.join(e.file_name());
if t.is_dir() {
copied += copy_tree(&e.path(), &target, cancel)?;
} else if t.is_file() {
copy_file(&e.path(), &target)?;
copied += 1;
}
}
Ok(copied)
}
fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
use std::io::Write;
let err = |e: &dyn std::fmt::Display| IdeError::internal(format!("cannot write {} ({e})", to.display()));
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).map_err(|e| err(&e))?;
}
let mut zip = zip::ZipWriter::new(fs::File::create(to).map_err(|e| err(&e))?);
let options = zip::write::SimpleFileOptions::default();
if let Some(manifest) = manifest {
zip.add_directory("META-INF/", options).map_err(|e| err(&e))?;
zip.start_file("META-INF/MANIFEST.MF", options).map_err(|e| err(&e))?;
zip.write_all(manifest.as_bytes()).map_err(|e| err(&e))?;
}
let mut stack = vec![from.to_path_buf()];
while let Some(dir) = stack.pop() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(&dir) else { continue };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
let path = e.path();
let name = path.strip_prefix(from).unwrap_or(&path).to_string_lossy().replace('\\', "/");
if manifest.is_some() && name.eq_ignore_ascii_case("META-INF/MANIFEST.MF") {
continue;
}
match e.file_type() {
Ok(t) if t.is_dir() => {
if !(manifest.is_some() && name == "META-INF") {
zip.add_directory(format!("{name}/"), options).map_err(|e| err(&e))?;
}
stack.push(path);
}
Ok(t) if t.is_file() => {
zip.start_file(name, options).map_err(|e| err(&e))?;
let mut file = fs::File::open(&path).map_err(|e| err(&e))?;
std::io::copy(&mut file, &mut zip).map_err(|e| err(&e))?;
}
_ => {}
}
}
}
zip.finish().map_err(|e| err(&e))?;
Ok(())
}
fn copy_resources(base: &Path, dir: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(dir) else { return Ok(0) };
let mut copied = 0;
for e in entries.flatten() {
let path = e.path();
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
// The output folder can sit inside a source root (`src` holding `classes`).
if path != to && !path.starts_with(to) {
copied += copy_resources(base, &path, to, cancel)?;
}
continue;
}
if !t.is_file() || path.extension().is_some_and(|x| x == "java") {
continue;
}
let target = to.join(path.strip_prefix(base).unwrap_or(&path));
let newer =
match (fs::metadata(&path).and_then(|m| m.modified()), fs::metadata(&target).and_then(|m| m.modified())) {
(Ok(source), Ok(existing)) => source > existing,
_ => true,
};
if newer {
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
fs::copy(&path, &target)
.map_err(|e| IdeError::internal(format!("cannot copy {} ({e})", path.display())))?;
copied += 1;
}
}
Ok(copied)
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::settings::{FacetConfig, ModuleDependency, ProjectLibrary};
fn write(path: &Path, text: &str) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
#[test]
fn reads_language_levels() {
assert_eq!(language_release("17"), Some(17));
assert_eq!(language_release("1.8"), Some(8));
assert_eq!(language_release("JDK_11"), Some(11));
assert_eq!(language_release(""), None);
}
#[test]
fn plans_javac_over_source_roots_with_libraries_and_web_lib() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/A.java"), "package com.a; class A {}");
write(&root.join("src/com/a/app.properties"), "x=1");
write(&root.join("test/com/a/ATest.java"), "package com.a; class ATest {}");
write(&root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>");
write(&root.join("WebRoot/WEB-INF/lib/x.jar"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "tools".into(), classes: vec!["lib/*.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
facets: vec![FacetConfig {
kind: "web".into(),
module: ".".into(),
descriptor: "WebRoot/WEB-INF/web.xml".into(),
web_root: String::new(),
}],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk = StructureJdk { home: PathBuf::from("/jdk"), major: 21 };
let plan = structure_plan(&root, &ps, &roots, Some(&jdk), "17", BuildKind::Rebuild, &tmp.path().join("cache"))
.unwrap()
.unwrap();
assert_eq!(plan.system, BuildSystem::Javac);
let shown: Vec<String> = plan.steps.iter().map(BuildStep::display).collect();
assert_eq!(shown[0], "Clean out/production/shop, out/test/shop");
let javac = &plan.steps[1];
let cp = |s: &BuildStep| s.args[s.args.iter().position(|a| a == "-cp").unwrap() + 1].clone();
let sep = if cfg!(windows) { ";" } else { ":" };
let main_cp = cp(javac);
let entries: Vec<&str> = main_cp.split(sep).collect();
assert_eq!(entries.len(), 2, "{main_cp}");
assert!(entries[0].ends_with("lib/*"));
assert!(entries[1].ends_with("WEB-INF/lib/*"));
assert!(javac.args.windows(2).any(|w| w == ["--release", "17"]));
let args = fs::read_to_string(tmp.path().join("cache/javac/production.args")).unwrap();
assert!(args.contains("A.java") && !args.contains("ATest.java"));
assert_eq!(shown[2], "Copy resources to out/production/shop");
let test = &plan.steps[3];
let test_cp = cp(test);
assert!(test_cp.starts_with(&root.join("out/production/shop").to_string_lossy().into_owned()));
assert!(test_cp.contains("junit.jar"));
}
#[test]
fn a_module_dependency_gives_its_library_a_scope_and_jdk_8_gets_source_and_target() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("p");
write(&root.join("src/A.java"), "class A {}");
let mut ps = ProjectStructureSettings {
libraries: vec![ProjectLibrary {
name: "junit".into(),
classes: vec!["junit.jar".into()],
..Default::default()
}],
compiler_output: "build/classes".into(),
..Default::default()
};
ps.modules.insert(
".".into(),
ModuleStructureSettings {
language_level: "1.8".into(),
dependencies: vec![ModuleDependency {
kind: "library".into(),
target: "junit".into(),
scope: DependencyScope::Test,
exported: false,
}],
..Default::default()
},
);
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let jdk = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let plan = structure_plan(&root, &ps, &roots, Some(&jdk), "21", BuildKind::Build, &tmp.path().join("c"))
.unwrap()
.unwrap();
let javac = &plan.steps[0];
assert!(!javac.args.iter().any(|a| a == "-cp"), "{:?}", javac.args);
assert!(javac.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(javac.args.windows(2).any(|w| w[0] == "-d" && w[1].ends_with("build/classes/production/p")));
}
#[test]
fn no_plan_without_java_sources() {
let tmp = tempfile::tempdir().unwrap();
let roots = StructureRoots { sources: vec![tmp.path().join("src")], ..Default::default() };
let plan =
structure_plan(tmp.path(), &Default::default(), &roots, None, "", BuildKind::Build, &tmp.path().join("c"));
assert!(plan.unwrap().is_none());
}
#[test]
fn copies_resources_but_not_sources_and_skips_up_to_date_files() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
write(&src.join("a/A.java"), "class A {}");
write(&src.join("a/x.xml"), "<x/>");
let out = tmp.path().join("out");
let action = Action::CopyResources { from: vec![src], to: out.clone() };
let cancel = CancellationToken::new();
assert_eq!(action.run(&cancel).unwrap(), "1 resource file(s) copied");
assert!(out.join("a/x.xml").is_file() && !out.join("a/A.java").exists());
assert_eq!(action.run(&cancel).unwrap(), "0 resource file(s) copied");
Action::Clean(vec![out.clone()]).run(&cancel).unwrap();
assert!(!out.exists());
}
fn entries(archive: &Path) -> Vec<String> {
let mut zip = zip::ZipArchive::new(fs::File::open(archive).unwrap()).unwrap();
(0..zip.len()).map(|i| zip.by_index(i).unwrap().name().unwrap().into_owned()).collect()
}
fn run_plan(plan: &BuildPlan) {
let cancel = CancellationToken::new();
for step in &plan.steps {
if let Some((action, _)) = &step.action {
action.run(&cancel).unwrap();
}
}
}
#[test]
fn lays_out_war_jar_and_exploded_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("WebRoot/index.jsp"), "hi");
write(&root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>");
write(&root.join("WebRoot/WEB-INF/lib/inside.jar"), "");
write(&root.join("lib/extra.jar"), "");
let classes = root.join("out/production/shop");
write(&classes.join("com/a/A.class"), "");
let artifact = |name: &str, kind| ArtifactConfig {
name: name.into(),
kind,
module: ".".into(),
include_libraries: vec!["extra".into()],
main_class: "com.a.A".into(),
..Default::default()
};
let ps = ProjectStructureSettings {
libraries: vec![ProjectLibrary {
name: "extra".into(),
classes: vec!["lib/*.jar".into()],
..Default::default()
}],
facets: vec![FacetConfig {
kind: "web".into(),
module: ".".into(),
descriptor: "WebRoot/WEB-INF/web.xml".into(),
web_root: String::new(),
}],
artifacts: vec![
artifact("shop:war", ArtifactKind::War),
artifact("shop:war exploded", ArtifactKind::WarExploded),
artifact("shop:jar", ArtifactKind::Jar),
],
..Default::default()
};
let cache = tmp.path().join("cache");
for a in &ps.artifacts {
let plan = BuildPlan {
system: BuildSystem::Javac,
title: String::new(),
steps: artifact_steps(&root, &ps, a, &classes, None, &cache),
};
run_plan(&plan);
}
let war = entries(&root.join("out/artifacts/shop_war/shop.war"));
for name in [
"index.jsp",
"WEB-INF/web.xml",
"WEB-INF/lib/inside.jar",
"WEB-INF/lib/extra.jar",
"WEB-INF/classes/com/a/A.class",
] {
assert!(war.iter().any(|e| e == name), "{name} in {war:?}");
}
let exploded = root.join("out/artifacts/shop_war_exploded");
assert!(exploded.join("WEB-INF/classes/com/a/A.class").is_file());
assert!(exploded.join("WEB-INF/lib/extra.jar").is_file());
let jar_dir = root.join("out/artifacts/shop_jar");
let jar = entries(&jar_dir.join("shop.jar"));
assert_eq!(jar[..2], ["META-INF/".to_owned(), "META-INF/MANIFEST.MF".to_owned()]);
assert!(jar.iter().any(|e| e == "com/a/A.class"));
assert!(jar_dir.join("extra.jar").is_file());
let mut zip = zip::ZipArchive::new(fs::File::open(jar_dir.join("shop.jar")).unwrap()).unwrap();
let mut manifest = String::new();
std::io::Read::read_to_string(&mut zip.by_name("META-INF/MANIFEST.MF").unwrap(), &mut manifest).unwrap();
assert!(manifest.contains("Main-Class: com.a.A") && manifest.contains("Class-Path: extra.jar"));
}
#[test]
fn never_lays_out_over_its_own_sources() {
let tmp = tempfile::tempdir().unwrap();
let web = tmp.path().join("WebRoot");
write(&web.join("a.jsp"), "");
let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] };
assert!(action.run(&CancellationToken::new()).is_err());
assert!(web.join("a.jsp").is_file());
}
}
+47
Переглянути файл
@@ -67,6 +67,10 @@ pub struct Settings {
pub mcp_server: McpServerSettings,
/// Tools › Agents: Command Execution Policy.
pub agent_security: AgentSecuritySettings,
/// Appearance & Behavior › Scopes: named file sets other settings refer to.
pub scopes: Vec<NamedScope>,
/// Appearance & Behavior › File Colors.
pub file_colors: FileColorSettings,
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
@@ -502,6 +506,8 @@ impl Default for Settings {
agents: AgentSettings::default(),
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
scopes: Vec::new(),
file_colors: FileColorSettings::default(),
plugins: BTreeMap::new(),
}
}
@@ -512,6 +518,47 @@ fn default_keymap() -> &'static str {
if cfg!(target_os = "macos") { "intellij-macos" } else { "intellij-windows" }
}
/// A named set of files: `file:src//*.ts && !file:*.test.ts` (project-relative path patterns
/// joined with `||`, `&&`, `!` and parentheses).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct NamedScope {
pub name: String,
pub pattern: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FileColorSettings {
pub enabled: bool,
pub editor_tabs: bool,
pub project_view: bool,
/// Scope → colour; the first scope that holds a file gives its colour.
pub colors: Vec<FileColor>,
}
impl Default for FileColorSettings {
fn default() -> Self {
let color = |scope: &str, color: &str| FileColor { scope: scope.into(), color: color.into() };
Self {
enabled: true,
editor_tabs: true,
project_view: true,
colors: vec![color("Non-Project Files", "yellow"), color("Tests", "green")],
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FileColor {
/// A built-in scope (`Tests`, `Production`, `Project Files`, `Non-Project Files`) or a
/// `scopes` entry, by name.
pub scope: String,
/// A palette name (`blue`, `green`, `orange`, `rose`, `violet`, `yellow`, `gray`) or `#rrggbb`.
pub color: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CustomKeymap {
+62 -11
Переглянути файл
@@ -641,6 +641,58 @@ pub async fn maven_exclude_dependency(
.map_err(join_err)?
}
/// Build / Rebuild / Build Artifacts of a Java project without a build tool, from its
/// Project Structure; `None` when it has no Java sources under its source roots.
fn structure_plan(
root: &Path,
settings: &Settings,
detected: &[ide_workspace::roots::SourceFolder],
kind: BuildKind,
cache: &Path,
) -> IdeResult<Option<compile::BuildPlan>> {
let (roots, jdk) = structure_inputs(root, settings, detected);
compile::structure_plan(
root,
&settings.project_structure,
&roots,
jdk.as_ref(),
&settings.languages.java.language_level,
kind,
cache,
)
}
/// The roots and JDK a build of a project without a build tool uses.
pub(crate) fn structure_inputs(
root: &Path,
settings: &Settings,
detected: &[ide_workspace::roots::SourceFolder],
) -> (compile::StructureRoots, Option<compile::StructureJdk>) {
use ide_workspace::roots::{ProjectRoots, RootKind};
let roots = ProjectRoots::compute(detected.to_vec(), &settings.project_structure);
let of = |kind: RootKind| roots.roots.iter().filter(|r| r.kind == kind).map(|r| root.join(&r.path)).collect();
let module = settings.project_structure.module_settings(root, root);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.unwrap_or(&settings.languages.java.language_level);
// Without a configured SDK, an installed JDK that can compile the language level.
let jdk = ide_sdk::apply::module_jdk(root, root, settings)
.or_else(|| {
let installed = ide_sdk::java::installed_jdks();
ide_sdk::java::pick_jdk(&installed, compile::language_release(level)).cloned()
})
.map(|j| compile::StructureJdk { home: j.home, major: j.major });
let roots = compile::StructureRoots {
sources: of(RootKind::Source),
tests: of(RootKind::Test),
resources: of(RootKind::Resources),
test_resources: of(RootKind::TestResources),
excluded: of(RootKind::Excluded),
};
(roots, jdk)
}
fn cmake_plan(root: &Path, kind: BuildKind, configs: &[ide_run::RunConfig], id: &str) -> IdeResult<compile::BuildPlan> {
let commands = ide_run::cmake_build_configs(configs, id)?;
let title = commands.last().map(|c| c.name.clone()).unwrap_or_default();
@@ -675,6 +727,7 @@ pub async fn build_run(
let project = host.project(window)?;
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
@@ -738,17 +791,15 @@ pub async fn build_run(
plan.title = workspace.name;
plan
} else {
prepare_plan(
compile::plan(
&root,
&with_profiles(load(&root, &cache, &settings), &cache),
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
)?,
&root,
&settings,
)
let model = with_profiles(load(&root, &cache, &settings), &cache);
match compile::plan(&root, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref()) {
Ok(plan) => prepare_plan(plan, &root, &settings),
// No build tool: a Java project builds from its Project Structure.
Err(e) if e.kind == ide_core::error::ErrorKind::NotFound => {
structure_plan(&root, &settings, &detected, kind, &cache)?.ok_or(e)?
}
Err(e) => return Err(e),
}
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
+81 -2
Переглянути файл
@@ -202,12 +202,85 @@ pub async fn run_tomcat_installations(
.map_err(|e| IdeError::internal(e.to_string()))
}
/// Id prefix of a Project Structure WAR artifact (a project without a build tool).
const PROJECT_ARTIFACT: &str = "project:";
fn project_web_artifacts(settings: &ide_core::settings::Settings) -> Vec<ide_build::web::WebArtifact> {
ide_build::compile::structure_web_artifacts(&settings.project_structure)
.into_iter()
.map(|a| ide_build::web::WebArtifact {
id: format!("{PROJECT_ARTIFACT}{}", a.name),
name: a.name.split(':').next().unwrap_or(&a.name).to_owned(),
module: if a.module == "." { String::new() } else { a.module.clone() },
tool: "project".into(),
})
.collect()
}
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
/// deploys, recorded in `base` like a build tool's archive.
fn build_project_war(
root: &std::path::Path,
settings: &ide_core::settings::Settings,
detected: &[ide_workspace::roots::SourceFolder],
name: &str,
base: &std::path::Path,
cache: &std::path::Path,
) -> IdeResult<()> {
use ide_build::compile;
let artifact = settings
.project_structure
.artifacts
.iter()
.find(|a| a.name == name)
.ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?;
let (roots, jdk) = crate::ops::build::structure_inputs(root, settings, detected);
let war = base.join("artifact").join(format!(
"{}.war",
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
));
let plan = compile::structure_war_plan(
root,
&settings.project_structure,
&roots,
jdk.as_ref(),
&settings.languages.java.language_level,
artifact,
&war,
cache,
)?;
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
if !result.success {
let first = result.messages.iter().find(|m| m.severity == ide_core::Severity::Error);
let text = match first {
Some(m) => match (&m.path, m.range) {
(Some(path), Some(range)) => {
format!("{}:{}: {}", std::path::PathBuf::from(path.clone()).display(), range.start.line + 1, m.text)
}
_ => m.text.clone(),
},
None => "the build failed".into(),
};
return Err(IdeError::invalid(format!("Cannot build {name}: {text}")));
}
std::fs::create_dir_all(base)?;
std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?;
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
Ok(())
}
pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<ide_build::web::WebArtifact>> {
host.require_trust(window)?;
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
ide_build::web::artifacts(&project.root, &model)
let settings = project.settings.effective();
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
let mut artifacts = ide_build::web::artifacts(&project.root, &model);
// Without a build tool, the Project Structure's WAR artifacts are built by the IDE.
if model.maven.is_none() && model.gradle.is_empty() {
artifacts.extend(project_web_artifacts(&settings));
}
artifacts
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -230,6 +303,12 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
.or_else(|| artifacts.first().map(|a| &a.id))
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?;
return Ok(None);
}
// "Build before launch" is skipped when the built WAR is already newer than the
// sources of every module in the build, so a repeated run does not rebuild (IDEA's
// up-to-date check) but a change in a dependency module does.
+38 -1
Переглянути файл
@@ -2942,7 +2942,9 @@ export type BuildResult = {
messages: BuildMessage[],
};
export type BuildSystem = "maven" | "gradle" | "cargo" | "go" | "typescript" | "cmake" | "dotnet";
export type BuildSystem = "maven" | "gradle" | "cargo" | "go" | "typescript" | "cmake" | "dotnet" |
/** A Java project without a build tool, compiled from its Project Structure. */
"javac";
export type BuildTool = "maven" | "gradle";
@@ -5259,6 +5261,24 @@ export type FieldValue = { kind: "label"; value: string } | { kind: "readonlyTex
selected: string,
} };
export type FileColor = {
/**
* A built-in scope (`Tests`, `Production`, `Project Files`, `Non-Project Files`) or a
* `scopes` entry, by name.
*/
scope?: string,
/** A palette name (`blue`, `green`, `orange`, `rose`, `violet`, `yellow`, `gray`) or `#rrggbb`. */
color?: string,
};
export type FileColorSettings = {
enabled?: boolean,
editorTabs?: boolean,
projectView?: boolean,
/** Scope → colour; the first scope that holds a file gives its colour. */
colors?: FileColor[],
};
export type FileCoverage = {
path: IpcPath,
/** Sorted by line. */
@@ -7782,6 +7802,15 @@ export type ModuleStructureSettings = {
dependencies?: ModuleDependency[],
};
/**
* A named set of files: `file:src//*.ts && !file:*.test.ts` (project-relative path patterns
* joined with `||`, `&&`, `!` and parentheses).
*/
export type NamedScope = {
name?: string,
pattern?: string,
};
/**
* Where the Navigation Bar (the file path breadcrumbs) is shown. Mirrors
* IDEA's `View | Appearance | Navigation Bar` (Top / Status Bar / Don't show).
@@ -9895,6 +9924,10 @@ export type Settings_Deserialize = {
mcpServer?: McpServerSettings,
/** Tools › Agents: Command Execution Policy. */
agentSecurity?: AgentSecuritySettings,
/** Appearance & Behavior › Scopes: named file sets other settings refer to. */
scopes?: NamedScope[],
/** Appearance & Behavior › File Colors. */
fileColors?: FileColorSettings,
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
plugins?: { [key in string]: { [key in string]: unknown } },
};
@@ -9961,6 +9994,10 @@ export type Settings_Serialize = {
mcpServer: McpServerSettings,
/** Tools › Agents: Command Execution Policy. */
agentSecurity: AgentSecuritySettings,
/** Appearance & Behavior › Scopes: named file sets other settings refer to. */
scopes: NamedScope[],
/** Appearance & Behavior › File Colors. */
fileColors: FileColorSettings,
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
plugins: { [key in string]: { [key in string]: unknown } },
};
+5 -1
Переглянути файл
@@ -31,6 +31,7 @@ import {
type EditorKindContribution,
} from "@/workbench/contributions";
import { useDistractionFree } from "@/workbench/distractionFree";
import { useFileColors } from "@/workbench/fileColors";
import { EmptyEditor } from "@/workbench/EditorArea";
import {
EmptyState,
@@ -177,6 +178,7 @@ function PaneView({ paneId }: { paneId: string }) {
const dirty = tabs.map((tab, i) => inputDirty(tab.input, kinds) ?? textDirty[i] ?? false);
const colors = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.color ?? "") : ""))));
const tints = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.tint ?? "") : ""))));
const fileColors = useFileColors("editorTabs");
const hints = useTitleHints();
const [dropZone, setDropZone] = useState<DropZone | null>(null);
@@ -225,7 +227,8 @@ function PaneView({ paneId }: { paneId: string }) {
// (middle click, Shift+click, Delete) alive when its position is None.
showCloseButton,
color: colors[i] || undefined,
tint: tints[i] || undefined,
tint:
tints[i] || (fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined),
tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined),
trailing:
kindMark || pin ? (
@@ -244,6 +247,7 @@ function PaneView({ paneId }: { paneId: string }) {
dirty,
colors,
tints,
fileColors,
hints,
showExtension,
markModified,
+7
Переглянути файл
@@ -33,6 +33,7 @@ import {
useFileDecoration,
type DecorationSegment,
} from "@/workbench/contributions";
import { useFileColors } from "@/workbench/fileColors";
import {
FILES_DRAG,
REMOTE_FILES_DRAG,
@@ -461,6 +462,7 @@ export function ProjectView() {
useFileIconRevision();
const root = useProjectTree((s) => s.root);
const model = useProjectTree(selectModel);
const fileColors = useFileColors("projectView");
const expanded = useProjectTree((s) => s.expanded);
const selected = useProjectTree((s) => s.selected);
const editing = useProjectTree((s) => s.editing);
@@ -872,6 +874,11 @@ export function ProjectView() {
loadChildren={loadChildren}
renderNode={renderNode}
rowClassName={(n) => (n.excluded ? styles.excludedRow : undefined)}
rowTint={
fileColors
? (n) => (n.excluded || n.group || n.placeholder ? undefined : fileColors(n.path, n.dir))
: undefined
}
expanded={expanded}
onExpandedChange={onExpandedChange}
selected={selected}
+12
Переглянути файл
@@ -151,8 +151,20 @@ describe("project view context menu", () => {
"Git",
"-",
"Compare With…",
"File Color",
]);
expect(sub(items, "Refactor")).toEqual(["Rename…", "Move File…", "Copy File…", "-", "Safe Delete…"]);
expect(sub(items, "File Color")).toEqual([
"Blue",
"Green",
"Orange",
"Rose",
"Violet",
"Yellow",
"Gray",
"-",
"Edit File Colors…",
]);
expect(sub(items, "Open In")).toEqual([revealLabel(), "Terminal"]);
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
});
+5
Переглянути файл
@@ -9,6 +9,7 @@ import type { MenuItem } from "@/ui";
import { menuGroupItems, toolWindowService, type MenuGroupContext } from "@/workbench/contributions";
import type { FolderRole } from "@/platform/languageSettings";
import { directoryRole, markDirectory } from "./markDirectory";
import { fileColorMenu } from "./fileColor";
import type { ProjectNode } from "./model";
import { packageKindAt } from "./packages";
import {
@@ -456,6 +457,10 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
],
});
}
if (inProject && single && !single.root && !single.placeholder && !single.group) {
const color = fileColorMenu(single.path, single.dir);
if (color) push(color);
}
return items;
}
+55
Переглянути файл
@@ -0,0 +1,55 @@
/**
* Project view › File Color: gives a file or folder its own background colour, kept as a
* scope of that path and a File Colors entry in the project's settings.
*/
import { executeAction } from "@/platform/actions";
import { FILE_COLOR_NAMES, ownFileColor, pathPattern, withOwnFileColor } from "@/platform/fileColors";
import { call, commands, isTauri } from "@/platform/ipc";
import { loadSettings, relativePath, useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
blue: "Blue",
green: "Green",
orange: "Orange",
rose: "Rose",
violet: "Violet",
yellow: "Yellow",
gray: "Gray",
};
export async function setFileColor(path: string, dir: boolean, color: string | null): Promise<void> {
const { project, settings } = useProject.getState();
if (!project || !isTauri()) return;
const next = withOwnFileColor(settings, relativePath(project.root, path), dir, color);
if (!next) return;
await call(commands.settingsSet("project", "scopes", JSON.stringify(next.scopes)));
await call(commands.settingsSet("project", "fileColors", JSON.stringify(next.fileColors)));
await loadSettings();
}
/** The File Color submenu of a file or folder inside the project, or null when it can't have one. */
export function fileColorMenu(path: string, dir: boolean): MenuItem | null {
const { project, settings } = useProject.getState();
if (!project) return null;
const rel = relativePath(project.root, path);
if (rel === path || !pathPattern(rel, dir)) return null;
const current = ownFileColor(rel, dir, settings)?.toLowerCase();
return {
id: "fileColor",
label: "File Color",
submenu: [
...FILE_COLOR_NAMES.map((name): MenuItem => ({
id: name,
label: LABELS[name],
checked: current === name,
run: () => void setFileColor(path, dir, name),
})),
{ kind: "separator" },
...(current
? [{ id: "clear", label: "Clear File Color", run: () => void setFileColor(path, dir, null) } as MenuItem]
: []),
{ id: "edit", label: "Edit File Colors…", run: () => void executeAction("file.settings", "fileColors") },
],
};
}
+1 -1
Переглянути файл
@@ -125,7 +125,7 @@ describe("theme tokens", () => {
* the selection foreground, whose base default preserves syntax colours.
*/
const INHERITED_FROM_BASE =
/^--(project-color-|db-color-|caption-close-|fg-caption-close-|tint-strength$|fg-editor-selection$)/;
/^--(project-color-|db-color-|file-color-|caption-close-|fg-caption-close-|tint-strength$|file-tint-strength$|fg-editor-selection$)/;
describe("palette themes", () => {
const ISLANDS = ["light", "dark", "dark-hc"];
+3 -2
Переглянути файл
@@ -225,7 +225,8 @@ export function Select<V extends string>({
export interface ColorSwatchesProps {
value: string;
presets: readonly { value: string; label: string }[];
/** `css`: how the swatch is drawn when `value` is a name rather than a colour. */
presets: readonly { value: string; label: string; css?: string }[];
onChange: (value: string) => void;
/** Offer a custom colour picker + hex field. */
allowCustom?: boolean;
@@ -253,7 +254,7 @@ export function ColorSwatches({ value, presets, onChange, allowCustom = true, ..
className={clsx(styles.swatch, on && styles.swatchOn)}
onClick={() => onChange(p.value)}
>
<span className={styles.swatchColor} style={{ background: p.value }} />
<span className={styles.swatchColor} style={{ background: p.css ?? p.value }} />
</button>
);
})}
+2 -1
Переглянути файл
@@ -1576,7 +1576,8 @@ function ArtifactsSection() {
if (!root || !isTauri()) return;
let live = true;
call(commands.runTomcatArtifacts())
.then((list) => live && setWebArtifacts(list))
// Artifacts the IDE builds itself are the ones this page configures.
.then((list) => live && setWebArtifacts(list.filter((a) => a.tool !== "project")))
.catch(() => {});
return () => {
live = false;
+8
Переглянути файл
@@ -4,6 +4,8 @@
* so `validateSettings` never throws — anything unknown or malformed falls
* back to the default (mirrors `ide-core::settings` defaults).
*/
import { DEFAULT_FILE_COLORS, validateFileColors, type FileColorSettings } from "@/platform/fileColors";
import { validateScopes, type NamedScope } from "@/platform/scopes";
import { validateCMake } from "@/platform/cmakeSettings";
import { SUPPORTED_LOCALES, type Locale } from "@/platform/i18n";
import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames";
@@ -59,6 +61,8 @@ export interface CustomKeymapSettings {
export interface ValidSettings extends WorkflowSettings {
plugins: Record<string, Record<string, unknown>>;
scopes: NamedScope[];
fileColors: FileColorSettings;
general: {
reopenLastProject: boolean;
confirmExit: boolean;
@@ -159,6 +163,8 @@ export { ACCENT_PRESETS } from "@/workbench/theme";
export const DEFAULT_SETTINGS: ValidSettings = {
plugins: {},
scopes: [],
fileColors: DEFAULT_FILE_COLORS,
general: {
reopenLastProject: true,
confirmExit: true,
@@ -332,6 +338,8 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
}
return {
plugins: Object.fromEntries(Object.entries(obj(root.plugins)).map(([id, values]) => [id, obj(values)])),
scopes: validateScopes(root.scopes),
fileColors: validateFileColors(root.fileColors),
general: {
...validateGeneralExtras(g),
reopenLastProject: bool(g.reopenLastProject, d.general.reopenLastProject),
+28
Переглянути файл
@@ -0,0 +1,28 @@
.error {
color: var(--danger);
}
.color {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
}
.swatch {
flex: none;
width: 12px;
height: 12px;
border-radius: 3px;
border: 1px solid var(--border-strong);
}
.custom {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.picker {
width: 32px;
height: 22px;
padding: 0;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm, 4px);
background: none;
}
+2
Переглянути файл
@@ -11,6 +11,7 @@ import { EXECUTION_PAGES } from "./execution";
import { LANGUAGE_PAGES } from "./languages";
import { OptionsPage } from "./OptionsPage";
import { RUN_TARGET_PAGES } from "./runTargets";
import { SCOPE_PAGES } from "./scopes";
import { specLabels, type PageSpec } from "./spec";
import { SSH_PAGES } from "./ssh";
import { TOOLS_PAGES } from "./tools";
@@ -18,6 +19,7 @@ import { VCS_PAGES } from "./vcs";
const BUILTIN_PAGES = [
...BEHAVIOR_PAGES,
...SCOPE_PAGES,
UPDATES_PAGE,
...CORE_PAGES,
...EDITOR_PAGES,
+313
Переглянути файл
@@ -0,0 +1,313 @@
/**
* Appearance & Behavior › Scopes (named file sets) and › File Colors (a background
* colour per scope in the project view and on editor tabs). Both are project settings.
*/
import { useId, useState } from "react";
import clsx from "clsx";
import { FILE_COLOR_NAMES, fileColorCss, validateFileColors, type FileColorEntry } from "@/platform/fileColors";
import { tx } from "@/platform/i18n";
import { BUILTIN_SCOPES, scopeError, validateScopes, type NamedScope } from "@/platform/scopes";
import { IconButton, Input, T, type SelectOption } from "@/ui";
import { ColorSwatches, Row, Section, Select } from "../components/Form";
import { useSetting } from "../components/context";
import { APPEARANCE_GROUP } from "./behavior";
import type { PageSpec } from "./spec";
import styles from "./Workflow.module.css";
import own from "./Scopes.module.css";
/** Toolbar of an ordered list: add, remove, move up / down. */
function ListToolbar({
label,
index,
count,
onAdd,
onRemove,
onMove,
}: {
label: string;
index: number;
count: number;
onAdd: () => void;
onRemove: () => void;
onMove: (d: -1 | 1) => void;
}) {
return (
<div className={styles.toolbar} role="toolbar" aria-label={tx(label)}>
<IconButton icon="plus" title="Add" size="small" onClick={onAdd} />
<IconButton icon="minus" title="Remove" size="small" disabled={index < 0} onClick={onRemove} />
<IconButton icon="arrow-up" title="Move Up" size="small" disabled={index <= 0} onClick={() => onMove(-1)} />
<IconButton
icon="arrow-down"
title="Move Down"
size="small"
disabled={index < 0 || index >= count - 1}
onClick={() => onMove(1)}
/>
</div>
);
}
function moved<T>(list: readonly T[], index: number, d: -1 | 1): T[] | null {
const j = index + d;
if (index < 0 || j < 0 || j >= list.length) return null;
const next = [...list];
[next[index], next[j]] = [next[j]!, next[index]!];
return next;
}
/** A name not taken yet: `Scope`, `Scope 2`, … */
function freshName(taken: readonly string[]): string {
const base = tx("Scope");
for (let n = 1; ; n++) {
const name = n === 1 ? base : `${base} ${n}`;
if (!taken.includes(name)) return name;
}
}
/** A pattern, the same in every language. */
const PATTERN_EXAMPLE = "file:src//*";
function errorText(error: { message: string; at: number }): string {
const message = tx(error.message);
const column = error.at + 1;
return tx`${message} at column ${column}`;
}
function ScopesEditor() {
const [raw, setRaw] = useSetting<unknown>("scopes");
const scopes = validateScopes(raw);
const [selected, setSelected] = useState(0);
const index = scopes.length ? Math.min(selected, scopes.length - 1) : -1;
const current = scopes[index];
const nameId = useId();
const patternId = useId();
const set = (next: NamedScope[]) => setRaw(next);
const update = (patch: Partial<NamedScope>) => set(scopes.map((s, i) => (i === index ? { ...s, ...patch } : s)));
const error = current?.pattern.trim() ? scopeError(current.pattern) : null;
const taken = [...BUILTIN_SCOPES, ...scopes.map((s) => s.name)];
const nameClash = !!current && taken.filter((n) => n === current.name).length > 1;
return (
<div className={styles.toolsLayout}>
<div className={styles.tableBox}>
<ListToolbar
label="Scopes actions"
index={index}
count={scopes.length}
onAdd={() => {
set([...scopes, { name: freshName(taken), pattern: "" }]);
setSelected(scopes.length);
}}
onRemove={() => set(scopes.filter((_, i) => i !== index))}
onMove={(d) => {
const next = moved(scopes, index, d);
if (next) {
set(next);
setSelected(index + d);
}
}}
/>
<div className={styles.toolList} role="listbox" aria-label={tx("Scopes")}>
{scopes.length === 0 && (
<div className={clsx(styles.toolRow, styles.empty)}>
<T>No scopes. Click + to add one.</T>
</div>
)}
{scopes.map((s, i) => (
<div
key={i}
role="option"
aria-selected={i === index}
className={clsx(styles.toolRow, i === index && styles.toolRowSelected)}
onMouseDown={() => setSelected(i)}
>
<span className={styles.toolName}>{s.name}</span>
<span className={styles.toolGroup} title={s.pattern}>
{s.pattern}
</span>
</div>
))}
</div>
</div>
{current && (
<Section title="Scope">
<Row label="Name" htmlFor={nameId} className={styles.alignedRow}>
<Input
id={nameId}
className={styles.wide}
value={current.name}
invalid={nameClash || !current.name.trim()}
onChange={(e) => update({ name: e.target.value })}
/>
</Row>
<Row
label="Pattern"
htmlFor={patternId}
className={styles.alignedRow}
hint={
error ? (
<span className={own.error} role="alert">
{errorText(error)}
</span>
) : (
"file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module."
)
}
>
<Input
id={patternId}
mono
className={styles.wide}
value={current.pattern}
invalid={!!error}
placeholder={PATTERN_EXAMPLE}
onChange={(e) => update({ pattern: e.target.value })}
/>
</Row>
</Section>
)}
</div>
);
}
const COLOR_LABELS: Record<string, string> = {
blue: "Blue",
green: "Green",
orange: "Orange",
rose: "Rose",
violet: "Violet",
yellow: "Yellow",
gray: "Gray",
};
const colorLabel = (color: string) => COLOR_LABELS[color.toLowerCase()] ?? color;
function FileColorsEditor() {
const [raw, setRaw] = useSetting<unknown>("fileColors");
const [rawScopes] = useSetting<unknown>("scopes");
const settings = validateFileColors(raw);
const colors = settings.colors;
const [selected, setSelected] = useState(0);
const index = colors.length ? Math.min(selected, colors.length - 1) : -1;
const current = colors[index];
const set = (next: FileColorEntry[]) => setRaw({ ...settings, colors: next });
const update = (patch: Partial<FileColorEntry>) => set(colors.map((c, i) => (i === index ? { ...c, ...patch } : c)));
const scopeNames = [...BUILTIN_SCOPES, ...validateScopes(rawScopes).map((s) => s.name)];
const scopeOptions: SelectOption[] = scopeNames.map((n) => ({ value: n, label: n }));
if (current && !scopeNames.includes(current.scope))
scopeOptions.push({ value: current.scope, label: tx`${current.scope} (missing)` });
const presets = FILE_COLOR_NAMES.map((n) => ({ value: n, label: colorLabel(n), css: fileColorCss(n) }));
return (
<div className={styles.toolsLayout}>
<div className={styles.tableBox}>
<ListToolbar
label="File colors actions"
index={index}
count={colors.length}
onAdd={() => {
const scope = scopeNames.find((n) => !colors.some((c) => c.scope === n)) ?? scopeNames[0]!;
set([...colors, { scope, color: "blue" }]);
setSelected(colors.length);
}}
onRemove={() => set(colors.filter((_, i) => i !== index))}
onMove={(d) => {
const next = moved(colors, index, d);
if (next) {
set(next);
setSelected(index + d);
}
}}
/>
<div className={styles.toolList} role="listbox" aria-label={tx("File colors")}>
{colors.length === 0 && (
<div className={clsx(styles.toolRow, styles.empty)}>
<T>No file colors. Click + to add one.</T>
</div>
)}
{colors.map((c, i) => (
<div
key={i}
role="option"
aria-selected={i === index}
className={clsx(styles.toolRow, i === index && styles.toolRowSelected)}
onMouseDown={() => setSelected(i)}
>
<span className={styles.toolName}>{tx(c.scope)}</span>
<span className={own.color}>
<span className={own.swatch} style={{ background: fileColorCss(c.color) }} aria-hidden />
{tx(colorLabel(c.color))}
</span>
</div>
))}
</div>
</div>
{current && (
<Section title="File Color">
<Row label="Scope" className={styles.alignedRow}>
<Select
value={current.scope}
options={scopeOptions}
onChange={(scope) => update({ scope })}
aria-label="Scope"
/>
</Row>
<Row label="Color" className={styles.alignedRow}>
<ColorSwatches
value={current.color}
presets={presets}
onChange={(color) => update({ color })}
aria-label="Color"
/>
</Row>
</Section>
)}
</div>
);
}
export const SCOPE_PAGES: PageSpec[] = [
{
id: "fileColors",
title: "File Colors",
group: APPEARANCE_GROUP,
order: 1.5,
projectScope: true,
defaultScope: "project",
keywords: ["colour", "color", "tab", "background", "tests", "non-project"],
sections: [
{
options: [
{ kind: "toggle", key: "fileColors.enabled", label: "Enable file colors" },
{ kind: "toggle", key: "fileColors.editorTabs", label: "Use in editor tabs" },
{ kind: "toggle", key: "fileColors.projectView", label: "Use in project view" },
],
},
{
options: [
{
kind: "custom",
label: "File Colors",
keywords: ["Scope", "Color", "Custom", "Hex value"],
component: FileColorsEditor,
},
],
},
],
},
{
id: "scopes",
title: "Scopes",
group: APPEARANCE_GROUP,
order: 1.6,
projectScope: true,
defaultScope: "project",
keywords: ["scope", "file set", "pattern"],
sections: [
{
options: [{ kind: "custom", label: "Scopes", keywords: ["Name", "Pattern"], component: ScopesEditor }],
},
],
},
];
+129
Переглянути файл
@@ -0,0 +1,129 @@
/**
* File Colors (Settings › Appearance & Behavior › File Colors): files of a scope get a
* background colour in the project view and on their editor tabs. The first scope in the
* list that holds a file decides its colour.
*/
import { inScope, validateScopes, type NamedScope, type ScopeContext } from "./scopes";
export const FILE_COLOR_NAMES = ["blue", "green", "orange", "rose", "violet", "yellow", "gray"] as const;
export interface FileColorEntry {
scope: string;
/** A palette name or `#rrggbb`. */
color: string;
}
export interface FileColorSettings {
enabled: boolean;
editorTabs: boolean;
projectView: boolean;
colors: FileColorEntry[];
}
export const DEFAULT_FILE_COLORS: FileColorSettings = {
enabled: true,
editorTabs: true,
projectView: true,
colors: [
{ scope: "Non-Project Files", color: "yellow" },
{ scope: "Tests", color: "green" },
],
};
const HEX = /^#[0-9a-f]{6}$/i;
export function validateFileColors(raw: unknown): FileColorSettings {
const v = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
const d = DEFAULT_FILE_COLORS;
const bool = (x: unknown, def: boolean) => (typeof x === "boolean" ? x : def);
const colors = Array.isArray(v.colors)
? v.colors.flatMap((c: unknown) => {
const e = c && typeof c === "object" ? (c as Record<string, unknown>) : {};
return typeof e.scope === "string" && e.scope && typeof e.color === "string"
? [{ scope: e.scope, color: e.color }]
: [];
})
: d.colors;
return {
enabled: bool(v.enabled, d.enabled),
editorTabs: bool(v.editorTabs, d.editorTabs),
projectView: bool(v.projectView, d.projectView),
colors,
};
}
/** The CSS colour of a stored colour value. */
export function fileColorCss(color: string): string | undefined {
const name = color.toLowerCase();
if ((FILE_COLOR_NAMES as readonly string[]).includes(name)) return `var(--file-color-${name})`;
return HEX.test(color) ? color : undefined;
}
/** Where a file colour shows. */
export type FileColorPlace = "editorTabs" | "projectView";
/** The colour of the absolute `path` from these settings, or undefined. */
export function fileColorOf(
path: string,
settings: FileColorSettings,
ctx: ScopeContext,
dir = false,
): string | undefined {
if (!settings.enabled) return undefined;
for (const entry of settings.colors) {
if (inScope(entry.scope, path, ctx, dir)) return fileColorCss(entry.color);
}
return undefined;
}
let cachedRaw: unknown = Symbol("unset");
let cached = DEFAULT_FILE_COLORS;
/** The File Colors settings in the raw settings `fileColors` (cached per object). */
export function fileColorSettings(raw: unknown): FileColorSettings {
if (raw !== cachedRaw) {
cachedRaw = raw;
cached = validateFileColors(raw);
}
return cached;
}
/**
* A pattern for exactly `rel` (a folder: everything in it), or null when the path has
* characters a pattern can't hold.
*/
export function pathPattern(rel: string, dir: boolean): string | null {
if (!rel || /[\s()|&!*[\]]/.test(rel)) return null;
return dir ? `file:${rel}//*` : `file:${rel}`;
}
/** The colour given to `rel` itself through its own scope (Set File Color), if any. */
export function ownFileColor(rel: string, dir: boolean, settings: unknown): string | null {
const pattern = pathPattern(rel, dir);
const s = settings as { scopes?: unknown; fileColors?: unknown } | null;
const scope = validateScopes(s?.scopes).find((x) => x.name === rel && x.pattern === pattern);
return (scope && validateFileColors(s?.fileColors).colors.find((c) => c.scope === scope.name)?.color) ?? null;
}
/**
* The project's scopes and File Colors with `rel` given `color` (first in the list, so it
* wins over broader scopes), or with that colour and its scope removed (`null`).
*/
export function withOwnFileColor(
settings: unknown,
rel: string,
dir: boolean,
color: string | null,
): { scopes: NamedScope[]; fileColors: FileColorSettings } | null {
const pattern = pathPattern(rel, dir);
if (!pattern) return null;
const s = settings as { scopes?: unknown; fileColors?: unknown } | null;
const scopes = validateScopes(s?.scopes).filter((x) => x.name !== rel);
const fileColors = validateFileColors(s?.fileColors);
const colors = fileColors.colors.filter((c) => c.scope !== rel);
return color
? {
scopes: [...scopes, { name: rel, pattern }],
fileColors: { ...fileColors, colors: [{ scope: rel, color }, ...colors] },
}
: { scopes, fileColors: { ...fileColors, colors } };
}
+33 -1
Переглянути файл
@@ -1927,5 +1927,37 @@
"Collapse All Files": "Collapse All Files",
"Show Files in Separate Diff Tabs": "Show Files in Separate Diff Tabs",
"Show All Files in One Diff View": "Show All Files in One Diff View",
"No changes": "No changes"
"No changes": "No changes",
"Scopes actions": "Scopes actions",
"Scopes": "Scopes",
"No scopes. Click + to add one.": "No scopes. Click + to add one.",
"Scope": "Scope",
"Pattern": "Pattern",
"{message} at column {column}": "{message} at column {column}",
"')' expected": "')' expected",
"'file:' expected": "'file:' expected",
"':' expected": "':' expected",
"']' expected": "']' expected",
"Pattern expected": "Pattern expected",
"Unexpected text": "Unexpected text",
"File colors actions": "File colors actions",
"File colors": "File colors",
"No file colors. Click + to add one.": "No file colors. Click + to add one.",
"File Color": "File Color",
"Color": "Color",
"File Colors": "File Colors",
"Enable file colors": "Enable file colors",
"Use in editor tabs": "Use in editor tabs",
"Use in project view": "Use in project view",
"Orange": "Orange",
"Rose": "Rose",
"Violet": "Violet",
"Gray": "Gray",
"Project Files": "Project Files",
"Production": "Production",
"Tests": "Tests",
"Non-Project Files": "Non-Project Files",
"file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.": "file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.",
"Clear File Color": "Clear File Color",
"Edit File Colors…": "Edit File Colors…"
}
+25 -1
Переглянути файл
@@ -8328,5 +8328,29 @@
"Expand All Files": "展开所有文件",
"Collapse All Files": "折叠所有文件",
"Show Files in Separate Diff Tabs": "在单独的差异标签页中显示文件",
"Show All Files in One Diff View": "在一个差异视图中显示所有文件"
"Show All Files in One Diff View": "在一个差异视图中显示所有文件",
"Scopes actions": "作用域操作",
"No scopes. Click + to add one.": "没有作用域。点击 + 添加。",
"{message} at column {column}": "{message}(第 {column} 列)",
"')' expected": "缺少 ')'",
"'file:' expected": "缺少 'file:'",
"':' expected": "缺少 ':'",
"']' expected": "缺少 ']'",
"Pattern expected": "缺少模式",
"Unexpected text": "意外的文本",
"File colors actions": "文件颜色操作",
"File colors": "文件颜色",
"No file colors. Click + to add one.": "没有文件颜色。点击 + 添加。",
"File Color": "文件颜色",
"File Colors": "文件颜色",
"Enable file colors": "启用文件颜色",
"Use in editor tabs": "在编辑器标签页中使用",
"Use in project view": "在项目视图中使用",
"Rose": "玫瑰色",
"Gray": "灰色",
"Production": "生产",
"Non-Project Files": "非项目文件",
"file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.": "file:src//*.ts && !file:*.test.ts —— 路径相对于项目;// 表示任意层文件夹,* 表示任意字符。file[module]:pattern 将模式限定在某个模块内。",
"Clear File Color": "清除文件颜色",
"Edit File Colors…": "编辑文件颜色…"
}
+130
Переглянути файл
@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
DEFAULT_FILE_COLORS,
fileColorCss,
fileColorOf,
ownFileColor,
validateFileColors,
withOwnFileColor,
} from "./fileColors";
import { useProject } from "./project";
import { filePatternRegExp, inScope, parseScope, scopeError, type ScopeContext } from "./scopes";
const ctx = (scopes: ScopeContext["scopes"] = [], extra: Partial<ScopeContext> = {}): ScopeContext => ({
roots: [
{ path: "src/test", kind: "test" },
{ path: "build", kind: "excluded" },
] as never,
modules: [
{ name: "p", path: "" },
{ name: "web", path: "web" },
],
scopes,
...extra,
});
beforeEach(() => {
useProject.setState({ project: { name: "p", root: "/p", trusted: true, settings: {} } as never });
});
describe("file patterns", () => {
const m = (pattern: string, path: string) => filePatternRegExp(pattern).test(path);
it("reads * within a name, ** and a trailing * as one name, // as any folders", () => {
expect(m("src/*", "src/a.ts")).toBe(true);
expect(m("src/*", "src/a/b.ts")).toBe(false);
// A `*` followed by more of the name matches across folders.
expect(m("src/*.ts", "src/a/b.ts")).toBe(true);
expect(m("src/**.ts", "src/a/b.ts")).toBe(false);
expect(m("src//*", "src/a/b/c.ts")).toBe(true);
expect(m("src//*", "lib/a.ts")).toBe(false);
expect(m("*.md", "README.md")).toBe(true);
expect(m("*.md", "README.mdx")).toBe(false);
// Folders end in `/`.
expect(m("src//*", "src/a/")).toBe(true);
});
});
describe("scope expressions", () => {
it("combines file patterns with !, && and || in precedence order", () => {
const scope = { name: "TS", pattern: "file:src//*.ts && !file:*.test.ts || file:README.md" };
const c = ctx([scope]);
expect(inScope("TS", "/p/src/a/b.ts", c)).toBe(true);
expect(inScope("TS", "/p/src/a/b.test.ts", c)).toBe(false);
expect(inScope("TS", "/p/README.md", c)).toBe(true);
expect(inScope("TS", "/elsewhere/src/a.ts", c)).toBe(false);
});
it("limits a pattern to a module", () => {
const c = ctx([{ name: "Web", pattern: "file[web]:*.ts" }]);
expect(inScope("Web", "/p/web/app.ts", c)).toBe(true);
expect(inScope("Web", "/p/src/app.ts", c)).toBe(false);
});
it("reports where a pattern goes wrong", () => {
expect(scopeError("file:a && (file:b")).toEqual({ message: "')' expected", at: 17 });
expect(scopeError("src/*")).toEqual({ message: "'file:' expected", at: 0 });
expect(scopeError("file:")).toEqual({ message: "Pattern expected", at: 5 });
expect(scopeError("file:a)")).toEqual({ message: "Unexpected text", at: 6 });
expect(() => parseScope("(file:a || file:b) && !file:c")).not.toThrow();
});
it("knows the built-in scopes", () => {
const c = ctx([], { ownFolders: ["/scratches"] });
expect(inScope("Tests", "/p/src/test/A.java", c)).toBe(true);
expect(inScope("Production", "/p/src/main/A.java", c)).toBe(true);
expect(inScope("Project Files", "/p/build/out.class", c)).toBe(false);
expect(inScope("Non-Project Files", "/lib/rt.jar", c)).toBe(true);
expect(inScope("Non-Project Files", "/scratches/a.sql", c)).toBe(false);
expect(inScope("Non-Project Files", "/p/a.ts", c)).toBe(false);
});
});
describe("file colors", () => {
it("colours tests green and non-project files yellow by default; the first matching scope wins", () => {
const c = ctx([{ name: "Docs", pattern: "file:*.md" }]);
expect(fileColorOf("/p/src/test/A.java", DEFAULT_FILE_COLORS, c)).toBe("var(--file-color-green)");
expect(fileColorOf("/lib/A.java", DEFAULT_FILE_COLORS, c)).toBe("var(--file-color-yellow)");
expect(fileColorOf("/p/src/A.java", DEFAULT_FILE_COLORS, c)).toBeUndefined();
const s = validateFileColors({
colors: [
{ scope: "Docs", color: "#112233" },
{ scope: "Project Files", color: "Blue" },
],
});
expect(fileColorOf("/p/a.md", s, c)).toBe("#112233");
expect(fileColorOf("/p/a.ts", s, c)).toBe("var(--file-color-blue)");
expect(fileColorOf("/p/a.ts", { ...s, enabled: false }, c)).toBeUndefined();
});
it("ignores colours it can't draw", () => {
expect(fileColorCss("red; background: url(x)")).toBeUndefined();
expect(fileColorCss("Gray")).toBe("var(--file-color-gray)");
});
});
describe("a file or folder's own colour", () => {
it("adds a scope of the path ahead of the other colours, and removes both again", () => {
const set = withOwnFileColor({}, "src/api", true, "rose")!;
expect(set.scopes).toEqual([{ name: "src/api", pattern: "file:src/api//*" }]);
expect(set.fileColors.colors[0]).toEqual({ scope: "src/api", color: "rose" });
expect(set.fileColors.colors.slice(1)).toEqual(DEFAULT_FILE_COLORS.colors);
expect(ownFileColor("src/api", true, set)).toBe("rose");
const c = ctx(set.scopes);
// Everything in the folder, including its tests, takes the folder's colour.
expect(fileColorOf("/p/src/api/x_test.go", set.fileColors, c)).toBe("var(--file-color-rose)");
expect(fileColorOf("/p/src/api", set.fileColors, c, true)).toBe("var(--file-color-rose)");
expect(fileColorOf("/p/src/apix/a.go", set.fileColors, c)).toBeUndefined();
const recolored = withOwnFileColor(set, "src/api", true, "blue")!;
expect(recolored.fileColors.colors.filter((x) => x.scope === "src/api")).toHaveLength(1);
const cleared = withOwnFileColor(set, "src/api", true, null)!;
expect(cleared.scopes).toEqual([]);
expect(cleared.fileColors.colors).toEqual(DEFAULT_FILE_COLORS.colors);
});
it("is not offered for paths a pattern can't name", () => {
expect(withOwnFileColor({}, "my docs", true, "blue")).toBeNull();
expect(withOwnFileColor({}, "", true, "blue")).toBeNull();
});
});
+255
Переглянути файл
@@ -0,0 +1,255 @@
/**
* Scopes (Settings › Appearance & Behavior › Scopes): named sets of files that other
* settings refer to, e.g. File Colors. A scope's pattern is an expression over file
* patterns: `file:src//*.ts && !file:*.test.ts`, `file[web]:*.ts` or `(a || b) && !c`.
*
* A file pattern matches the project-relative path (folders end in `/`): `*` stands for
* any characters, `**` and a trailing `*` for characters within one name, and `//` for
* any folders in between. `file[module]:` also requires the file to be in a module of that name.
*/
import { useMemo } from "react";
import type { RootFolder } from "./languageSettings";
import { useProject } from "./project";
import {
inFileSet,
projectModules,
projectRelative,
useDetectedRoots,
useEffectiveRoots,
type ProjectModule,
} from "./projectRoots";
export interface NamedScope {
name: string;
pattern: string;
}
/** Scopes every project has, by name. */
export const BUILTIN_SCOPES = ["Project Files", "Production", "Tests", "Non-Project Files"] as const;
type Node =
| { kind: "file"; module: RegExp | null; path: RegExp }
| { kind: "not"; of: Node }
| { kind: "and" | "or"; left: Node; right: Node };
export class ScopeSyntaxError extends Error {
constructor(
message: string,
readonly at: number,
) {
super(message);
}
}
/** The regular expression of a file pattern, read the way the pattern syntax defines it. */
export function filePatternRegExp(pattern: string): RegExp {
let out = "";
let afterSlash = false;
let afterStar = false;
for (const c of pattern) {
if (c !== "/" && afterSlash) {
out += "\\/";
afterSlash = false;
}
if (c !== "*" && afterStar) {
out += ".*";
afterStar = false;
}
if (c === "*") {
if (afterStar) out += "[^/]*";
afterStar = !afterStar;
} else if (c === "/") {
if (afterSlash) out += "\\/(.*\\/)?";
afterSlash = !afterSlash;
} else {
out += c.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
}
}
if (afterStar) out += "[^/]*";
return new RegExp(`^${out}$`);
}
/** A module name pattern: `*` stands for any characters. */
const moduleRegExp = (pattern: string) =>
new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
/** Parses a scope pattern; throws `ScopeSyntaxError` with the offset of the problem. */
export function parseScope(text: string): Node {
let i = 0;
const ws = () => {
while (i < text.length && /\s/.test(text[i]!)) i++;
};
const eat = (token: string) => {
ws();
if (!text.startsWith(token, i)) return false;
i += token.length;
return true;
};
const or = (): Node => {
let left = and();
while (eat("||")) left = { kind: "or", left, right: and() };
return left;
};
const and = (): Node => {
let left = unary();
while (eat("&&")) left = { kind: "and", left, right: unary() };
return left;
};
const unary = (): Node => {
if (eat("!")) return { kind: "not", of: unary() };
if (eat("(")) {
const inner = or();
if (!eat(")")) throw new ScopeSyntaxError("')' expected", i);
return inner;
}
return atom();
};
const atom = (): Node => {
ws();
const start = i;
if (!text.startsWith("file", i)) throw new ScopeSyntaxError("'file:' expected", start);
i += 4;
let module: RegExp | null = null;
if (text[i] === "[") {
const close = text.indexOf("]", i);
if (close < 0) throw new ScopeSyntaxError("']' expected", i);
module = moduleRegExp(text.slice(i + 1, close).trim());
i = close + 1;
}
if (text[i] !== ":") throw new ScopeSyntaxError("':' expected", i);
i++;
const from = i;
// A pattern runs to whitespace or an operator.
while (i < text.length && !/[\s()|&!]/.test(text[i]!)) i++;
if (i === from) throw new ScopeSyntaxError("Pattern expected", i);
return { kind: "file", module, path: filePatternRegExp(text.slice(from, i)) };
};
const node = or();
ws();
if (i < text.length) throw new ScopeSyntaxError("Unexpected text", i);
return node;
}
/** The problem with a scope pattern and its offset, or null when it parses. */
export function scopeError(pattern: string): { message: string; at: number } | null {
try {
parseScope(pattern);
return null;
} catch (e) {
return e instanceof ScopeSyntaxError ? { message: e.message, at: e.at } : { message: String(e), at: 0 };
}
}
/** What a scope is matched against. */
export interface ScopeContext {
roots: readonly RootFolder[];
modules: readonly ProjectModule[];
scopes: readonly NamedScope[];
/** Folders outside the project that are not Non-Project Files either (scratches). */
ownFolders?: readonly string[];
}
/** The innermost module holding the file (`rel` in the project, `path` absolute). */
function moduleOf(rel: string, path: string, modules: readonly ProjectModule[]): ProjectModule | undefined {
let best: ProjectModule | undefined;
for (const m of modules) {
// Workspace members have absolute paths.
const at = m.path.startsWith("/") ? path : rel;
const holds = m.path === "" || at === m.path || at.startsWith(`${m.path}/`);
if (holds && (!best || m.path.length > best.path.length)) best = m;
}
return best;
}
function matches(node: Node, rel: string, path: string, dir: boolean, ctx: ScopeContext): boolean {
switch (node.kind) {
case "not":
return !matches(node.of, rel, path, dir, ctx);
case "and":
return matches(node.left, rel, path, dir, ctx) && matches(node.right, rel, path, dir, ctx);
case "or":
return matches(node.left, rel, path, dir, ctx) || matches(node.right, rel, path, dir, ctx);
case "file": {
if (node.module) {
const m = moduleOf(rel, path, ctx.modules);
if (!m || !node.module.test(m.name)) return false;
}
return node.path.test(dir ? `${rel}/` : rel);
}
}
}
const parsed = new Map<string, Node | null>();
function compiled(pattern: string): Node | null {
let node = parsed.get(pattern);
if (node === undefined) {
try {
node = parseScope(pattern);
} catch {
node = null;
}
if (parsed.size > 200) parsed.clear();
parsed.set(pattern, node);
}
return node;
}
/** Whether the absolute `path` is in the scope called `name` (built-in or user-defined). */
export function inScope(name: string, path: string, ctx: ScopeContext, dir = false): boolean {
switch (name) {
case "Project Files":
return inFileSet("all", path, ctx.roots);
case "Production":
return inFileSet("production", path, ctx.roots);
case "Tests":
return inFileSet("test", path, ctx.roots);
case "Non-Project Files":
return projectRelative(path) === null && !ctx.ownFolders?.some((d) => path === d || path.startsWith(`${d}/`));
}
const scope = ctx.scopes.find((s) => s.name === name);
const node = scope ? compiled(scope.pattern) : null;
const rel = projectRelative(path);
return !!node && rel !== null && rel !== "" && matches(node, rel, path, dir, ctx);
}
/** User scopes from settings. */
export function validateScopes(raw: unknown): NamedScope[] {
if (!Array.isArray(raw)) return [];
return raw.flatMap((s) =>
s && typeof s === "object" && typeof s.name === "string" && s.name.trim()
? [{ name: s.name, pattern: typeof s.pattern === "string" ? s.pattern : "" }]
: [],
);
}
let cachedRaw: unknown = Symbol("unset");
let cachedScopes: NamedScope[] = [];
/** The project's user scopes (cached per settings object). */
export function userScopes(raw: unknown = (useProject.getState().settings as { scopes?: unknown } | null)?.scopes) {
if (raw !== cachedRaw) {
cachedRaw = raw;
cachedScopes = validateScopes(raw);
}
return cachedScopes;
}
function modulesOf(detected: readonly RootFolder[]): ProjectModule[] {
const project = useProject.getState().project;
return project?.workspace
? project.workspace.projects.map((path) => ({ path, name: path.slice(path.lastIndexOf("/") + 1) }))
: projectModules(detected, project?.name ?? "");
}
/** The scope context, following roots and settings. */
export function useScopeContext(): ScopeContext {
const roots = useEffectiveRoots();
const detected = useDetectedRoots();
const raw = useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes);
const project = useProject((s) => s.project);
return useMemo(
() => ({ roots, modules: modulesOf(detected), scopes: userScopes(raw) }),
// `project` changes the module names.
// eslint-disable-next-line react-hooks/exhaustive-deps
[roots, detected, raw, project],
);
}
+9
Переглянути файл
@@ -477,6 +477,15 @@ html {
--db-color-blue: #3b92b8;
--db-color-violet: #955ae0;
--tint-strength: 22%;
/* File Colors palette (Appearance › File Colors); drawn as tints like the data source colours. */
--file-color-blue: #3b92b8;
--file-color-green: #5fad65;
--file-color-orange: #e08855;
--file-color-rose: #e06c88;
--file-color-violet: #955ae0;
--file-color-yellow: #d4b106;
--file-color-gray: #8c8c8c;
--file-tint-strength: 14%;
}
/* Windows caption buttons (frameless title bar): the system close red in every theme. */
+11
Переглянути файл
@@ -68,6 +68,17 @@
.row:hover {
background: var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent));
}
/* File Colors: the row's background takes its scope's colour. */
.tinted {
background: color-mix(in srgb, var(--row-tint) var(--file-tint-strength, 14%), transparent);
}
.tinted:hover {
background: color-mix(
in srgb,
var(--row-tint) var(--file-tint-strength, 14%),
var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent))
);
}
/* Tree.selectionInactiveBackground when unfocused, selectionBackground when focused. */
.selected,
.selected:hover {
+7 -1
Переглянути файл
@@ -15,6 +15,7 @@ import {
useMemo,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
@@ -128,6 +129,8 @@ export interface TreeProps<T> {
indent?: number;
className?: string;
rowClassName?: (node: T) => string | undefined;
/** CSS colour the row background is tinted with (File Colors). */
rowTint?: (node: T) => string | undefined;
"aria-label"?: string;
handleRef?: Ref<TreeHandle>;
/** Context key set while the tree itself has keyboard focus. */
@@ -273,6 +276,7 @@ export function Tree<T>(props: TreeProps<T>) {
indent = 20,
className,
rowClassName,
rowTint,
handleRef,
empty,
} = props;
@@ -748,6 +752,7 @@ export function Tree<T>(props: TreeProps<T>) {
const icon = getIcon?.(row.node, row.expanded);
const detail = getDetail?.(row.node);
const color = getColor?.(row.node);
const tint = rowTint?.(row.node);
return (
<div
key={v.key}
@@ -763,13 +768,14 @@ export function Tree<T>(props: TreeProps<T>) {
styles.row,
props.horizontalScroll && styles.wideRow,
rowClassName?.(row.node),
tint && styles.tinted,
isSelected && styles.selected,
joinPrev && styles.joinPrev,
joinNext && styles.joinNext,
isLead && styles.lead,
reordering.drop?.key === row.key && styles[reordering.drop.position],
)}
style={style}
style={tint ? ({ ...style, "--row-tint": tint } as CSSProperties) : style}
onPointerDown={
props.reorder
? (e) => reordering.start(e, row)
+31
Переглянути файл
@@ -0,0 +1,31 @@
/** File Colors for the views that show them (project view, editor tabs). */
import { useMemo } from "react";
import { fileColorOf, fileColorSettings, type FileColorPlace } from "@/platform/fileColors";
import { useProject } from "@/platform/project";
import { useScopeContext } from "@/platform/scopes";
import { useProjectViewRoots } from "./contributions";
const rawFileColors = (s: { settings: unknown }) => (s.settings as { fileColors?: unknown } | null)?.fileColors;
/**
* The colour lookup of `place`, or null while file colours are off there. It changes
* with the settings and the project's roots; lookups are memoised per path.
*/
export function useFileColors(place: FileColorPlace): ((path: string, dir?: boolean) => string | undefined) | null {
const raw = useProject(rawFileColors);
const ctx = useScopeContext();
const extra = useProjectViewRoots((s) => s.roots);
return useMemo(() => {
const s = fileColorSettings(raw);
if (!s.enabled || !s[place] || !s.colors.length) return null;
// Scratches are neither project nor non-project files.
const ownFolders = [...extra.values()].flatMap((r) => (r.scope === "scratches" && r.path ? [r.path] : []));
const scope = { ...ctx, ownFolders };
const memo = new Map<string, string | undefined>();
return (path, dir = false) => {
const key = dir ? `${path}/` : path;
if (!memo.has(key)) memo.set(key, fileColorOf(path, s, scope, dir));
return memo.get(key);
};
}, [raw, ctx, extra, place]);
}