Small Rust scripts
1#!/usr/bin/env -S cargo +nightly -Zscript
2
3---
4[package]
5edition = "2024"
6[dependencies]
7argh = "0.1"
8---
9
10use std::io::{BufRead, BufReader, Write};
11use std::net::{Shutdown, TcpStream};
12
13use argh::FromArgs;
14
15const FLUSH_COMMAND: &str = "FLUSHALL\r\n";
16
17#[derive(FromArgs)]
18#[argh(description = "Flush the cache of a redis instance.")]
19struct App {
20 #[argh(
21 option,
22 description = "host for the redis instance.",
23 default = "\"127.0.0.1\".to_string()"
24 )]
25 host: String,
26
27 #[argh(option, description = "port redis is listening on.", default = "6379")]
28 port: u16,
29}
30
31fn main() {
32 let app: App = argh::from_env();
33
34 let address = format!("{}:{}", app.host, app.port);
35 let mut stream = TcpStream::connect(address).expect("should be able to connect to redis");
36
37 stream
38 .write(FLUSH_COMMAND.as_bytes())
39 .expect("should be able to write flush command");
40 stream
41 .flush()
42 .expect("should be able to send flush command");
43 stream
44 .shutdown(Shutdown::Write)
45 .expect("should be able to shutdown writer");
46
47 let mut stream = BufReader::new(stream);
48
49 let mut output = String::new();
50 let _ = stream
51 .read_line(&mut output)
52 .expect("should be able to read response");
53 println!("{}", &output);
54}