Skip to content

Provide a string that does not expand globs #9558

Closed

Description

@haitemura

Related problem

Motivating example:
Recently I downloaded a video with yt-dlp. This tool puts youtube's video id into the file name in brackets, like so: video_title [video_id].webm. I wanted to mv the file and used tab completion to get its name, but the returned string did not match the video title. This was because it didn't escape the glob characters [ and ]. Hence, I had to fire up zsh to move the file.

There is currently no simple way to define a string which does not expand glob characters when working with file paths.
In #6014, it was implemented that glob expansion does not happen in " and ' strings, but only when an external command is executed.
I think this is confusing, see here:

touch a *
ls '*' # shows both files
^ls '*' # shows only one file

I believe that having behaviour differ for externals and built-ins like that is confusing and counterintuitive.

As far as I know, the only way right now to circumvent glob expansion when you're not doing external commands is by creating a character class—in which there can be no nested globs—so that *, and friends are not parsed as glob characters, like so:

touch "hello [world] *"
rm `hello [[]world[]] [*]` # this works

This is very hard to read and I don't event know if it is the intentional way to deal with this kind of problem.

Describe the solution you'd like

  1. Have single-quoted (') strings not expand globs, regardless of where they're used.
  2. Make glob characters escapable in double-quoted (") strings.
  3. Remove the different treatment of glob expansion for external commands (as introduced in Conditionally disable expansion for external command #6014).

Describe alternatives you've considered

An alternative could be to do it like bash and have globs only be expanded in bare strings, but this would require cumbersome notation when mixed with spaces:

ls *.rs # expand
ls "*.rs" # don't expand
ls ("the folder/" + *.rs) # expand, mixed with space -> need concatenation

Though, maybe this could in fact be an alternative if string concatenation didn't require the + operator and parentheses. (i.e. if adjacent strings were concatenated like in bash.)

Additional context and details

There's a discussion in #4631 about this. The requirements @jntrnr mentioned there would be satisfied by a non-expanding single-quoted string:

  • A glob that expands automatically: "*.rs"
  • A glob looking thing that doesn't expand automatically: '*.rs'
  • A path with a space and a glob that expands automatically: "my files/*.rs"
  • A path with a space and a glob that doesn't expand automatically 'my files/*.rs'
    With Windows path syntax you could write the third bullet as "my files\\*.rs".

Also, this is a list of some issues this would fix:

Lastly, I noticed that glob behaviour is different in ls to how it is with mv, cp and rm. Here's an example:

touch a b c aa bb cc
ls ? # does not work, "directory not found"
mkdir somedir
mv ? somedir # moves the three shorter files as expected

Another example:

touch "[]" # "escaped" file name is "[[][]]"
ls "[[][]]" # does not work, "Pattern, file or folder not found"
mv "[[][]]" nice_name # works

When doing the above, ls returns this error: Pattern, file or folder not found.
I believe this difference in behaviour may possibly (partially?) be caused by recent pull request #9416, as doing the same with an asterisk works fine:

touch "*"
ls "[*]" # works fine, expected output

Maybe this last part about ls belongs in its own issue, but it is somewhat related.

Activity

  1. added
    category:enhancement
    status:needs-triage
    on Jun 29, 2023
  2. fdncred commented on Jun 29, 2023

    @fdncred
    Contributor

    agreed, this needs to be fixed prior to 1.0. nice write up! thanks.

  3. fdncred commented on Jun 29, 2023

    @fdncred
    Contributor

    Just for fun, I created a file named video_title [video_id].webm and then used umv from this draft PR to see if it worked and it did.

    image

  4. haitemura commented on Jun 29, 2023

    @haitemura
    Author

    Ah, I just built that and tried it too, looks like when using umv there's not any glob expansion done at all
    image

  5. fdncred commented on Jun 29, 2023

    @fdncred
    Contributor

    it should work however the uutils mv command works. if it doesn't then it's a bug somewhere in the PR. it's just passing parameters to the uutils uumain function.

  6. added
    A:quoting-expansion
    A:file-system
    on Jun 29, 2023
  7. fdncred commented on Jun 30, 2023

    @fdncred
    Contributor

    It looks like coreutils works but umv does not. So, that's a bug in the umv code somewhere.
    image

  8. added
    A:glob
    and removed
    status:needs-triage
    on Jul 9, 2023
  9. dedebenui commented on Aug 18, 2023

    @dedebenui

    Thank you @Spickelbing for the writeup, which I've only found now unfortunately.

    I think the uu_mv thing doesn't really solve this issue. There is a fundamental problem where, for commands like ls, mv etc., there is a need for the user to be able to chose whether to expand glob pattern in strings or not. @Spickelbing suggests to have different kinds of quotes determining whether to expand glob patterns or not. I think this is not the best solution for three-ish reasons:

    1. It would be a huge breaking change. Of course, if there is a breaking change to make, we might as well do it before v1.0, but still...
    2. (extension of 1.) The glob-expanding type of quotes would be essentially reserved exclusively for glob patterns. Indeed, if a command accepts a string other than file names and the user has some * or [] in their input, the argument would be wrongly transformed if the user uses double quotes without escaping the problematic characters.
    3. In situation other than string literals passed to commands, it would require a kind of hack to specify whether to expand the glob pattern or not. Consider the following command
    ["[ab].zip", "*important* file.txt"] | each {|| cp $in "backup/"}
    

    Does the user want to execute cp for each glob pattern or each specific file (assuming both would apply) ? The hack would be to be explicit by typing ... cp $'($in)' ... or ... cp $"($in)" ..., but I don't find this particularly elegant (would that even work?).

    Or would the expansion be already done when the string is created? What would that data look like? A list? A special new expandedGlob type? What if the strings come from a command that doesn't care about whether its output is a glob pattern or not? I admit, I'm only a user and I don't know the inner working of Nu, so I don't know how it currently works, but what would that look like if I want to write a command that accepts glob patterns? In the current version, I would just accept any string and run it through glob in the command itself. (BTW I just tried that and glob "[[]ab[]].zip" failed, but that's certainly a separate issue)

    My proposition to solve this issue, as commented in #9790, would be to simply add a escape globe command that would escape glob character in strings. For example, ("[ab].zip" | escape globe) would yield the string "[[]ab[]].zip", which can be safely passed on to a command that takes in glob patterns. My example above would become

    # execute for each glob pattern (current behavior unchanged)
    ["[ab].zip", "*important* file.txt"] | each {|| cp $in "backup/"}
    
    # execute for those two specific files
    ["[ab].zip", "*important* file.txt"] | each {|| cp ($in | escape glob) "backup/"}
    

    Unless glob patterns become their own, separate data types, I think it's better to leave it to each to command to decide what to do with them.

  10. ChrisDenton commented on Aug 18, 2023

    @ChrisDenton
    Contributor

    This is just me thinking aloud but a big thing with nushell is that it's not just passing strings around. You pass around data, not strings. Therefore it would make sense to me to have a glob type that can be passed to anything (also a regex type, etc). Then a string is a string and a glob is a glob. There's no ambiguity and all commands are consistent, even if a glob is being piped through something else.

    Admittedly the problem with this line of thought is that people will want a short hand syntax for globbing in some contexts.

  11. fdncred commented on Aug 18, 2023

    @fdncred
    Contributor

    @ChrisDenton Sounds like a good idea. We do have a SyntaxShape::GlobPattern now. It's what cp, mv, rm use now. Maybe we've implemented it wrong.

    Looking now, I see:
    SyntaxShape::GlobPattern
    Expr::GlobPattern
    FlatShape::GlobPattern

    🤔

  12. bobhy commented on Sep 25, 2023

    @bobhy
    Contributor

    A thing about Nushell is that it's the individual commands, not the shell, which decides whether to treat an individual argument as a string or a glob. So, for example the parameters for cp command are:

    Parameters:
      source <glob>: the place to copy from
      destination <path>: the place to copy to
    

    That's 2 arguments, the first of which is a glob. Other commands do likewise, though they aren't always consistent in documenting this in help (see e.g, rm).

    Now, in looking into this, I do not see that the Nu file utilities that do globbing support any escape character to suppress the glob wildchar (like bash \). Let me look into this a bit more. I tried this:

    > touch 'a\*b'
    > ls
    ╭───┬──────┬──────┬──────┬────────────────╮
    │ # │ name │ type │ size │    modified    │
    ├───┼──────┼──────┼──────┼────────────────┤
    │ 0 │ a\*b │ file │  0 B │ 19 seconds ago │
    ╰───┴──────┴──────┴──────┴────────────────╯
    

    But I expected file to be a*b. I think this is a bug, will look deeper.

    In the meantime though, I think this means you just have to filter the glob wildcards out of your file names, or translate them to something innocuous.

  13. 4 remaining items

  14. bobhy commented on Oct 10, 2023

    @bobhy
    Contributor

    I believe this is fixed by #10557. I changed cp, rm and mv to try each argument first as a literal filename, only a glob if no such file is found.

  15. dedebenui commented on Oct 11, 2023

    @dedebenui

    glob *thing | action feels like nushell. action *thing* feels like oldshell.

    totally agreed, and that makes me change my mind compared to my comment from last August. If we want to implement that without breaking changes though, we're still left with the problem of what to do with glob patterns fed to these commands in the oldshell way. C.f. my comment above with the files ab, a*b and acb. What should rm a*b do?

    I think it would be elegant to have only the glob command expand glob patterns into lists. This would simplify @bobhy's PR (#10557) into having ls, mv, rm & co unambiguously accept only literal file names, as piped lists or arguments:

    rm a*b        # remove only `a*b
    `a*b` | rm    # remove only `a*b`
    glob a*b | rm # remove ab, a*b and acb
    
    # this is not strictly necessary to support
    rm (glob a*b) # remove ab, a*b and acb,
    

    That has the added benefit of easily merging several glob patterns for these commands:

    glob a*b | append (glob *.zip) | mv ./old_data/
    

    I totally follow @Ghoughpteighbteau's line of thinking about having a canonical way of doing thing, which is get-data | action coupled with a 1 command <=> 1 task principle (#10650). Accepting glob patterns in other commands for old time's sake seems to be a headache (c.f. all the issues and PRs on this problem). After solving #9116 and related issues, users could still easily redefine their own ls command if they want it to work in the oldshell style. One could even imagine including glob flavors (i.e. the current versions) of all these command in the standard library.

  16. Ghoughpteighbteau commented on Oct 11, 2023

    @Ghoughpteighbteau

    C.f. my comment above with the files ab, a*b and acb. What should rm a*b do?

    Any change to the behaviour as it exists right now is a breaking change 😔.

    I think it would be elegant to have only the glob command expand glob patterns into lists.

    Now this is what I think nushell 1.0 should look like. Maybe even have some syntactic sugar for the glob command wouldn't be amiss.

    But simply adding the capability for the filesystem commands to accept piped inputs of lists of strings, strings, our even lists of strings as arguments, is only expanding the signature of the current commands, and won't break existing scripts. (Unless someone depended on a filesystem command dieing when it got a list... God help that person. )

  17. Ghoughpteighbteau commented on Oct 11, 2023

    @Ghoughpteighbteau

    I'm torn on @bobhy 's change. On the one hand, this is a very ergonomic way to solve the problem, and avoids the majority of issues. On the other... gosh... it feels ugly to check if a file that matches the glob pattern exists, operate on that first, and if it doesn't then to glob. Honestly Why not just have a --no-glob arg instead rather than this transparent checking stuff?

    It feels like a potential footgun as well. Like... what if you're trying to delete a file with glob characters in it but you typo part of the name. Consider the highly realistic scenario of:

    ────┬───────────────────────────────────────────────┬─────
      # │                     name                      │ ... 
    ────┼───────────────────────────────────────────────┼───── 
      0 │ T*O*M*M*IE.doc                                │ ...
      1 │ TheOnlyMastercopyofMypoemsasaYouth.doc        │ ... 
    

    and I go to rm T*O*M*M*Y.doc because I forget Tommie has a weird way of spelling his name.

    Oh well I don't mean to sound too negative. There's always a trade off between convenience and safety. The scenarios where you'd get the footgun behaviour are rather contrived. I did just check and glob patterns like **TOMMY** are not valid. You need to have /'s when you use **'s. Files are forbidden from having slashes, so that glob pattern can only be activated if the file is literally named **.

    I think to avoid having to wait for nushell 1.0, this is an OK fix.

    I would prefer target | action. I think it should happen even if the PR gets merged. Maybe I should make it. I'm a little rusty with rust though 😆

  18. mb21 commented on Oct 18, 2023

    @mb21

    As a user, I agree with Ghoughpteighbteau's comment and dedebenui's comment.

    Any change to the behaviour as it exists right now is a breaking change

    Yes, but there's no way around that. Because the current behaviour is obviously unexpected to lots of users and the idea is to change that. So it's a breaking change.

    Only way around this would be to fix the tab-completion to complete to non-globbing patterns and see whether that fixes users' expectations.

    Or if the supported globs are fewer or at least more similar to existing shells (or at least escape using a backslash), then maybe it's good enough.

  19. bobhy commented on Oct 18, 2023

    @bobhy
    Contributor

    Nushell is still pre version 1.0, I don't regard "breaking change" as a major impediment.

    But I don't think PR #10557 actually makes a breaking change. At least, I don't think it breaks any scripts that were previously working.

    @dedebenui You ask what rm a*b should do. This PR makes that argument match not only patterns, but an individual file (with an unusual name) as well. The behavior was always dependent on which files are present in the directory, the PR makes it more comprehensive than it was.

  20. mb21 commented on Oct 23, 2023

    @mb21

    In Nushell, glob expansion is not done by the shell, but by the individual programs. Is there a documented reason for that decision? It's kind of handy for things like pandoc *.md But if it's decided to keep it that way, ls, rm, etc. should at least all implement this the same way, by sharing the same utility function. And documentation should be aligned, the different commands use glob, sometimes string and sometimes even path in their docs:

    help ls:
      pattern <string>
    
    help rm:
      filename <glob>: the file or files you want to remove
      ...rest <glob>: additional file path(s) to remove
    
    help cp:
      ...paths <path>: Copy SRC file/s to DEST
    
  21. added a commit that references this issue on Jan 26, 2024
    d646903
  22. added this to the v0.90.0 milestone on Jan 26, 2024
  23. added a commit that references this issue on Feb 20, 2024
    549cee9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A:file-systemA:globA:quoting-expansioncategory:enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions