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
use std::env;
use std::path::Path;
use std::process::Command;

#[derive(Debug)]
pub struct Config {
    pub remote: Option<String>,
    pub filename: String,
    pub range_start: Option<u32>,
    pub range_end: Option<u32>,
}

impl Config {
    pub fn new(args: &Vec<String>) -> Result<Config, String> {
        if args.len() < 2 {
            return Err("Not enough arguments.".to_string());
        }

        let filename = args[1].clone();
        if !Path::new(&filename).exists() {
            return Err(format!("File {} doesn't exist.", filename));
        }

        let range_start = match args.get(2) {
            Some(value) => {
                if let Ok(v) = value.parse() {
                    Some(v)
                } else {
                    return Err(format!("Invalid range {}: not a number.", value));
                }
            }
            None => None,
        };

        let range_end = match args.get(3) {
            Some(value) => {
                if let Ok(v) = value.parse() {
                    Some(v)
                } else {
                    return Err(format!("Invalid range {}: not a number.", value));
                }
            }
            None => None,
        };

        let remote = if let Ok(value) = env::var("REMOTE") {
            Some(value.to_lowercase())
        } else {
            None
        };

        Ok(Config {
            remote,
            filename,
            range_start,
            range_end,
        })
    }
}

pub fn run(config: Config) -> Result<String, String> {
    let command = Command::new("git");
    let url = get_remote_url(command, &config.remote)?;

    let web_url = normalize(url);

    let command = Command::new("git");
    let blob_url = get_blob_url(command, web_url, &config.filename)?;

    let link = add_range(blob_url, &config.range_start, &config.range_end);

    Ok(link)
}

#[cfg_attr(test, mockall::automock)]
trait GitCommand {
    fn run_config_get_local(&mut self, remote: &str) -> Result<String, String>;
    fn run_rev_parse_head(&mut self) -> Result<String, String>;
}

impl GitCommand for Command {
    fn run_config_get_local(&mut self, remote: &str) -> Result<String, String> {
        let command = self.args(&[
            "config",
            "--get",
            "--local",
            format!("remote.{}.url", remote).as_str(),
        ]);

        let output = command
            .output()
            .expect("failed to execute git config command");

        match String::from_utf8(output.stdout) {
            Ok(value) => Ok(value.trim().to_string()),
            _ => Err("Invalid String from git config output.".to_string()),
        }
    }

    fn run_rev_parse_head(&mut self) -> Result<String, String> {
        let command = self.args(&["rev-parse", "HEAD"]);

        let output = command
            .output()
            .expect("failed to execute git config command");

        match String::from_utf8(output.stdout) {
            Ok(value) => Ok(value.trim().to_string()),
            _ => Err("Invalid String from git config output.".to_string()),
        }
    }
}

fn get_remote_url<T: GitCommand>(mut command: T, remote: &Option<String>) -> Result<String, String> {
    let remote = if let Some(value) = remote {
        value
    } else {
        "origin"
    };

    let url = command.run_config_get_local(&remote)?;

    if url.is_empty() {
        return Err(format!("Remote {} doesn't exist.", remote));
    } else if !url.starts_with("https://") && !url.starts_with("git@") {
        return Err("Remote URL is invalid. Scheme should be https or git".to_string());
    } else if !url.contains("github") && !url.contains("gitlab") {
        return Err("Only github or gitlab URLs supported.".to_string());
    }

    Ok(url)
}

fn normalize(url: String) -> String {
    if url.starts_with("https") {
        return url;
    }

    // We know this is a git scheme url, like git@gitlab.com:tonchis/repo_link.git, so:
    // 1. we drop the "git@" part
    // 2. replace the .com:tonchis with .com/tonchis
    // 3. remove the trailing .git
    // 4. prepend "https://"
    let mut url = url[4..].to_string().replace(":", "/").replace(".git", "");

    url.insert_str(0, "https://");

    url
}

fn get_blob_url<T: GitCommand>(
    mut command: T,
    web_url: String,
    filename: &String,
) -> Result<String, String> {
    let sha_head = command.run_rev_parse_head()?;

    let blob_url = vec![web_url, "blob".to_string(), sha_head, filename.to_string()];

    Ok(blob_url.join("/"))
}

fn add_range(blob_url: String, range_start: &Option<u32>, range_end: &Option<u32>) -> String {
    match range_start {
        None => blob_url,
        Some(start) => match range_end {
            None => format!("{}#L{}", blob_url, start),
            Some(end) => {
                if blob_url.contains("gitlab") {
                    format!("{}#L{}-{}", blob_url, start, end)
                } else {
                    format!("{}#L{}-L{}", blob_url, start, end)
                }
            }
        },
    }
}

