rustilities 3.0.1

This crate offers a few utils for Rust development
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// SPDX-License-Identifier: GPL-3.0

#[cfg(test)]
mod tests;
mod types;

use crate::Error;
use cargo_toml::Manifest;
use std::path::{Path, PathBuf};
use toml_edit::{Array, DocumentMut, InlineTable, Item, Table, Value};
pub use types::{ManifestDependencyConfig, ManifestDependencyOrigin};

/// Given a path, this function finds the manifest corresponding to the innermost crate/workspace
/// containing that path if there's any.
///
/// # Examples
/// ```
/// use std::fs::File;
///
/// let tempdir = tempfile::tempdir().unwrap();
///
/// let crate_path = tempdir.path().join("crate");
/// let manifest_path = crate_path.join("Cargo.toml");
/// let src_path = crate_path.join("src");
/// let main_path = src_path.join("main.rs");
/// let lib_path = src_path.join("lib.rs");
/// std::fs::create_dir_all(&src_path).unwrap();
/// File::create(&manifest_path).unwrap();
/// File::create(&main_path).unwrap();
/// File::create(&lib_path).unwrap();
/// std::fs::write(
///     &manifest_path,
///     r#"
/// [package]
/// name = "test"
/// version = "0.1.0"
/// edition = "2021"
///
/// [dependencies]
///      "#,
///  ).unwrap();
///
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&main_path), Some(manifest_path.clone()));
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&lib_path), Some(manifest_path.clone()));
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&src_path), Some(manifest_path.clone()));
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&manifest_path), Some(manifest_path.clone()));
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&crate_path), Some(manifest_path.clone()));
///
/// let non_crate_path = tempdir.path().join("somewhere");
/// let non_crate_inner_path = non_crate_path.join("somewhere_deeper");
/// std::fs::create_dir_all(&non_crate_inner_path).unwrap();
///
/// assert_eq!(rustilities::manifest::find_innermost_manifest(&non_crate_inner_path), None);
/// ```
pub fn find_innermost_manifest<P: AsRef<Path>>(path: P) -> Option<PathBuf> {
	fn do_find_innermost_manifest(path: &Path) -> Option<PathBuf> {
		let mut path = path;
		// If the target itself contains a manifest, return it
		let cargo_toml_path = path.join("Cargo.toml");
		match Manifest::from_path(&cargo_toml_path) {
			Ok(manifest) if manifest.package.is_some() || manifest.workspace.is_some() =>
				return Some(cargo_toml_path),
			_ => (),
		}

		// Otherwise, search in the parent dirs
		while let Some(parent) = path.parent() {
			let cargo_toml_path = parent.join("Cargo.toml");
			match Manifest::from_path(&cargo_toml_path) {
				Ok(manifest) if manifest.package.is_some() || manifest.workspace.is_some() =>
					return Some(cargo_toml_path),
				_ => path = parent,
			}
		}
		None
	}
	do_find_innermost_manifest(&crate::paths::prefix_with_current_dir(path))
}

