Skip to content

Add into cell-path for dynamic cell-path creation - #11322

Merged
fdncred merged 5 commits into
nushell:mainfrom
drbrain:into-cell-path
Jan 24, 2024
Merged

fdncred merged 5 commits into
nushell:mainfrom
drbrain:into-cell-path

Conversation

@drbrain

@drbrain drbrain commented Dec 14, 2023

Copy link
Copy Markdown
Contributor

Description

The cell-path is a type that can be created statically with $.nested.structure.5, but can't be created from user input. This makes it difficult to take advantage of commands that accept a cell-path to operate on data structures.

This PR adds into cell-path for dynamic cell-path creation.

into cell-path accepts the following input shapes:

  • Bare integer (equivalent to $.1)
  • List of strings and integers
  • List of records with entries value and optional
  • String (parsed into a cell-path)

Example usage

An example of where into cell-path can be used is in working with git config --list. The git configuration has a tree structure that maps well to nushell records. With dynamic cell paths it is easy to convert git config list to a record:

git config --list
| lines
| parse -r '^(?<key>[^=]+)=(?<value>.*)'
| reduce --fold {} {|entry, result|
  let path = $entry.key | into cell-path

  $result
  | upsert $path {||
    $entry.value
  }
}
| select remote

Output:

╭────────┬──────────────────────────────────────────────────────────────────╮
│        │ ╭──────────┬───────────────────────────────────────────────────╮ │
│ remote │ │          │ ╭───────┬───────────────────────────────────────╮ │ │
│        │ │ upstream │ │ url   │ [email protected]:nushell/nushell.git    │ │ │
│        │ │          │ │ fetch │ +refs/heads/*:refs/remotes/upstream/* │ │ │
│        │ │          │ ╰───────┴───────────────────────────────────────╯ │ │
│        │ │          │ ╭───────┬─────────────────────────────────────╮   │ │
│        │ │ origin   │ │ url   │ [email protected]:drbrain/nushell      │   │ │
│        │ │          │ │ fetch │ +refs/heads/*:refs/remotes/origin/* │   │ │
│        │ │          │ ╰───────┴─────────────────────────────────────╯   │ │
│        │ ╰──────────┴───────────────────────────────────────────────────╯ │
╰────────┴──────────────────────────────────────────────────────────────────╯

Errors

lex() + parse_cell_path() are forgiving about what is allowed in a cell-path so it will allow what appears to be nonsense to become a cell-path:

let table = [["!@$%^&*" value]; [key value]]

$table | get ("!@$%^&*.0" | into cell-path)
# => key

But it will reject bad cell-paths:

❯ "a b" | into cell-path
Error: nu::shell::cant_convert

  × Can't convert to cell-path.
   ╭─[entry #14:1:1]
 1 │ "a b" | into cell-path
   ·         ───────┬──────
   ·                ╰── can't convert string to cell-path
   ╰────
  help: "a b" is not a valid cell-path (Parse mismatch during operation.)

User-Facing Changes

New conversion command into cell-path

Tests + Formatting

  • 🟢 toolkit fmt
  • 🟢 toolkit clippy
  • 🟢 toolkit test
  • 🟢 toolkit test stdlib

After Submitting

Automatic documentation updates

@fdncred

fdncred commented Dec 14, 2023 •

Copy link
Copy Markdown
Contributor

Reminds me of this one #8482

I vote yes to this, just like I did last time.

@drbrain

drbrain commented Dec 14, 2023

Copy link
Copy Markdown
Contributor Author

Looks like your example 3 from #8482 works now (probably not due to anything in this PR):

let data = {a: {b: {c: [1 2 3]}}}
let target = "a.b.c.1" | into cell-path

$data | get $target
# => 2

@kubouch

kubouch commented Dec 14, 2023

Copy link
Copy Markdown
Contributor

The problem is that it's essentially doing eval, that's why the two previous PRs were closed/reverted (see fdncred's link, from there you can find the second PR). I'm not sure we'll be able to accept the PR since we didn't the two previous ones implementing the same thing. What might be the preferred way is extending the cell path syntax to allow things like $foo.$bar.

@drbrain

drbrain commented Dec 14, 2023 •

Copy link
Copy Markdown
Contributor Author

The problem is that it's essentially doing eval

Would this be acceptable without using parse_cell_path(), and instead allowing only the list conversions? This would allow manual parsing like:

'some.structure.path' | split row '.' | into cell-path

From #8482 I see:

it gets worse when you get subexpressions like jt mentioned, so something like [name == $var] if it ever does land

With subexpressions currently absent would making a new EngineState to prevent untrusted input accessing nushell internals be acceptable?

In a future where cell-path subexpressions exist would using parse_cell_path() be acceptable if that feature raised errors for into cell-path?

@sophiajt

Copy link
Copy Markdown
Contributor

I could imagine that into cell-path could take in a list. I think that's definitely preferable to calling into the parser.

That said, I was hoping we could use the cell-path literals and just use those as values without resorting to strings. That gives us something that's a bit more self-documenting.

There are also some plans in the future to extend cell-paths to do more, like glob matching across cells. If we get too narrow with how cell-paths work now, then we might limit ourselves.

I agree with the others who mentioned we should steer clear of anything that's like eval, which includes calling the parser from the evaluator except in very specific cases (like supporting nuon).

@drbrain

drbrain commented Jan 6, 2024

Copy link
Copy Markdown
Contributor Author

I have updated this PR to remove converting a string into a cell-path. There is an example that shows how a user can do their own parsing to create a cell path with 'some.path' | split row '.' | into cell-path.

To (hopefully) reduce confusion passing a string to into cell-path will always return an error, along with a note in the extra usage:

❯ into cell-path --help
Convert value to a cell-path.

Converting a string directly into a cell path is intentionally not supported.

Usage:
  > into cell-path

Flags:
  -h, --help - Display the help message for this command

Input/output types:
  ╭───┬──────────────────────────────────────────┬───────────╮
  │ # │                  input                   │  output   │
  ├───┼──────────────────────────────────────────┼───────────┤
  │ 0 │ int                                      │ cell-path │
  │ 1 │ list<any>                                │ cell-path │
  │ 2 │ list<record<value: any, optional: bool>> │ cell-path │
  ╰───┴──────────────────────────────────────────┴───────────╯

Examples:
  Convert integer into cell path
  > 5 | into cell-path
  5

  Convert string into cell path
  > 'some.path' | split row '.' | into cell-path
  some.path

  Convert list into cell path
  > [5 c 7 h] | into cell-path
  5.c.7.h

  Convert table into cell path
  > [[value, optional]; [5 true] [c false]] | into cell-path
  5.c

@fdncred
fdncred merged commit 2a65d43 into nushell:main Jan 24, 2024
@fdncred

fdncred commented Jan 24, 2024

Copy link
Copy Markdown
Contributor

Thanks for working on this @drbrain. Sorry it took so long for us to come to a decision.

@kubouch kubouch added this to the v0.90.0 milestone Jan 24, 2024
@kubouch kubouch added notes:mention Noted in "Hall of Fame" section deprecated:pr-commands (deprecated: too vague) This PR changes our commands in some way labels Jan 24, 2024
dmatos2012 pushed a commit to dmatos2012/nushell that referenced this pull request Feb 20, 2024
# Description

The `cell-path` is a type that can be created statically with
`$.nested.structure.5`, but can't be created from user input. This makes
it difficult to take advantage of commands that accept a cell-path to
operate on data structures.

This PR adds `into cell-path` for dynamic cell-path creation.

`into cell-path` accepts the following input shapes:
* Bare integer (equivalent to `$.1`)
* List of strings and integers
* List of records with entries `value` and `optional`
* String (parsed into a cell-path)

## Example usage

An example of where `into cell-path` can be used is in working with `git
config --list`. The git configuration has a tree structure that maps
well to nushell records. With dynamic cell paths it is easy to convert
`git config list` to a record:

```nushell
git config --list
| lines
| parse -r '^(?<key>[^=]+)=(?<value>.*)'
| reduce --fold {} {|entry, result|
  let path = $entry.key | into cell-path

  $result
  | upsert $path {||
    $entry.value
  }
}
| select remote
```

Output:

```
╭────────┬──────────────────────────────────────────────────────────────────╮
│        │ ╭──────────┬───────────────────────────────────────────────────╮ │
│ remote │ │          │ ╭───────┬───────────────────────────────────────╮ │ │
│        │ │ upstream │ │ url   │ [email protected]:nushell/nushell.git    │ │ │
│        │ │          │ │ fetch │ +refs/heads/*:refs/remotes/upstream/* │ │ │
│        │ │          │ ╰───────┴───────────────────────────────────────╯ │ │
│        │ │          │ ╭───────┬─────────────────────────────────────╮   │ │
│        │ │ origin   │ │ url   │ [email protected]:drbrain/nushell      │   │ │
│        │ │          │ │ fetch │ +refs/heads/*:refs/remotes/origin/* │   │ │
│        │ │          │ ╰───────┴─────────────────────────────────────╯   │ │
│        │ ╰──────────┴───────────────────────────────────────────────────╯ │
╰────────┴──────────────────────────────────────────────────────────────────╯
```

## Errors

`lex()` + `parse_cell_path()` are forgiving about what is allowed in a
cell-path so it will allow what appears to be nonsense to become a
cell-path:

```nushell
let table = [["!@$%^&*" value]; [key value]]

$table | get ("!@$%^&*.0" | into cell-path)
# => key
```

But it will reject bad cell-paths:

```
❯ "a b" | into cell-path
Error: nu::shell::cant_convert

  × Can't convert to cell-path.
   ╭─[entry nushell#14:1:1]
 1 │ "a b" | into cell-path
   ·         ───────┬──────
   ·                ╰── can't convert string to cell-path
   ╰────
  help: "a b" is not a valid cell-path (Parse mismatch during operation.)
```

# User-Facing Changes

New conversion command `into cell-path`

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

Automatic documentation updates
@drbrain
drbrain deleted the into-cell-path branch May 3, 2024 17:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deprecated:pr-commands (deprecated: too vague) This PR changes our commands in some way notes:mention Noted in "Hall of Fame" section

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants