|
| 1 | +# Helper function for `path with` commands |
| 2 | +def with-field [field: string, value: string] { |
| 3 | + path parse |
| 4 | + | update $field $value |
| 5 | + | path join |
| 6 | +} |
| 7 | + |
| 8 | +# Replace extension of input file paths. |
| 9 | +# |
| 10 | +# Note that it doesn't change the file name locally. |
| 11 | +# |
| 12 | +# # Example |
| 13 | +# - setting path ext to `rs` |
| 14 | +# ```nushell |
| 15 | +# > "ab.txt" | path with-extension "rs" |
| 16 | +# ab.rs |
| 17 | +# > "ab.txt" | path with-extension ".rs" |
| 18 | +# ab.rs |
| 19 | +# |
| 20 | +# - setting a list of input path ext to `rs` |
| 21 | +# > ["ab.txt", "cd.exe"] | path with-extension "rs" |
| 22 | +# ╭───┬──────────╮ |
| 23 | +# │ 0 │ ab.rs │ |
| 24 | +# │ 1 │ cd.rs │ |
| 25 | +# ╰───┴──────────╯ |
| 26 | +# ``` |
| 27 | +export def with-extension [ext: string] { |
| 28 | + let path = $in |
| 29 | + let ext_trim = if $ext starts-with "." { |
| 30 | + $ext | str substring 1.. |
| 31 | + } else { |
| 32 | + $ext |
| 33 | + } |
| 34 | + $path | with-field extension $ext_trim |
| 35 | +} |
| 36 | + |
| 37 | +# Replace stem of input file paths. |
| 38 | +# |
| 39 | +# Note that it doesn't change the file name locally. |
| 40 | +# |
| 41 | +# # Example |
| 42 | +# - replace stem with "share" |
| 43 | +# ```nushell |
| 44 | +# > "/usr/bin" | path with-stem "share" |
| 45 | +# /usr/share |
| 46 | +# |
| 47 | +# - replace stem with "nushell" |
| 48 | +# > ["/home/alice/", "/home/bob/secret.txt"] | path with-stem "nushell" |
| 49 | +# ╭───┬───────────────────────╮ |
| 50 | +# │ 0 │ /home/nushell │ |
| 51 | +# │ 1 │ /home/bob/nushell.txt │ |
| 52 | +# ╰───┴───────────────────────╯ |
| 53 | +# ``` |
| 54 | +export def with-stem [stem: string] { with-field stem $stem } |
| 55 | + |
| 56 | +# Replace parent field of input file paths. |
| 57 | +# |
| 58 | +# # Example |
| 59 | +# - replace parent path with `/usr/share` |
| 60 | +# ```nushell |
| 61 | +# > "/etc/foobar" | path with-parent "/usr/share/" |
| 62 | +# /usr/share/foobar |
| 63 | +# |
| 64 | +# - replace parent path with `/root/` for all filenames in list |
| 65 | +# > ["/home/rose/meow", "/home/fdncred/"] | path with-parent "/root/" |
| 66 | +# ╭───┬────────────╮ |
| 67 | +# │ 0 │ /root/meow │ |
| 68 | +# │ 1 │ /root/spam │ |
| 69 | +# ╰───┴────────────╯ |
| 70 | +# ``` |
| 71 | +export def with-parent [parent: string] { with-field parent $parent } |
0 commit comments