/// Given a path, this function finds the manifest corresponding to the workspace
/// containing that path if there's any.
///
/// # Examples
/// ```
/// use std::fs::File;
///
/// let tempdir = tempfile::tempdir().unwrap();
///
/// let workspace_manifest_path = tempdir.path().join("Cargo.toml");
/// let crate_path = tempdir.path().join("crate");
/// let manifest_path = crate_path.join("Cargo.toml");
/// let src_path = crate_path.join("src");
/// let main_path = src_path.join("main.rs");
/// let lib_path = src_path.join("lib.rs");
/// std::fs::create_dir_all(&src_path).unwrap();
/// File::create(&workspace_manifest_path).unwrap();
/// File::create(&manifest_path).unwrap();
/// File::create(&main_path).unwrap();
/// File::create(&lib_path).unwrap();
/// std::fs::write(
///     &manifest_path,
///     r#"
/// [package]
/// name = "test"
/// version = "0.1.0"
/// edition = "2021"
///
/// [dependencies]
///      "#,
///  ).unwrap();
///
/// std::fs::write(
///        &workspace_manifest_path,
///        r#"
/// [workspace]
/// resolver = "2"
/// members = ["crate"]
///
/// [dependencies]
///         "#,
///  ).unwrap();
///
/// assert_eq!(
///     rustilities::manifest::find_workspace_manifest(&main_path),
///     Some(workspace_manifest_path)
/// );
/// ```
pub fn find_workspace_manifest<P: AsRef<Path>>(path: P) -> Option<PathBuf> {
	fn do_find_workspace_manifest(path: &Path) -> Option<PathBuf> {
		let mut path = path;
		// If the target itself contains a manifest, return it
		let cargo_toml_path = path.join("Cargo.toml");
		match Manifest::from_path(&cargo_toml_path) {
			Ok(manifest) if manifest.workspace.is_some() => return Some(cargo_toml_path),
			_ => (),
		}

		// Otherwise, search in the parent dirs
		while let Some(parent) = path.parent() {
			let cargo_toml_path = parent.join("Cargo.toml");
			match Manifest::from_path(&cargo_toml_path) {
				Ok(manifest) if manifest.workspace.is_some() => return Some(cargo_toml_path),
				_ => path = parent,
			}
		}
		None
	}
	do_find_workspace_manifest(&crate::paths::prefix_with_current_dir(path))
}

/// Given a path, this function tries to determine if it points to a crate's manifest and if that's
/// the case, returns the crate's name.
///
/// # Examples
/// ```
/// use std::fs::File;
///
/// let tempdir = tempfile::tempdir().unwrap();
///
/// let crate_path = tempdir.path().join("crate");
/// let manifest_path = crate_path.join("Cargo.toml");
/// std::fs::create_dir_all(&crate_path).unwrap();
/// File::create(&manifest_path).unwrap();
/// std::fs::write(
///     &manifest_path,
///     r#"
/// [package]
/// name = "test"
/// version = "0.1.0"
/// edition = "2021"
///
/// [dependencies]
///      "#,
///  ).unwrap();
///
/// assert_eq!(rustilities::manifest::find_crate_name(manifest_path).unwrap(), "test");
/// assert!(rustilities::manifest::find_crate_name(crate_path).is_none());
/// ```
pub fn find_crate_name<P: AsRef<Path>>(manifest_path: P) -> Option<String> {
	Manifest::from_path(manifest_path.as_ref())
		.ok()?
		.package
		.map(|package| package.name)
}

