Skip to content

Commit d397ecb

Browse files
Add hints when uv init finds pyproject.toml without a project table (#22916)
## Summary `uv init` reports that a project is already initialized even when `pyproject.toml` contains only tool configuration. We now explain that the file already exists and suggest how to add project metadata when the file contains only tool settings. ```console $ uv init error: Cannot initialize a project in `/work/example` because `pyproject.toml` already exists hint: To use this directory as a project, declare its name, version, and other metadata in a `[project]` table ``` For a legacy Poetry project, the hint explains that uv reads project metadata from `[project]` and suggests converting the `[tool.poetry]` metadata to that format. Existing projects, workspace roots, and projects explicitly marked unmanaged get the file-exists error alone. --------- Co-authored-by: Charlie Marsh <[email protected]>
1 parent 7b5d227 commit d397ecb

3 files changed

Lines changed: 161 additions & 7 deletions

File tree

‎crates/uv-project-commands/src/error.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Failures specific to project metadata and editing.
22
3+
use std::path::PathBuf;
34
use std::{fmt, io};
45

56
use owo_colors::OwoColorize;
@@ -11,6 +12,12 @@ use uv_workspace::WorkspaceError;
1112
/// A failure from project metadata, editing, or a shared workflow.
1213
#[derive(thiserror::Error, Debug)]
1314
pub enum ProjectError {
15+
#[error("Cannot initialize a project in `{}` because `pyproject.toml` already exists", .path.display().cyan())]
16+
PyprojectTomlExists {
17+
path: PathBuf,
18+
hint: Option<&'static str>,
19+
},
20+
1421
#[error("Failed to parse `pyproject.toml`")]
1522
PyprojectTomlParse(#[source] uv_workspace::pyproject::PyprojectTomlError),
1623

@@ -50,7 +57,8 @@ impl From<ProjectError> for UvError {
5057
match error {
5158
ProjectError::Lock(error) => Self::from(error),
5259
ProjectError::Environment(error) => Self::from(error),
53-
error @ (ProjectError::PyprojectTomlParse(_)
60+
error @ (ProjectError::PyprojectTomlExists { .. }
61+
| ProjectError::PyprojectTomlParse(_)
5462
| ProjectError::PyprojectTomlUpdate
5563
| ProjectError::Pep723ScriptTomlParse(_)
5664
| ProjectError::PyprojectMut(_)
@@ -66,6 +74,7 @@ impl From<ProjectError> for UvError {
6674
impl Hinted for ProjectError {
6775
fn hints(&self) -> Hints<'_> {
6876
match self {
77+
Self::PyprojectTomlExists { hint, .. } => hint.map_or_else(Hints::none, Hints::from),
6978
Self::Lock(error) => error.hints(),
7079
Self::Environment(error) => error.hints(),
7180
Self::MissingProjectVersion(_) => Hints::from(format!(

‎crates/uv-project-commands/src/init.rs‎

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ use std::str::FromStr;
66

77
use anyhow::{Context, Result, bail};
88
use owo_colors::OwoColorize;
9+
use serde::Deserialize;
10+
use serde::de::IgnoredAny;
11+
use toml::Table;
912
use toml_edit::{InlineTable, Value};
1013
use tracing::{debug, trace, warn};
1114

@@ -43,6 +46,8 @@ use uv_workspace::{
4346
DiscoveryOptions, MemberDiscovery, Workspace, WorkspaceCache, WorkspaceErrorKind,
4447
};
4548

49+
use crate::ProjectError;
50+
4651
/// Add one or more packages to the project requirements.
4752
#[expect(clippy::single_match_else, clippy::fn_params_excessive_bools)]
4853
pub async fn init(
@@ -107,14 +112,17 @@ pub async fn init(
107112
Some(ref path) => std::path::absolute(path)?,
108113
};
109114

110-
// Make sure a project does not already exist in the given directory.
111-
if path.join("pyproject.toml").exists() {
115+
// Avoid overwriting an existing `pyproject.toml`.
116+
let pyproject_path = path.join("pyproject.toml");
117+
if let Ok(metadata) = fs_err::tokio::metadata(&pyproject_path).await {
118+
let hint = if metadata.is_file() {
119+
existing_pyproject_hint(&pyproject_path).await
120+
} else {
121+
None
122+
};
112123
let path =
113124
std::path::absolute(&path).unwrap_or_else(|_| path.simplified().to_path_buf());
114-
anyhow::bail!(
115-
"Project is already initialized in `{}` (`pyproject.toml` file exists)",
116-
path.display().cyan()
117-
);
125+
return Err(ProjectError::PyprojectTomlExists { path, hint }.into());
118126
}
119127

120128
// Default to the directory name if a name was not provided.
@@ -285,6 +293,55 @@ async fn init_script(
285293
Ok(())
286294
}
287295

296+
/// The parts of an existing `pyproject.toml` that determine which `uv init` hint to show.
297+
#[derive(Deserialize)]
298+
struct InitPyProjectToml {
299+
project: Option<IgnoredAny>,
300+
tool: Option<InitTools>,
301+
#[serde(flatten)]
302+
other: Table,
303+
}
304+
305+
#[derive(Deserialize)]
306+
struct InitTools {
307+
poetry: Option<Table>,
308+
uv: Option<InitToolUv>,
309+
}
310+
311+
#[derive(Deserialize)]
312+
struct InitToolUv {
313+
workspace: Option<IgnoredAny>,
314+
managed: Option<bool>,
315+
}
316+
317+
/// Suggest how to declare project metadata in an existing manifest.
318+
async fn existing_pyproject_hint(path: &Path) -> Option<&'static str> {
319+
let contents = fs_err::tokio::read_to_string(path).await.ok()?;
320+
let pyproject: InitPyProjectToml = toml::from_str(&contents).ok()?;
321+
if pyproject.project.is_some() {
322+
return None;
323+
}
324+
325+
let tool = pyproject.tool?;
326+
if let Some(uv) = tool.uv
327+
&& (uv.workspace.is_some() || uv.managed == Some(false))
328+
{
329+
return None;
330+
}
331+
332+
if tool.poetry.is_some() {
333+
Some(
334+
"uv reads project metadata from `[project]`. To migrate, convert the metadata in `[tool.poetry]` to that format",
335+
)
336+
} else if pyproject.other.is_empty() {
337+
Some(
338+
"To use this directory as a project, declare its name, version, and other metadata in a `[project]` table",
339+
)
340+
} else {
341+
None
342+
}
343+
}
344+
288345
/// Initialize a project (and, implicitly, a workspace root) at the given path.
289346
#[expect(clippy::fn_params_excessive_bools)]
290347
async fn init_project(

‎crates/uv/tests/project/init.rs‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ fn init() {
2121
Initialized project `foo` at `[TEMP_DIR]/foo`
2222
");
2323

24+
uv_snapshot!(context.filters(), context.init().arg("foo"), @"
25+
exit_code: 2 (failure)
26+
----- stderr -----
27+
error: Cannot initialize a project in `[TEMP_DIR]/foo` because `pyproject.toml` already exists
28+
");
29+
2430
let pyproject = context.read("foo/pyproject.toml");
2531
let _ = context.read("foo/README.md");
2632

@@ -65,6 +71,76 @@ fn init() {
6571
});
6672
}
6773

74+
#[test]
75+
fn init_existing_pyproject_tool_only() -> Result<()> {
76+
let context = uv_test::test_context_with_versions!(&[]);
77+
context
78+
.temp_dir
79+
.child("pyproject.toml")
80+
.write_str("[tool.ruff]\n")?;
81+
82+
uv_snapshot!(context.filters(), context.init(), @"
83+
exit_code: 2 (failure)
84+
----- stderr -----
85+
error: Cannot initialize a project in `[TEMP_DIR]/` because `pyproject.toml` already exists
86+
87+
hint: To use this directory as a project, declare its name, version, and other metadata in a `[project]` table
88+
");
89+
90+
Ok(())
91+
}
92+
93+
#[test]
94+
fn init_existing_pyproject_poetry() -> Result<()> {
95+
let context = uv_test::test_context_with_versions!(&[]);
96+
let pyproject_toml = context.temp_dir.child("pyproject.toml");
97+
pyproject_toml.write_str(indoc! {
98+
r#"
99+
[tool.poetry]
100+
name = "example"
101+
version = "0.1.0"
102+
103+
[build-system]
104+
requires = ["poetry-core"]
105+
build-backend = "poetry.core.masonry.api"
106+
"#,
107+
})?;
108+
109+
uv_snapshot!(context.filters(), context.init(), @"
110+
exit_code: 2 (failure)
111+
----- stderr -----
112+
error: Cannot initialize a project in `[TEMP_DIR]/` because `pyproject.toml` already exists
113+
114+
hint: uv reads project metadata from `[project]`. To migrate, convert the metadata in `[tool.poetry]` to that format
115+
");
116+
117+
Ok(())
118+
}
119+
120+
/// A build backend can read project metadata from outside `pyproject.toml`.
121+
#[test]
122+
fn init_existing_pyproject_build_system() -> Result<()> {
123+
let context = uv_test::test_context_with_versions!(&[]);
124+
let pyproject_toml = context.temp_dir.child("pyproject.toml");
125+
pyproject_toml.write_str(indoc! {
126+
r#"
127+
[build-system]
128+
requires = ["setuptools"]
129+
build-backend = "setuptools.build_meta"
130+
131+
[tool.ruff]
132+
"#,
133+
})?;
134+
135+
uv_snapshot!(context.filters(), context.init(), @"
136+
exit_code: 2 (failure)
137+
----- stderr -----
138+
error: Cannot initialize a project in `[TEMP_DIR]/` because `pyproject.toml` already exists
139+
");
140+
141+
Ok(())
142+
}
143+
68144
#[test]
69145
fn init_bare() {
70146
let context = uv_test::test_context!("3.12");
@@ -2230,6 +2306,12 @@ fn init_virtual_workspace() -> Result<()> {
22302306
",
22312307
})?;
22322308

2309+
uv_snapshot!(context.filters(), context.init().current_dir(&child), @"
2310+
exit_code: 2 (failure)
2311+
----- stderr -----
2312+
error: Cannot initialize a project in `[TEMP_DIR]/foo` because `pyproject.toml` already exists
2313+
");
2314+
22332315
uv_snapshot!(context.filters(), context.init().current_dir(&child).arg("bar"), @"
22342316
exit_code: 0 (success)
22352317
----- stderr -----
@@ -2727,6 +2809,12 @@ fn init_unmanaged() -> Result<()> {
27272809
",
27282810
})?;
27292811

2812+
uv_snapshot!(context.filters(), context.init(), @"
2813+
exit_code: 2 (failure)
2814+
----- stderr -----
2815+
error: Cannot initialize a project in `[TEMP_DIR]/` because `pyproject.toml` already exists
2816+
");
2817+
27302818
uv_snapshot!(context.filters(), context.init().arg("foo"), @"
27312819
exit_code: 0 (success)
27322820
----- stderr -----

0 commit comments

Comments
 (0)