tauri icon indicating copy to clipboard operation
tauri copied to clipboard

[bug] Tauri resources work in dev but not build

Open colin99d opened this issue 2 years ago • 15 comments

Describe the bug

I have added a folder created with pyinstaller to my resources, then I use command::new() to run the main binary inside this folder. When I use cargo tauri dev everything works fine, but when I run cargo tauri build I get the below error:

Screenshot 2022-11-29 at 7 29 06 PM

Reproduction

Add in the resources item below, then try to run cargo tauri build (cargo tauri dev runs fine):

{
  "build": {
    "beforeDevCommand": "npm run dev",
    "beforeBuildCommand": "npm run build",
    "devPath": "http://localhost:1420",
    "distDir": "../dist"
  },
  "package": {
    "productName": "Application",
    "version": "0.0.0"
  },
  "tauri": {
    "allowlist": {
      "all": true
    },
    "bundle": {
      "active": true,
      "category": "Finance",
      "copyright": "",
      "deb": {
        "depends": []
      },
      "externalBin": [],
      "icon": [
        "icons/32x32.png",
        "icons/128x128.png",
        "icons/[email protected]",
        "icons/icon.icns",
        "icons/icon.ico"
      ],
      "identifier": "",
      "longDescription": "",
      "macOS": {
        "entitlements": null,
        "exceptionDomain": "",
        "frameworks": [],
        "providerShortName": null,
        "signingIdentity": null
      },
      "resources": ["/Users/colindelahunty/terminalpro-poc/src-tauri/pyfolder/*"],
      "shortDescription": "",
      "targets": "all",
      "windows": {
        "certificateThumbprint": null,
        "digestAlgorithm": "sha256",
        "timestampUrl": ""
      }
    },
    "security": {
      "csp": null
    },
    "updater": {
      "active": false
    },
    "windows": [
      {
        "fullscreen": false,
        "height": 800,
        "resizable": true,
        "title": "Application",
        "width": 1000
      }
    ]
  }
}

Expected behavior

I would expect cargo to function the same in dev and build.

Platform and versions

Environment › OS: Mac OS 13.0.0 X64 › Node.js: 19.1.0 › npm: 8.19.3 › pnpm: Not installed! › yarn: 1.22.19 › rustup: 1.25.1 › rustc: 1.65.0 › cargo: 1.65.0 › Rust toolchain: stable-aarch64-apple-darwin

Stack trace

No response

Additional context

I know technically I should use pyinstaller onefile, and then use sidecar, BUT my program is really big. Using --onefile brings the time the application has to wait before it starts running from 8 seconds to 84 seconds, which is something I would like to avoid.

colin99d avatar Nov 30 '22 00:11 colin99d

please provide a minimal repro

amrbashir avatar Nov 30 '22 00:11 amrbashir

I created one locally but I am having an issue pushing the binary files to Github. Do you have any advice?

colin99d avatar Nov 30 '22 02:11 colin99d

But the only changes I made to a cargo create-tauri-app are the following: Changed tauri.conf.json to have this: "resources": ["pyfolder/*"], Made main.rs this:

