nushell/crates/nu-parser/src/parse/source.rs
Andrés N. Robalino 9d8845d7ad
Allow custom lib dir path for sourcing nu script libraries. (#3940)
Given we can write nu scripts. As the codebase grows, splitting into many smaller nu scripts is necessary.

In general, when we work with paths and files we seem to face quite a few difficulties. Here we just tackle one of them and it involves sourcing
files that also source other nu files and so forth. The current working directory becomes important here and being on a different directory
when sourcing scripts will not work. Mostly because we expand the path on the current working directory and parse the files when a source command
call is done.

For the moment, we introduce a `lib_dirs` configuration value and, unfortunately, introduce a new dependency in `nu-parser` (`nu-data`) to get
a handle of the configuration file to retrieve it. This should give clues and ideas as the new parser engine continues (introduce a way to also know paths)

With this PR we can do the following:

Let's assume we want to write a nu library called `my_library`. We will have the code in a directory called `project`: The file structure will looks like this:

```
project/my_library.nu
project/my_library/hello.nu
project/my_library/name.nu
```

This "pattern" works well, that is, when creating a library have a directory named `my_library` and next to it a `my_library.nu` file. Filling them like this:

```

source my_library/hello.nu
source my_library/name.nu
```

```

def hello [] {
  "hello world"
}
```

```

def name [] {
  "Nu"
end
```

Assuming this `project` directory is stored at `/path/to/lib/project`, we can do:

```
config set lib_dirs ['path/to/lib/project']
```

Given we have this `lib_dirs` configuration value, we can be anywhere while using Nu and do the following:

```
source my_library.nu

echo (hello) (name)

```
2021-08-26 02:04:04 -05:00

94 lines
2.7 KiB
Rust

use crate::{lex::tokens::LiteCommand, ParserScope};
use nu_errors::{ArgumentError, ParseError};
use nu_path::expand_path;
use nu_protocol::hir::{Expression, InternalCommand};
use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
pub fn parse_source_internal(
lite_cmd: &LiteCommand,
command: &InternalCommand,
scope: &dyn ParserScope,
) -> Result<(), ParseError> {
if lite_cmd.parts.len() != 2 {
return Err(ParseError::argument_error(
lite_cmd.parts[0].clone(),
ArgumentError::MissingMandatoryPositional("a path for sourcing".into()),
));
}
if lite_cmd.parts[1].item.starts_with('$') {
return Err(ParseError::mismatch(
"a filepath constant",
lite_cmd.parts[1].clone(),
));
}
// look for source files in lib dirs first
// if not files are found, try the current path
// first file found wins.
find_source_file(lite_cmd, command, scope)
}
fn find_source_file(
lite_cmd: &LiteCommand,
command: &InternalCommand,
scope: &dyn ParserScope,
) -> Result<(), ParseError> {
let file = if let Some(ref positional_args) = command.args.positional {
if let Expression::FilePath(ref p) = positional_args[0].expr {
p
} else {
Path::new(&lite_cmd.parts[1].item)
}
} else {
Path::new(&lite_cmd.parts[1].item)
};
let lib_dirs = nu_data::config::config(nu_source::Tag::unknown())
.ok()
.as_ref()
.map(|configuration| match configuration.get("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.into_iter().flatten() {
let path = PathBuf::from(lib_path).join(&file);
if let Ok(contents) =
std::fs::read_to_string(&expand_path(Cow::Borrowed(path.as_path())))
{
return parse(&contents, 0, scope);
}
}
}
let path = Path::new(&file);
let contents = std::fs::read_to_string(&expand_path(Cow::Borrowed(path)));
match contents {
Ok(contents) => parse(&contents, 0, scope),
Err(_) => Err(ParseError::argument_error(
lite_cmd.parts[1].clone(),
ArgumentError::BadValue("can't load source file".into()),
)),
}
}
pub fn parse(input: &str, span_offset: usize, scope: &dyn ParserScope) -> Result<(), ParseError> {
if let (_, Some(parse_error)) = super::parse(input, span_offset, scope) {
Err(parse_error)
} else {
Ok(())
}
}