Skip to content

Commit

Permalink
Turn on clippy::pedantic lints (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
coreyja committed Mar 5, 2024
1 parent 8d30386 commit 0273651
Show file tree
Hide file tree
Showing 46 changed files with 290 additions and 195 deletions.
13 changes: 13 additions & 0 deletions Cargo.toml
Expand Up @@ -10,6 +10,19 @@ members = [
]
resolver = "2"

[workspace.lints.clippy]
pedantic = "deny"
missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
blocks_in_conditions = "allow"
must_use_candidate = "allow"
no-effect-underscore-binding = "allow"
items-after-statements = "allow"

[workspace.lints.rust]
unsafe_code = "forbid"

[workspace.dependencies]
clap = { version = "4.2", features = ["derive"] }
reqwest = { version = "0.11.12", features = [
Expand Down
3 changes: 3 additions & 0 deletions byte/Cargo.toml
Expand Up @@ -25,3 +25,6 @@ irc = { version = "0.15.0", default-features = false, features = ["tls-rust"] }
samplerate = "0.2.4"
whisper-rs = { version = "0.8.0" }
futures = "0.3.28"

[lints]
workspace = true
28 changes: 14 additions & 14 deletions byte/src/audio.rs
Expand Up @@ -7,7 +7,7 @@ use crate::Config;

const PREFERRED_MIC_NAME: &str = "Samson G-Track Pro";

fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> miette::Result<()> {
fn recording_thread_main(string_sender: &tokio::sync::mpsc::Sender<String>) -> miette::Result<()> {
let host = cpal::default_host();

let device = host
Expand All @@ -16,7 +16,7 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
.find(|device| match device.name() {
Ok(name) => name == PREFERRED_MIC_NAME,
Err(err) => {
eprintln!("Failed to get device name: {}", err);
eprintln!("Failed to get device name: {err}");
false
}
})
Expand All @@ -28,12 +28,12 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
.default_input_config()
.into_diagnostic()
.wrap_err("Failed to get default input config")?;
println!("Default input config: {:?}", config);
println!("Default input config: {config:?}");

println!("Begin recording...");

let err_fn = move |err| {
eprintln!("an error occurred on stream: {}", err);
eprintln!("an error occurred on stream: {err}");
};

let (sender, receiver) = std::sync::mpsc::channel::<Vec<f32>>();
Expand Down Expand Up @@ -65,9 +65,11 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
while let Ok(mut data) = receiver.recv() {
recorded_sample.append(&mut data);

if recorded_sample.len() >= 480000 {
if recorded_sample.len() >= 480_000 {
let audio_data = &recorded_sample[..];
let audio_data = if config.sample_rate().0 != 16_000 {
let audio_data = if config.sample_rate().0 == 16_000 {
audio_data.to_vec()
} else {
samplerate::convert(
config.sample_rate().0,
16000,
Expand All @@ -77,8 +79,6 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
)
.into_diagnostic()
.wrap_err("Failed to convert to 16kHz")?
} else {
audio_data.to_vec()
};
let audio_data = match config.channels() {
1 => audio_data,
Expand Down Expand Up @@ -109,7 +109,7 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
.expect("failed to get number of segments");
for i in 0..num_segments {
if let Ok(segment) = state.full_get_segment_text(i) {
println!("Segment {}: {}", i, segment);
println!("Segment {i}: {segment}");
string_sender.blocking_send(segment).unwrap();
}
}
Expand All @@ -124,14 +124,14 @@ fn recording_thread_main(string_sender: tokio::sync::mpsc::Sender<String>) -> mi
pub(crate) async fn run_audio_loop(config: Config) -> miette::Result<()> {
let (sender, mut reciever) = tokio::sync::mpsc::channel::<String>(32);

std::thread::spawn(|| recording_thread_main(sender));
std::thread::spawn(move || recording_thread_main(&sender));

let (message_sender, mut message_reciever) = tokio::sync::mpsc::channel::<String>(32);

let _detecting = tokio::task::spawn(async move {
while let Some(text) = reciever.recv().await {
let text = text.to_lowercase();
println!("{}", text);
println!("{text}");

if text.contains("bite") || text.contains("byte") {
println!("Bite detected!");
Expand All @@ -146,12 +146,12 @@ pub(crate) async fn run_audio_loop(config: Config) -> miette::Result<()> {
});

while let Some(message) = message_reciever.recv().await {
println!("{}", message);
println!("{message}");

let messages = vec![
ChatMessage {
role: ChatRole::System,
content: r#"
content: r"
The following message was recorded and transcribed during a live chat.
I have a bot named Byte (or maybe Bite) that I might be trying to talk to.
Remeber this is a AI transcribed audio, so there may be errors in the transcription.
Expand All @@ -161,7 +161,7 @@ pub(crate) async fn run_audio_loop(config: Config) -> miette::Result<()> {
Do NOT comment on the spelling of your name under any circumstances
If I didn't ask a question keep your answer short and consise
"#
"
.to_string(),
},
ChatMessage {
Expand Down
8 changes: 4 additions & 4 deletions byte/src/twitch.rs
Expand Up @@ -45,7 +45,7 @@ pub(crate) async fn run_twitch_bot(config: super::Config) -> Result<()> {
respond_to_twitch_chat_prompt(),
ChatMessage {
role: ChatRole::User,
content: format!("{}: {}", preferred_name, chat_msg),
content: format!("{preferred_name}: {chat_msg}"),
},
];
let resp = complete_chat(&config.openai, "gpt-3.5-turbo", messages).await?;
Expand Down Expand Up @@ -94,8 +94,8 @@ pub(crate) async fn run_twitch_bot(config: super::Config) -> Result<()> {

let preferred_name = preferred_twitch_name(&config.db, &nick).await?;

let prompt = format!("{} has joined the channel", preferred_name);
println!("{}", prompt);
let prompt = format!("{preferred_name} has joined the channel");
println!("{prompt}");

let resp = complete_chat(
&config.openai,
Expand All @@ -113,7 +113,7 @@ pub(crate) async fn run_twitch_bot(config: super::Config) -> Result<()> {
};
}
_ => {
println!("Unhandled message: {:?}", message);
println!("Unhandled message: {message:?}");
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions cja/Cargo.toml
Expand Up @@ -24,3 +24,6 @@ async-trait = "0.1.77"
thiserror = "1.0.56"
tower-cookies = { version = "0.10.0", features = ["signed", "private"] }
http = "1.0.0"

[lints]
workspace = true
2 changes: 1 addition & 1 deletion cja/src/cron/registry.rs
Expand Up @@ -43,7 +43,7 @@ impl<
async fn run(&self, app_state: AppState, context: String) -> Result<(), String> {
(self.func)(app_state, context)
.await
.map_err(|err| format!("{:?}", err))
.map_err(|err| format!("{err:?}"))
}
}

Expand Down
2 changes: 1 addition & 1 deletion cja/src/cron/worker.rs
Expand Up @@ -34,7 +34,7 @@ impl<AppState: AS> Worker<AppState> {
worker_id: &uuid::Uuid,
last_enqueue_map: &mut HashMap<&str, Instant>,
) -> Result<(), TickError> {
for (_, job) in self.registry.jobs.iter() {
for job in self.registry.jobs.values() {
job.tick(self.state.clone(), last_enqueue_map).await?;
}

Expand Down
14 changes: 6 additions & 8 deletions cja/src/server/session.rs
Expand Up @@ -63,12 +63,10 @@ impl<AppState: AS> FromRequestParts<AppState> for DBSession {
let return_to_path = parts
.uri
.path_and_query()
.map(|x| x.as_str())
.unwrap_or("/");
.map_or("/", http::uri::PathAndQuery::as_str);

Err(SessionRedirect::temporary(&format!(
"/login?return_to={}",
return_to_path
"/login?return_to={return_to_path}"
)))?
};

Expand All @@ -80,11 +78,11 @@ impl<AppState: AS> FromRequestParts<AppState> for DBSession {
};

let session = sqlx::query_as::<_, DBSession>(
r#"
r"
SELECT *
FROM Sessions
WHERE session_id = $1
"#,
",
)
.bind(session_id)
.fetch_one(state.db())
Expand All @@ -106,11 +104,11 @@ impl DBSession {
cookies: &Cookies,
) -> miette::Result<Self> {
let session = sqlx::query_as::<_, DBSession>(
r#"
r"
INSERT INTO Sessions (session_id, user_id)
VALUES ($1, $2)
RETURNING *
"#,
",
)
.bind(uuid::Uuid::new_v4())
.bind(user_id)
Expand Down
3 changes: 3 additions & 0 deletions db/Cargo.toml
Expand Up @@ -10,3 +10,6 @@ chrono.workspace = true
miette = { workspace = true }
sqlx = { workspace = true }
tracing = { workspace = true }

[lints]
workspace = true
3 changes: 2 additions & 1 deletion db/src/lib.rs
Expand Up @@ -9,14 +9,15 @@ pub use sqlx::PgPool;

#[tracing::instrument(err)]
pub async fn setup_db_pool() -> Result<PgPool> {
const MIGRATION_LOCK_ID: i64 = 0xDB_DB_DB_DB_DB_DB_DB;

let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.into_diagnostic()?;

const MIGRATION_LOCK_ID: i64 = 0xDB_DB_DB_DB_DB_DB_DB;
sqlx::query!("SELECT pg_advisory_lock($1)", MIGRATION_LOCK_ID)
.execute(&pool)
.await
Expand Down
3 changes: 3 additions & 0 deletions posts/Cargo.toml
Expand Up @@ -22,3 +22,6 @@ include_dir = { workspace = true }
path-absolutize = { workspace = true }
thiserror = "1.0.44"
url = "2.5.0"

[lints]
workspace = true
15 changes: 10 additions & 5 deletions posts/src/blog.rs
Expand Up @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf};

use chrono::NaiveDate;
use include_dir::{include_dir, Dir, File};
use markdown::mdast::*;
use markdown::mdast::Node;
use miette::IntoDiagnostic;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -190,7 +190,10 @@ impl BlogPostPath {
}

pub fn file_is_markdown(&self) -> bool {
self.file_exists() && self.path.ends_with(".md")
self.file_exists()
&& std::path::Path::new(&self.path)
.extension()
.map_or(false, |ext| ext.eq_ignore_ascii_case("md"))
}

pub fn to_markdown(&self) -> Option<PostMarkdown> {
Expand Down Expand Up @@ -269,6 +272,8 @@ impl ToCanonicalPath for PathBuf {

#[cfg(test)]
mod test {
use markdown::mdast::Root;

use super::*;

#[test]
Expand All @@ -294,10 +299,12 @@ mod test {

#[test]
fn test_path_matching() {
use MatchesPath::*;

let path = PathBuf::from("2020-01-01-test/index.md");
let meta = BlogFrontMatter {
title: "Sample Post".to_string(),
date: Default::default(),
date: NaiveDate::default(),
is_newsletter: false,
};
let post = BlogPost {
Expand All @@ -309,8 +316,6 @@ mod test {
frontmatter: meta,
};

use MatchesPath::*;

assert_eq!(post.matches_path("2020-01-01-test/"), Some(CanonicalPath));
assert_eq!(
post.matches_path("2020-01-01-test/index.md"),
Expand Down
2 changes: 1 addition & 1 deletion posts/src/lib.rs
Expand Up @@ -34,7 +34,7 @@ impl FromStr for MarkdownAst {
type Err = ErrReport;

fn from_str(contents: &str) -> Result<Self> {
let mut options: ParseOptions = Default::default();
let mut options: ParseOptions = ParseOptions::default();
options.constructs.gfm_footnote_definition = true;
options.constructs.frontmatter = true;

Expand Down

0 comments on commit 0273651

Please sign in to comment.