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

Fill in authors filed during uv init #7756

Merged
merged 6 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions crates/uv-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2314,6 +2314,17 @@ impl ExternalCommand {
}
}

#[derive(Debug, Default, Copy, Clone, clap::ValueEnum)]
pub enum AuthorFrom {
/// Fetch the author information from some sources (e.g., Git) automatically.
#[default]
Auto,
/// Fetch the author information from Git configuration only.
Git,
/// Do not infer the author information.
None,
}

#[derive(Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct InitArgs {
Expand Down Expand Up @@ -2400,6 +2411,14 @@ pub struct InitArgs {
#[arg(long)]
pub no_readme: bool,

/// Fill in the `authors` field in the `pyproject.toml`.
///
/// By default, uv will attempt to infer the author information from some sources (e.g., Git) (`auto`).
/// Use `--author-from git` to only infer from Git configuration.
/// Use `--author-from none` to avoid inferring the author information.
#[arg(long, value_enum)]
pub author_from: Option<AuthorFrom>,

/// Do not create a `.python-version` file for the project.
///
/// By default, uv will create a `.python-version` file containing the minor version of
Expand Down
122 changes: 116 additions & 6 deletions crates/uv/src/commands/project/init.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use anyhow::{anyhow, Context, Result};
use owo_colors::OwoColorize;

use tracing::{debug, warn};
use uv_cache::Cache;
use uv_cli::AuthorFrom;
use uv_client::{BaseClientBuilder, Connectivity};
use uv_configuration::{VersionControlError, VersionControlSystem};
use uv_fs::{Simplified, CWD};
Expand Down Expand Up @@ -36,6 +38,7 @@ pub(crate) async fn init(
init_kind: InitKind,
vcs: Option<VersionControlSystem>,
no_readme: bool,
author_from: Option<AuthorFrom>,
no_pin_python: bool,
python: Option<String>,
no_workspace: bool,
Expand All @@ -62,6 +65,7 @@ pub(crate) async fn init(
printer,
no_workspace,
no_readme,
author_from,
no_pin_python,
package,
native_tls,
Expand Down Expand Up @@ -111,6 +115,7 @@ pub(crate) async fn init(
project_kind,
vcs,
no_readme,
author_from,
no_pin_python,
python,
no_workspace,
Expand Down Expand Up @@ -165,6 +170,7 @@ async fn init_script(
printer: Printer,
no_workspace: bool,
no_readme: bool,
author_from: Option<AuthorFrom>,
no_pin_python: bool,
package: bool,
native_tls: bool,
Expand All @@ -175,6 +181,9 @@ async fn init_script(
if no_readme {
warn_user_once!("`--no_readme` is a no-op for Python scripts, which are standalone");
}
if author_from.is_some() {
warn_user_once!("`--author-from` is a no-op for Python scripts, which are standalone");
}
if package {
warn_user_once!("`--package` is a no-op for Python scripts, which are standalone");
}
Expand Down Expand Up @@ -237,6 +246,7 @@ async fn init_project(
project_kind: InitProjectKind,
vcs: Option<VersionControlSystem>,
no_readme: bool,
author_from: Option<AuthorFrom>,
no_pin_python: bool,
python: Option<String>,
no_workspace: bool,
Expand Down Expand Up @@ -475,6 +485,7 @@ async fn init_project(
&requires_python,
python_request.as_ref(),
vcs,
author_from,
no_readme,
package,
)
Expand Down Expand Up @@ -564,6 +575,7 @@ impl InitProjectKind {
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
author_from: Option<AuthorFrom>,
no_readme: bool,
package: bool,
) -> Result<()> {
Expand All @@ -575,6 +587,7 @@ impl InitProjectKind {
requires_python,
python_request,
vcs,
author_from,
no_readme,
package,
)
Expand All @@ -587,6 +600,7 @@ impl InitProjectKind {
requires_python,
python_request,
vcs,
author_from,
no_readme,
package,
)
Expand All @@ -603,11 +617,24 @@ impl InitProjectKind {
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
author_from: Option<AuthorFrom>,
no_readme: bool,
package: bool,
) -> Result<()> {
fs_err::create_dir_all(path)?;

// Do no fill in `authors` for non-packaged applications unless explicitly requested.
let author_from = author_from.unwrap_or_else(|| {
if package {
AuthorFrom::default()
} else {
AuthorFrom::None
}
});
let author = get_author_info(path, author_from);

// Create the `pyproject.toml`
let mut pyproject = pyproject_project(name, requires_python, no_readme);
let mut pyproject = pyproject_project(name, requires_python, author.as_ref(), no_readme);

// Include additional project configuration for packaged applications
if package {
Expand All @@ -620,8 +647,6 @@ impl InitProjectKind {
pyproject.push_str(pyproject_build_system());
}

fs_err::create_dir_all(path)?;

// Create the source structure.
if package {
// Create `src/{name}/__init__.py`, if it doesn't exist already.
Expand Down Expand Up @@ -684,21 +709,25 @@ impl InitProjectKind {
requires_python: &RequiresPython,
python_request: Option<&PythonRequest>,
vcs: Option<VersionControlSystem>,
author_from: Option<AuthorFrom>,
no_readme: bool,
package: bool,
) -> Result<()> {
if !package {
return Err(anyhow!("Library projects must be packaged"));
}

fs_err::create_dir_all(path)?;

let author = get_author_info(path, author_from.unwrap_or_default());

// Create the `pyproject.toml`
let mut pyproject = pyproject_project(name, requires_python, no_readme);
let mut pyproject = pyproject_project(name, requires_python, author.as_ref(), no_readme);

// Always include a build system if the project is packaged.
pyproject.push('\n');
pyproject.push_str(pyproject_build_system());

fs_err::create_dir_all(path)?;
fs_err::write(path.join("pyproject.toml"), pyproject)?;

// Create `src/{name}/__init__.py`, if it doesn't exist already.
Expand Down Expand Up @@ -742,21 +771,42 @@ impl InitProjectKind {
}
}

#[derive(Debug)]
enum Author {
Name(String),
Email(String),
NameEmail { name: String, email: String },
}

impl Author {
fn to_toml_string(&self) -> String {
match self {
Self::NameEmail { name, email } => {
format!("{{ name = \"{name}\", email = \"{email}\" }}")
}
Self::Name(name) => format!("{{ name = \"{name}\" }}"),
Self::Email(email) => format!("{{ email = \"{email}\" }}"),
}
}
}

/// Generate the `[project]` section of a `pyproject.toml`.
fn pyproject_project(
name: &PackageName,
requires_python: &RequiresPython,
author: Option<&Author>,
no_readme: bool,
) -> String {
indoc::formatdoc! {r#"
[project]
name = "{name}"
version = "0.1.0"
description = "Add your description here"{readme}
description = "Add your description here"{readme}{authors}
requires-python = "{requires_python}"
dependencies = []
"#,
readme = if no_readme { "" } else { "\nreadme = \"README.md\"" },
authors = author.map_or_else(String::new, |author| format!("\nauthors = [\n {} \n]", author.to_toml_string())),
requires_python = requires_python.specifiers(),
}
}
Expand Down Expand Up @@ -826,3 +876,63 @@ fn init_vcs(path: &Path, vcs: Option<VersionControlSystem>) -> Result<()> {

Ok(())
}

/// Try to get the author information.
///
/// Currently, this only tries to get the author information from git.
fn get_author_info(path: &Path, author_from: AuthorFrom) -> Option<Author> {
if matches!(author_from, AuthorFrom::None) {
return None;
}
if matches!(author_from, AuthorFrom::Auto | AuthorFrom::Git) {
match get_author_from_git(path) {
Ok(author) => return Some(author),
Err(err) => warn!("Failed to get author from git: {err}"),
}
}

None
}

/// Fetch the default author from git configuration.
fn get_author_from_git(path: &Path) -> Result<Author> {
let Ok(git) = which::which("git") else {
anyhow::bail!("`git` not found in PATH")
};

let mut name = None;
let mut email = None;

let output = Command::new(&git)
.arg("config")
.arg("get")
.arg("user.name")
.current_dir(path)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()?;
if output.status.success() {
name = Some(String::from_utf8_lossy(&output.stdout).trim().to_string());
}

let output = Command::new(&git)
.arg("config")
.arg("get")
.arg("user.email")
.current_dir(path)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()?;
if output.status.success() {
email = Some(String::from_utf8_lossy(&output.stdout).trim().to_string());
}

let author = match (name, email) {
(Some(name), Some(email)) => Author::NameEmail { name, email },
(Some(name), None) => Author::Name(name),
(None, Some(email)) => Author::Email(email),
(None, None) => anyhow::bail!("No author information found"),
};

Ok(author)
}
1 change: 1 addition & 0 deletions crates/uv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,7 @@ async fn run_project(
args.kind,
args.vcs,
args.no_readme,
args.author_from,
args.no_pin_python,
args.python,
args.no_workspace,
Expand Down
5 changes: 4 additions & 1 deletion crates/uv/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use url::Url;
use uv_cache::{CacheArgs, Refresh};
use uv_cli::{
options::{flag, resolver_installer_options, resolver_options},
BuildArgs, ExportArgs, PublishArgs, ToolUpgradeArgs,
AuthorFrom, BuildArgs, ExportArgs, PublishArgs, ToolUpgradeArgs,
};
use uv_cli::{
AddArgs, ColorChoice, ExternalCommand, GlobalArgs, InitArgs, ListFormat, LockArgs, Maybe,
Expand Down Expand Up @@ -164,6 +164,7 @@ pub(crate) struct InitSettings {
pub(crate) kind: InitKind,
pub(crate) vcs: Option<VersionControlSystem>,
pub(crate) no_readme: bool,
pub(crate) author_from: Option<AuthorFrom>,
pub(crate) no_pin_python: bool,
pub(crate) no_workspace: bool,
pub(crate) python: Option<String>,
Expand All @@ -184,6 +185,7 @@ impl InitSettings {
script,
vcs,
no_readme,
author_from,
no_pin_python,
no_workspace,
python,
Expand All @@ -206,6 +208,7 @@ impl InitSettings {
kind,
vcs,
no_readme,
author_from,
no_pin_python,
no_workspace,
python,
Expand Down
Loading
Loading