How to get path.join in Rust? - node.js

How do I write the path.join in Rust. I tried multiple examples but couldn't get it.
const exeDirectory = path.join(__dirname, '..', 'bin', 'openvpn.exe');
const processFile = path.join(__dirname, '..', '1');
I want to convert these lines of JS into Rust.

Use Path which has the .join method
Path::new("..").join("bin").join("openvpn.exe");

I may be missing something but have you looked at Path::join, and PathBuf::push linked from it?
let exe_directory = Path::new(dirname).join("..").join("bin").join("openvpn.exe");
println!("{:?}", exe_directory);
let mut exe_directory = PathBuf::new();
exe_directory.push(dirname);
exe_directory.push("..");
exe_directory.push("bin");
exe_directory.push("openvpn.exe");
println!("{:?}", exe_directory);
Playground link

Another option is collecting an iterator of string into a PathBuf:
let path: PathBuf = ["..", "bin", "openvpn.exe"].iter().collect();
This is equivalent to creating a new PathBuf and calling .push() for each string in the iterator. To add multiple new components to an existing PathBuf, you can use the extend() method:
let mut path = PathBuf::from(dir_name);
path.extend(&["..", "bin", "openvpn.exe"]);

Related

What is the best way to check if an executable exists for `std::process::Command`?

I want to create a std::process::Command and check whether an executable actually exists at that location before actually spawning the Command later. What would be the pragmatic way to do this?
I have this code:
let c = std::process::Command::new("my_exe");
// something here
c.spawn().unwrap();
I want to be able to validate the my_exe path when creating the Command and then spawn way later.
check whether an executable actually exists at that location before actually spawning the Command.
Don't as that's a time-of-check to time-of-use race condition. Instead, check the error value from executing the Command: Check if a command is in PATH/executable as process.
If you want to check if a file is present in the working directory, you can use Path::exists, as described in How to check whether a path exists?.
Also, Command::spawn() takes a mutable reference to self so c needs to be mutable.
use std::path::Path;
use std::process::Command;
if Path::new("PATH_TO_EXECUTABLE").exists() {
let mut c = Command::new("PATH_TO_EXECUTABLE");
// do something
c.spawn().unwrap();
}
Use the is_executable crate:
use is_executable::IsExecutable;
use std::fs;
let paths = fs::read_dir("./").unwrap();
for path in paths {
let file_path = path.unwrap().path();
if file_path.is_executable() {
println!("File: {:?} is executable!", file_path);
} else {
println!("File: {:?} is _not_ executable!", file_path);
}
}

Rust lightningcss minify

Trying to figure out how to use minify from lightningcss. Here's my code
let fs = FileProvider::new();
let mut bundler = Bundler::new(&fs, None, ParserOptions::default());
let stylesheet = bundler.bundle(Path::new("./assets/css/global.css")).unwrap();
stylesheet.minify(MinifyOptions::default());
println!("{}", stylesheet.to_css(PrinterOptions::default()).unwrap().code);
If I try to print the unwrapped version of the minified output that is empty.
taken more from here https://docs.rs/lightningcss/1.0.0-alpha.34/lightningcss/stylesheet/struct.StyleSheet.html
And the question: how do I use the minify output?

Rust and Rocket: retrieve raw file content from form-data

Working with Rust and Rocket here. I have an endpoint to upload one file at a time with form-data:
use rocket::form::{Form, FromForm};
use rocket::fs::TempFile;
use std::ffi::OsStr;
use std::path::{Path};
use uuid::Uuid;
#[post("/file_upload", format = "multipart/form-data", data = "<form>")]
pub async fn file_upload(mut form: Form<Upload<'_>>) -> std::io::Result<String> {
// Get raw file
let file_name = form.file.raw_name().unwrap().dangerous_unsafe_unsanitized_raw().as_str();name
// Get extension of file name
let extension = Path::new(file_name).extension().and_then(OsStr::to_str).unwrap();
// Generate new UUID
let id: String = Uuid::new_v4().to_string();
// Build path to save file
let file_path = String::from("media/temp_files") + "/" + &id + "." + extension;
// Save file
form.file.persist_to(file_path).await?;
Ok(String::from("Ok"))
}
This works, but I am mixing persistence, business logic and http infrastructure in the same module.
I want to rely on Rocket only to retrieve the file stream and metadata (file name, size and content type), and pass it to another function that would be in charge or validation, image processing, etc.
I have access to the metadata, but I don't know how to retrieve the Buffered content from the TempFile struct.
// rocket-0.5.0-rc.2/src/fs/temp_file.rs
[…]
pub enum TempFile<'v> {
#[doc(hidden)]
File {
file_name: Option<&'v FileName>,
content_type: Option<ContentType>,
path: Either<TempPath, PathBuf>,
len: u64,
},
#[doc(hidden)]
Buffered {
content: &'v str,
}
}
[…]
I don't see any method returning it.Is there any method I'm missing to retrieve the raw file content? Or maybe there is a different struct/trait in Rocket to achieve this.

Is it possible to access current file name?

Is it possible to access current file name in Rust by
// main.rs
fn main() {
println!("filename: {}", FILE_NAME);
}
?
(This program should print filename: main.rs)
You can use the std::file macro to get the current source filename at the compile time.
let this_file = file!();
If you want to remove the path from the returned filename, you can construct a Path with it and call the file_name method.
let filename_only = Path::new(this_file).file_name().and_then(|s| s.to_str()).unwrap();
Playground

Convert filename to URI in Rust

In Python, we have:
pathlib.Path("~/hello/world").expanduser().as_uri()
# or
pathlib.Path("/hello/world").as_uri()
In C, we have:
char* uri = g_filename_to_uri("/hello/world", NULL, NULL)
// ...
g_free(uri)
What is the Rust's equivalent?
The from_file_path method from the url crate seems to provide the functionality you're after:
let url = Url::from_file_path("/hello/world").unwrap();
println!("{}", url); // prints file:///hello/world
Playground

Resources