refactor: replace Arc<Refcell<Config>> with Arc<Mutex<Config>> (#46)

pull/47/head
sigoden 1 year ago committed by GitHub
parent ebd3cb2401
commit 1ec451da89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

1
Cargo.lock generated

@ -26,6 +26,7 @@ dependencies = [
"futures-util",
"inquire",
"is-terminal",
"parking_lot",
"reedline",
"reqwest",
"serde",

@ -31,6 +31,7 @@ atty = "0.2.14"
unicode-width = "0.1.10"
bincode = "1.3.3"
ctrlc = "3.2.5"
parking_lot = "0.12.1"
[dependencies.reqwest]
version = "0.11.14"

@ -69,8 +69,8 @@ impl ChatGptClient {
}
async fn send_message_inner(&self, content: &str) -> Result<String> {
if self.config.borrow().dry_run {
return Ok(self.config.borrow().merge_prompt(content));
if self.config.lock().dry_run {
return Ok(self.config.lock().merge_prompt(content));
}
let builder = self.request_builder(content, false)?;
@ -88,8 +88,8 @@ impl ChatGptClient {
content: &str,
handler: &mut ReplyStreamHandler,
) -> Result<()> {
if self.config.borrow().dry_run {
handler.text(&self.config.borrow().merge_prompt(content))?;
if self.config.lock().dry_run {
handler.text(&self.config.lock().merge_prompt(content))?;
return Ok(());
}
let builder = self.request_builder(content, true)?;
@ -122,7 +122,7 @@ impl ChatGptClient {
fn build_client(&self) -> Result<Client> {
let mut builder = Client::builder();
if let Some(proxy) = self.config.borrow().proxy.as_ref() {
if let Some(proxy) = self.config.lock().proxy.as_ref() {
builder = builder.proxy(Proxy::all(proxy).with_context(|| "Invalid config.proxy")?);
}
let client = builder
@ -134,7 +134,7 @@ impl ChatGptClient {
fn request_builder(&self, content: &str, stream: bool) -> Result<RequestBuilder> {
let user_message = json!({ "role": "user", "content": content });
let messages = match self.config.borrow().get_prompt() {
let messages = match self.config.lock().get_prompt() {
Some(prompt) => {
let system_message = json!({ "role": "system", "content": prompt.trim() });
json!([system_message, user_message])
@ -148,7 +148,7 @@ impl ChatGptClient {
"messages": messages,
});
if let Some(v) = self.config.borrow().get_temperature() {
if let Some(v) = self.config.lock().get_temperature() {
body.as_object_mut()
.and_then(|m| m.insert("temperature".into(), json!(v)));
}
@ -161,7 +161,7 @@ impl ChatGptClient {
let builder = self
.build_client()?
.post(API_URL)
.bearer_auth(&self.config.borrow().api_key)
.bearer_auth(&self.config.lock().api_key)
.json(&body);
Ok(builder)

@ -1,5 +1,4 @@
use std::{
cell::RefCell,
env,
fs::{create_dir_all, read_to_string, File, OpenOptions},
io::Write,
@ -8,6 +7,8 @@ use std::{
sync::Arc,
};
use parking_lot::Mutex;
use anyhow::{anyhow, Context, Result};
use inquire::{Confirm, Text};
use serde::{Deserialize, Serialize};
@ -56,7 +57,7 @@ pub struct Config {
pub role: Option<Role>,
}
pub type SharedConfig = Arc<RefCell<Config>>;
pub type SharedConfig = Arc<Mutex<Config>>;
impl Config {
pub fn init(is_interactive: bool) -> Result<Config> {

@ -7,7 +7,6 @@ mod term;
#[macro_use]
mod utils;
use std::cell::RefCell;
use std::io::{stdin, Read};
use std::sync::Arc;
use std::{io::stdout, process::exit};
@ -17,6 +16,7 @@ use client::ChatGptClient;
use config::{Config, SharedConfig};
use crossbeam::sync::WaitGroup;
use is_terminal::IsTerminal;
use parking_lot::Mutex;
use anyhow::{anyhow, Result};
use clap::Parser;
@ -26,10 +26,10 @@ use repl::{AbortSignal, Repl};
fn main() -> Result<()> {
let cli = Cli::parse();
let text = cli.text();
let config = Arc::new(RefCell::new(Config::init(text.is_none())?));
let config = Arc::new(Mutex::new(Config::init(text.is_none())?));
if cli.list_roles {
config
.borrow()
.lock()
.roles
.iter()
.for_each(|v| println!("{}", v.name));
@ -38,15 +38,15 @@ fn main() -> Result<()> {
let role = match &cli.role {
Some(name) => Some(
config
.borrow()
.lock()
.find_role(name)
.ok_or_else(|| anyhow!("Unknown role '{name}'"))?,
),
None => None,
};
config.borrow_mut().role = role;
config.lock().role = role;
if cli.no_highlight {
config.borrow_mut().highlight = false;
config.lock().highlight = false;
}
let no_stream = cli.no_stream;
let client = ChatGptClient::init(config.clone())?;
@ -71,7 +71,7 @@ fn start_directive(
input: &str,
no_stream: bool,
) -> Result<()> {
let highlight = config.borrow().highlight && stdout().is_terminal();
let highlight = config.lock().highlight && stdout().is_terminal();
let output = if no_stream {
let output = client.send_message(input)?;
if highlight {
@ -93,7 +93,7 @@ fn start_directive(
wg.wait();
output
};
config.borrow().save_message(input, &output)
config.lock().save_message(input, &output)
}
fn start_interactive(client: ChatGptClient, config: SharedConfig) -> Result<()> {

@ -48,7 +48,7 @@ impl ReplCmdHandler {
self.reply.borrow_mut().clear();
return Ok(());
}
let highlight = self.config.borrow().highlight;
let highlight = self.config.lock().highlight;
let wg = WaitGroup::new();
let ret = render_stream(
&input,
@ -60,27 +60,27 @@ impl ReplCmdHandler {
);
wg.wait();
let buffer = ret?;
self.config.borrow().save_message(&input, &buffer)?;
self.config.lock().save_message(&input, &buffer)?;
*self.reply.borrow_mut() = buffer;
}
ReplCmd::SetRole(name) => {
let output = self.config.borrow_mut().change_role(&name);
let output = self.config.lock().change_role(&name);
print_now!("{}\n\n", output.trim_end());
}
ReplCmd::ClearRole => {
self.config.borrow_mut().role = None;
self.config.lock().role = None;
print_now!("\n");
}
ReplCmd::Prompt(prompt) => {
self.config.borrow_mut().create_temp_role(&prompt);
self.config.lock().create_temp_role(&prompt);
print_now!("\n");
}
ReplCmd::Info => {
let output = self.config.borrow().info()?;
let output = self.config.lock().info()?;
print_now!("{}\n\n", output.trim_end());
}
ReplCmd::UpdateConfig(input) => {
let output = self.config.borrow_mut().update(&input)?;
let output = self.config.lock().update(&input)?;
let output = output.trim();
if output.is_empty() {
print_now!("\n");

@ -47,7 +47,7 @@ impl Repl {
.into_iter()
.map(|(v, _, _)| v.to_string())
.collect();
completion.extend(config.borrow().repl_completions());
completion.extend(config.lock().repl_completions());
let mut completer = DefaultCompleter::with_inclusions(&['.', '-', '_']).set_min_word_len(2);
completer.insert(completion.clone());
completer

Loading…
Cancel
Save