chore: Bump Rust edition to 2024 (#27800)

Follow-up to https://github.com/zed-industries/zed/pull/27791

Release Notes:

- N/A
This commit is contained in:
Piotr Osiewicz 2025-03-31 20:55:27 +02:00 committed by GitHub
parent d50905e000
commit dc64ec9cc8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
802 changed files with 3775 additions and 3662 deletions

View file

@ -6,12 +6,13 @@ pub mod ips_file;
pub mod slack;
use crate::{
auth,
AppState, Error, Result, auth,
db::{User, UserId},
rpc, AppState, Error, Result,
rpc,
};
use anyhow::anyhow;
use axum::{
Extension, Json, Router,
body::Body,
extract::{Path, Query},
headers::Header,
@ -19,7 +20,6 @@ use axum::{
middleware::{self, Next},
response::IntoResponse,
routing::{get, post},
Extension, Json, Router,
};
use axum_extra::response::ErasedJson;
use serde::{Deserialize, Serialize};

View file

@ -1,8 +1,8 @@
use anyhow::{anyhow, bail, Context};
use anyhow::{Context, anyhow, bail};
use axum::{
Extension, Json, Router,
extract::{self, Query},
routing::{get, post},
Extension, Json, Router,
};
use chrono::{DateTime, SecondsFormat, Utc};
use collections::HashSet;
@ -24,17 +24,16 @@ use crate::api::events::SnowflakeRow;
use crate::db::billing_subscription::{StripeCancellationReason, StripeSubscriptionStatus};
use crate::llm::{DEFAULT_MAX_MONTHLY_SPEND, FREE_TIER_MONTHLY_SPENDING_LIMIT};
use crate::rpc::{ResultExt as _, Server};
use crate::{AppState, Cents, Error, Result};
use crate::{db::UserId, llm::db::LlmDatabase};
use crate::{
db::{
billing_customer, BillingSubscriptionId, CreateBillingCustomerParams,
CreateBillingSubscriptionParams, CreateProcessedStripeEventParams,
UpdateBillingCustomerParams, UpdateBillingPreferencesParams,
UpdateBillingSubscriptionParams,
BillingSubscriptionId, CreateBillingCustomerParams, CreateBillingSubscriptionParams,
CreateProcessedStripeEventParams, UpdateBillingCustomerParams,
UpdateBillingPreferencesParams, UpdateBillingSubscriptionParams, billing_customer,
},
stripe_billing::StripeBilling,
};
use crate::{AppState, Cents, Error, Result};
pub fn router() -> Router {
Router::new()

View file

@ -2,9 +2,9 @@ use std::sync::{Arc, OnceLock};
use anyhow::anyhow;
use axum::{
Extension, Json, Router,
extract::{self, Query},
routing::get,
Extension, Json, Router,
};
use chrono::{NaiveDateTime, SecondsFormat};
use serde::{Deserialize, Serialize};

View file

@ -1,14 +1,14 @@
use super::ips_file::IpsFile;
use crate::api::CloudflareIpCountryHeader;
use crate::{api::slack, AppState, Error, Result};
use crate::{AppState, Error, Result, api::slack};
use anyhow::anyhow;
use aws_sdk_s3::primitives::ByteStream;
use axum::{
Extension, Router, TypedHeader,
body::Bytes,
headers::Header,
http::{HeaderMap, HeaderName, StatusCode},
routing::post,
Extension, Router, TypedHeader,
};
use chrono::Duration;
use semantic_version::SemanticVersion;

View file

@ -1,13 +1,13 @@
use crate::db::ExtensionVersionConstraints;
use crate::{db::NewExtensionVersion, AppState, Error, Result};
use anyhow::{anyhow, Context as _};
use crate::{AppState, Error, Result, db::NewExtensionVersion};
use anyhow::{Context as _, anyhow};
use aws_sdk_s3::presigning::PresigningConfig;
use axum::{
Extension, Json, Router,
extract::{Path, Query},
http::StatusCode,
response::Redirect,
routing::get,
Extension, Json, Router,
};
use collections::{BTreeSet, HashMap};
use rpc::{ExtensionApiManifest, ExtensionProvides, GetExtensionsResponse};
@ -16,7 +16,7 @@ use serde::Deserialize;
use std::str::FromStr;
use std::{sync::Arc, time::Duration};
use time::PrimitiveDateTime;
use util::{maybe, ResultExt};
use util::{ResultExt, maybe};
pub fn router() -> Router {
Router::new()

View file

@ -1,20 +1,20 @@
use crate::{
AppState, Error, Result,
db::{self, AccessTokenId, Database, UserId},
rpc::Principal,
AppState, Error, Result,
};
use anyhow::{anyhow, Context as _};
use anyhow::{Context as _, anyhow};
use axum::{
http::{self, Request, StatusCode},
middleware::Next,
response::IntoResponse,
};
use base64::prelude::*;
use prometheus::{exponential_buckets, register_histogram, Histogram};
use prometheus::{Histogram, exponential_buckets, register_histogram};
pub use rpc::auth::random_token;
use scrypt::{
password_hash::{PasswordHash, PasswordVerifier},
Scrypt,
password_hash::{PasswordHash, PasswordVerifier},
};
use serde::{Deserialize, Serialize};
use sha2::Digest;
@ -232,7 +232,7 @@ mod test {
use sea_orm::EntityTrait;
use super::*;
use crate::db::{access_token, NewUserParams};
use crate::db::{NewUserParams, access_token};
#[gpui::test]
async fn test_verify_access_token(cx: &mut gpui::TestAppContext) {

View file

@ -4,24 +4,24 @@ mod tables;
#[cfg(test)]
pub mod tests;
use crate::{executor::Executor, Error, Result};
use crate::{Error, Result, executor::Executor};
use anyhow::anyhow;
use collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use dashmap::DashMap;
use futures::StreamExt;
use project_repository_statuses::StatusKind;
use rand::{prelude::StdRng, Rng, SeedableRng};
use rand::{Rng, SeedableRng, prelude::StdRng};
use rpc::ExtensionProvides;
use rpc::{
proto::{self},
ConnectionId, ExtensionMetadata,
proto::{self},
};
use sea_orm::{
entity::prelude::*,
sea_query::{Alias, Expr, OnConflict},
ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction, DbErr,
FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
TransactionTrait,
entity::prelude::*,
sea_query::{Alias, Expr, OnConflict},
};
use semantic_version::SemanticVersion;
use serde::{Deserialize, Serialize};

View file

@ -1,6 +1,6 @@
use crate::Result;
use rpc::proto;
use sea_orm::{entity::prelude::*, DbErr};
use sea_orm::{DbErr, entity::prelude::*};
use serde::{Deserialize, Serialize};
#[macro_export]

View file

@ -1,7 +1,7 @@
use super::*;
use rpc::{
proto::{channel_member::Kind, ChannelBufferVersion, VectorClockEntry},
ErrorCode, ErrorCodeExt,
proto::{ChannelBufferVersion, VectorClockEntry, channel_member::Kind},
};
use sea_orm::{DbBackend, TryGetableMany};

View file

@ -480,7 +480,7 @@ impl Database {
self.notification_kinds_by_id
.iter()
.find(|(_, kind)| **kind == notification_kind)
.map(|kind| kind.0 .0)
.map(|kind| kind.0.0)
}
/// Removes the channel message with the given ID.

View file

@ -1,4 +1,4 @@
use crate::db::{channel_member, ChannelId, ChannelMemberId, ChannelRole, UserId};
use crate::db::{ChannelId, ChannelMemberId, ChannelRole, UserId, channel_member};
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]

View file

@ -20,8 +20,8 @@ use parking_lot::Mutex;
use sea_orm::ConnectionTrait;
use sqlx::migrate::MigrateDatabase;
use std::sync::{
atomic::{AtomicI32, AtomicU32, Ordering::SeqCst},
Arc,
atomic::{AtomicI32, AtomicU32, Ordering::SeqCst},
};
pub struct TestDb {

View file

@ -111,10 +111,11 @@ async fn test_channel_buffers(db: &Arc<Database>) {
assert_eq!(buffer_b.text(), "hello, cruel world");
// Ensure that C fails to open the buffer
assert!(db
.join_channel_buffer(zed_id, c_id, ConnectionId { owner_id, id: 3 })
.await
.is_err());
assert!(
db.join_channel_buffer(zed_id, c_id, ConnectionId { owner_id, id: 3 })
.await
.is_err()
);
// Ensure that both collaborators have shown up
assert_eq!(

View file

@ -1,13 +1,13 @@
use crate::{
db::{
tests::{channel_tree, new_test_connection, new_test_user},
Channel, ChannelId, ChannelRole, Database, NewUserParams, RoomId, UserId,
tests::{channel_tree, new_test_connection, new_test_user},
},
test_both_dbs,
};
use rpc::{
proto::{self},
ConnectionId,
proto::{self},
};
use std::sync::Arc;
@ -142,10 +142,11 @@ async fn test_joining_channels(db: &Arc<Database>) {
let room_id = RoomId::from_proto(joined_room.room.id);
drop(joined_room);
// cannot join a room without membership to its channel
assert!(db
.join_room(room_id, user_2, ConnectionId { owner_id, id: 1 },)
.await
.is_err());
assert!(
db.join_room(room_id, user_2, ConnectionId { owner_id, id: 1 },)
.await
.is_err()
);
}
test_both_dbs!(
@ -547,8 +548,8 @@ async fn test_user_is_channel_participant(db: &Arc<Database>) {
db.set_channel_member_role(zed_channel, admin, guest, ChannelRole::Banned)
.await
.unwrap();
assert!(db
.transaction(|tx| async move {
assert!(
db.transaction(|tx| async move {
db.check_user_is_channel_participant(
&db.get_channel_internal(public_channel_id, &tx)
.await
@ -559,7 +560,8 @@ async fn test_user_is_channel_participant(db: &Arc<Database>) {
.await
})
.await
.is_err());
.is_err()
);
let (mut members, _) = db
.get_channel_participant_details(public_channel_id, "", 100, admin)
@ -640,8 +642,8 @@ async fn test_user_is_channel_participant(db: &Arc<Database>) {
})
.await
.unwrap();
assert!(db
.transaction(|tx| async move {
assert!(
db.transaction(|tx| async move {
db.check_user_is_channel_participant(
&db.get_channel_internal(internal_channel_id, &tx)
.await
@ -652,7 +654,8 @@ async fn test_user_is_channel_participant(db: &Arc<Database>) {
.await
})
.await
.is_err(),);
.is_err(),
);
db.transaction(|tx| async move {
db.check_user_is_channel_participant(
@ -720,19 +723,21 @@ async fn test_guest_access(db: &Arc<Database>) {
.await
.unwrap();
assert!(db
.join_channel_chat(zed_channel, guest_connection, guest)
.await
.is_err());
assert!(
db.join_channel_chat(zed_channel, guest_connection, guest)
.await
.is_err()
);
db.join_channel(zed_channel, guest, guest_connection)
.await
.unwrap();
assert!(db
.join_channel_chat(zed_channel, guest_connection, guest)
.await
.is_ok())
assert!(
db.join_channel_chat(zed_channel, guest_connection, guest)
.await
.is_ok()
)
}
#[track_caller]

View file

@ -1,7 +1,7 @@
use super::TestDb;
use crate::db::embedding;
use collections::HashMap;
use sea_orm::{sea_query::Expr, ColumnTrait, EntityTrait, QueryFilter};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, sea_query::Expr};
use std::ops::Sub;
use time::{Duration, OffsetDateTime, PrimitiveDateTime};

View file

@ -6,7 +6,7 @@ use rpc::ExtensionProvides;
use super::Database;
use crate::db::ExtensionVersionConstraints;
use crate::{
db::{queries::extensions::convert_time_to_chrono, ExtensionMetadata, NewExtensionVersion},
db::{ExtensionMetadata, NewExtensionVersion, queries::extensions::convert_time_to_chrono},
test_both_dbs,
};
@ -162,10 +162,11 @@ async fn test_extensions(db: &Arc<Database>) {
}
// Record download returns false if the extension does not exist.
assert!(!db
.record_extension_download("no-such-extension", "0.0.2")
.await
.unwrap());
assert!(
!db.record_extension_download("no-such-extension", "0.0.2")
.await
.unwrap()
);
// Extensions are returned in descending order of total downloads.
let extensions = db.get_extensions(None, None, 1, 5).await.unwrap();

View file

@ -1,4 +1,4 @@
use anyhow::{anyhow, Result};
use anyhow::{Result, anyhow};
use std::fs;
use std::path::Path;

View file

@ -2,30 +2,30 @@ mod authorization;
pub mod db;
mod token;
use crate::api::events::SnowflakeRow;
use crate::api::CloudflareIpCountryHeader;
use crate::api::events::SnowflakeRow;
use crate::build_kinesis_client;
use crate::rpc::MIN_ACCOUNT_AGE_FOR_LLM_USE;
use crate::{db::UserId, executor::Executor, Cents, Config, Error, Result};
use anyhow::{anyhow, Context as _};
use crate::{Cents, Config, Error, Result, db::UserId, executor::Executor};
use anyhow::{Context as _, anyhow};
use authorization::authorize_access_to_language_model;
use axum::routing::get;
use axum::{
Extension, Json, Router, TypedHeader,
body::Body,
http::{self, HeaderName, HeaderValue, Request, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::post,
Extension, Json, Router, TypedHeader,
};
use chrono::{DateTime, Duration, Utc};
use collections::HashMap;
use db::TokenUsage;
use db::{usage_measure::UsageMeasure, ActiveUserCount, LlmDatabase};
use db::{ActiveUserCount, LlmDatabase, usage_measure::UsageMeasure};
use futures::{Stream, StreamExt as _};
use reqwest_client::ReqwestClient;
use rpc::{
proto::Plan, LanguageModelProvider, PerformCompletionParams, EXPIRED_LLM_TOKEN_HEADER_NAME,
EXPIRED_LLM_TOKEN_HEADER_NAME, LanguageModelProvider, PerformCompletionParams, proto::Plan,
};
use rpc::{ListModelsResponse, MAX_LLM_MONTHLY_SPEND_REACHED_HEADER_NAME};
use serde_json::json;

View file

@ -21,15 +21,15 @@ use std::sync::Arc;
use anyhow::anyhow;
pub use queries::usages::{ActiveUserCount, TokenUsage};
use sea_orm::prelude::*;
pub use sea_orm::ConnectOptions;
use sea_orm::prelude::*;
use sea_orm::{
ActiveValue, DatabaseConnection, DatabaseTransaction, IsolationLevel, TransactionTrait,
};
use crate::Result;
use crate::db::TransactionHandle;
use crate::executor::Executor;
use crate::Result;
/// The database for the LLM service.
pub struct LlmDatabase {

View file

@ -1,4 +1,4 @@
use sea_orm::{entity::prelude::*, DbErr};
use sea_orm::{DbErr, entity::prelude::*};
use serde::{Deserialize, Serialize};
use crate::id_type;

View file

@ -1,5 +1,5 @@
use super::*;
use sea_orm::{sea_query::OnConflict, QueryOrder};
use sea_orm::{QueryOrder, sea_query::OnConflict};
use std::str::FromStr;
use strum::IntoEnumIterator as _;

View file

@ -1,10 +1,11 @@
use crate::{
Cents,
db::UserId,
llm::{
db::{queries::providers::ModelParams, LlmDatabase, TokenUsage},
FREE_TIER_MONTHLY_SPENDING_LIMIT,
db::{LlmDatabase, TokenUsage, queries::providers::ModelParams},
},
test_llm_db, Cents,
test_llm_db,
};
use chrono::{DateTime, Utc};
use pretty_assertions::assert_eq;

View file

@ -1,11 +1,12 @@
use crate::llm::FREE_TIER_MONTHLY_SPENDING_LIMIT;
use crate::{
Cents,
db::UserId,
llm::db::{
queries::{providers::ModelParams, usages::Usage},
LlmDatabase, TokenUsage,
queries::{providers::ModelParams, usages::Usage},
},
test_llm_db, Cents,
test_llm_db,
};
use chrono::{DateTime, Duration, Utc};
use pretty_assertions::assert_eq;

View file

@ -1,8 +1,8 @@
use crate::Cents;
use crate::db::user;
use crate::llm::{DEFAULT_MAX_MONTHLY_SPEND, FREE_TIER_MONTHLY_SPENDING_LIMIT};
use crate::Cents;
use crate::{db::billing_preference, Config};
use anyhow::{anyhow, Result};
use crate::{Config, db::billing_preference};
use anyhow::{Result, anyhow};
use chrono::{NaiveDateTime, Utc};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

View file

@ -1,22 +1,22 @@
use anyhow::anyhow;
use axum::headers::HeaderMapExt;
use axum::{
Extension, Router,
extract::MatchedPath,
http::{Request, Response},
routing::get,
Extension, Router,
};
use collab::api::billing::sync_llm_usage_with_stripe_periodically;
use collab::api::CloudflareIpCountryHeader;
use collab::api::billing::sync_llm_usage_with_stripe_periodically;
use collab::llm::{db::LlmDatabase, log_usage_periodically};
use collab::migrations::run_database_migrations;
use collab::user_backfiller::spawn_user_backfiller;
use collab::{api::billing::poll_stripe_events_periodically, llm::LlmState, ServiceMode};
use collab::{
api::fetch_extensions_from_blob_store_periodically, db, env, executor::Executor,
rpc::ResultExt, AppState, Config, RateLimiter, Result,
AppState, Config, RateLimiter, Result, api::fetch_extensions_from_blob_store_periodically, db,
env, executor::Executor, rpc::ResultExt,
};
use collab::{ServiceMode, api::billing::poll_stripe_events_periodically, llm::LlmState};
use db::Database;
use std::{
env::args,
@ -29,9 +29,9 @@ use std::{
use tokio::signal::unix::SignalKind;
use tower_http::trace::TraceLayer;
use tracing_subscriber::{
filter::EnvFilter, fmt::format::JsonFields, util::SubscriberInitExt, Layer,
Layer, filter::EnvFilter, fmt::format::JsonFields, util::SubscriberInitExt,
};
use util::{maybe, ResultExt as _};
use util::{ResultExt as _, maybe};
const VERSION: &str = env!("CARGO_PKG_VERSION");
const REVISION: Option<&'static str> = option_env!("GITHUB_SHA");

View file

@ -1,11 +1,11 @@
use std::path::Path;
use std::time::Duration;
use anyhow::{anyhow, Result};
use anyhow::{Result, anyhow};
use collections::HashMap;
use sea_orm::ConnectOptions;
use sqlx::migrate::{Migrate, Migration, MigrationSource};
use sqlx::Connection;
use sqlx::migrate::{Migrate, Migration, MigrationSource};
/// Runs the database migrations for the specified database.
pub async fn run_database_migrations(

View file

@ -1,4 +1,4 @@
use crate::{db::UserId, executor::Executor, Database, Error, Result};
use crate::{Database, Error, Result, db::UserId, executor::Executor};
use chrono::{DateTime, Duration, Utc};
use dashmap::{DashMap, DashSet};
use rpc::ErrorCodeExt;

View file

@ -3,7 +3,7 @@ mod connection_pool;
use crate::api::{CloudflareIpCountryHeader, SystemIdHeader};
use crate::llm::LlmTokenClaims;
use crate::{
auth,
AppState, Config, Error, RateLimit, Result, auth,
db::{
self, BufferId, Capability, Channel, ChannelId, ChannelRole, ChannelsForUser,
CreatedChannelMessage, Database, InviteMemberResult, MembershipUpdated, MessageId,
@ -11,47 +11,46 @@ use crate::{
RespondToChannelInvite, RoomId, ServerId, UpdatedChannelMessage, User, UserId,
},
executor::Executor,
AppState, Config, Error, RateLimit, Result,
};
use anyhow::{anyhow, bail, Context as _};
use anyhow::{Context as _, anyhow, bail};
use async_tungstenite::tungstenite::{
protocol::CloseFrame as TungsteniteCloseFrame, Message as TungsteniteMessage,
Message as TungsteniteMessage, protocol::CloseFrame as TungsteniteCloseFrame,
};
use axum::{
Extension, Router, TypedHeader,
body::Body,
extract::{
ws::{CloseFrame as AxumCloseFrame, Message as AxumMessage},
ConnectInfo, WebSocketUpgrade,
ws::{CloseFrame as AxumCloseFrame, Message as AxumMessage},
},
headers::{Header, HeaderName},
http::StatusCode,
middleware,
response::IntoResponse,
routing::get,
Extension, Router, TypedHeader,
};
use chrono::Utc;
use collections::{HashMap, HashSet};
pub use connection_pool::{ConnectionPool, ZedVersion};
use core::fmt::{self, Debug, Formatter};
use http_client::HttpClient;
use open_ai::{OpenAiEmbeddingModel, OPEN_AI_API_URL};
use open_ai::{OPEN_AI_API_URL, OpenAiEmbeddingModel};
use reqwest_client::ReqwestClient;
use rpc::proto::split_repository_update;
use sha2::Digest;
use supermaven_api::{CreateExternalUserRequest, SupermavenAdminApi};
use futures::{
channel::oneshot, future::BoxFuture, stream::FuturesUnordered, FutureExt, SinkExt, StreamExt,
TryStreamExt,
FutureExt, SinkExt, StreamExt, TryStreamExt, channel::oneshot, future::BoxFuture,
stream::FuturesUnordered,
};
use prometheus::{register_int_gauge, IntGauge};
use prometheus::{IntGauge, register_int_gauge};
use rpc::{
Connection, ConnectionId, ErrorCode, ErrorCodeExt, ErrorExt, Peer, Receipt, TypedEnvelope,
proto::{
self, Ack, AnyTypedEnvelope, EntityMessage, EnvelopedMessage, LiveKitConnectionInfo,
RequestMessage, ShareProject, UpdateChannelBufferCollaborators,
},
Connection, ConnectionId, ErrorCode, ErrorCodeExt, ErrorExt, Peer, Receipt, TypedEnvelope,
};
use semantic_version::SemanticVersion;
use serde::{Serialize, Serializer};
@ -64,17 +63,18 @@ use std::{
ops::{Deref, DerefMut},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering::SeqCst},
Arc, OnceLock,
atomic::{AtomicBool, Ordering::SeqCst},
},
time::{Duration, Instant},
};
use time::OffsetDateTime;
use tokio::sync::{watch, MutexGuard, Semaphore};
use tokio::sync::{MutexGuard, Semaphore, watch};
use tower::ServiceBuilder;
use tracing::{
Instrument,
field::{self},
info_span, instrument, Instrument,
info_span, instrument,
};
pub const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
@ -1115,7 +1115,7 @@ pub async fn handle_websocket_request(
.into_response();
}
let Some(version) = app_version_header.map(|header| ZedVersion(header.0 .0)) else {
let Some(version) = app_version_header.map(|header| ZedVersion(header.0.0)) else {
return (
StatusCode::UPGRADE_REQUIRED,
"no version header found".to_string(),

View file

@ -1,5 +1,5 @@
use crate::db::{ChannelId, ChannelRole, UserId};
use anyhow::{anyhow, Result};
use anyhow::{Result, anyhow};
use collections::{BTreeMap, HashMap, HashSet};
use rpc::ConnectionId;
use semantic_version::SemanticVersion;
@ -159,12 +159,13 @@ impl ConnectionPool {
#[cfg(test)]
pub fn check_invariants(&self) {
for (connection_id, connection) in &self.connections {
assert!(self
.connected_users
.get(&connection.user_id)
.unwrap()
.connection_ids
.contains(connection_id));
assert!(
self.connected_users
.get(&connection.user_id)
.unwrap()
.connection_ids
.contains(connection_id)
);
}
for (user_id, state) in &self.connected_users {

View file

@ -3,7 +3,7 @@ use crate::db::{self, ChannelRole, NewUserParams};
use anyhow::Context as _;
use chrono::{DateTime, Utc};
use db::Database;
use serde::{de::DeserializeOwned, Deserialize};
use serde::{Deserialize, de::DeserializeOwned};
use std::{fs, path::Path};
use crate::Config;

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use crate::{llm, Cents, Result};
use crate::{Cents, Result, llm};
use anyhow::Context as _;
use chrono::{Datelike, Utc};
use collections::HashMap;

View file

@ -20,9 +20,9 @@ mod randomized_test_helpers;
mod remote_editing_collaboration_tests;
mod test_server;
use language::{tree_sitter_rust, Language, LanguageConfig, LanguageMatcher};
use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
pub use randomized_test_helpers::{
run_randomized_test, save_randomized_test_plan, RandomizedTest, TestError, UserTestPlan,
RandomizedTest, TestError, UserTestPlan, run_randomized_test, save_randomized_test_plan,
};
pub use test_server::{TestClient, TestServer};

View file

@ -1,6 +1,6 @@
use crate::{
rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
tests::{test_server::open_channel_notes, TestServer},
tests::{TestServer, test_server::open_channel_notes},
};
use call::ActiveCall;
use channel::ACKNOWLEDGE_DEBOUNCE_INTERVAL;
@ -10,7 +10,7 @@ use collections::HashMap;
use editor::{Anchor, Editor, ToOffset};
use futures::future;
use gpui::{BackgroundExecutor, Context, Entity, TestAppContext, Window};
use rpc::{proto::PeerId, RECEIVE_TIMEOUT};
use rpc::{RECEIVE_TIMEOUT, proto::PeerId};
use serde_json::json;
use std::ops::Range;

View file

@ -51,13 +51,15 @@ async fn test_channel_guests(
Some(project_id),
);
assert!(project_b.read_with(cx_b, |project, cx| project.is_read_only(cx)));
assert!(project_b
.update(cx_b, |project, cx| {
let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
project.create_entry((worktree_id, "b.txt"), false, cx)
})
.await
.is_err());
assert!(
project_b
.update(cx_b, |project, cx| {
let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
project.create_entry((worktree_id, "b.txt"), false, cx)
})
.await
.is_err()
);
assert!(room_b.read_with(cx_b, |room, _| room.is_muted()));
}
@ -110,10 +112,12 @@ async fn test_channel_guest_promotion(cx_a: &mut TestAppContext, cx_b: &mut Test
cx_b.update(|_window, cx_b| {
assert!(room_b.read_with(cx_b, |room, _| !room.can_use_microphone()));
});
assert!(room_b
.update(cx_b, |room, cx| room.share_microphone(cx))
.await
.is_err());
assert!(
room_b
.update(cx_b, |room, cx| room.share_microphone(cx))
.await
.is_err()
);
// B is promoted
active_call_a
@ -161,10 +165,12 @@ async fn test_channel_guest_promotion(cx_a: &mut TestAppContext, cx_b: &mut Test
// project and buffers are no longer editable
assert!(project_b.read_with(cx_b, |project, cx| project.is_read_only(cx)));
assert!(editor_b.update(cx_b, |editor, cx| editor.read_only(cx)));
assert!(room_b
.update(cx_b, |room, cx| room.share_microphone(cx))
.await
.is_err());
assert!(
room_b
.update(cx_b, |room, cx| room.share_microphone(cx))
.await
.is_err()
);
}
#[gpui::test]

View file

@ -1,7 +1,7 @@
use crate::{
db::{self, UserId},
rpc::RECONNECT_TIMEOUT,
tests::{room_participants, RoomParticipants, TestServer},
tests::{RoomParticipants, TestServer, room_participants},
};
use call::ActiveCall;
use channel::{ChannelMembership, ChannelStore};
@ -9,8 +9,8 @@ use client::{ChannelId, User};
use futures::future::try_join_all;
use gpui::{BackgroundExecutor, Entity, SharedString, TestAppContext};
use rpc::{
proto::{self, ChannelRole},
RECEIVE_TIMEOUT,
proto::{self, ChannelRole},
};
use std::sync::Arc;
@ -348,10 +348,12 @@ async fn test_joining_channel_ancestor_member(
let active_call_b = cx_b.read(ActiveCall::global);
assert!(active_call_b
.update(cx_b, |active_call, cx| active_call.join_channel(sub_id, cx))
.await
.is_ok());
assert!(
active_call_b
.update(cx_b, |active_call, cx| active_call.join_channel(sub_id, cx))
.await
.is_ok()
);
}
#[gpui::test]
@ -1203,10 +1205,12 @@ async fn test_guest_access(
let active_call_b = cx_b.read(ActiveCall::global);
// Non-members should not be allowed to join
assert!(active_call_b
.update(cx_b, |call, cx| call.join_channel(channel_a, cx))
.await
.is_err());
assert!(
active_call_b
.update(cx_b, |call, cx| call.join_channel(channel_a, cx))
.await
.is_err()
);
// Make channels A and B public
client_a
@ -1271,10 +1275,12 @@ async fn test_invite_access(
let active_call_b = cx_b.read(ActiveCall::global);
// should not be allowed to join
assert!(active_call_b
.update(cx_b, |call, cx| call.join_channel(channel_b_id, cx))
.await
.is_err());
assert!(
active_call_b
.update(cx_b, |call, cx| call.join_channel(channel_b_id, cx))
.await
.is_err()
);
client_a
.channel_store()

View file

@ -1,9 +1,10 @@
use crate::{
rpc::RECONNECT_TIMEOUT,
tests::{rust_lang, TestServer},
tests::{TestServer, rust_lang},
};
use call::ActiveCall;
use editor::{
Editor, RowInfo,
actions::{
ConfirmCodeAction, ConfirmCompletion, ConfirmRename, ContextMenuFirst,
ExpandMacroRecursively, Redo, Rename, ToggleCodeActions, Undo,
@ -12,23 +13,22 @@ use editor::{
editor_test_context::{AssertionContextManager, EditorTestContext},
expand_macro_recursively,
},
Editor, RowInfo,
};
use fs::Fs;
use futures::StreamExt;
use gpui::{TestAppContext, UpdateGlobal, VisualContext, VisualTestContext};
use indoc::indoc;
use language::{
language_settings::{AllLanguageSettings, InlayHintSettings},
FakeLspAdapter,
language_settings::{AllLanguageSettings, InlayHintSettings},
};
use project::{
ProjectPath, SERVER_PROGRESS_THROTTLE_TIMEOUT,
lsp_store::{
lsp_ext_command::{ExpandedMacro, LspExpandMacro},
rust_analyzer_ext::RUST_ANALYZER_NAME,
},
project_settings::{InlineBlameSettings, ProjectSettings},
ProjectPath, SERVER_PROGRESS_THROTTLE_TIMEOUT,
};
use recent_projects::disconnected_overlay::DisconnectedOverlay;
use rpc::RECEIVE_TIMEOUT;
@ -38,8 +38,8 @@ use std::{
ops::Range,
path::{Path, PathBuf},
sync::{
atomic::{self, AtomicBool, AtomicUsize},
Arc,
atomic::{self, AtomicBool, AtomicUsize},
},
};
use text::Point;

View file

@ -8,8 +8,8 @@ use collab_ui::{
};
use editor::{Editor, ExcerptRange, MultiBuffer};
use gpui::{
point, AppContext as _, BackgroundExecutor, BorrowAppContext, Entity, SharedString,
TestAppContext, VisualTestContext,
AppContext as _, BackgroundExecutor, BorrowAppContext, Entity, SharedString, TestAppContext,
VisualTestContext, point,
};
use language::Capability;
use project::WorktreeSettings;
@ -17,7 +17,7 @@ use rpc::proto::PeerId;
use serde_json::json;
use settings::SettingsStore;
use util::path;
use workspace::{item::ItemHandle as _, SplitDirection, Workspace};
use workspace::{SplitDirection, Workspace, item::ItemHandle as _};
use super::TestClient;
@ -441,7 +441,7 @@ async fn test_basic_following(
use crate::rpc::RECONNECT_TIMEOUT;
use gpui::TestScreenCaptureSource;
use workspace::{
dock::{test::TestPanel, DockPosition},
dock::{DockPosition, test::TestPanel},
item::test::TestItem,
shared_screen::SharedScreen,
};

View file

@ -1,38 +1,39 @@
use crate::{
rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
tests::{
channel_id, following_tests::join_channel, room_participants, rust_lang, RoomParticipants,
TestClient, TestServer,
RoomParticipants, TestClient, TestServer, channel_id, following_tests::join_channel,
room_participants, rust_lang,
},
};
use anyhow::{anyhow, Result};
use anyhow::{Result, anyhow};
use assistant_context_editor::ContextStore;
use assistant_slash_command::SlashCommandWorkingSet;
use buffer_diff::{assert_hunks, DiffHunkSecondaryStatus, DiffHunkStatus};
use call::{room, ActiveCall, ParticipantLocation, Room};
use client::{User, RECEIVE_TIMEOUT};
use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus, assert_hunks};
use call::{ActiveCall, ParticipantLocation, Room, room};
use client::{RECEIVE_TIMEOUT, User};
use collections::{HashMap, HashSet};
use fs::{FakeFs, Fs as _, RemoveOptions};
use futures::{channel::mpsc, StreamExt as _};
use futures::{StreamExt as _, channel::mpsc};
use git::status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode};
use gpui::{
px, size, App, BackgroundExecutor, Entity, Modifiers, MouseButton, MouseDownEvent,
TestAppContext, UpdateGlobal,
App, BackgroundExecutor, Entity, Modifiers, MouseButton, MouseDownEvent, TestAppContext,
UpdateGlobal, px, size,
};
use language::{
Diagnostic, DiagnosticEntry, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher,
LineEnding, OffsetRangeExt, Point, Rope,
language_settings::{
AllLanguageSettings, Formatter, FormatterList, PrettierSettings, SelectedFormatter,
},
tree_sitter_rust, tree_sitter_typescript, Diagnostic, DiagnosticEntry, FakeLspAdapter,
Language, LanguageConfig, LanguageMatcher, LineEnding, OffsetRangeExt, Point, Rope,
tree_sitter_rust, tree_sitter_typescript,
};
use lsp::{LanguageServerId, OneOf};
use parking_lot::Mutex;
use pretty_assertions::assert_eq;
use project::{
DiagnosticSummary, HoverBlockKind, Project, ProjectPath,
lsp_store::{FormatTrigger, LspFormatTarget},
search::{SearchQuery, SearchResult},
DiagnosticSummary, HoverBlockKind, Project, ProjectPath,
};
use prompt_store::PromptBuilder;
use rand::prelude::*;
@ -44,8 +45,8 @@ use std::{
path::{Path, PathBuf},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering::SeqCst},
Arc,
atomic::{AtomicBool, Ordering::SeqCst},
},
time::Duration,
};
@ -6206,15 +6207,19 @@ async fn test_contact_requests(
executor.run_until_parked();
assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
assert!(client_b
.summarize_contacts(cx_b)
.incoming_requests
.is_empty());
assert!(
client_b
.summarize_contacts(cx_b)
.incoming_requests
.is_empty()
);
assert!(client_c.summarize_contacts(cx_c).current.is_empty());
assert!(client_c
.summarize_contacts(cx_c)
.outgoing_requests
.is_empty());
assert!(
client_c
.summarize_contacts(cx_c)
.outgoing_requests
.is_empty()
);
async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
client.disconnect(&cx.to_async());

View file

@ -3,7 +3,7 @@ use std::sync::Arc;
use gpui::{BackgroundExecutor, TestAppContext};
use notifications::NotificationEvent;
use parking_lot::Mutex;
use rpc::{proto, Notification};
use rpc::{Notification, proto};
use crate::tests::TestServer;

View file

@ -1,6 +1,6 @@
use crate::db::ChannelRole;
use super::{run_randomized_test, RandomizedTest, TestClient, TestError, TestServer, UserTestPlan};
use super::{RandomizedTest, TestClient, TestError, TestServer, UserTestPlan, run_randomized_test};
use anyhow::Result;
use async_trait::async_trait;
use gpui::{BackgroundExecutor, SharedString, TestAppContext};

View file

@ -1,6 +1,6 @@
use super::{RandomizedTest, TestClient, TestError, TestServer, UserTestPlan};
use crate::{db::UserId, tests::run_randomized_test};
use anyhow::{anyhow, Result};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use call::ActiveCall;
use collections::{BTreeMap, HashMap};
@ -9,12 +9,12 @@ use fs::{FakeFs, Fs as _};
use git::status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode};
use gpui::{BackgroundExecutor, Entity, TestAppContext};
use language::{
range_to_lsp, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, PointUtf16,
FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, PointUtf16, range_to_lsp,
};
use lsp::FakeLanguageServer;
use pretty_assertions::assert_eq;
use project::{
search::SearchQuery, search::SearchResult, Project, ProjectPath, DEFAULT_COMPLETION_CONTEXT,
DEFAULT_COMPLETION_CONTEXT, Project, ProjectPath, search::SearchQuery, search::SearchResult,
};
use rand::{
distributions::{Alphanumeric, DistString},
@ -27,7 +27,7 @@ use std::{
rc::Rc,
sync::Arc,
};
use util::{path, ResultExt};
use util::{ResultExt, path};
#[gpui::test(
iterations = 100,
@ -784,10 +784,12 @@ impl RandomizedTest for ProjectCollaborationTest {
let save = cx.spawn(|cx| async move {
save.await
.map_err(|err| anyhow!("save request failed: {:?}", err))?;
assert!(buffer
.read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })
.expect("App should not be dropped")
.observed_all(&requested_version));
assert!(
buffer
.read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })
.expect("App should not be dropped")
.observed_all(&requested_version)
);
anyhow::Ok(())
});
if detach {

View file

@ -9,7 +9,7 @@ use gpui::{BackgroundExecutor, Task, TestAppContext};
use parking_lot::Mutex;
use rand::prelude::*;
use rpc::RECEIVE_TIMEOUT;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use settings::SettingsStore;
use std::sync::OnceLock;
use std::{
@ -17,8 +17,8 @@ use std::{
path::PathBuf,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering::SeqCst},
Arc,
atomic::{AtomicBool, Ordering::SeqCst},
},
};

View file

@ -10,17 +10,17 @@ use gpui::{
};
use http_client::BlockedHttpClient;
use language::{
FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, LanguageRegistry,
language_settings::{
language_settings, AllLanguageSettings, Formatter, FormatterList, PrettierSettings,
SelectedFormatter,
AllLanguageSettings, Formatter, FormatterList, PrettierSettings, SelectedFormatter,
language_settings,
},
tree_sitter_typescript, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher,
LanguageRegistry,
tree_sitter_typescript,
};
use node_runtime::NodeRuntime;
use project::{
lsp_store::{FormatTrigger, LspFormatTarget},
ProjectPath,
lsp_store::{FormatTrigger, LspFormatTarget},
};
use remote::SshRemoteClient;
use remote_server::{HeadlessAppState, HeadlessProject};

View file

@ -1,22 +1,22 @@
use crate::{
db::{tests::TestDb, NewUserParams, UserId},
executor::Executor,
rpc::{Principal, Server, ZedVersion, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
AppState, Config, RateLimiter,
db::{NewUserParams, UserId, tests::TestDb},
executor::Executor,
rpc::{CLEANUP_TIMEOUT, Principal, RECONNECT_TIMEOUT, Server, ZedVersion},
};
use anyhow::anyhow;
use call::ActiveCall;
use channel::{ChannelBuffer, ChannelStore};
use client::{
self, proto::PeerId, ChannelId, Client, Connection, Credentials, EstablishConnectionError,
UserStore,
self, ChannelId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
proto::PeerId,
};
use clock::FakeSystemClock;
use collab_ui::channel_view::ChannelView;
use collections::{HashMap, HashSet};
use dap::DapRegistry;
use fs::FakeFs;
use futures::{channel::oneshot, StreamExt as _};
use futures::{StreamExt as _, channel::oneshot};
use git::GitHostingProviderRegistry;
use gpui::{AppContext as _, BackgroundExecutor, Entity, Task, TestAppContext, VisualTestContext};
use http_client::FakeHttpClient;
@ -27,8 +27,8 @@ use parking_lot::Mutex;
use project::{Project, WorktreeId};
use remote::SshRemoteClient;
use rpc::{
proto::{self, ChannelRole},
RECEIVE_TIMEOUT,
proto::{self, ChannelRole},
};
use semantic_version::SemanticVersion;
use serde_json::json;
@ -40,8 +40,8 @@ use std::{
ops::{Deref, DerefMut},
path::Path,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
},
};
use util::path;

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use anyhow::{anyhow, Context as _, Result};
use anyhow::{Context as _, Result, anyhow};
use chrono::{DateTime, Utc};
use util::ResultExt;