diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index a65120507de..3ba55fc2ae7 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -970,33 +970,34 @@ fn update_manifest_with_new_member( // in the array already includes the new package's relative path. // - Add the relative path if the members don't match the new package's path. // - Create a new members array if there are no members element in the workspace yet. - if let Some(members) = workspace_document - .get_mut("workspace") - .and_then(|workspace| workspace.get_mut("members")) - .and_then(|members| members.as_array_mut()) - { - for member in members.iter() { - let pat = member - .as_str() - .with_context(|| format!("invalid non-string member `{}`", member))?; - let pattern = glob::Pattern::new(pat) - .with_context(|| format!("cannot build glob pattern from `{}`", pat))?; + if let Some(workspace) = workspace_document.get_mut("workspace") { + if let Some(members) = workspace + .get_mut("members") + .and_then(|members| members.as_array_mut()) + { + for member in members.iter() { + let pat = member + .as_str() + .with_context(|| format!("invalid non-string member `{}`", member))?; + let pattern = glob::Pattern::new(pat) + .with_context(|| format!("cannot build glob pattern from `{}`", pat))?; + + if pattern.matches(&display_path) { + return Ok(()); + } + } - if pattern.matches(&display_path) { - return Ok(()); + let was_sorted = is_sorted(members.iter().map(Value::as_str)); + members.push(display_path); + if was_sorted { + members.sort_by(|lhs, rhs| lhs.as_str().cmp(&rhs.as_str())); } - } + } else { + let mut array = Array::new(); + array.push(display_path); - let was_sorted = is_sorted(members.iter().map(Value::as_str)); - members.push(display_path); - if was_sorted { - members.sort_by(|lhs, rhs| lhs.as_str().cmp(&rhs.as_str())); + workspace["members"] = toml_edit::value(array); } - } else { - let mut array = Array::new(); - array.push(display_path); - - workspace_document["workspace"]["members"] = toml_edit::value(array); } write_atomic( diff --git a/tests/testsuite/cargo_new/add_members_to_non_workspace/out/Cargo.toml b/tests/testsuite/cargo_new/add_members_to_non_workspace/out/Cargo.toml index 74a8b782a38..878c6729147 100644 --- a/tests/testsuite/cargo_new/add_members_to_non_workspace/out/Cargo.toml +++ b/tests/testsuite/cargo_new/add_members_to_non_workspace/out/Cargo.toml @@ -1,4 +1,3 @@ -workspace = { members = ["bar"] } [package] name = "foo" version = "0.1.0"