/// Given a manifest file path, this function adds a dependency to the dependencies section of the
/// manifest based on the provided config.
///
/// If the path refers to a crate manifest, the dependency will be added to the `dependencies`
/// section, while if the path refers to a workspace manifest the dependency will be added to
/// `workspace.dependencies`. If none of these sections exist, the needed section will be added
/// with the new dependency, taking into account if the manifest is a crate manifest or a workspace
/// manifest (an empty manifest is considered a crate manifest).
///
///
/// # Errors
///
/// - If the path cannot be read.
/// - If the path doesn't correspond to a valid Rust manifes (empty files are valid).
/// - If the path cannot overwritten.
///
/// # Examples
///
/// ```
/// use std::{fs::File, io::ErrorKind};
/// use rustilities::{Error, manifest::{ManifestDependencyOrigin, ManifestDependencyConfig}};
///
/// let tempdir = tempfile::tempdir().unwrap();
/// let manifest_path = tempdir.path().join("Cargo.toml");
/// std::fs::write(
///     &manifest_path,
///     r#"
/// [package]
/// name = "test"
/// version = "0.1.0"
/// edition = "2021"
///
/// [dependencies]
/// "#,
/// ).unwrap();
///
/// // Add some dependencies
/// assert!(rustilities::manifest::add_crate_to_dependencies(
///     &manifest_path,
///     "syn",
///     ManifestDependencyConfig::new(
///         ManifestDependencyOrigin::workspace(),
///         false, // default_features = false
///         vec![], // features
///         false // optional = false
///     )
/// )
/// .is_ok());
///
/// assert!(rustilities::manifest::add_crate_to_dependencies(
///     &manifest_path,
///     "serde",
///     ManifestDependencyConfig::new(
///         ManifestDependencyOrigin::crates_io("1.0.0"),
///         true, // default_features = true
///         vec!["derive"], // features
///         false // optional = false
///     )
/// )
/// .is_ok());
///
/// // Check that the dependencies was added to the manifest
/// assert_eq!(
///     std::fs::read_to_string(&manifest_path).unwrap(),
///     r#"
/// [package]
/// name = "test"
/// version = "0.1.0"
/// edition = "2021"
///
/// [dependencies]
/// syn = { workspace = true, default-features = false }
/// serde = { version = "1.0.0", features = ["derive"] }
/// "#,
/// );
///
/// // Fails in unexisting file
/// assert!(matches!(
///     rustilities::manifest::add_crate_to_dependencies(
///         tempdir.path().join("file.txt"),
///         "syn",
///         ManifestDependencyConfig::new(
///             ManifestDependencyOrigin::workspace(),
///             false,
///             vec![],
///             false
///         )
///     ),
///     Err(Error::IO(err)) if err.kind() == ErrorKind::NotFound
/// ));
/// ```
pub fn add_crate_to_dependencies<P: AsRef<Path>>(
	manifest_path: P,
	dependency_name: &str,
	dependency_config: ManifestDependencyConfig,
) -> Result<(), Error> {
	let mut doc = std::fs::read_to_string(manifest_path.as_ref())?.parse::<DocumentMut>()?;
	if let Some(Item::Table(dependencies)) = doc.get_mut("dependencies") {
		add_dependency_to_dependencies_table(dependencies, dependency_name, dependency_config);
	} else if let Some(Item::Table(workspace)) = doc.get_mut("workspace") {
		if let Some(Item::Table(dependencies)) = workspace.get_mut("dependencies") {
			add_dependency_to_dependencies_table(dependencies, dependency_name, dependency_config);
		} else {
			let mut dependencies = Table::new();
			add_dependency_to_dependencies_table(
				&mut dependencies,
				dependency_name,
				dependency_config,
			);
			workspace.insert("dependencies", Item::Table(dependencies));
		}
	} else {
		let mut dependencies = Table::new();
		add_dependency_to_dependencies_table(&mut dependencies, dependency_name, dependency_config);
		doc.insert("dependencies", Item::Table(dependencies));
	}

	std::fs::write(manifest_path, doc.to_string())?;

	Ok(())
}

fn add_dependency_to_dependencies_table(
	dependencies: &mut Table,
	dependency_name: &str,
	dependency_config: ManifestDependencyConfig,
) {
	let mut dependency_declaration = InlineTable::new();
	match &dependency_config.origin {
		ManifestDependencyOrigin::Workspace => {
			dependency_declaration.insert(
				"workspace",
				toml_edit::value(true)
					.into_value()
					.expect("true is bool, so value(true) is Value::Boolean;qed;"),
			);
		},
		ManifestDependencyOrigin::Git { url, branch } => {
			dependency_declaration.insert(
				"git",
				toml_edit::value(url.to_owned())
					.into_value()
					.expect("url is String, so value(url) is Value::String; qed;"),
			);
			dependency_declaration.insert(
				"branch",
				toml_edit::value(branch.to_owned())
					.into_value()
					.expect("branch is String, so value(branch) is Value::String; qed;"),
			);
		},
		ManifestDependencyOrigin::CratesIO { version } => {
			dependency_declaration.insert(
				"version",
				toml_edit::value(version.to_owned())
					.into_value()
					.expect("version is String, so value(version) is Value::String; qed;"),
			);
		},
		ManifestDependencyOrigin::Local { relative_path } => {
			dependency_declaration.insert(
				"path",
				toml_edit::value(relative_path.to_string_lossy().into_owned())
					.into_value()
					.expect(
						"relative_path is String, so value(relative_path) is Value::String; qed;",
					),
			);
		},
	}

	if !dependency_config.default_features {
		dependency_declaration.insert(
			"default-features",
			toml_edit::value(false)
				.into_value()
				.expect("false is bool so value(false) is Value::Boolean; qed;"),
		);
	}

	if !dependency_config.features.is_empty() {
		let mut features = Array::new();
		dependency_config
			.features
			.iter()
			.for_each(|feature| features.push(feature.to_owned()));
		dependency_declaration.insert(
			"features",
			toml_edit::value(features)
				.into_value()
				.expect("features is Array, so value(features) is Value::Array; qed;"),
		);
	}

	if dependency_config.optional {
		dependency_declaration.insert(
			"optional",
			toml_edit::value(true)
				.into_value()
				.expect("true is bool so value(true) is Value::Boolean; qed;"),
		);
	}

	dependencies.insert(dependency_name, toml_edit::value(dependency_declaration));
}

