@@ -13,7 +13,7 @@ use miette::{miette, IntoDiagnostic, Result};
1313use nu_protocol:: {
1414 ast:: { Block , PathMember } ,
1515 engine:: { EngineState , StateDelta , StateWorkingSet } ,
16- DeclId , ModuleId , Span , Type , VarId ,
16+ DeclId , ModuleId , Span , Type , Value , VarId ,
1717} ;
1818use std:: {
1919 collections:: BTreeMap ,
@@ -315,13 +315,26 @@ impl LanguageServer {
315315 Ok ( reset)
316316 }
317317
318- pub ( crate ) fn new_engine_state ( & self ) -> EngineState {
318+ /// Create a clone of the initial_engine_state with:
319+ ///
320+ /// * PWD set to the parent directory of given uri. Fallback to `$env.PWD` if None.
321+ /// * `StateDelta` cache merged
322+ pub ( crate ) fn new_engine_state ( & self , uri : Option < & Uri > ) -> EngineState {
319323 let mut engine_state = self . initial_engine_state . clone ( ) ;
320- let cwd = std:: env:: current_dir ( ) . expect ( "Could not get current working directory." ) ;
321- engine_state. add_env_var (
322- "PWD" . into ( ) ,
323- nu_protocol:: Value :: test_string ( cwd. to_string_lossy ( ) ) ,
324- ) ;
324+ match uri {
325+ Some ( uri) => {
326+ let path = uri_to_path ( uri) ;
327+ if let Some ( path) = path. parent ( ) {
328+ engine_state
329+ . add_env_var ( "PWD" . into ( ) , Value :: test_string ( path. to_string_lossy ( ) ) )
330+ } ;
331+ }
332+ None => {
333+ let cwd =
334+ std:: env:: current_dir ( ) . expect ( "Could not get current working directory." ) ;
335+ engine_state. add_env_var ( "PWD" . into ( ) , Value :: test_string ( cwd. to_string_lossy ( ) ) ) ;
336+ }
337+ }
325338 // merge the cached `StateDelta` if text not changed
326339 if !self . need_parse {
327340 engine_state
@@ -458,10 +471,7 @@ mod tests {
458471 engine_state. generate_nu_constant ( ) ;
459472 assert ! ( load_standard_library( & mut engine_state) . is_ok( ) ) ;
460473 let cwd = std:: env:: current_dir ( ) . expect ( "Could not get current working directory." ) ;
461- engine_state. add_env_var (
462- "PWD" . into ( ) ,
463- nu_protocol:: Value :: test_string ( cwd. to_string_lossy ( ) ) ,
464- ) ;
474+ engine_state. add_env_var ( "PWD" . into ( ) , Value :: test_string ( cwd. to_string_lossy ( ) ) ) ;
465475 if let Some ( code) = nu_config_code {
466476 assert ! ( merge_input( code. as_bytes( ) , & mut engine_state, & mut Stack :: new( ) ) . is_ok( ) ) ;
467477 }
0 commit comments