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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
use std::{
    collections::{self, hash_map},
    env,
    io::{self, BufRead},
    path,
    str::FromStr,
};

/// An integer part of a version specifier (e.g. the `X or `Y of `X.Y`).
type VersionComponent = u16;

/// Represents the version of Python a user requsted.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RequestedVersion {
    Any,
    Loose(VersionComponent),
    Exact(VersionComponent, VersionComponent),
}

impl FromStr for RequestedVersion {
    type Err = String;

    fn from_str(version_string: &str) -> Result<Self, Self::Err> {
        if version_string.is_empty() {
            return Err("version string is empty".to_string());
        }

        let mut char_iter = version_string.chars();
        let mut major_ver = Vec::new();
        let mut dot = false;

        for c in char_iter.by_ref() {
            if c == '.' {
                dot = true;
                break;
            } else if c.is_ascii_digit() {
                major_ver.push(c);
            } else {
                return Err(format!(
                    "{:?} contains a non-numeric and non-period character",
                    version_string
                ));
            }
        }

        let mut minor_ver = Vec::new();
        if dot {
            for c in char_iter.by_ref() {
                if c.is_ascii_digit() {
                    minor_ver.push(c);
                } else {
                    return Err(format!(
                        "{:?} contains a non-numeric character after a period",
                        version_string
                    ));
                }
            }
        }

        let major = char_vec_to_int(&major_ver)?;
        if !dot {
            Ok(RequestedVersion::Loose(major))
        } else if minor_ver.is_empty() {
            Err(format!(
                "{:?} is missing a minor version number",
                version_string
            ))
        } else {
            let minor = char_vec_to_int(&minor_ver)?;
            Ok(RequestedVersion::Exact(major, minor))
        }
    }
}

impl RequestedVersion {
    /// Returns the string representing the environment variable for the requested version.
    pub fn env_var(self) -> Option<String> {
        match self {
            RequestedVersion::Any => Some("PY_PYTHON".to_string()),
            RequestedVersion::Loose(major) => Some(format!("PY_PYTHON{}", major)),
            _ => None,
        }
    }
}

/// The version of Python found.
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Version {
    major: VersionComponent,
    minor: VersionComponent,
}

/// Represents how tight of a match a `Version` is to a `RequestedVersion`.
#[derive(Debug, PartialEq)]
pub enum VersionMatch {
    NotAtAll, // Not compatible.
    Loosely,  // Compatible, but potential for a better, newer match.
    Exactly,  // Matches a major.minor exactly.
}