/// Given a workspace manifest file path, and a path to a crate contained inside the workspace this
/// function adds the crate to the `members` section of the workspace.
///
/// # Errors
///
/// - If the workspace path cannot be read.
/// - If the workspace path doesn't correspond to a valid Rust manifest (empty files are valid).
/// - If the crate path isn't prefixed by the workspace path.
/// - If the `members` section isn't an array
/// - If the workspace path doesn't correspond to a workspace manifest.
/// - If the path cannot overwritten.
///
/// # Examples
///
/// ```
/// use std::{fs::File, io::ErrorKind};
/// use rustilities::{Error, manifest::{ManifestDependencyOrigin, ManifestDependencyConfig}};
///
/// let tempdir = tempfile::tempdir().unwrap();
/// let manifest_path = tempdir.path().join("Cargo.toml");
/// std::fs::write(
///     &manifest_path,
///     r#"
/// [workspace]
/// resolver = "2"
/// members = ["crate"]
///
/// [workspace.dependencies]
/// "#,
/// ).unwrap();
///
/// // Add some dependencies
/// assert!(rustilities::manifest::add_crate_to_workspace(
///     &manifest_path,
///     &tempdir.path().join("other_crate")    
/// )
/// .is_ok());
///
/// // Check that the dependencies was added to the manifest
/// assert_eq!(
///     std::fs::read_to_string(&manifest_path).unwrap(),
///     r#"
/// [workspace]
/// resolver = "2"
/// members = ["crate", "other_crate"]
///
/// [workspace.dependencies]
/// "#,
/// );
/// ```
pub fn add_crate_to_workspace<P: AsRef<Path>, Q: AsRef<Path>>(
	workspace_toml: P,
	crate_path: Q,
) -> Result<(), Error> {
	fn do_add_crate_to_workspace(workspace_toml: &Path, crate_path: &Path) -> Result<(), Error> {
		let mut doc = std::fs::read_to_string(workspace_toml)?.parse::<DocumentMut>()?;

		// Find the workspace dir
		let workspace_dir = workspace_toml.parent().expect("A file always lives inside a dir; qed");
		// Find the relative path to the crate from the workspace root
		let crate_relative_path = crate_path.strip_prefix(workspace_dir)?;

		if let Some(Item::Table(workspace_table)) = doc.get_mut("workspace") {
			if let Some(Item::Value(members_array)) = workspace_table.get_mut("members") {
				if let Value::Array(array) = members_array {
					let crate_relative_path =
						crate_relative_path.to_str().expect("target's always a valid string; qed");
					let already_in_array = array.iter().any(
						|member| matches!(member.as_str(), Some(s) if s == crate_relative_path),
					);
					if !already_in_array {
						array.push(crate_relative_path);
					}
				} else {
					return Err(Error::Descriptive(
						"The provided manifest path members field is corrupted".to_owned(),
					));
				}
			} else {
				let mut toml_array = Array::new();
				toml_array.push(
					crate_relative_path
						.to_str()
						.expect("Path::to_str() is always a valid string; qed"),
				);
				workspace_table["members"] = toml_edit::value(toml_array);
			}
		} else {
			return Err(Error::Descriptive(
				"The provided manifest path isn't a workspace manifest".to_owned(),
			));
		}

		std::fs::write(workspace_toml, doc.to_string())?;
		Ok(())
	}
	do_add_crate_to_workspace(workspace_toml.as_ref(), crate_path.as_ref())
}