1
- use std:: iter:: FromIterator ;
1
+ use std:: { iter:: FromIterator , mem :: take } ;
2
2
3
3
use include_dir:: Dir ;
4
4
@@ -7,7 +7,7 @@ use crate::{loader::from_directory, MigrationHook, Result, M};
7
7
/// Allows to build a `Vec<M<'u>>` with additional edits.
8
8
#[ derive( Default , Debug ) ]
9
9
pub struct MigrationsBuilder < ' u > {
10
- migrations : Vec < M < ' u > > ,
10
+ migrations : Vec < Option < M < ' u > > > ,
11
11
}
12
12
13
13
impl < ' u > MigrationsBuilder < ' u > {
@@ -42,28 +42,25 @@ impl<'u> MigrationsBuilder<'u> {
42
42
///
43
43
/// Panics if no migration with the `id` provided exists.
44
44
#[ must_use]
45
- pub fn edit ( mut self , id : usize , f : impl Fn ( & mut M ) ) -> Self {
45
+ pub fn edit ( mut self , id : usize , f : impl Fn ( M ) -> M ) -> Self {
46
46
if id < 1 {
47
47
panic ! ( "id cannot be equal to 0" ) ;
48
48
}
49
- f ( self
50
- . migrations
51
- . get_mut ( id - 1 )
52
- . expect ( "No migration with the given index" ) ) ;
49
+ self . migrations [ id - 1 ] = take ( & mut self . migrations [ id - 1 ] ) . map ( f) ;
53
50
self
54
51
}
55
52
56
53
/// Finalizes the builder and creates either a [`crate::Migrations`] or a
57
54
/// [`crate::AsyncMigrations`] instance.
58
- pub fn finalize < T : FromIterator < M < ' u > > > ( self ) -> T {
59
- T :: from_iter ( self . migrations )
55
+ pub fn finalize < T : FromIterator < M < ' u > > > ( mut self ) -> T {
56
+ T :: from_iter ( self . migrations . drain ( .. ) . flatten ( ) )
60
57
}
61
58
}
62
59
63
60
impl < ' u > FromIterator < M < ' u > > for MigrationsBuilder < ' u > {
64
61
fn from_iter < T : IntoIterator < Item = M < ' u > > > ( iter : T ) -> Self {
65
62
Self {
66
- migrations : Vec :: from_iter ( iter) ,
63
+ migrations : Vec :: from_iter ( iter. into_iter ( ) . map ( Some ) ) ,
67
64
}
68
65
}
69
66
}
@@ -76,8 +73,9 @@ impl<'u> M<'u> {
76
73
/// Use [`M::up_with_hook`] instead if you're creating a new migration.
77
74
/// This method is meant for editing existing transactions
78
75
/// when using the [`MigrationsBuilder`].
79
- pub fn set_up_hook ( & mut self , hook : impl MigrationHook + ' static ) {
76
+ pub fn set_up_hook ( mut self , hook : impl MigrationHook + ' static ) -> Self {
80
77
self . up_hook = Some ( hook. clone_box ( ) ) ;
78
+ self
81
79
}
82
80
83
81
/// Replace the `down_hook` in the given migration with the provided one.
@@ -87,7 +85,8 @@ impl<'u> M<'u> {
87
85
/// Use [`M::down_with_hook`] instead if you're creating a new migration.
88
86
/// This method is meant for editing existing transactions
89
87
/// when using the [`MigrationsBuilder`].
90
- pub fn set_down_hook ( & mut self , hook : impl MigrationHook + ' static ) {
88
+ pub fn set_down_hook ( mut self , hook : impl MigrationHook + ' static ) -> Self {
91
89
self . down_hook = Some ( hook. clone_box ( ) ) ;
90
+ self
92
91
}
93
92
}
0 commit comments