Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read and write .python-version in the workspace root #7815

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/uv-workspace/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ uv-fs = { workspace = true, features = ["tokio", "schemars"] }
uv-git = { workspace = true }
uv-macros = { workspace = true }
uv-normalize = { workspace = true }
uv-python = { workspace = true }
uv-warnings = { workspace = true }
uv-options-metadata = { workspace = true }

Expand Down
41 changes: 41 additions & 0 deletions crates/uv-workspace/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use pep508_rs::{MarkerTree, RequirementOrigin, VerbatimUrl};
use pypi_types::{Requirement, RequirementSource, SupportedEnvironments, VerbatimParsedUrl};
use uv_fs::{Simplified, CWD};
use uv_normalize::{GroupName, PackageName, DEV_DEPENDENCIES};
use uv_python::{PythonVersionFile, PYTHON_VERSION_FILENAME};
use uv_warnings::{warn_user, warn_user_once};

use crate::pyproject::{
Expand Down Expand Up @@ -81,6 +82,9 @@ pub struct Workspace {
sources: BTreeMap<PackageName, Source>,
/// The `pyproject.toml` of the workspace root.
pyproject_toml: PyProjectToml,
/// The `.python-version` or `.python-versions` file of the workspace.
#[cfg_attr(test, serde(skip))]
python_version_file: PythonVersionFile,
}

impl Workspace {
Expand Down Expand Up @@ -172,6 +176,13 @@ impl Workspace {
)
};

// Discover the `.python-version` or `.python-versions` file.
let python_version_file =
match PythonVersionFile::discover(&workspace_root, false, false).await? {
Some(file) => file,
None => PythonVersionFile::new(workspace_root.join(PYTHON_VERSION_FILENAME)),
};

debug!(
"Found workspace root: `{}`",
workspace_root.simplified_display()
Expand All @@ -194,6 +205,7 @@ impl Workspace {
workspace_root.clone(),
workspace_definition,
workspace_pyproject_toml,
python_version_file,
current_project,
options,
)
Expand Down Expand Up @@ -542,6 +554,11 @@ impl Workspace {
&self.pyproject_toml
}

/// The `.python-version` or `.python-versions` file in the workspace.
pub fn python_version_file(&self) -> &PythonVersionFile {
&self.python_version_file
}

/// Returns `true` if the path is excluded by the workspace.
pub fn excludes(&self, project_path: &Path) -> Result<bool, WorkspaceError> {
if let Some(workspace) = self
Expand Down Expand Up @@ -577,6 +594,7 @@ impl Workspace {
workspace_root: PathBuf,
workspace_definition: ToolUvWorkspace,
workspace_pyproject_toml: PyProjectToml,
workspace_python_version_file: PythonVersionFile,
current_project: Option<WorkspaceMember>,
options: &DiscoveryOptions<'_>,
) -> Result<Workspace, WorkspaceError> {
Expand Down Expand Up @@ -757,6 +775,7 @@ impl Workspace {
packages: workspace_members,
sources: workspace_sources,
pyproject_toml: workspace_pyproject_toml,
python_version_file: workspace_python_version_file,
})
}
}
Expand Down Expand Up @@ -1046,6 +1065,13 @@ impl ProjectWorkspace {
// above it, so the project is an implicit workspace root identical to the project root.
debug!("No workspace root found, using project root");

// Discover the `.python-version` or `.python-versions` file.
let python_version_file =
match PythonVersionFile::discover(&project_path, false, false).await? {
Some(file) => file,
None => PythonVersionFile::new(project_path.join(PYTHON_VERSION_FILENAME)),
};

let current_project_as_members =
BTreeMap::from_iter([(project.name.clone(), current_project)]);
return Ok(Self {
Expand All @@ -1058,10 +1084,17 @@ impl ProjectWorkspace {
// workspace sources.
sources: BTreeMap::default(),
pyproject_toml: project_pyproject_toml.clone(),
python_version_file,
},
});
};

let python_version_file =
match PythonVersionFile::discover(&workspace_root, false, false).await? {
Some(file) => file,
None => PythonVersionFile::new(workspace_root.join(PYTHON_VERSION_FILENAME)),
};

debug!(
"Found workspace root: `{}`",
workspace_root.simplified_display()
Expand All @@ -1071,6 +1104,7 @@ impl ProjectWorkspace {
workspace_root,
workspace_definition,
workspace_pyproject_toml,
python_version_file,
Some(current_project),
options,
)
Expand Down Expand Up @@ -1389,12 +1423,19 @@ impl VirtualProject {
.map_err(WorkspaceError::Normalize)?
.clone();

let python_version_file =
match PythonVersionFile::discover(&project_path, false, false).await? {
Some(file) => file,
None => PythonVersionFile::new(project_path.join(PYTHON_VERSION_FILENAME)),
};

check_nested_workspaces(&project_path, options);

let workspace = Workspace::collect_members(
project_path,
workspace.clone(),
pyproject_toml,
python_version_file,
None,
options,
)
Expand Down
73 changes: 48 additions & 25 deletions crates/uv/src/commands/project/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use uv_configuration::{VersionControlError, VersionControlSystem};
use uv_fs::{Simplified, CWD};
use uv_python::{
EnvironmentPreference, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest,
PythonVersionFile, VersionRequest,
PythonVersionFile, VersionRequest, PYTHON_VERSION_FILENAME,
};
use uv_resolver::RequiresPython;
use uv_scripts::{Pep723Script, ScriptTag};
Expand Down Expand Up @@ -458,6 +458,7 @@ async fn init_project(
.init(
name,
path,
workspace.as_ref(),
&requires_python,
python_request.as_ref(),
vcs,
Expand Down Expand Up @@ -547,6 +548,7 @@ impl InitProjectKind {
self,
name: &PackageName,
path: &Path,
workspace: Option<&Workspace>,
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
Expand All @@ -558,6 +560,7 @@ impl InitProjectKind {
self.init_application(
name,
path,
workspace,
requires_python,
python_request,
vcs,
Expand All @@ -570,6 +573,7 @@ impl InitProjectKind {
self.init_library(
name,
path,
workspace,
requires_python,
python_request,
vcs,
Expand All @@ -586,6 +590,7 @@ impl InitProjectKind {
self,
name: &PackageName,
path: &Path,
workspace: Option<&Workspace>,
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
Expand Down Expand Up @@ -643,18 +648,8 @@ impl InitProjectKind {
}
fs_err::write(path.join("pyproject.toml"), pyproject)?;

// Write .python-version if it doesn't exist.
if let Some(python_request) = python_request {
if PythonVersionFile::discover(path, false, false)
.await?
.is_none()
{
PythonVersionFile::new(path.join(".python-version"))
.with_versions(vec![python_request.clone()])
.write()
.await?;
}
}
// Write `.python-version` if it doesn't exist.
write_python_version_file(path, python_request, workspace).await?;

// Initialize the version control system.
init_vcs(path, vcs)?;
Expand All @@ -667,6 +662,7 @@ impl InitProjectKind {
self,
name: &PackageName,
path: &Path,
workspace: Option<&Workspace>,
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
Expand Down Expand Up @@ -708,18 +704,8 @@ impl InitProjectKind {
fs_err::write(py_typed, "")?;
}

// Write .python-version if it doesn't exist.
if let Some(python_request) = python_request {
if PythonVersionFile::discover(path, false, false)
.await?
.is_none()
{
PythonVersionFile::new(path.join(".python-version"))
.with_versions(vec![python_request.clone()])
.write()
.await?;
}
}
// Write `.python-version` if it doesn't exist.
write_python_version_file(path, python_request, workspace).await?;

// Initialize the version control system.
init_vcs(path, vcs)?;
Expand Down Expand Up @@ -765,6 +751,43 @@ fn pyproject_project_scripts(package: &PackageName, executable_name: &str, targe
"#}
}

/// Create or update the `.python-version` file in the given path or workspace.
async fn write_python_version_file(
path: &Path,
python_request: Option<&PythonRequest>,
workspace: Option<&Workspace>,
) -> Result<()> {
let Some(python_request) = python_request else {
return Ok(());
};

if let Some(workspace) = workspace {
let version_file = workspace.python_version_file();
// TODO: If the version file already exists, but does not contain the requested version,
// should we update it? (add the version, or replace the existing one)
// For now, we keep the existing behavior: if the file exists, we don't update it.
if !version_file.path().try_exists()? {
version_file
.clone()
.with_versions(vec![python_request.clone()])
.write()
.await?;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the version file already exists, but does not contain the requested version, should we update it? (add the version, or replace the existing one)
For now, we keep the existing behavior: if the file exists, we don't update it.

} else {
if PythonVersionFile::discover(path, false, false)
.await?
.is_none()
{
PythonVersionFile::new(path.join(PYTHON_VERSION_FILENAME))
.with_versions(vec![python_request.clone()])
.write()
.await?;
}
}

Ok(())
}

/// Initialize the version control system at the given path.
fn init_vcs(path: &Path, vcs: Option<VersionControlSystem>) -> Result<()> {
// Detect any existing version control system.
Expand Down
Loading