impl Version {
    // XXX Make VersionMatch a part of Version.
    /// Sees how well of a match this Python version is for `requested`.
    pub fn matches(&self, requested: RequestedVersion) -> VersionMatch {
        match requested {
            RequestedVersion::Any => VersionMatch::Loosely,
            RequestedVersion::Loose(major) => {
                if self.major == major {
                    VersionMatch::Loosely
                } else {
                    VersionMatch::NotAtAll
                }
            }
            RequestedVersion::Exact(major, minor) => {
                if self.major == major && self.minor == minor {
                    VersionMatch::Exactly
                } else {
                    VersionMatch::NotAtAll
                }
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Action {
    Help(path::PathBuf),
    Execute {
        launcher_path: path::PathBuf,
        version: RequestedVersion,
        args: Vec<String>,
    },
}

/// Figure out what action is being requested based on the arguments to the executable.
///
/// # Examples
/// Typically you will construct a `Vec<String>` from `env::args()`.
/// ```
/// use std::env;
/// use python_launcher as py;
/// let args = env::args().collect::<Vec<String>>();
/// let action = py::action_from_args(args);
/// ```
pub fn action_from_args(mut args: Vec<String>) -> Action {
    let launcher_path = path::PathBuf::from(args.remove(0)); // Strip the path to this executable.
    if !args.is_empty() {
        let flag = &args[0];

        if flag == "-h" || flag == "--help" {
            return Action::Help(launcher_path);
        } else if let Some(version) = version_from_flag(&flag) {
            args.remove(0);
            return Action::Execute {
                launcher_path,
                version,
                args,
            };
        }
    }
    Action::Execute {
        launcher_path,
        version: RequestedVersion::Any,
        args,
    }
}

/// Converts a `Vec<char>` to a `VersionComponent` integer.
fn char_vec_to_int(char_vec: &[char]) -> Result<VersionComponent, String> {
    let joined_string = char_vec.iter().collect::<String>();
    let parse_result = joined_string.parse();
    parse_result.or_else(|_| Err(format!("error converting {:?} to a number", joined_string)))
}

/// Attempts to find a version specifier from a CLI argument.
///
/// It is assumed that the flag from the command-line is passed as-is
/// (i.e. the flag starts with `-`).
pub fn version_from_flag(arg: &str) -> Option<RequestedVersion> {
    if !arg.starts_with('-') {
        None
    } else {
        RequestedVersion::from_str(&arg[1..]).ok()
    }
}

/// Returns the path to the activated virtual environment.
///
/// A virtual environment is determined to be activated based on the existence of the `VIRTUAL_ENV`
/// environment variable.
pub fn virtual_env() -> Option<path::PathBuf> {
    match env::var_os("VIRTUAL_ENV") {
        None => None,
        Some(venv_root) => {
            let mut path = path::PathBuf::new();
            path.push(venv_root);
            path.push("bin");
            path.push("python");
            // TODO: Do a is_file() check first?
            Some(path)
        }
    }
}

/// Convert `PATH` into a `Vec<path::PathBuf>`.
pub fn path_entries() -> Vec<path::PathBuf> {
    if let Some(path_val) = env::var_os("PATH") {
        env::split_paths(&path_val).collect()
    } else {
        Vec::new()
    }
}

/// Gets the contents of a directory.
///
/// Exists primarily to unwrap and ignore any unencodeable names.
pub fn directory_contents(path: &path::Path) -> collections::HashSet<path::PathBuf> {
    let mut paths = collections::HashSet::new();
    if let Ok(contents) = path.read_dir() {
        for content in contents {
            if let Ok(found_content) = content {
                paths.insert(found_content.path());
            }
        }
    }

    paths
}

/// Filters the paths down to `pythonX.Y` paths.
pub fn filter_python_executables(
    paths: collections::HashSet<path::PathBuf>,
) -> collections::HashMap<Version, path::PathBuf> {
    let mut executables = collections::HashMap::new();
    for path in paths {
        let unencoded_file_name = match path.file_name() {
            Some(x) => x,
            None => continue,
        };
        let file_name = match unencoded_file_name.to_str() {
            Some(x) => x,
            None => continue,
        };
        if file_name.len() < "python3.0".len() || !file_name.starts_with("python") {
            continue;
        }
        let version_part = &file_name["python".len()..];
        if let Ok(found_version) = RequestedVersion::from_str(&version_part) {
            match found_version {
                RequestedVersion::Exact(major, minor) => {
                    executables.insert(Version { major, minor }, path.clone())
                }
                _ => continue,
            };
        }
    }

    executables
}

// XXX Write tests
/// Find all available executables that are acceptable for the requested version as found on `PATH`.
pub fn available_executables(
    requested_version: RequestedVersion,
) -> collections::HashMap<Version, path::PathBuf> {
    let mut found_versions = collections::HashMap::new();
    for path in path_entries() {
        let all_contents = directory_contents(&path);
        for (version, path) in filter_python_executables(all_contents) {
            if let hash_map::Entry::Vacant(entry) = found_versions.entry(version) {
                match entry.key().matches(requested_version) {
                    VersionMatch::NotAtAll => continue,
                    VersionMatch::Loosely => {
                        if path.is_file() {
                            entry.insert(path);
                        }
                    }
                    VersionMatch::Exactly => {
                        if path.is_file() {
                            entry.insert(path);
                            return found_versions;
                        }
                    }
                }
            }
        }
    }
    found_versions
}

/// Finds the executable representing the latest Python version.
pub fn choose_executable(
    version_paths: &collections::HashMap<Version, path::PathBuf>,
) -> Option<path::PathBuf> {
    let mut pairs: Vec<(&Version, &path::PathBuf)> = version_paths.iter().collect();
    pairs.sort_unstable_by_key(|p| p.0);
    pairs.last().map(|(_, path)| path.to_path_buf())
}

// XXX Shebang:
//      In main():
//          Prepend extra arguments to `argv`
//          Continue search for an appropriate Python version

/// Finds the shebang line from `reader`.
///
/// If a shebang line is found, then the `#!` is removed and the line is stripped of leading and trailing whitespace.
pub fn find_shebang(reader: impl io::Read) -> Option<String> {
    let mut buffered_reader = io::BufReader::new(reader);

    let mut line = String::new();
    if buffered_reader.read_line(&mut line).is_err() {
        return None;
    };

    if !line.starts_with("#!") {
        None
    } else {
        Some(line[2..].trim().to_string())
    }
}

/// Split the shebang into the Python version specified and the arguments to pass to the executable.
///
/// `Some` is only returned if the specified executable is one of:
/// - `/usr/bin/python`
/// - `/usr/local/bin/python`
/// - `/usr/bin/env python`
/// - `python`
pub fn split_shebang(shebang_line: &str) -> Option<(RequestedVersion, Vec<String>)> {
    let accepted_paths = [
        "/usr/bin/python",
        "/usr/local/bin/python",
        "/usr/bin/env python",
        "python",
    ];

    for exec_path in &accepted_paths {
        if !shebang_line.starts_with(exec_path) {
            continue;
        }

        let trimmed_shebang = shebang_line[exec_path.len()..].to_string();
        let version_string: String = trimmed_shebang
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        let specified_version = if version_string.is_empty() {
            Ok(RequestedVersion::Loose(2))
        } else {
            RequestedVersion::from_str(&version_string)
        };

        return specified_version
            .map(|version| {
                let args = trimmed_shebang[version_string.len()..].trim();
                (
                    version,
                    args.split_whitespace().map(|s| s.to_string()).collect(),
                )
            })
            .ok();
    }

    None
}

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

    #[test]
    #[allow(non_snake_case)]
    fn test_RequestedVersion_from_string() {
        assert!(RequestedVersion::from_str(&".3".to_string()).is_err());
        assert!(RequestedVersion::from_str(&"3.".to_string()).is_err());
        assert!(RequestedVersion::from_str(&"h".to_string()).is_err());
        assert!(RequestedVersion::from_str(&"3.b".to_string()).is_err());
        assert!(RequestedVersion::from_str(&"a.7".to_string()).is_err());
        assert_eq!(
            RequestedVersion::from_str(&"3".to_string()),
            Ok(RequestedVersion::Loose(3))
        );
        assert_eq!(
            RequestedVersion::from_str(&"3.8".to_string()),
            Ok(RequestedVersion::Exact(3, 8))
        );
        assert_eq!(
            RequestedVersion::from_str(&"42.13".to_string()),
            Ok(RequestedVersion::Exact(42, 13))
        );
        assert!(RequestedVersion::from_str(&"3.6.5".to_string()).is_err());
    }

    #[test]
    fn test_version_from_flag() {
        assert!(version_from_flag(&"-S".to_string()).is_none());
        assert!(version_from_flag(&"--something".to_string()).is_none());
        assert_eq!(
            version_from_flag(&"-3".to_string()),
            Some(RequestedVersion::Loose(3))
        );
        assert_eq!(
            version_from_flag(&"-3.6".to_string()),
            Some(RequestedVersion::Exact(3, 6))
        );
        assert_eq!(
            version_from_flag(&"-42.13".to_string()),
            Some(RequestedVersion::Exact(42, 13))
        );
        assert!(version_from_flag(&"-3.6.4".to_string()).is_none());
    }

    #[test]
    fn test_action_from_args() {
        let launcher_string = String::from("/py");
        let launcher_path = path::PathBuf::from(&launcher_string);

        assert_eq!(
            action_from_args(vec![launcher_string.clone()]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Any,
                args: Vec::new(),
            }
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("-h")]),
            Action::Help(launcher_path.clone())
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("--help")]),
            Action::Help(launcher_path.clone())
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("-V")]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Any,
                args: vec![String::from("-V")],
            }
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("-3")]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Loose(3),
                args: Vec::new(),
            }
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("-3.6")]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Exact(3, 6),
                args: Vec::new(),
            }
        );

        assert_eq!(
            action_from_args(vec![
                launcher_string.clone(),
                String::from("-3.6"),
                String::from("script.py"),
            ]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Exact(3, 6),
                args: vec![String::from("script.py")],
            }
        );

        assert_eq!(
            action_from_args(vec![launcher_string.clone(), String::from("script.py")]),
            Action::Execute {
                launcher_path: launcher_path.clone(),
                version: RequestedVersion::Any,
                args: vec![String::from("script.py")],
            }
        );
    }

    #[test]
    fn test_virtual_env() {
        let original_venv = env::var_os("VIRTUAL_ENV");

        env::remove_var("VIRTUAL_ENV");
        assert_eq!(virtual_env(), None);

        env::set_var("VIRTUAL_ENV", "/some/path");
        assert_eq!(
            virtual_env(),
            Some(path::PathBuf::from("/some/path/bin/python"))
        );

        match original_venv {
            None => env::remove_var("VIRTUAL_ENV"),
            Some(venv_value) => env::set_var("VIRTUAL_ENV", venv_value),
        }
    }

    #[test]
    fn unit_test_path_entries() {
        let paths = vec!["/a", "/b", "/c"];
        if let Ok(joined_paths) = env::join_paths(&paths) {
            let original_paths = env::var_os("PATH");
            env::set_var("PATH", joined_paths);
            assert_eq!(
                path_entries(),
                paths
                    .iter()
                    .map(|p| path::PathBuf::from(p))
                    .collect::<Vec<path::PathBuf>>()
            );
            match original_paths {
                Some(paths) => env::set_var("PATH", paths),
                None => env::set_var("PATH", ""),
            }
        }
    }

    #[test]
    fn system_test_path_entries() {
        if let Some(paths) = env::var_os("PATH") {
            let found_paths = path_entries();
            assert_eq!(found_paths.len(), env::split_paths(&paths).count());
            for (index, path) in env::split_paths(&paths).enumerate() {
                assert_eq!(found_paths[index], path);
            }
        }
    }

    #[test]
    fn test_filter_python_executables() {
        let paths = vec![
            "/bad/path/python",    // Under-specified.
            "/bad/path/python3",   // Under-specified.
            "/bad/path/hello",     // Not Python.
            "/bad/path/pytho3.6",  // Typo.
            "/bad/path/rython3.6", // Typo.
            "/good/path/python3.6",
            "/good/python42.13",
        ];
        let all_paths = paths
            .iter()
            .map(path::PathBuf::from)
            .collect::<collections::HashSet<path::PathBuf>>();
        let results = filter_python_executables(all_paths);
        let good_version1 = Version { major: 3, minor: 6 };
        let good_version2 = Version {
            major: 42,
            minor: 13,
        };
        let mut expected = paths[5];
        match results.get(&good_version1) {
            Some(path) => assert_eq!(*path, path::PathBuf::from(expected)),
            None => panic!("{:?} not found", good_version1),
        };
        expected = paths[6];
        match results.get(&good_version2) {
            Some(path) => assert_eq!(*path, path::PathBuf::from(expected)),
            None => panic!("{:?} not found", good_version2),
        }
    }

    #[test]
    fn test_version_matches() {
        let any = RequestedVersion::Any;
        let loose_42 = RequestedVersion::Loose(42);
        let exact_42_13 = RequestedVersion::Exact(42, 13);

        let version_3_6 = Version { major: 3, minor: 6 };
        let version_42_0 = Version {
            major: 42,
            minor: 0,
        };
        let version_42_13 = Version {
            major: 42,
            minor: 13,
        };

        assert_eq!(version_3_6.matches(any), VersionMatch::Loosely);
        assert_eq!(version_3_6.matches(loose_42), VersionMatch::NotAtAll);
        assert_eq!(version_3_6.matches(exact_42_13), VersionMatch::NotAtAll);

        assert_eq!(version_42_0.matches(any), VersionMatch::Loosely);
        assert_eq!(version_42_0.matches(loose_42), VersionMatch::Loosely);
        assert_eq!(version_42_0.matches(exact_42_13), VersionMatch::NotAtAll);

        assert_eq!(version_42_13.matches(any), VersionMatch::Loosely);
        assert_eq!(version_42_13.matches(loose_42), VersionMatch::Loosely);
        assert_eq!(version_42_13.matches(exact_42_13), VersionMatch::Exactly);
    }

    #[test]
    fn test_choose_executable() {
        let version_3_6 = Version { major: 3, minor: 6 };
        let version_42_0 = Version {
            major: 42,
            minor: 0,
        };
        let version_42_13 = Version {
            major: 42,
            minor: 13,
        };
        let path_3_6 = path::PathBuf::from("/python3.6");
        let path_42_0 = path::PathBuf::from("/python42.0");
        let path_42_13 = path::PathBuf::from("/python42.13");
        let mut mapping = collections::HashMap::new();

        if choose_executable(&mapping).is_some() {
            panic!("found a non-existent path");
        };

        mapping.insert(version_3_6, path_3_6.clone());
        match choose_executable(&mapping) {
            Some(path) => assert_eq!(path, path_3_6),
            None => panic!("no path found"),
        }

        mapping.insert(version_42_0, path_42_0);
        mapping.insert(version_42_13, path_42_13.clone());
        match choose_executable(&mapping) {
            Some(path) => assert_eq!(path, path_42_13),
            None => panic!("no path found"),
        }
    }

    #[test]
    fn test_requested_version_env_var() {
        assert_eq!(
            RequestedVersion::Any.env_var(),
            Some("PY_PYTHON".to_string())
        );
        assert_eq!(
            RequestedVersion::Loose(3).env_var(),
            Some("PY_PYTHON3".to_string())
        );
        assert_eq!(
            RequestedVersion::Loose(42).env_var(),
            Some("PY_PYTHON42".to_string())
        );
        assert!(RequestedVersion::Exact(3, 8).env_var().is_none());
    }

    #[test]
    fn test_find_shebang() {
        // Common case.
        assert_eq!(
            find_shebang("#! /usr/bin/cat\nprint('Hello!')\n".as_bytes()),
            Some("/usr/bin/cat".to_string())
        );

        // No shebang.
        assert_eq!(find_shebang("print('Hello!')".as_bytes()), None);

        // No whitespace between `#!` and command.
        assert_eq!(
            find_shebang("#!/usr/bin/cat\nHello".as_bytes()),
            Some("/usr/bin/cat".to_string())
        );

        // Command wtih arguments.
        assert_eq!(
            find_shebang("#! /usr/bin/env python -S".as_bytes()),
            Some("/usr/bin/env python -S".to_string())
        );

        // Strip trailing whitespace.
        assert_eq!(
            find_shebang("#! /usr/bin/python \n# Hello".as_bytes()),
            Some("/usr/bin/python".to_string())
        );

        // Nothing but a shebang.
        assert_eq!(
            find_shebang("#! /usr/bin/python".as_bytes()),
            Some("/usr/bin/python".to_string())
        );
    }

    #[test]
    fn test_split_shebang() {
        assert_eq!(split_shebang(&"/usr/bin/rustup".to_string()), None);
        assert_eq!(
            split_shebang(&"/usr/bin/rustup self update".to_string()),
            None
        );
        assert_eq!(
            split_shebang(&"/usr/bin/env python".to_string()),
            Some((RequestedVersion::Loose(2), Vec::new()))
        );
        assert_eq!(
            split_shebang(&"/usr/bin/python42.13".to_string()),
            Some((RequestedVersion::Exact(42, 13), Vec::new()))
        );
        assert_eq!(
            split_shebang(&"python -S -v".to_string()),
            Some((
                RequestedVersion::Loose(2),
                vec!["-S".to_string(), "-v".to_string()]
            ))
        );
        assert_eq!(
            split_shebang(&"/usr/local/bin/python3.7 -S".to_string()),
            Some((RequestedVersion::Exact(3, 7), vec!["-S".to_string()]))
        );
    }
}