Skip to content

Commit

Permalink
fix: 🚨 fix many clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
Jisu-Woniu committed Apr 15, 2024
1 parent a25ce88 commit 271890e
Show file tree
Hide file tree
Showing 22 changed files with 67 additions and 16 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ version = "0.1.0"
authors = ["NJUPT-SAST"]
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/NJUPT-SAST/rsjudge"

# clap requires Rust 1.74+ to work
rust-version = "1.74"
Expand All @@ -29,6 +30,7 @@ version.workspace = true
authors.workspace = true
edition = "2021"
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "online judge sandbox server in Rust"

Expand Down
2 changes: 2 additions & 0 deletions crates/rsjudge-grpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "gRPC server for rsjudge"

[package.metadata.cargo-machete]
ignored = ["prost", "prost-types"]
Expand Down
4 changes: 4 additions & 0 deletions crates/rsjudge-grpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ use crate::{proto::judge_service_server::JudgeServiceServer, server::JudgeServer
mod proto;
mod server;

/// Serve the gRPC judge server on the given address.
///
/// # Errors
///
pub async fn serve(addr: SocketAddr) -> Result<(), Error> {
Server::builder()
.add_service(JudgeServiceServer::new(JudgeServerImpl))
Expand Down
2 changes: 1 addition & 1 deletion crates/rsjudge-grpc/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::proto::{
};

#[derive(Debug, Default)]
pub(crate) struct JudgeServerImpl;
pub struct JudgeServerImpl;

#[async_trait]
impl JudgeService for JudgeServerImpl {
Expand Down
1 change: 1 addition & 0 deletions crates/rsjudge-judger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
Expand Down
3 changes: 2 additions & 1 deletion crates/rsjudge-judger/src/comparer/default_comparer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ use std::io;

use async_trait::async_trait;
use futures::try_join;
use rsjudge_utils::trim::trim_ascii_end;
use rsjudge_utils::trim_ascii_end;
use tokio::io::{AsyncBufReadExt as _, AsyncRead, BufReader};

use crate::{CompareResult, Comparer};

/// A default comparer implementation with basic configurations.
#[must_use = "Comparer makes no sense if it is not used"]
pub struct DefaultComparer {
ignore_trailing_whitespace: bool,
ignore_trailing_newline: bool,
Expand Down
6 changes: 4 additions & 2 deletions crates/rsjudge-judger/src/comparer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
// SPDX-License-Identifier: Apache-2.0

pub mod default_comparer;
mod default_comparer;

use std::io;

use async_trait::async_trait;
use tokio::io::AsyncRead;

#[derive(Debug, PartialEq)]
pub use self::default_comparer::DefaultComparer;

#[derive(Debug, PartialEq, Eq)]
pub enum CompareResult {
Accepted,
WrongAnswer,
Expand Down
2 changes: 1 addition & 1 deletion crates/rsjudge-judger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

pub mod comparer;

pub use comparer::{default_comparer::DefaultComparer, CompareResult, Comparer};
pub use comparer::{CompareResult, Comparer, DefaultComparer};
1 change: 1 addition & 0 deletions crates/rsjudge-rest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
Expand Down
4 changes: 4 additions & 0 deletions crates/rsjudge-rest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ use std::{io, net::SocketAddr};
use axum::{routing::get, Router};
use tokio::net::TcpListener;

/// Serve the REST API at the given address.
///
/// # Errors
///
pub async fn serve(addr: SocketAddr) -> io::Result<()> {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = TcpListener::bind(addr).await?;
Expand Down
1 change: 1 addition & 0 deletions crates/rsjudge-runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "Command runner for rsjudge"

Expand Down
2 changes: 1 addition & 1 deletion crates/rsjudge-runner/examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rsjudge_runner::{
use uzers::{get_current_uid, get_user_by_uid};
fn main() -> anyhow::Result<()> {
let self_output = Command::new("id")
.run_as(&get_user_by_uid(get_current_uid()).ok_or(anyhow!("invalid user"))?)?
.run_as(&get_user_by_uid(get_current_uid()).ok_or_else(|| anyhow!("invalid user"))?)?
.output()?;
println!("{}", String::from_utf8_lossy(&self_output.stdout));

Expand Down
11 changes: 9 additions & 2 deletions crates/rsjudge-runner/src/cap_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc};

use caps::{drop as drop_cap, has_cap, raise as raise_cap, Capability};

use crate::Result;
use crate::{Error, Result};

#[derive(Debug, PartialEq, Eq, Hash)]
pub struct CapHandle {
Expand All @@ -16,6 +16,13 @@ impl CapHandle {
static LOCAL_CAPS: RefCell<HashMap<Capability,Rc<()>>> = RefCell::new(HashMap::new());
}

/// Create a new capability handle.
///
/// The capability will be raised if it is permitted but not effective.
///
/// # Errors
///
/// Returns an error if the capability is not permitted,
pub fn new(cap: Capability) -> Result<Self> {
let ref_count = Self::LOCAL_CAPS
.with_borrow_mut(|local_caps| local_caps.entry(cap).or_default().clone());
Expand Down Expand Up @@ -44,6 +51,6 @@ fn try_raise_cap(cap: Capability) -> Result<bool> {
raise_cap(None, caps::CapSet::Effective, cap)?;
Ok(true)
} else {
Ok(false)
Err(Error::CapRequired(cap))
}
}
4 changes: 2 additions & 2 deletions crates/rsjudge-runner/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
/// Capabilities required but not set.
#[error("{caps:?} required but not set.")]
CapsRequired { caps: Box<[Capability]> },
#[error("{0} required but not set.")]
CapRequired(Capability),

/// The requested user is not found.
#[error("User '{username}' not found")]
Expand Down
10 changes: 10 additions & 0 deletions crates/rsjudge-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,21 @@ pub mod user;

pub trait RunAs {
type Error;

/// Run the command as the given user.
///
/// This function will set the UID, GID, and supplementary groups of the command.
///
/// # Errors
///
/// This function will return an error if the user does not exist,
/// or if the process does not have the necessary capabilities.
fn run_as(&mut self, user: &User) -> Result<&mut Self>;
}

impl RunAs for Command {
type Error = Error;

fn run_as(&mut self, user: &User) -> Result<&mut Self> {
let uid = user.uid();
let gid = user.primary_group_id();
Expand Down
1 change: 1 addition & 0 deletions crates/rsjudge-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
12 changes: 9 additions & 3 deletions crates/rsjudge-utils/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use thiserror::Error;
/// cmd.arg("Hello, world!");
/// assert_eq!(display_cmd(&cmd), "echo 'Hello, world!'");
/// ```
#[must_use = "this function returns the formatted command"]
pub fn display_cmd(cmd: &Command) -> String {
let args = iter::once(cmd.get_program())
.chain(cmd.get_args())
Expand Down Expand Up @@ -68,6 +69,11 @@ pub enum ExecutionError {
/// let output = check_output(&mut cmd).unwrap();
/// assert_eq!(output.stdout, b"Hello, world!\n");
/// ```
///
/// # Errors
///
/// This function returns an error if the command was not found, failed to start,
/// or failed with a non-zero exit status.
pub fn check_output(cmd: &mut Command) -> Result<Output, ExecutionError> {
let child = cmd
.stdout(Stdio::piped())
Expand All @@ -82,13 +88,13 @@ pub fn check_output(cmd: &mut Command) -> Result<Output, ExecutionError> {

let output = child.wait_with_output()?;

if !output.status.success() {
if output.status.success() {
Ok(output)
} else {
Err(ExecutionError::NonZeroExitStatus {
command: display_cmd(cmd),
output,
})
} else {
Ok(output)
}
}

Expand Down
4 changes: 3 additions & 1 deletion crates/rsjudge-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#[macro_use]
mod error_macros;

pub mod trim;
mod trim;

pub use trim::{trim_ascii, trim_ascii_end, trim_ascii_start};

pub mod command;
3 changes: 3 additions & 0 deletions crates/rsjudge-utils/src/trim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
/// assert_eq!(trim_ascii_start(b""), b"");
/// ```
#[inline]
#[must_use = "This function does not modify the input."]
pub const fn trim_ascii_start(mut bytes: &[u8]) -> &[u8] {
// Note: A pattern matching based approach (instead of indexing) allows
// making the function const.
Expand Down Expand Up @@ -43,6 +44,7 @@ pub const fn trim_ascii_start(mut bytes: &[u8]) -> &[u8] {
/// assert_eq!(trim_ascii_end(b""), b"");
/// ```
#[inline]
#[must_use = "This function does not modify the input."]
pub const fn trim_ascii_end(mut bytes: &[u8]) -> &[u8] {
// Note: A pattern matching based approach (instead of indexing) allows
// making the function const.
Expand Down Expand Up @@ -71,6 +73,7 @@ pub const fn trim_ascii_end(mut bytes: &[u8]) -> &[u8] {
/// assert_eq!(trim_ascii(b""), b"");
/// ```
#[inline]
#[must_use = "This function does not modify the input."]
pub const fn trim_ascii(bytes: &[u8]) -> &[u8] {
trim_ascii_end(trim_ascii_start(bytes))
}
4 changes: 2 additions & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use clap::Parser;

#[derive(Debug, Parser)]
#[command(author, about, version)]
pub(crate) struct Args {
pub struct Args {
#[arg(short, long, default_value = "./config", value_name = "DIR")]
/// Specify the configuration directory
pub(crate) config_dir: PathBuf,
pub config_dir: PathBuf,
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use crate::cli::Args;

mod cli;

/// # Errors
///
pub async fn main_impl() -> anyhow::Result<()> {
env_logger::Builder::from_env(
Env::new()
Expand Down
2 changes: 2 additions & 0 deletions xtask/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
publish = false
rust-version.workspace = true
description = "A task runner for cargo workspaces"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down

0 comments on commit 271890e

Please sign in to comment.