Skip to content

Instantly share code, notes, and snippets.

@hashar
Created March 5, 2025 17:07
Show Gist options
  • Save hashar/7342df010edc00bfca2ff35c7faa575d to your computer and use it in GitHub Desktop.
Save hashar/7342df010edc00bfca2ff35c7faa575d to your computer and use it in GitHub Desktop.
bash2rust by mistral 3
/// The bash version https://github.com/hashar/alix/blob/123c2f01360f2619ab4abbe49adeb6dd32dbccd8/bin/docker
/// Converted using Mistral Small 3
/// Prompt:
/// port the following bash script to rust. Give comments explaining the mapping from bash to rust: <paste of above script>
///
/// Answer:
/// Porting the given Bash script to Rust involves several steps,
/// including handling command-line arguments, checking for specific conditions,
/// and executing external commands. Below is the Rust equivalent of the provided
/// Bash script with comments explaining the mapping from Bash to Rust:
use std::env;
use std::process::{Command, exit};
use std::ffi::OsString;
/// Function to check if a needle is in a haystack array
fn in_array(needle: &str, haystack: &[&str]) -> bool {
haystack.contains(&needle)
}
fn main() {
// Get the command-line arguments
let args: Vec<String> = env::args().collect();
// Check if the first argument is "compose"
if args.get(1).map_or(false, |arg| arg == "compose") {
// Shift the arguments to remove the "compose" argument
let docker_compose_args: Vec<&str> = args.iter().skip(2).map(AsRef::as_ref).collect();
// Execute docker-compose with the remaining arguments
let status = Command::new("docker-compose")
.args(docker_compose_args)
.status()
.expect("Failed to execute docker-compose");
exit(status.code().unwrap_or(1));
}
// Check if DOCKER_BUILDKIT is set to 1 or if "buildx" is in the arguments
let docker_buildkit = env::var("DOCKER_BUILDKIT").unwrap_or_else(|_| "0".to_string());
if docker_buildkit == "1" || in_array("buildx", &args[1..]) {
// Filter out the "buildx" argument
let mut args = args.iter().skip(1).map(AsRef::as_ref).collect::<Vec<&str>>();
args.retain(|&arg| arg != "buildx");
// Check if there are any remaining arguments
if args.is_empty() {
// Execute docker-buildx without arguments
let status = Command::new("/usr/libexec/docker/cli-plugins/docker-buildx")
.status()
.expect("Failed to execute docker-buildx");
exit(status.code().unwrap_or(1));
} else {
// Execute docker-buildx with the remaining arguments
let status = Command::new("/usr/libexec/docker/cli-plugins/docker-buildx")
.args(args)
.status()
.expect("Failed to execute docker-buildx");
exit(status.code().unwrap_or(1));
}
} else {
// Execute podman with the remaining arguments
let podman_args: Vec<&str> = args.iter().skip(1).map(AsRef::as_ref).collect();
let status = Command::new("podman")
.args(podman_args)
.status()
.expect("Failed to execute podman");
exit(status.code().unwrap_or(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment