fn add_to_root_toml()

in tools/hakari/src/cli_ops/workspace_ops.rs [156:214]


    fn add_to_root_toml(
        workspace_root: &Utf8Path,
        crate_path: &Utf8Path,
    ) -> Result<(), ApplyError> {
        let root_toml_path = workspace_root.join("Cargo.toml");

        let mut doc = read_toml(&root_toml_path)?;
        let members = Self::get_workspace_members_array(&root_toml_path, &mut doc)?;

        let add = |members: &mut Array, idx: usize| {
            // idx can be within the array (0..members.len()) or at the end (members.len() + 1).
            let existing = if idx < members.len() {
                members.get(idx).expect("valid idx")
            } else {
                members.get(members.len() - 1).expect("valid idx")
            };

            let write_path = with_forward_slashes(crate_path).into_string();
            let write_path = decorate(existing, write_path);
            members.insert_formatted(idx, write_path);
        };

        let mut written = false;
        for idx in 0..members.len() {
            let member = members.get(idx).expect("valid idx");
            match member.as_str() {
                Some(path) => {
                    let path = Utf8Path::new(path);
                    // Insert the crate path before the first element greater than it. If the list
                    // is kept in alphabetical order, this works out correctly.
                    match path.cmp(crate_path) {
                        Ordering::Greater => {
                            add(members, idx);
                            written = true;
                            break;
                        }
                        Ordering::Equal => {
                            // The crate path already exists -- skip it.
                            written = true;
                            break;
                        }
                        Ordering::Less => {}
                    }
                }
                None => {
                    return Err(ApplyError::misc(
                        "workspace.members contains non-strings",
                        root_toml_path,
                    ))
                }
            }
        }

        if !written {
            add(members, members.len());
        }

        write_document(&doc, &root_toml_path)
    }