rusttrunk-rs

Rust Trunk can't get environment variables with powershell


While trying to use tailwindcss, some tutorial I found online uses this hook configuration:

[[hooks]]
stage = "build"
command = "sh"
command_arguments = ["-c", "tailwind -i ./src/tailwind.css -o $TRUNK_STAGING_DIR/tailwind.css"]

I do not have sh available on this machine so I tried installing the tailwind cli and using it as the command:

[[hooks]]
stage = "build"
command = "tailwindcss"
command_arguments = ["-i", "./src/tailwind.css", "-o", "$TRUNK_STAGING_DIR/tailwind.css"]

This does execute, but instead of creating the file in the trunk staging directory, it created a new folder literally called $TRUNK_STAGING_DIR in my working directory.

So, since I am running this from a Powershell terminal, I tried $($env:TRUNK_STAGING_DIR) to access the environment variable. But of course I am getting an error.

[[hooks]]
stage = "build"
command = "tailwindcss"
command_arguments = ["-i", "./src/tailwind.css", "-o", "$($env:TRUNK_STAGING_DIR)/tailwind.css"]
[Error: ENOENT: no such file or directory, mkdir 'C:\project_path\$($Env:TRUNK_STAGING_DIR)'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'mkdir',
  path: 'C:\\project_path\\$($Env:TRUNK_STAGING_DIR)'
}

Is this a bug? Is there something else I should know to make this work?


Solution

  • The $TRUNK_STAGING_DIR syntax for environment variables is specific to the sh shell and its cousins. When you execute tailwindcss directly, the only things that could expand the environment variable are Trunk or Tailwind, since this string never touches your current shell. It would be unusual for Tailwind to do it, and it's apparent that Trunk doesn't do it. If you want to use pwsh's expansion, you can use it in place of sh:

    [[hooks]]
    stage = "build"
    command = "pwsh"
    command_arguments = ["-Command", "tailwindcss -i ./src/tailwind.css -o $env:TRUNK_STAGING_DIR/tailwind.css"]
    

    pwsh is for PowerShell Core. If you're using Windows PowerShell instead, change the name to powershell. Or if you want to use cmd, the environment variable syntax is a little different:

    [[hooks]]
    stage = "build"
    command = "cmd"
    command_arguments = ["/C", "tailwindcss -i ./src/tailwind.css -o %TRUNK_STAGING_DIR%/tailwind.css"]