willbe 0.35.0

Utility to publish multi-crate and multi-workspace environments and maintain their consistency.
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#[ allow( clippy ::std_instead_of_alloc, clippy ::std_instead_of_core ) ]
mod private
{

  use crate :: *;
  use collection_tools :: collection;

  use std ::fmt;
  use process_tools ::process;
  use
  {
  iter ::Itertools,
  error ::
  {
   // Result,
   untyped :: { format_err, Error },
 }
 };
  use error ::ErrWith;
  // Explicit import for Result and its variants for pattern matching
  use std ::result ::Result :: { Ok, Err };

  /// Represents instructions for publishing a package.
  #[ derive( Debug, Clone ) ]
  pub struct PackagePublishInstruction
  {
  /// The name of the package.
  pub package_name: package ::PackageName,
  /// Options for packing the package using Cargo.
  pub pack: cargo ::PackOptions,
  /// Options for bumping the package version.
  pub bump: version ::BumpOptions,
  /// Git options related to the package.
  pub git_options: entity ::git ::GitOptions,
  /// Options for publishing the package using Cargo.
  pub publish: cargo ::PublishOptions,
  /// Indicates whether the process should be dry-run (no actual publishing).
  pub dry: bool,
 }

  /// Finds all workspace members that depend on the specified crate.
  ///
  /// This function scans ALL workspace members (workspace-scoped) rather than just
  /// the dependency tree of a specific crate (tree-scoped). This is critical for
  /// ensuring that when a workspace dependency is bumped, every workspace member
  /// that depends on it gets its `Cargo.toml` updated.
  ///
  /// # Arguments
  /// * `workspace` - The workspace to scan
  /// * `crate_name` - Name of the crate to find dependents for
  ///
  /// # Returns
  /// Vector of `CrateDir` for each workspace member that depends on `crate_name`
  ///
  /// # Example
  /// If workspace has: `crate_a`, `crate_b`, `crate_c`
  /// And `crate_b` and `crate_c` both depend on `crate_a`
  /// Then `find_workspace_dependents( workspace, "crate_a" )` returns `[crate_b_dir, crate_c_dir]`
  fn find_workspace_dependents
  (
  workspace: &Workspace,
  crate_name: &str,
 ) -> Vec< CrateDir >
  {
  workspace
  .packages()
  .filter_map( | pkg |
  {
  // Check if this package depends on crate_name
  let has_dependency = pkg
  .dependencies()
  .any( | dep | dep.name() == crate_name );

  if has_dependency
  {
  pkg.crate_dir().ok()
 }
  else
  {
  None
 }
 })
  .collect()
 }

  /// Represents a planner for publishing a single package.
  #[ derive( Debug, former ::Former ) ]
  #[ perform( fn build() -> PackagePublishInstruction ) ]
  pub struct PublishSinglePackagePlanner< 'a >
  {
  workspace_dir: CrateDir,
  package: package ::Package< 'a >,
  channel: channel ::Channel,
  base_temp_dir: Option< path ::PathBuf >,
  #[ former( default = true ) ]
  dry: bool,
 }

