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
use crate::prelude::*;
use nu_engine::{script, WholeStreamCommand};

use nu_errors::ShellError;
use nu_path::{canonicalize, canonicalize_with};
use nu_protocol::{Signature, SyntaxShape};
use nu_source::Tagged;

use std::path::Path;

pub struct Source;

#[derive(Deserialize)]
pub struct SourceArgs {
    pub filename: Tagged<String>,
}

impl WholeStreamCommand for Source {
    fn name(&self) -> &str {
        "source"
    }

    fn signature(&self) -> Signature {
        Signature::build("source").required(
            "filename",
            SyntaxShape::FilePath,
            "the filepath to the script file to source",
        )
    }

    fn usage(&self) -> &str {
        "Runs a script file in the current context."
    }

    fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
        source(args)
    }

    fn examples(&self) -> Vec<Example> {
        vec![]
    }
}

pub fn source(args: CommandArgs) -> Result<OutputStream, ShellError> {
    let ctx = &args.context;
    let filename: Tagged<String> = args.req(0)?;

    let source_file = Path::new(&filename.item);

    // Note: this is a special case for setting the context from a command
    // In this case, if we don't set it now, we'll lose the scope that this
    // variable should be set into.

    let lib_dirs = &ctx
        .configs()
        .lock()
        .global_config
        .as_ref()
        .map(|configuration| match configuration.var("lib_dirs") {
            Some(paths) => paths
                .table_entries()
                .cloned()
                .map(|path| path.as_string())
                .collect(),
            None => vec![],
        });

    if let Some(dir) = lib_dirs {
        for lib_path in dir {
            match lib_path {
                Ok(name) => {
                    let path = if let Ok(p) = canonicalize_with(&source_file, name) {
                        p
                    } else {
                        continue;
                    };

                    if let Ok(contents) = std::fs::read_to_string(path) {
                        let result = script::run_script_standalone(contents, true, ctx, false);

                        if let Err(err) = result {
                            ctx.error(err);
                        }
                        return Ok(OutputStream::empty());
                    }
                }
                Err(reason) => {
                    ctx.error(reason.clone());
                }
            }
        }
    }

    let path = canonicalize(source_file).map_err(|e| {
        ShellError::labeled_error(
            format!("Can't load source file. Reason: {}", e),
            "Can't load this file",
            filename.span(),
        )
    })?;

    let contents = std::fs::read_to_string(path);

    match contents {
        Ok(contents) => {
            let result = script::run_script_standalone(contents, true, ctx, false);

            if let Err(err) = result {
                ctx.error(err);
            }
            Ok(OutputStream::empty())
        }
        Err(e) => {
            ctx.error(ShellError::labeled_error(
                format!("Can't load source file. Reason: {}", e),
                "Can't load this file",
                filename.span(),
            ));

            Ok(OutputStream::empty())
        }
    }
}