8000 crates/minimal{2,d}: scaffold binary crates for Minimal One by twitchyliquid64 · Pull Request #227 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,085 changes: 1,064 additions & 21 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ members = [
"crates/ot",
"crates/orchestrator",
"crates/minimal",
"crates/minimal2",
"crates/minimald",
"crates/remote-client",
"crates/remote-proto",
"crates/sandbox2",
Expand Down Expand Up @@ -73,6 +75,7 @@ prost = "0.14"
prost-build = "0.14"
prost-types = "0.14"
resolv-conf = "0.7"
russh = "0.61"
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved
serde_json = { version = "1.0" }
serial_test = "3"
sha2 = "0.11"
Expand Down
18 changes: 18 additions & 0 deletions crates/minimal2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "minimal2"
version = "0.0.1"
edition.workspace = true
publish.workspace = true

[dependencies]
clap.workspace = true
clap_complete.workspace = true
dirs.workspace = true
futures.workspace = true

tokio.workspace = true
tokio-util.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true

ot.workspace = true
26 changes: 26 additions & 0 deletions crates/minimal2/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::process::Command;
fn main() {
let output = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved

let is_clean = std::process::Command::new("git")
.args(["status", "--porcelain=v1"])
.output()
.map(|o| o.stdout.is_empty())
.unwrap_or(false);
Comment on lines +10 to +14
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Check git command success before reading stdout.

Line 13 checks o.stdout.is_empty() but doesn't verify o.status.success(). If the git command fails, stdout might be empty but that doesn't mean the tree is clean—it means the command failed.

🛡️ Proposed fix
     let is_clean = std::process::Command::new("git")
         .args(["status", "--porcelain=v1"])
         .output()
-        .map(|o| o.stdout.is_empty())
+        .map(|o| o.status.success() && o.stdout.is_empty())
         .unwrap_or(false);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let is_clean = std::process::Command::new("git")
.args(["status", "--porcelain=v1"])
.output()
.map(|o| o.stdout.is_empty())
.unwrap_or(false);
let is_clean = std::process::Command::new("git")
.args(["status", "--porcelain=v1"])
.output()
.map(|o| o.status.success() && o.stdout.is_empty())
.unwrap_or(false);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/minimal2/build.rs` around lines 10 - 14, The current is_clean
computation reads o.stdout.is_empty() without verifying the git Command
succeeded; change the mapping for the Command::output() result used to set
is_clean (the closure handling the Output from Command::new("git")...output())
to first test o.status.success() and only then check o.stdout.is_empty(), e.g.
produce true only when both o.status.success() and o.stdout.is_empty() are true,
and treat failures (non-success status or Err from output()) as not clean.

if !is_clean && std::env::var("PROFILE").unwrap() == "release" {
println!("cargo::warning=Building a release binary from an unclean working tree!!");
println!("cargo::warning=Always build production binaries from a clean checkout.");
}

println!(
"cargo:rustc-env=LONG_VERSION={} ({}{})",
std::env::var("CARGO_PKG_VERSION").unwrap().as_str(),
if is_clean { "" } else { "dirty " },
git_hash.strip_suffix("\n").unwrap(),
);
}
66 changes: 66 additions & 0 deletions crates/minimal2/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//! The minimal CLI which pairs/talks-with minimald.

use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use std::path::PathBuf;
use tracing_subscriber::{EnvFilter, fmt, prelude::*};

#[derive(Parser)]
#[command(name = "minimal", version = env!("CARGO_PKG_VERSION"), long_version = env!("LONG_VERSION"))]
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved
#[command(about = "The Minimal CLI")]
struct Cli { 8000
#[command(subcommand)]
command: Command,

#[command(flatten)]
global_args: GlobalArgs,
}

#[derive(Subcommand)]
enum Command {
/// Generate shell completion script
#[command(
long_about = "Generate a shell tab-completion script for the minimal CLI.\nSupported shells include bash, zsh, elvish and fish.\n\n source <(minimal completions bash)"
)]
Completions(CompletionsArgs),
}

#[derive(Debug, clap::Args)]
struct CompletionsArgs {
/// The shell type for a CLI completion script should be printed
#[arg(value_parser)]
shell: Shell,
}

/// Shared arguments all subcommands
#[derive(Debug, Args)]
pub struct GlobalArgs {
/// Override the base directory used for operations (default: ~/.cache/minimal)
#[arg(long)]
minimal_dir: Option<PathBuf>,
}

#[tokio::main]
async fn main() -> Result<(), ()> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Use application-grade error type for main.

Result<(), ()> drops error context and makes propagation/diagnostics weak; prefer anyhow::Result<()> at app boundaries.

Suggested fix
+use anyhow::Result;
@@
-async fn main() -> Result<(), ()> {
+async fn main() -> Result<()> {

As per coding guidelines, "In application crates, use anyhow::Result and attach .context(...) / .with_context(|| ...) at layer boundaries".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async fn main() -> Result<(), ()> {
use anyhow::Result;
async fn main() -> Result<()> {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/minimal2/src/main.rs` at line 44, The async function signature `async
fn main() -> Result<(), ()>` should return an application-grade error type;
change it to use `anyhow::Result<()>` (i.e., `async fn main() ->
anyhow::Result<()>`) and update call sites to propagate errors with
`.context(...)` or `.with_context(...)` at boundaries; also add the `anyhow`
dependency to the crate if missing and ensure any `Err(())` or `Err` returns are
converted to context-rich `anyhow::Error` values before propagating from `main`.

let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| {
EnvFilter::new("info")
.add_directive("topiary=off".parse().unwrap())
.add_directive("libcgroups=off".parse().unwrap())
});

