From fc2d7c925867e6fd348ff4e26de2b2462ddcdf6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 01:30:10 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20Linux=20CLI=20in=20the=20cl?= =?UTF-8?q?ient=20binary:=20yumush=20login|logout|chats|read|send|tail|ci|?= =?UTF-8?q?build|import=20[--publish=20server|client|both]=20shares=20the?= =?UTF-8?q?=20GUI's=20token=20and=20network=20code;=20Side=20moves=20to=20?= =?UTF-8?q?common::update,=20job=20label=20to=20ci::Job?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 131 +++++++ crates/client/Cargo.toml | 2 + crates/client/src/ci.rs | 9 + crates/client/src/cli.rs | 411 ++++++++++++++++++++++ crates/client/src/gui/builder/ci_view.rs | 8 +- crates/client/src/gui/builder/releases.rs | 19 +- crates/client/src/lib.rs | 2 + crates/client/src/main.rs | 5 + crates/common/src/update.rs | 30 ++ 9 files changed, 592 insertions(+), 25 deletions(-) create mode 100644 crates/client/src/cli.rs diff --git a/Cargo.lock b/Cargo.lock index d3dfd28..dbd6239 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -225,12 +225,56 @@ dependencies = [ "unicode-width 0.2.3", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "antithesis_sdk" version = "0.3.0" @@ -1261,12 +1305,53 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "client" version = "0.1.0" dependencies = [ "ashpd 0.14.3", "bytes", + "clap", "common", "coreaudio-rs", "dirs 7.0.0", @@ -1297,6 +1382,7 @@ dependencies = [ "quinn", "reed-solomon-simd", "resvg 0.50.0", + "rpassword", "rtrb", "rustls-platform-verifier", "ruzstd", @@ -1411,6 +1497,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -5013,6 +5105,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.11.0" @@ -6650,6 +6748,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oo7" version = "0.6.0" @@ -7792,6 +7896,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "rpassword" +version = "7.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rtrb" version = "0.4.1" @@ -10006,6 +10131,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index c83d984..9733ab3 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -51,6 +51,8 @@ nokhwa = { version = "0.10.11", default-features = false, features = ["input-nat v4l = "0.14.0" pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" +clap = { version = "4.6.10", features = ["derive"] } +rpassword = "7.5.5" ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } [target.'cfg(target_os = "windows")'.dependencies] diff --git a/crates/client/src/ci.rs b/crates/client/src/ci.rs index 666b212..f05b137 100644 --- a/crates/client/src/ci.rs +++ b/crates/client/src/ci.rs @@ -65,6 +65,15 @@ impl State { } } +impl Job { + pub fn label(&self) -> &str { + self.name + .strip_prefix("build (") + .and_then(|name| name.strip_suffix(')')) + .unwrap_or(&self.name) + } +} + impl Run { pub fn tag(&self) -> Option<&str> { self.reference.strip_prefix("refs/tags/") diff --git a/crates/client/src/cli.rs b/crates/client/src/cli.rs new file mode 100644 index 0000000..4bc411c --- /dev/null +++ b/crates/client/src/cli.rs @@ -0,0 +1,411 @@ +use std::{collections::HashMap, io::Read, process::exit, time::Duration}; + +use clap::{Parser, Subcommand}; +use common::{ + call::{ + CreateMessage, CreateTag, GetForge, ImportRelease, ListCommunities, ListMembers, + ListMessages, OpenNotes, PublishRelease, + }, + event::Event, + model::{Community, CommunityKind, Id, Message}, + update::Side, +}; +use tokio::sync::mpsc::Receiver; + +use crate::{ + Server, accounts, ci, + net::{self, Fail, NetworkEvent, NetworkHandle}, +}; + +const CONNECT: Duration = Duration::from_secs(15); + +#[derive(Parser)] +#[command(name = "yumush", bin_name = "yumush")] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + Login { + username: String, + }, + Logout, + Chats, + Read { + chat: String, + #[arg(short = 'n', default_value_t = 20)] + count: usize, + }, + Send { + chat: String, + words: Vec, + }, + Tail { + chat: Option, + }, + Ci { + tag: Option, + }, + Build { + tag: String, + }, + Import { + tag: String, + #[arg(long)] + publish: Option, + #[arg(long)] + required: bool, + }, +} + +pub fn wanted() -> bool { + std::env::args() + .nth(1) + .is_some_and(|arg| !arg.starts_with('-') || arg == "--help" || arg == "-h") +} + +pub fn run() { + let command = Cli::parse().command; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("cli runtime"); + if let Err(error) = runtime.block_on(execute(command)) { + eprintln!("{error}"); + exit(1); + } +} + +struct Session { + network: NetworkHandle, + events: Receiver, +} + +async fn execute(command: Command) -> Result<(), String> { + match command { + Command::Login { username } => login(&username).await, + Command::Logout => logout().await, + Command::Chats => { + let session = open().await?; + for community in session.communities().await? { + println!("{}", title(&community)); + } + Ok(()) + } + Command::Read { chat, count } => { + let session = open().await?; + let community = session.chat(&chat).await?; + let names = session.names(community.id).await?; + let messages = session + .network + .call(ListMessages { + community_id: community.id, + before: None, + }) + .await + .map_err(text)?; + let skip = messages.len().saturating_sub(count); + for message in &messages[skip..] { + print_message(message, &names, None); + } + Ok(()) + } + Command::Send { chat, words } => { + let body = if words.is_empty() { + let mut body = String::new(); + std::io::stdin() + .read_to_string(&mut body) + .map_err(|error| error.to_string())?; + body.trim_end().to_string() + } else { + words.join(" ") + }; + let session = open().await?; + let community = session.chat(&chat).await?; + session + .network + .call(CreateMessage { + community_id: community.id, + body, + attachments: Vec::new(), + reply_to: None, + }) + .await + .map_err(text)?; + Ok(()) + } + Command::Tail { chat } => tail(open().await?, chat).await, + Command::Ci { tag } => follow(&open().await?, tag.as_deref()).await, + Command::Build { tag } => { + let session = open().await?; + session + .network + .call(CreateTag { tag: tag.clone() }) + .await + .map_err(text)?; + println!("tag {tag} created"); + follow(&session, Some(&tag)).await + } + Command::Import { + tag, + publish, + required, + } => import(open().await?, tag, publish, required).await, + } +} + +fn text(fail: Fail) -> String { + fail.to_string() +} + +fn start() -> (NetworkHandle, Receiver, accounts::Accounts) { + let server = Server::load(); + let accounts = accounts::load(&server.address); + let (network, events) = net::start(server); + (network, events, accounts) +} + +async fn login(username: &str) -> Result<(), String> { + let password = rpassword::prompt_password("password: ").map_err(|error| error.to_string())?; + let (network, events, mut accounts) = start(); + let session = Session { network, events }; + let (user, token) = session + .connect(session.network.login(username, &password)) + .await?; + accounts.sign_in(&user, token); + println!("signed in as {}", user.username); + Ok(()) +} + +async fn logout() -> Result<(), String> { + let session = open().await?; + session.network.logout().await.map_err(text)?; + let mut accounts = accounts::load(&session.network.server().address); + if let Some(user_id) = accounts.active { + accounts.forget(user_id); + } + Ok(()) +} + +async fn open() -> Result { + let (network, events, accounts) = start(); + let token = accounts + .active + .and_then(|user_id| accounts.get(user_id)) + .map(|account| account.token.clone()) + .ok_or("not signed in: yumush login ")?; + let session = Session { network, events }; + session.connect(session.network.resume(&token)).await?; + Ok(session) +} + +impl Session { + async fn connect( + &self, + sign_in: impl Future>, + ) -> Result { + tokio::time::timeout(CONNECT, sign_in) + .await + .map_err(|_| "server unreachable".to_string())? + .map_err(text) + } + + async fn communities(&self) -> Result, String> { + let mut communities = self.network.call(ListCommunities).await.map_err(text)?; + if !communities + .iter() + .any(|community| matches!(community.kind, CommunityKind::Notes)) + { + communities.push(self.network.call(OpenNotes).await.map_err(text)?); + } + Ok(communities) + } + + async fn chat(&self, chat: &str) -> Result { + self.communities() + .await? + .into_iter() + .find(|community| title(community).eq_ignore_ascii_case(chat)) + .ok_or_else(|| format!("no chat named {chat}; see yumush chats")) + } + + async fn names(&self, community_id: Id) -> Result, String> { + Ok(self + .network + .call(ListMembers { community_id }) + .await + .map_err(text)? + .into_iter() + .map(|member| (member.user.id, member.user.username)) + .collect()) + } + + async fn event(&mut self) -> Result { + loop { + match self.events.recv().await { + Some(NetworkEvent::Pushed(event)) => return Ok(*event), + Some(NetworkEvent::SessionLost) => return Err("session lost".to_string()), + Some(_) => {} + None => return Err("disconnected".to_string()), + } + } + } +} + +fn title(community: &Community) -> String { + match &community.kind { + CommunityKind::Group => community.name.clone(), + CommunityKind::Direct { peer } => peer.username.clone(), + CommunityKind::Notes => "notes".to_string(), + } +} + +fn print_message(message: &Message, names: &HashMap, chat: Option<&str>) { + if message.deleted { + return; + } + let time = jiff::Timestamp::from_millisecond(message.created_at as i64) + .map(|time| { + time.to_zoned_datetime(jiff::tz::TimeZone::system()) + .strftime("%m-%d %H:%M") + .to_string() + }) + .unwrap_or_default(); + let name = names.get(&message.user_id).map_or("?", String::as_str); + let files: String = message + .attachments + .iter() + .map(|attachment| format!(" [{}]", attachment.name)) + .collect(); + let chat = chat.map(|chat| format!("#{chat} ")).unwrap_or_default(); + let call = message + .call + .map(|call| format!("[call {}]", call.as_str())) + .unwrap_or_default(); + println!("{time} {chat}{name}: {call}{}{files}", message.body); +} + +async fn tail(mut session: Session, chat: Option) -> Result<(), String> { + let communities = session.communities().await?; + let only = match &chat { + Some(chat) => Some(session.chat(chat).await?.id), + None => None, + }; + let titles: HashMap = communities + .iter() + .map(|community| (community.id, title(community))) + .collect(); + let mut names: HashMap> = HashMap::new(); + loop { + let Event::MessageCreated(message) = session.event().await? else { + continue; + }; + if only.is_some_and(|id| id != message.community_id) { + continue; + } + if let std::collections::hash_map::Entry::Vacant(entry) = names.entry(message.community_id) + { + entry.insert(session.names(message.community_id).await?); + } + let chat = only + .is_none() + .then(|| titles.get(&message.community_id).map(String::as_str)) + .flatten(); + print_message(&message, &names[&message.community_id], chat); + } +} + +async fn follow(session: &Session, tag: Option<&str>) -> Result<(), String> { + let repo = session + .network + .call(GetForge) + .await + .map_err(text)? + .ok_or("the server has no forge set")?; + let (_watch, mut events) = ci::watch(repo); + let mut states: HashMap = HashMap::new(); + let mut labels: HashMap = HashMap::new(); + let mut number = None; + while let Some(event) = events.recv().await { + match event { + ci::Event::Run(run) => { + if tag.is_some_and(|tag| run.tag() != Some(tag)) { + continue; + } + if number != Some(run.number) { + number = Some(run.number); + println!( + "run #{} {}", + run.number, + run.tag().unwrap_or(&run.reference) + ); + } + for job in &run.jobs { + labels.insert(job.id.clone(), job.label().to_string()); + let state = ci::State::of(&job.state); + if states.insert(job.id.clone(), state) != Some(state) { + println!("{} {}", job.label(), job.state); + } + } + if ci::State::of(&run.state).finished() { + println!("run #{} {}", run.number, run.state); + return match ci::State::of(&run.state) { + ci::State::Success => Ok(()), + _ => Err(format!("run #{} {}", run.number, run.state)), + }; + } + } + ci::Event::Line { job, line } => { + if let Some(label) = labels.get(&job) { + println!("{label} | {line}"); + } + } + } + } + Err("forge unreachable".to_string()) +} + +async fn import( + mut session: Session, + tag: String, + publish: Option, + required: bool, +) -> Result<(), String> { + session + .network + .call(ImportRelease { tag: tag.clone() }) + .await + .map_err(text)?; + println!("importing {tag}"); + let staged = loop { + if let Event::Imported { tag: done, result } = session.event().await? + && done == tag + { + break result.map_err(|problem| problem.to_string())?; + } + }; + if staged.is_empty() { + println!("nothing new"); + return Ok(()); + } + for file in &staged { + println!("staged {} {} bytes", file.target, file.size); + } + let Some(side) = publish else { + return Ok(()); + }; + let files = staged + .iter() + .filter(|file| side.takes(&file.target)) + .map(|file| file.file) + .collect(); + let release = session + .network + .call(PublishRelease { files, required }) + .await + .map_err(text)?; + println!("published release #{}", release.seq); + Ok(()) +} diff --git a/crates/client/src/gui/builder/ci_view.rs b/crates/client/src/gui/builder/ci_view.rs index db949e9..8077400 100644 --- a/crates/client/src/gui/builder/ci_view.rs +++ b/crates/client/src/gui/builder/ci_view.rs @@ -74,12 +74,6 @@ impl Live { } } -fn job_label(name: &str) -> &str { - name.strip_prefix("build (") - .and_then(|name| name.strip_suffix(')')) - .unwrap_or(name) -} - fn span(from: Option<&str>, to: Option<&str>, seconds: bool) -> Option { let from: jiff::Timestamp = from?.parse().ok()?; let to = to @@ -141,7 +135,7 @@ fn job_row( div() .text_size(text(text::LABEL)) .text_color(palette.text) - .child(job_label(&job.name).to_string()), + .child(job.label().to_string()), ) .children(detail.map(|detail| caption_text(detail, palette.muted).truncate())); let id = job.id.clone(); diff --git a/crates/client/src/gui/builder/releases.rs b/crates/client/src/gui/builder/releases.rs index c265183..b30ddb6 100644 --- a/crates/client/src/gui/builder/releases.rs +++ b/crates/client/src/gui/builder/releases.rs @@ -2,7 +2,7 @@ use common::{ call::{ImportRelease, ListReleases, PublishRelease, SetReleaseRequired}, error::ReleaseProblem, model::{ReleaseInfo, Staged}, - update::{SERVER_TARGET, Sha}, + update::{Sha, Side}, }; use gpui_kit::{ AnyElement, Context, Div, Entity, Hsla, IntoElement, ParentElement, PathPromptOptions, Styled, @@ -37,23 +37,6 @@ pub(crate) struct Desk { pub(super) live: super::ci_view::Live, } -#[derive(Clone, Copy)] -enum Side { - Server, - Client, - Both, -} - -impl Side { - fn takes(self, target: &str) -> bool { - match self { - Self::Server => target == SERVER_TARGET, - Self::Client => target != SERVER_TARGET, - Self::Both => true, - } - } -} - struct Draft { id: u64, name: String, diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 675bf94..c377f35 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -7,6 +7,8 @@ pub mod accounts; pub mod autostart; pub mod avatar; pub mod ci; +#[cfg(target_os = "linux")] +pub mod cli; pub mod embed; pub mod emoji; pub mod gui; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 8cafd16..b798eac 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -27,6 +27,11 @@ fn main() { ); return; } + #[cfg(target_os = "linux")] + if client::cli::wanted() { + client::cli::run(); + return; + } tracing_subscriber::registry() .with(tracing_subscriber::fmt::layer()) .with( diff --git a/crates/common/src/update.rs b/crates/common/src/update.rs index 70fa44f..9e3ccd9 100644 --- a/crates/common/src/update.rs +++ b/crates/common/src/update.rs @@ -143,3 +143,33 @@ mod tests { ); } } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Side { + Server, + Client, + Both, +} + +impl Side { + pub fn takes(self, target: &str) -> bool { + match self { + Self::Server => target == SERVER_TARGET, + Self::Client => target != SERVER_TARGET, + Self::Both => true, + } + } +} + +impl std::str::FromStr for Side { + type Err = &'static str; + + fn from_str(side: &str) -> Result { + match side { + "server" => Ok(Self::Server), + "client" => Ok(Self::Client), + "both" => Ok(Self::Both), + _ => Err("server, client or both"), + } + } +}