#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]
use tauri::api::process::{Command, CommandEvent};

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn main() {
    tauri::Builder::default()
        .setup(|_| {
            tauri::async_runtime::spawn(async move {
                let (mut rx, _child) = Command::new("pyfolder/OpenBBTerminal")
                    .args(&["rest"])
                    .spawn()
                    .expect("Failed to spawn node");

                while let Some(event) = rx.recv().await {
                    if let CommandEvent::Stdout(line) = event {
                        println!("{}", line);
                    }
                }
            });

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Lastly I add a pyfolder folder containing output from the pyinstaller command and add it in src-tauri

In this example cargo tauri dev works fine, and cargo tauri build gives the same error.

colin99d avatar Nov 30 '22 03:11 colin99d

try using https://docs.rs/tauri/latest/tauri/struct.PathResolver.html#method.resolve_resource to get a path that you can use with Command::new

amrbashir avatar Nov 30 '22 10:11 amrbashir

And try cargo tauri build --verbose to get a (hopefully) more helpful build error.

FabianLars avatar Nov 30 '22 11:11 FabianLars

#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]
use tauri::api::process::{Command, CommandEvent};

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn main() {
    tauri::Builder::default()
        .setup(move |app| {
            let resource_path = app.path_resolver()
              .resolve_resource("pyfolder/OpenBBTerminal")
              .expect("failed to resolve resource dir");
            println!("{}", resource_path.display());
            tauri::async_runtime::spawn(async move {
                let (mut rx, _child) = Command::new(resource_path.as_path().to_str().unwrap())
                    .args(&["rest"])
                    .spawn()
                    .expect("Failed to spawn node");

                while let Some(event) = rx.recv().await {
                    if let CommandEvent::Stdout(line) = event {
                        println!("{}", line);
                    }
                }
            });

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

I switched to using the resolve_resource command, and it is still working in dev but not build.

colin99d avatar Nov 30 '22 13:11 colin99d

So it actually works now, but still shows the same error which is weird. Should I just ignore the error, or could this cause issues in the future? Also, if I run in verbose mode no error is thrown.

Output of cargo tauri build (error, but everything works):

Screenshot 2022-11-30 at 8 24 16 AM

Output of `cargo tauri build --verbose (no error, everything works):

Screenshot 2022-11-30 at 8 31 27 AM

colin99d avatar Nov 30 '22 13:11 colin99d

how the hell does it work fine with the verbose flag but not without it 😂

FabianLars avatar Nov 30 '22 14:11 FabianLars

The funniest part it gives an error, but works fine.

colin99d avatar Nov 30 '22 14:11 colin99d

I have a similar issue. I'm using sidecar to run a binary app which need to read a config json file from the resource directory. I'm invoking my binary from Javascript side following the two embedding guides. Everything works fine using npm run tauri dev but the binary failed to find the config json file in the resource if I build the app.

const configPath = await resolveResource('configs/cool-config.json')
console.log(configPath)

const command = Command.sidecar('binaries/mycoolapp', [configPath])
const output = await command.execute()

Using npm run tauri build -- --debug console log shows the correct path to the file. On the console output debug screen, the binary returns no such file or directory. Digging into the object tree I see these errors:

constructor: function()
arguments: TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context.
assign(target, ...sources)
caller: TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context.
create(prototype, [propertiesObject])

Also passing the absolute path in the sidecar command works, which I really don't want to do because it will break development or if user runs the app from a different location.

const command = Command.sidecar('binaries/mycoolapp', ['/Applications/sidecar.app/Contents/Resources/configs/cool-config.json'])

Any help would be appreciated.

kalmufti avatar May 04 '23 18:05 kalmufti

@kalmufti you could try using https://tauri.app/v1/api/js/path#resolveresource or https://tauri.app/v1/api/js/path#resourcedir

amrbashir avatar May 06 '23 23:05 amrbashir

@amrbashir I'm using resolveResource see first code snippet. The console.log message shows the correct path to the file. It's just when building, looks like the app enforce something that makes the binary losses context access to path. Can't find out what's going on, I've even allowed access to everything from the tauri config file.

kalmufti avatar May 08 '23 19:05 kalmufti

Win 11 rustc 1.69.0 Tauri 1.3

"fs": {
        "readDir": true,
        "readFile": true,
        "scope": ["$HOME/models", "$RESOURCE/python/*"]
      },
      
 "bundle": {
      "resources": ["python/*"]
    },

Disclaimer** I'm not a Rust developer. I'm a JS / React frontend developer

I'm trying to include a folder but nothing seems to work. I've put the 'python' folder in the root, root/public, root/src-tauri. At my wit's end.

`  process didn't exit successfully: `C:\Users\Roscoe\Documents\dev\agent AI\src-tauri\target\debug\build\agent_ai-e15fcefdac8ee907\build-script-build` (exit code: 1)
  --- stdout
  cargo:rerun-if-env-changed=TAURI_CONFIG
  cargo:rerun-if-changed=tauri.conf.json
  cargo:rustc-cfg=desktop
  cargo:rustc-cfg=dev
  path matching python/* not found.`

I'm sure I'm making some basic error relating to path but can't figure it out.

roscoevanderboom avatar Jun 04 '23 07:06 roscoevanderboom

@roscoevanderboom the resources path is relative to the tauri.conf.json file. Also try manually restarting the CLI after changing the config and don't rely on the dev watcher to restart it.

FabianLars avatar Jun 04 '23 12:06 FabianLars

@FabianLars Thanks for the reply. The folder is relative to the tauri.conf.json. I've restarted the CLI, tried regular cmd, also tried moving the folder into wsl and using Ubuntu cli. Always getting the same error. I've also checked out awesome-tauri to find other apps that include resources, and followed their configs.

roscoevanderboom avatar Jun 05 '23 10:06 roscoevanderboom