@@ -4,7 +4,7 @@ use std::{
4
4
env:: set_current_dir,
5
5
fs:: { self , create_dir} ,
6
6
io:: { self , Write } ,
7
- path:: Path ,
7
+ path:: { Path , PathBuf } ,
8
8
process:: { Command , Stdio } ,
9
9
} ;
10
10
@@ -22,14 +22,27 @@ pub fn init() -> Result<()> {
22
22
let mut stdout = io:: stdout ( ) . lock ( ) ;
23
23
let mut init_git = true ;
24
24
25
- if Path :: new ( "Cargo.toml" ) . exists ( ) {
25
+ let manifest_path = Command :: new ( "cargo" )
26
+ . args ( [ "locate-project" , "--message-format=plain" ] )
27
+ . output ( ) ?;
28
+ if manifest_path. status . success ( ) {
29
+ let manifest_path: PathBuf = String :: from_utf8_lossy ( & manifest_path. stdout ) . trim ( ) . into ( ) ;
30
+
26
31
if Path :: new ( "exercises" ) . exists ( ) && Path :: new ( "solutions" ) . exists ( ) {
27
32
bail ! ( IN_INITIALIZED_DIR_ERR ) ;
28
33
}
29
-
30
- stdout. write_all ( CARGO_TOML_EXISTS_PROMPT_MSG ) ?;
31
- press_enter_prompt ( & mut stdout) ?;
32
- init_git = false ;
34
+ if fs:: read_to_string ( manifest_path) ?. contains ( "[workspace]" ) {
35
+ // make sure "rustlings" is added to `workspace.members` by making
36
+ // cargo initialize a new project
37
+ let output = Command :: new ( "cargo" ) . args ( [ "new" , "rustlings" ] ) . output ( ) ?;
38
+ if !output. status . success ( ) {
39
+ bail ! ( "Failed to initilize new workspace member" ) ;
40
+ }
41
+ fs:: remove_dir_all ( "rustlings" ) ?;
42
+ init_git = false ;
43
+ } else {
44
+ bail ! ( IN_NON_WORKSPACE_CARGO_PROJECT_ERR ) ;
45
+ }
33
46
}
34
47
35
48
stdout. write_all ( b"This command will create the directory `rustlings/` which will contain the exercises.\n Press ENTER to continue " ) ?;
@@ -128,19 +141,9 @@ You probably already initialized Rustlings.
128
141
Run `cd rustlings`
129
142
Then run `rustlings` again" ;
130
143
131
- const CARGO_TOML_EXISTS_PROMPT_MSG : & [ u8 ] = br#"You are about to initialize Rustlings in a directory that already contains a `Cargo.toml` file!
132
-
133
- => It is recommended to abort with CTRL+C and initialize Rustlings in another directory <=
134
-
135
- If you know what you are doing and want to initialize Rustlings in a Cargo workspace,
136
- then you need to add its directory to `members` in the `workspace` section of the `Cargo.toml` file:
137
-
138
- ```toml
139
- [workspace]
140
- members = ["rustlings"]
141
- ```
142
-
143
- Press ENTER if you are sure that you want to continue after reading the warning above "# ;
144
+ const IN_NON_WORKSPACE_CARGO_PROJECT_ERR : & str = "\
145
+ The current directory is already part of a cargo project.
146
+ Please initialize rustlings in a different directory." ;
144
147
145
148
const POST_INIT_MSG : & str = "Run `cd rustlings` to go into the generated directory.
146
149
Then run `rustlings` to get started." ;
0 commit comments