Skip to content

Commit

Permalink
Support stdin for test data
Browse files Browse the repository at this point in the history
  • Loading branch information
dragfire committed Sep 4, 2023
1 parent 71df560 commit 47d9934
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "leetup"
version = "1.2.1"
version = "1.2.3"
authors = ["dragfire <[email protected]>"]
edition = "2018"
description = "Leetcode cli"
Expand Down
2 changes: 1 addition & 1 deletion src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub struct Test {

/// Custom test cases.
#[structopt(short)]
pub test_data: String,
pub test_data: Option<Option<String>>,
}

#[derive(Debug, StructOpt)]
Expand Down
33 changes: 31 additions & 2 deletions src/service/leetcode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::cmp::Ord;
use std::collections::HashMap;
use std::env;
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{prelude::*, stdin};
use std::ops::Deref;
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -203,7 +203,9 @@ impl<'a> ServiceProvider<'a> for Leetcode<'a> {

async fn problem_test(&self, test: cmd::Test) -> Result<()> {
let problem = service::extract_problem(test.filename)?;
let test_data = test.test_data.replace("\\n", "\n");

let test_data = self.get_test_data(test.test_data);
debug!("Test data: {:?}", test_data);
let typed_code = parse_code(problem.typed_code.as_ref().expect("Expected typed_code"));
let body = json!({
"lang": problem.lang.to_owned(),
Expand Down Expand Up @@ -624,4 +626,31 @@ impl<'a> Leetcode<'a> {

Ok(())
}

/*
* Parse Option<Option<String>> from structopt
*
* Get string from command line if provided, otherwise try to get string from stdin
*
* We can provide test data as multiline input using stdin.
*
* # Example:
* ```bash
* leetup test 3sum.java -t << END
* [1,-1,0]
* [0, 1, 1, 1, 2, -3, -1]
* [1,2,3]
* END
* ```
*/
fn get_test_data(&self, test_data: Option<Option<String>>) -> String {
test_data.unwrap().unwrap_or_else(|| {
let mut buf = String::new();
stdin()
.lock()
.read_to_string(&mut buf)
.expect("test input expected from stdin");
buf
})
}
}

0 comments on commit 47d9934

Please sign in to comment.