  impl PublishSinglePackagePlanner< '_ > // fix clippy
  {
  fn build( self ) -> PackagePublishInstruction
  {
   let crate_dir = self.package.crate_dir();
   let workspace_root: AbsolutePath = self.workspace_dir.clone().absolute_path();
   let pack = cargo ::PackOptions
   {
  path: crate_dir.clone().absolute_path().inner(),
  channel: self.channel,
  allow_dirty: self.dry,
  checking_consistency: !self.dry,
  temp_path: self.base_temp_dir.clone(),
  dry: self.dry,
 };
   let old_version: Version = self.package.version().as_ref().unwrap().try_into().unwrap();
   let new_version = old_version.clone().bump();

   // Fix(issue-001): Find ALL workspace members depending on this crate for version updates
   // Root cause: Original code only updated workspace root, missing individual member manifests
   // Pitfall: Workspace dependency bumps affect ALL workspace members, not just publication tree

   // Get workspace to scan all members
   let workspace = Workspace ::try_from( self.workspace_dir.clone() ).unwrap();
   let package_name = self.package.name().unwrap();

   // Get all workspace members that depend on the package being published
   let mut dependencies = find_workspace_dependents( &workspace, package_name );

   // Also include workspace root if it has workspace-level dependencies
   let workspace_root_dir = CrateDir ::try_from( workspace_root.clone() ).unwrap();
   if !dependencies.contains( &workspace_root_dir )
   {
  dependencies.push( workspace_root_dir );
 }

   let bump = version ::BumpOptions
   {
  crate_dir: crate_dir.clone(),
  old_version: old_version.clone(),
  new_version: new_version.clone(),
  dependencies: dependencies.clone(),
  dry: self.dry,
 };
   let git_options = entity ::git ::GitOptions
   {
  git_root: workspace_root,
  items: dependencies.iter().chain( [ &crate_dir ] ).map( | d | d.clone().absolute_path().join( "Cargo.toml" ).expect( "Failed to join Cargo.toml path" ) ).collect(),
  message: format!( "{}-v{}", self.package.name().unwrap(), new_version ),
  dry: self.dry,
 };
   let publish = cargo ::PublishOptions
   {
  path: crate_dir.clone().absolute_path().inner(),
  temp_path: self.base_temp_dir.clone(),
  retry_count: 2,
  dry: self.dry,
 };

   PackagePublishInstruction
   {
  package_name: self.package.name().unwrap().to_string().into(),
  pack,
  bump,
  git_options,
  publish,
  dry: self.dry,
 }
 }
 }

  /// `PublishPlan` manages the overall publication process for multiple packages.
  /// It organizes the necessary details required for publishing each individual package.
  /// This includes the workspace root directory, any temporary directories used during the process,
  /// and the set of specific instructions for publishing each package.
  #[ derive( Debug, former ::Former, Clone ) ]
  pub struct PublishPlan
  {
  /// `workspace_dir` - This is the root directory of your workspace, containing all the Rust crates
  /// that make up your package. It is used to locate the packages within your workspace that are meant
  /// to be published. The value here is represented by `CrateDir` which indicates the directory of the crate.
  pub workspace_dir: CrateDir,

  /// `base_temp_dir` - This is used for any temporary operations during the publication process, like
  /// building the package or any other processes that might require the storage of transient data. It's
  /// optional as not all operations will require temporary storage. The type used is `PathBuf` which allows
  /// manipulation of the filesystem paths.
  pub base_temp_dir: Option< path ::PathBuf >,

  /// Release channels for rust.
  pub channel: channel ::Channel,

  /// `dry` - A boolean value indicating whether to do a dry run. If set to `true`, the application performs
  /// a simulated run without making any actual changes. If set to `false`, the operations are actually executed.
  /// This property is optional and defaults to `true`.
  #[ former( default = true ) ]
  pub dry: bool,

  /// Required for tree view only
  pub roots: Vec< CrateDir >,

  /// `plans` - This is a vector containing the instructions for publishing each package. Each item
  /// in the `plans` vector indicates a `PackagePublishInstruction` set for a single package. It outlines
  /// how to build and where to publish the package amongst other instructions. The `#[ setter( false ) ]`
  /// attribute indicates that there is no setter method for the `plans` variable and it can only be modified
  /// within the struct.
  #[ scalar( setter = false ) ]
  pub plans: Vec< PackagePublishInstruction >,
 }

