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
// Copyright (c) The Move Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{bail, Result};
use clap::Parser;
use move_command_line_common::{env::MOVE_HOME, movey_constants::MOVEY_URL};
use std::{fs, fs::File, io, path::PathBuf};
use toml_edit::easy::{map::Map, Value};

pub const MOVEY_CREDENTIAL_PATH: &str = "/movey_credential.toml";

#[derive(Parser)]
#[clap(name = "movey-login")]
pub struct MoveyLogin;

impl MoveyLogin {
    pub fn execute(self) -> Result<()> {
        println!(
            "Please paste the API Token found on {}/settings/tokens below",
            MOVEY_URL
        );
        let mut line = String::new();
        loop {
            match io::stdin().read_line(&mut line) {
                Ok(_) => {
                    line = line.trim().to_string();
                    if !line.is_empty() {
                        break;
                    }
                    println!("Invalid API Token. Try again!");
                }
                Err(err) => {
                    bail!("Error reading file: {}", err);
                }
            }
        }
        Self::save_credential(line, MOVE_HOME.clone())?;
        println!("Token for Movey saved.");
        Ok(())
    }

    pub fn save_credential(token: String, move_home: String) -> Result<()> {
        fs::create_dir_all(&move_home)?;
        let credential_path = move_home + MOVEY_CREDENTIAL_PATH;
        let credential_file = PathBuf::from(&credential_path);
        if !credential_file.exists() {
            create_credential_file(&credential_path)?;
        }

        let old_contents: String;
        match fs::read_to_string(&credential_path) {
            Ok(contents) => {
                old_contents = contents;
            }
            Err(error) => bail!("Error reading input: {}", error),
        }
        let mut toml: Value = old_contents.parse().map_err(|e| {
            anyhow::Error::from(e).context(format!(
                "could not parse input at {} as TOML",
                &credential_path
            ))
        })?;

        // only update token key, keep the rest of the file intact
        if let Some(registry) = toml.as_table_mut().unwrap().get_mut("registry") {
            if let Some(toml_token) = registry.as_table_mut().unwrap().get_mut("token") {
                *toml_token = Value::String(token);
            } else {
                registry
                    .as_table_mut()
                    .unwrap()
                    .insert(String::from("token"), Value::String(token));
            }
        } else {
            let mut value = Map::new();
            value.insert(String::from("token"), Value::String(token));
            toml.as_table_mut()
                .unwrap()
                .insert(String::from("registry"), Value::Table(value));
        }

        let new_contents = toml.to_string();
        fs::write(credential_file, new_contents).expect("Unable to write file");
        Ok(())
    }
}

#[cfg(unix)]
fn create_credential_file(credential_path: &str) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let credential_file = File::create(&credential_path)?;

    let mut perms = credential_file.metadata()?.permissions();
    perms.set_mode(0o600);
    credential_file.set_permissions(perms)?;
    Ok(())
}

#[cfg(windows)]
#[allow(unused)]
fn create_credential_file(credential_path: &str) -> Result<()> {
    let windows_path = credential_path.replace("/", "\\");
    File::create(&windows_path)?;
    Ok(())
}

#[cfg(not(any(unix, windows)))]
#[allow(unused)]
fn create_credential_file(credential_path: &str) -> Result<()> {
    bail!("OS not supported")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    fn setup_move_home(test_path: &str) -> (String, String) {
        let cwd = env::current_dir().unwrap();
        let mut move_home: String = String::from(cwd.to_string_lossy());
        if !test_path.is_empty() {
            move_home.push_str(&test_path);
        } else {
            move_home.push_str("/test");
        }
        let credential_path = move_home.clone() + MOVEY_CREDENTIAL_PATH;
        (move_home, credential_path)
    }

    fn clean_up(move_home: &str) {
        let _ = fs::remove_dir_all(move_home);
    }

    #[test]
    fn save_credential_works_if_no_credential_file_exists() {
        let (move_home, credential_path) =
            setup_move_home("/save_credential_works_if_no_credential_file_exists");
        let _ = fs::remove_dir_all(&move_home);
        MoveyLogin::save_credential(String::from("test_token"), move_home.clone()).unwrap();

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(token.to_string().contains("test_token"));

        clean_up(&move_home);
    }

    #[test]
    fn save_credential_works_if_empty_credential_file_exists() {
        let (move_home, credential_path) =
            setup_move_home("/save_credential_works_if_empty_credential_file_exists");

        let _ = fs::remove_dir_all(&move_home);
        fs::create_dir_all(&move_home).unwrap();
        File::create(&credential_path).unwrap();

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        assert!(toml.as_table_mut().unwrap().get_mut("registry").is_none());

        MoveyLogin::save_credential(String::from("test_token"), move_home.clone()).unwrap();

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(token.to_string().contains("test_token"));

        clean_up(&move_home);
    }

    #[test]
    fn save_credential_works_if_token_field_exists() {
        let (move_home, credential_path) =
            setup_move_home("/save_credential_works_if_token_field_exists");

        let _ = fs::remove_dir_all(&move_home);
        fs::create_dir_all(&move_home).unwrap();
        File::create(&credential_path).unwrap();

        let old_content =
            String::from("[registry]\ntoken = \"old_test_token\"\nversion = \"0.0.0\"\n");
        fs::write(&credential_path, old_content).expect("Unable to write file");

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(token.to_string().contains("old_test_token"));
        assert!(!token.to_string().contains("new_world"));

        MoveyLogin::save_credential(String::from("new_world"), move_home.clone()).unwrap();

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(token.to_string().contains("new_world"));
        assert!(!token.to_string().contains("old_test_token"));
        let version = registry.as_table_mut().unwrap().get_mut("version").unwrap();
        assert!(version.to_string().contains("0.0.0"));

        clean_up(&move_home);
    }

    #[test]
    fn save_credential_works_if_empty_token_field_exists() {
        let (move_home, credential_path) =
            setup_move_home("/save_credential_works_if_empty_token_field_exists");

        let _ = fs::remove_dir_all(&move_home);
        fs::create_dir_all(&move_home).unwrap();
        File::create(&credential_path).unwrap();

        let old_content = String::from("[registry]\ntoken = \"\"\nversion = \"0.0.0\"\n");
        fs::write(&credential_path, old_content).expect("Unable to write file");

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(!token.to_string().contains("test_token"));

        MoveyLogin::save_credential(String::from("test_token"), move_home.clone()).unwrap();

        let contents = fs::read_to_string(&credential_path).expect("Unable to read file");
        let mut toml: Value = contents.parse().unwrap();
        let registry = toml.as_table_mut().unwrap().get_mut("registry").unwrap();
        let token = registry.as_table_mut().unwrap().get_mut("token").unwrap();
        assert!(token.to_string().contains("test_token"));
        let version = registry.as_table_mut().unwrap().get_mut("version").unwrap();
        assert!(version.to_string().contains("0.0.0"));

        clean_up(&move_home);
    }
}