#[cfg(test)]
use mockall::predicate::*;

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

    #[test]
    fn config_needs_filename() {
        let argv = vec!["program".to_string()];
        let result = Config::new(&argv);

        assert_eq!(result.unwrap_err(), "Not enough arguments.");

        let argv = vec!["program".to_string(), "foo".to_string()];
        let result = Config::new(&argv);

        assert_eq!(result.unwrap_err(), "File foo doesn't exist.");

        let argv = vec!["program".to_string(), "src/lib.rs".to_string()];
        let result = Config::new(&argv);

        assert!(result.is_ok());
    }

    #[test]
    fn config_rejects_invalid_ranges() {
        let argv = vec!["program", "src/lib.rs", "foo"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let result = Config::new(&argv);

        assert_eq!(result.unwrap_err(), "Invalid range foo: not a number.");

        let argv = vec!["program", "src/lib.rs", "1", "bar"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let result = Config::new(&argv);

        assert_eq!(result.unwrap_err(), "Invalid range bar: not a number.");

        let argv = vec!["program", "src/lib.rs", "1", "2"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let result = Config::new(&argv);
        assert!(result.is_ok());
    }

    #[test]
    fn get_remote_url_rejects_invalid_remotes() {
        let mut mock_command = MockGitCommand::new();

        mock_command
            .expect_run_config_get_local()
            .returning(|_| Ok(String::from("")));

        let result = get_remote_url(mock_command, &Some("foo".to_string()));
        assert_eq!(result.unwrap_err(), "Remote foo doesn't exist.");
    }

    #[test]
    fn get_remote_url_rejects_unsupported_schemas() {
        let mut mock_command = MockGitCommand::new();

        mock_command
            .expect_run_config_get_local()
            .returning(|_| Ok(String::from("ftp://bitbucket.org")));

        let result = get_remote_url(mock_command, &None);
        assert_eq!(
            result.unwrap_err(),
            "Remote URL is invalid. Scheme should be https or git"
        );
    }

    #[test]
    fn get_remote_url_rejects_unsupported_hosts() {
        let mut mock_command = MockGitCommand::new();

        mock_command
            .expect_run_config_get_local()
            .returning(|_| Ok(String::from("https://bitbucket.org")));

        let result = get_remote_url(mock_command, &None);
        assert_eq!(result.unwrap_err(), "Only github or gitlab URLs supported.");
    }

    #[test]
    fn normalize_transforms_git_url_into_https() {
        let web_url = normalize(String::from("git@gitlab.com:tonchis/repo_link.git"));

        assert_eq!(web_url, "https://gitlab.com/tonchis/repo_link");

        let web_url = normalize(String::from("git@gitlab.com:tonchis/repo_link"));

        assert_eq!(web_url, "https://gitlab.com/tonchis/repo_link");
    }

    #[test]
    fn normalize_honors_https_urls() {
        let web_url = normalize(String::from("https://gitlab.com/tonchis/repo_link"));

        assert_eq!(web_url, "https://gitlab.com/tonchis/repo_link");
    }

    #[test]
    fn get_blob_url_generates_blob_using_sha_head() {
        let mut mock_command = MockGitCommand::new();

        mock_command
            .expect_run_rev_parse_head()
            .returning(|| Ok(String::from("abcd1234")));

        let web_url = String::from("https://gitlab.com/tonchis/repo_link");
        let filename = String::from("src/lib.rs");

        let result = get_blob_url(mock_command, web_url, &filename);

        assert_eq!(
            result.unwrap(),
            "https://gitlab.com/tonchis/repo_link/blob/abcd1234/src/lib.rs"
        );
    }

    #[test]
    fn add_range_adds_the_anchor_for_the_line_of_code() {
        let blob_url = String::from("https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs");

        let link = add_range(blob_url, &None, &None);

        assert_eq!(
            link,
            "https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs"
        );

        let blob_url = String::from("https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs");

        let link = add_range(blob_url, &Some(1), &None);

        assert_eq!(
            link,
            "https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs#L1"
        );
    }

    #[test]
    fn add_range_supports_github_and_gitlab_ranges() {
        let blob_url = String::from("https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs");

        let link = add_range(blob_url, &Some(1), &Some(3));

        assert_eq!(
            link,
            "https://gitlab.com/tonchis/repo_link/blob/abcd123/src/lib.rs#L1-3"
        );

        let blob_url = String::from("https://github.com/tonchis/repo_link/blob/abcd123/src/lib.rs");

        let link = add_range(blob_url, &Some(1), &Some(3));

        assert_eq!(
            link,
            "https://github.com/tonchis/repo_link/blob/abcd123/src/lib.rs#L1-L3"
        );
    }
}