tracing_subscriber::registry()
.with(fmt::layer().with_writer(ot::StdoutWriter::new))
.with(filter)
.init();

let cli = Cli::parse();

match cli.command {
Command::Completions(CompletionsArgs { shell }) => {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
Ok(())
}
}
}
20 changes: 20 additions & 0 deletions crates/minimald/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "minimald"
version = "0.0.1"
edition.workspace = true
publish.workspace = true

[dependencies]
clap.workspace = true
clap_complete.workspace = true
dirs.workspace = true
futures.workspace = true

russh.workspace = true
serde.workspace = true
tokio.workspace = true
tokio-util.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true

ot.workspace = true
26 changes: 26 additions & 0 deletions crates/minimald/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::process::Command;
fn main() {
let output = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved

let is_clean = std::process::Command::new("git")
.args(["status", "--porcelain=v1"])
.output()
.map(|o| o.stdout.is_empty())
.unwrap_or(false);
if !is_clean && std::env::var("PROFILE").unwrap() == "release" {
println!("cargo::warning=Building a release binary from an unclean working tree!!");
println!("cargo::warning=Always build production binaries from a clean checkout.");
}

println!(
"cargo:rustc-env=LONG_VERSION={} ({}{})",
std::env::var("CARGO_PKG_VERSION").unwrap().as_str(),
if is_clean { "" } else { "dirty " },
git_hash.strip_suffix("\n").unwrap(),
);
}
81 changes: 81 additions & 0 deletions crates/minimald/src/connection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use russh::server::{Config as RuConfig, RunningSession};
pub use std::sync::{Arc, Mutex};
use tokio::net::UnixStream;

/// The auth state of the SSH connection.
#[derive(Debug, Default, PartialEq, Eq)]
pub enum Auth {
#[default]
Pending,
Local,
}

/// Represents the SSH connection. Lives for the
/// lifetime of the connection.
#[derive(Debug, Default)]
#[allow(dead_code)]
pub struct Connection {
pub auth: Auth,

/// The username given via SSH. Not populated till the client
/// authenticates the connection.
pub ssh_username: Option<String>,
}

impl Connection {
pub(crate) async fn from_socket(
s: UnixStream,
c: Arc<RuConfig>,
was_local_uds: bool,
) -> (ConnectionHandle, RunningSession<ConnectionHandler>) {
let h = ConnectionHandle(Arc::new(Mutex::new(Self {
auth: if was_local_uds {
Auth::Local
} else {
Auth::Pending
},
..Default::default()
})));

(
h.clone(),
russh::server::run_stream(c, s, ConnectionHandler(h))
.await
.unwrap(),
)
Comment on lines +42 to +45
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Protocol setup error is unwrapped and can panic per connection.

Return/map this error into ConnectionError instead of panicking from from_socket.

As per coding guidelines, “Only use unwrap() and panic!() for broken invariants… never for recoverable conditions.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/minimald/src/connection.rs` around lines 42 - 45, The call to
russh::server::run_stream(...).await.unwrap() inside from_socket can panic
per-connection; change from_socket to propagate that error by replacing the
unwrap with proper error mapping/return: await the future, handle the Result
from russh::server::run_stream(...).await and convert its Err into your
ConnectionError (e.g. with map_err or ? after an Into<ConnectionError>
conversion), so ConnectionHandler and from_socket return Result<...,
ConnectionError> instead of panicking. Locate the unwrap in from_socket and
replace it with a mapped return of ConnectionError referencing
russh::server::run_stream and ConnectionHandler.

}
}

/// A thread-safe handle to the connection.
#[derive(Clone)]
pub struct ConnectionHandle(Arc<Mutex<Connection>>);

/// An error when handling the SSH connection.
#[derive(Debug)]
#[allow(dead_code)]
pub enum ConnectionError {
Protocol(russh::Error),
}

impl From<russh::Error> for ConnectionError {
fn from(value: russh::Error) -> Self {
ConnectionError::Protocol(value)
}
}

/// A [`russh::server::Handler`] for a [`Connection`].
pub struct ConnectionHandler(ConnectionHandle);

impl russh::server::Handler for ConnectionHandler {
type Error = ConnectionError;

async fn auth_none(&mut self, user: &str) -> Result<russh::server::Auth, Self::Error> {
let mut s = self.0.0.lock().unwrap();
if s.auth == Auth::Local {
s.ssh_username = Some(user.to_string());
Ok(russh::server::Auth::Accept)
} else {
Ok(russh::server::Auth::reject())
}
}
}
Loading
Loading
0