  impl PublishPlan
  {
  /// Displays a tree-like structure of crates and their dependencies.
  ///
  /// # Arguments
  ///
  /// * `f` - A mutable reference to a `Formatter` used for writing the output.
  ///
  /// # Errors
  ///
  /// Returns a `std ::fmt ::Error` if there is an error writing to the formatter.
  pub fn write_as_tree< W >( &self, f: &mut W ) -> fmt ::Result
  where
   W: fmt ::Write
  {
   let name_bump_report: collection ::HashMap< _, _ > = self
   .plans
   .iter()
   .map( | x | ( x.package_name.as_ref(), ( x.bump.old_version.to_string(), x.bump.new_version.to_string() ) ) )
   .collect();
   for wanted in &self.roots
   {
  let list = action ::list_all
  (
   action ::list ::ListOptions ::former()
   .path_to_manifest( wanted.clone() )
   .format( action ::list ::ListFormat ::Tree )
   .dependency_sources( [ action ::list ::DependencySource ::Local ] )
   .dependency_categories( [ action ::list ::DependencyCategory ::Primary ] )
   .form()
 )
  .map_err( | ( _, _e ) | fmt ::Error )?;
  let action ::list ::ListReport ::Tree( list ) = list else { unreachable!() };

  #[ allow( clippy ::items_after_statements ) ]
  fn callback( name_bump_report: &collection ::HashMap< &String, ( String, String ) >, mut r: tool ::ListNodeReport ) -> tool ::ListNodeReport
  {
   if let Some( ( old, new ) ) = name_bump_report.get( &r.name )
   {
  r.version = Some( format!( "({old} -> {new})" ) );
 }
   r.normal_dependencies = r.normal_dependencies.into_iter().map( | r | callback( name_bump_report, r ) ).collect();
   r.dev_dependencies = r.dev_dependencies.into_iter().map( | r | callback( name_bump_report, r ) ).collect();
   r.build_dependencies = r.build_dependencies.into_iter().map( | r | callback( name_bump_report, r ) ).collect();

   r
 }
  let printer = list;
  let rep: Vec< tool ::ListNodeReport > = printer.iter().map( | printer | printer.info.clone() ).collect();
  let list: Vec< tool ::ListNodeReport > = rep.into_iter().map( | r | callback( &name_bump_report, r ) ).collect();
  let printer: Vec< tool ::TreePrinter > = list.iter().map( tool ::TreePrinter ::new ).collect();

  let list = action ::list ::ListReport ::Tree( printer );
  writeln!( f, "{list}" )?;
 }

   Ok( () )
 }

  /// Format and display the list of packages and their version bumps in a formatted way.
  ///
  /// # Arguments
  ///
  /// - `f` : A mutable reference to a `Formatter` where the output will be written to.
  ///
  /// # Errors
  ///
  /// Returns a `std ::fmt ::Error` if there is an error writing to the formatter.
  pub fn write_as_list< W >( &self, f: &mut W ) -> fmt ::Result
  where
   W: fmt ::Write
  {
   for ( idx, package ) in self.plans.iter().enumerate()
   {
  let bump = &package.bump;
  writeln!( f, "[{idx}] {} ({} -> {})", package.package_name, bump.old_version, bump.new_version )?;
 }

   Ok( () )
 }
 }

  impl< 'a > PublishPlanFormer
  {
  pub fn option_base_temp_dir( mut self, path: Option< path ::PathBuf > ) -> Self
  {
   self.storage.base_temp_dir = path;
   self
 }

  pub fn package< IntoPackage >( mut self, package: IntoPackage ) -> Self
  where
   IntoPackage: Into< package ::Package< 'a > >,
  {
   let channel = self.storage.channel.unwrap_or_default();
   let mut plan = PublishSinglePackagePlanner ::former();
   if let Some( workspace ) = &self.storage.workspace_dir
   {
  plan = plan.workspace_dir( workspace.clone() );
 }
   if let Some( base_temp_dir ) = &self.storage.base_temp_dir
   {
  plan = plan.base_temp_dir( base_temp_dir.clone() );
 }
   if let Some( dry ) = self.storage.dry
   {
  plan = plan.dry( dry );
 }
   let plan = plan
   .channel( channel )
   .package( package )
   .perform();
   let mut plans = self.storage.plans.unwrap_or_default();
   plans.push( plan );

   self.storage.plans = Some( plans );

   self
 }

  pub fn packages< IntoPackageIter, IntoPackage >( mut self, packages: IntoPackageIter ) -> Self
  where
   IntoPackageIter: IntoIterator< Item = IntoPackage >,
   IntoPackage: Into< package ::Package< 'a > >,
  {
   for package in packages
   {
  self = self.package( package );
 }

   self
 }

 }

  /// Holds information about the publishing process.
  #[ derive( Debug, Default, Clone ) ]
  pub struct PublishReport
  {
  /// Retrieves information about the package.
  pub get_info: Option< process ::Report >,
  /// Bumps the version of the package.
  pub bump: Option< version ::ExtendedBumpReport >,
  /// Report of adding changes to the Git repository.
  pub add: Option< process ::Report >,
  /// Report of committing changes to the Git repository.
  pub commit: Option< process ::Report >,
  /// Report of pushing changes to the Git repository.
  pub push: Option< process ::Report >,
  /// Report of publishes the package using the `cargo publish` command.
  pub publish: Option< process ::Report >,
 }

