1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
|
//! Example for how to use `VisitMut` to iterate over a table.
use std::collections::BTreeSet;
use toml_edit::visit::{visit_table_like_kv, Visit};
use toml_edit::visit_mut::{visit_table_like_kv_mut, visit_table_mut, VisitMut};
use toml_edit::{Array, DocumentMut, InlineTable, Item, KeyMut, Table, Value};
/// This models the visit state for dependency keys in a `Cargo.toml`.
///
/// Dependencies can be specified as:
///
/// ```toml
/// [dependencies]
/// dep1 = "0.2"
///
/// [build-dependencies]
/// dep2 = "0.3"
///
/// [dev-dependencies]
/// dep3 = "0.4"
///
/// [target.'cfg(windows)'.dependencies]
/// dep4 = "0.5"
///
/// # and target build- and dev-dependencies
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum VisitState {
/// Represents the root of the table.
Root,
/// Represents "dependencies", "build-dependencies" or "dev-dependencies", or the target
/// forms of these.
Dependencies,
/// A table within dependencies.
SubDependencies,
/// Represents "target".
Target,
/// "target.[TARGET]".
TargetWithSpec,
/// Represents some other state.
Other,
}
impl VisitState {
/// Figures out the next visit state, given the current state and the given key.
fn descend(self, key: &str) -> Self {
match (self, key) {
(
VisitState::Root | VisitState::TargetWithSpec,
"dependencies" | "build-dependencies" | "dev-dependencies",
) => VisitState::Dependencies,
(VisitState::Root, "target") => VisitState::Target,
(VisitState::Root | VisitState::TargetWithSpec, _) => VisitState::Other,
(VisitState::Target, _) => VisitState::TargetWithSpec,
(VisitState::Dependencies, _) => VisitState::SubDependencies,
(VisitState::SubDependencies, _) => VisitState::SubDependencies,
(VisitState::Other, _) => VisitState::Other,
}
}
}
/// Collect the names of every dependency key.
#[derive(Debug)]
struct DependencyNameVisitor<'doc> {
state: VisitState,
names: BTreeSet<&'doc str>,
}
impl<'doc> Visit<'doc> for DependencyNameVisitor<'doc> {
fn visit_table_like_kv(&mut self, key: &'doc str, node: &'doc Item) {
if self.state == VisitState::Dependencies {
self.names.insert(key);
} else {
// Since we're only interested in collecting the top-level keys right under
// [dependencies], don't recurse unconditionally.
let old_state = self.state;
// Figure out the next state given the key.
self.state = self.state.descend(key);
// Recurse further into the document tree.
visit_table_like_kv(self, key, node);
// Restore the old state after it's done.
self.state = old_state;
}
}
}
/// Normalize all dependency tables into the format:
///
/// ```toml
/// [dependencies]
/// dep = { version = "1.0", features = ["foo", "bar"], ... }
/// ```
///
/// leaving other tables untouched.
#[derive(Debug)]
struct NormalizeDependencyTablesVisitor {
state: VisitState,
}
impl VisitMut for NormalizeDependencyTablesVisitor {
fn visit_table_mut(&mut self, node: &mut Table) {
visit_table_mut(self, node);
// The conversion from regular tables into inline ones might leave some explicit parent
// tables hanging, so convert them to implicit.
if matches!(self.state, VisitState::Target | VisitState::TargetWithSpec) {
node.set_implicit(true);
}
}
fn visit_table_like_kv_mut(&mut self, mut key: KeyMut<'_>, node: &mut Item) {
let old_state = self.state;
// Figure out the next state given the key.
self.state = self.state.descend(key.get());
match self.state {
VisitState::Target | VisitState::TargetWithSpec | VisitState::Dependencies => {
// Top-level dependency row, or above: turn inline tables into regular ones.
if let Item::Value(Value::InlineTable(inline_table)) = node {
let inline_table = std::mem::replace(inline_table, InlineTable::new());
let table = inline_table.into_table();
key.fmt();
*node = Item::Table(table);
}
}
VisitState::SubDependencies => {
// Individual dependency: turn regular tables into inline ones.
if let Item::Table(table) = node {
// Turn the table into an inline table.
let table = std::mem::replace(table, Table::new());
let inline_table = table.into_inline_table();
key.fmt();
*node = Item::Value(Value::InlineTable(inline_table));
}
}
_ => {}
}
// Recurse further into the document tree.
visit_table_like_kv_mut(self, key, node);
// Restore the old state after it's done.
self.state = old_state;
}
fn visit_array_mut(&mut self, node: &mut Array) {
// Format any arrays within dependencies to be on the same line.
if matches!(
self.state,
VisitState::Dependencies | VisitState::SubDependencies
) {
node.fmt();
}
}
}
/// This is the input provided to `visit_mut_example`.
static INPUT: &str = r#"
[package]
name = "my-package"
[package.metadata.foo]
bar = 42
[dependencies]
atty = "0.2"
cargo-platform = { path = "crates/cargo-platform", version = "0.1.2" }
[dependencies.pretty_env_logger]
version = "0.4"
optional = true
[target.'cfg(windows)'.dependencies]
fwdansi = "1.1.0"
[target.'cfg(windows)'.dependencies.winapi]
version = "0.3"
features = [
"handleapi",
"jobapi",
]
[target.'cfg(unix)']
dev-dependencies = { miniz_oxide = "0.5" }
[dev-dependencies.cargo-test-macro]
path = "crates/cargo-test-macro"
[build-dependencies.flate2]
version = "0.4"
"#;
/// This is the output produced by `visit_mut_example`.
#[cfg(test)]
static VISIT_MUT_OUTPUT: &str = r#"
[package]
name = "my-package"
[package.metadata.foo]
bar = 42
[dependencies]
atty = "0.2"
cargo-platform = { path = "crates/cargo-platform", version = "0.1.2" }
pretty_env_logger = { version = "0.4", optional = true }
[target.'cfg(windows)'.dependencies]
fwdansi = "1.1.0"
winapi = { version = "0.3", features = ["handleapi", "jobapi"] }
[target.'cfg(unix)'.dev-dependencies]
miniz_oxide = "0.5"
[dev-dependencies]
cargo-test-macro = { path = "crates/cargo-test-macro" }
[build-dependencies]
flate2 = { version = "0.4" }
"#;
fn visit_example(document: &DocumentMut) -> BTreeSet<&str> {
let mut visitor = DependencyNameVisitor {
state: VisitState::Root,
names: BTreeSet::new(),
};
visitor.visit_document(document);
visitor.names
}
fn visit_mut_example(document: &mut DocumentMut) {
let mut visitor = NormalizeDependencyTablesVisitor {
state: VisitState::Root,
};
visitor.visit_document_mut(document);
}
fn main() {
let mut document: DocumentMut = INPUT.parse().expect("input is valid TOML");
println!("** visit example");
println!("{:?}", visit_example(&document));
println!("** visit_mut example");
visit_mut_example(&mut document);
println!("{document}");
}
#[cfg(test)]
#[test]
fn visit_correct() {
let document: DocumentMut = INPUT.parse().expect("input is valid TOML");
let names = visit_example(&document);
let expected = vec![
"atty",
"cargo-platform",
"pretty_env_logger",
"fwdansi",
"winapi",
"miniz_oxide",
"cargo-test-macro",
"flate2",
]
.into_iter()
.collect();
assert_eq!(names, expected);
}
#[cfg(test)]
#[test]
fn visit_mut_correct() {
let mut document: DocumentMut = INPUT.parse().expect("input is valid TOML");
visit_mut_example(&mut document);
assert_eq!(format!("{document}"), VISIT_MUT_OUTPUT);
}
|