  impl fmt ::Display for PublishReport
  {
  fn fmt( &self, f: &mut fmt ::Formatter< '_ > ) -> fmt ::Result
  {
   let PublishReport
   {
  get_info,
  bump,
  add,
  commit,
  push,
  publish,
 } = self;

   if get_info.is_none()
   {
  f.write_str( "Empty report" )?;
  return Ok( () )
 }
   let info = get_info.as_ref().unwrap();
   write!( f, "{info}" )?;

   if let Some( bump ) = bump
   {
  writeln!( f, "{bump}" )?;
 }
   if let Some( add ) = add
   {
  write!( f, "{add}" )?;
 }
   if let Some( commit ) = commit
   {
  write!( f, "{commit}" )?;
 }
   if let Some( push ) = push
   {
  write!( f, "{push}" )?;
 }
   if let Some( publish ) = publish
   {
  write!( f, "{publish}" )?;
 }

   Ok( () )
 }
 }

  /// Performs package publishing based on the given arguments.
  ///
  /// # Arguments
  ///
  /// * `args` - The package publishing instructions.
  ///
  /// # Returns
  ///
  /// * `Result< PublishReport >` - The result of the publishing operation, including information about the publish, version bump, and git operations.
  ///
  /// # Errors
  /// qqq: doc
  #[ allow( clippy ::option_map_unit_fn, clippy ::result_large_err ) ]
  pub fn perform_package_publish( instruction: PackagePublishInstruction ) -> ResultWithReport< PublishReport, Error >
  {
  let mut report = PublishReport ::default();
  let PackagePublishInstruction
  {
   package_name: _,
   mut pack,
   mut bump,
   mut git_options,
   mut publish,
   dry,
 } = instruction;
  pack.dry = dry;
  bump.dry = dry;
  git_options.dry = dry;
  publish.dry = dry;

  report.get_info = Some( cargo ::pack( pack ).err_with_report( &report )? );
  // aaa: redundant field? // aaa: removed
  let bump_report = version ::bump( bump ).err_with_report( &report )?;
  report.bump = Some( bump_report.clone() );

  let git_root = git_options.git_root.clone();
  let git = match entity ::git ::perform_git_commit( git_options )
  {
   Ok( git ) => git,
   Err( e ) =>
   {
  version ::revert( &bump_report )
  .map_err( | le | format_err!( "Base error: \n{}\nRevert error: \n{}", e.to_string().replace( '\n', "\n\t" ), le.to_string().replace( '\n', "\n\t" ) ) )
  .err_with_report( &report )?;
  return Err( ( report, e ) );
 }
 };
  report.add = git.add;
  report.commit = git.commit;
  report.publish = match cargo ::publish( &publish )
  {
   Ok( publish ) => Some( publish ),
   Err( e ) =>
   {
  tool ::git ::reset( git_root.as_ref(), true, 1, false )
  .map_err
  (
   | le |
   format_err!( "Base error: \n{}\nRevert error: \n{}", e.to_string().replace( '\n', "\n\t" ), le.to_string().replace( '\n', "\n\t" ) )
 )
  .err_with_report( &report )?;
  return Err( ( report, e ) );
 }
 };

  let res = tool ::git ::push( &git_root, dry ).err_with_report( &report )?;
  report.push = Some( res );

  Ok( report )
 }

  /// Perform publishing of multiple packages based on the provided publish plan.
  ///
  /// # Arguments
  ///
  /// * `plan` - The publish plan with details of packages to be published.
  ///
  /// # Returns
  ///
  /// Returns a `Result` containing a vector of `PublishReport` if successful, else an error.
  ///
  /// # Errors
  /// qqq: doc
  pub fn perform_packages_publish( plan: PublishPlan ) -> error ::untyped ::Result< Vec< PublishReport > >
  // qqq: use typed error
  {
  let mut report = vec![];
  for package in plan.plans
  {
   let res = perform_package_publish( package ).map_err
   (
  | ( current_rep, e ) |
  format_err!( "{}\n{current_rep}\n{e}", report.iter().map( | r | format!( "{r}" ) ).join( "\n" ) )
 )?;
   report.push( res );
 }

  Ok( report )
 }

}

//

crate ::mod_interface!
{
  own use PublishPlan;
  own use PackagePublishInstruction;
  own use PublishSinglePackagePlanner;
  own use PublishReport;
  own use perform_package_publish;
  own use perform_packages_publish;
}