refactor: prefer Arc<str> to String

This commit is contained in:
2026-05-23 18:45:44 +01:00
parent 1ef91cb41e
commit 1843622540
15 changed files with 524 additions and 544 deletions

View File

@@ -175,8 +175,10 @@ fn render_github_fixtures(fixture_root: &Path) -> String {
if let Some(id) = parse_pull_request_file_tree_fixture_name(&file_name) {
let value = read_fixture_value(&entry.path());
pull_request_file_tree_fixtures
.insert(id, read_pull_request_file_tree_fixture(&value, &entry.path()));
pull_request_file_tree_fixtures.insert(
id,
read_pull_request_file_tree_fixture(&value, &entry.path()),
);
continue;
}

View File

@@ -8,9 +8,9 @@ fn main() {
for change in diff.iter_all_changes() {
let sign = match change.tag() {
ChangeTag::Delete => "-",
ChangeTag::Insert => "+",
ChangeTag::Equal => " ",
| ChangeTag::Delete => "-",
| ChangeTag::Insert => "+",
| ChangeTag::Equal => " ",
};
print!("{}{}", sign, change);
}

View File

@@ -1,3 +1,5 @@
use std::sync::Arc;
use reqwest::Method;
use serde::{Deserialize, Serialize};
@@ -22,7 +24,7 @@ pub struct QueryContext {
#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct AuthTokens {
pub(crate) access_token: String,
pub(crate) access_token: Arc<str>,
}
#[derive(Clone)]

View File

@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
use serde::Deserialize;
@@ -11,9 +11,9 @@ pub struct CreateDeviceCode;
#[derive(Deserialize)]
pub(crate) struct DeviceCodeResponse {
pub device_code: String,
pub user_code: String,
pub vertification_uri: Option<String>,
pub device_code: Arc<str>,
pub user_code: Arc<str>,
pub vertification_uri: Option<Arc<str>>,
pub expires_in: u16,
// minimum number of seconds between polling for access token
@@ -46,14 +46,14 @@ impl query::QueryFn for CreateDeviceCode {
#[derive(Clone)]
pub struct RequestAccessToken {
pub device_code: String,
pub device_code: Arc<str>,
}
#[derive(Deserialize)]
pub struct RequestAccessTokenResponse {
pub access_token: String,
pub token_type: String,
pub scope: String,
pub access_token: Arc<str>,
pub token_type: Arc<str>,
pub scope: Arc<str>,
}
impl query::QueryFn for RequestAccessToken {

View File

@@ -1,4 +1,4 @@
use std::ops::Deref;
use std::sync::Arc;
use graphql_client::GraphQLQuery;
use serde::Deserialize;
@@ -21,33 +21,7 @@ type GitObjectID = String;
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub(crate) struct Id(String);
impl Deref for Id {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<&str> for Id {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Id {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<Id> for String {
fn from(value: Id) -> Self {
value.0
}
}
pub(crate) struct Id(pub(crate) Arc<str>);
#[derive(Debug, Deserialize)]
pub(crate) struct PullRequestPaginatedResponse {
@@ -59,32 +33,32 @@ pub(crate) struct PullRequestPaginatedResponse {
#[derive(Debug, Deserialize)]
pub(crate) struct PullRequest {
pub(crate) id: Id,
pub(crate) title: String,
pub(crate) title: Arc<str>,
pub(crate) state: PullRequestState,
pub(crate) is_draft: bool,
pub(crate) repo_slug: String,
pub(crate) repo_slug: Arc<str>,
}
#[derive(Debug, Deserialize)]
pub(crate) struct DetailedPullRequest {
pub(crate) title: String,
pub(crate) title: Arc<str>,
pub(crate) state: PullRequestState,
pub(crate) is_draft: bool,
pub(crate) body: String,
pub(crate) body: Arc<str>,
pub(crate) created_at: Option<chrono::DateTime<chrono::FixedOffset>>,
pub(crate) author: Option<super::user::Actor>,
pub(crate) base_branch_name: String,
pub(crate) base_repo_slug: String,
pub(crate) base_ref: String,
pub(crate) head_branch_name: String,
pub(crate) head_ref: String,
pub(crate) head_repo_slug: String,
pub(crate) base_branch_name: Arc<str>,
pub(crate) base_repo_slug: Arc<str>,
pub(crate) base_ref: Arc<str>,
pub(crate) head_branch_name: Arc<str>,
pub(crate) head_ref: Arc<str>,
pub(crate) head_repo_slug: Arc<str>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PullRequestTimeline {
pub(crate) items: Vec<PullRequestTimelineItem>,
pub(crate) end_cursor: Option<String>,
pub(crate) end_cursor: Option<Arc<str>>,
pub(crate) has_next_page: bool,
}
@@ -245,12 +219,6 @@ pub(crate) struct TimelineActor {
pub(crate) avatar_url: Option<String>,
}
impl std::fmt::Display for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub(crate) enum PullRequestState {
@@ -310,6 +278,24 @@ pub(crate) struct ListPullRequests {
pub page: u32,
}
impl std::fmt::Display for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl From<String> for Id {
fn from(value: String) -> Self {
Self(value.into())
}
}
impl From<&str> for Id {
fn from(value: &str) -> Self {
Self(value.into())
}
}
impl query::QueryFn for ListPullRequests {
type Data = PullRequestPaginatedResponse;
type Error = api::Error;
@@ -357,13 +343,14 @@ impl query::QueryFn for ListPullRequests {
| PullRequestPaginationQuerySearchEdgesNode::PullRequest(p) => {
Some(PullRequest {
id: p.id.into(),
title: p.title,
title: p.title.into(),
state: p.state,
is_draft: p.is_draft,
repo_slug: format!(
"{}/{}",
p.repository.owner.login, p.repository.name
),
)
.into(),
})
}
| _ => None,
@@ -399,7 +386,7 @@ impl query::QueryFn for FetchPullRequest {
}
let gql = PullRequestQuery::build_query(pull_request_query::Variables {
id: self.id.clone().into(),
id: self.id.to_string(),
});
let res = c.github_graphql_request(&gql)?.send().await?;
@@ -421,26 +408,26 @@ impl query::QueryFn for FetchPullRequest {
})?;
Ok(DetailedPullRequest {
title: p.title,
title: p.title.into(),
state: p.state,
is_draft: p.is_draft,
body: p.body,
body: p.body.into(),
author: p.author.map(|it| api::user::Actor {
login: it.login,
avatar_url: it.avatar_url,
login: it.login.into(),
avatar_url: it.avatar_url.into(),
}),
base_repo_slug: p
.base_repository
.map(|it| it.name_with_owner)
.map(|it| it.name_with_owner.into())
.unwrap_or_default(),
base_branch_name: p.base_ref_name,
base_ref: p.base_ref_oid,
base_branch_name: p.base_ref_name.into(),
base_ref: p.base_ref_oid.into(),
head_repo_slug: p
.head_repository
.map(|it| it.name_with_owner)
.map(|it| it.name_with_owner.into())
.unwrap_or_default(),
head_branch_name: p.head_ref_name,
head_ref: p.head_ref_oid,
head_branch_name: p.head_ref_name.into(),
head_ref: p.head_ref_oid.into(),
created_at: Some(created_at),
})
}
@@ -473,7 +460,7 @@ impl query::QueryFn for FetchPullRequestFileTree {
} else {
let gql =
PullRequestFileTreeQuery::build_query(pull_request_file_tree_query::Variables {
id: self.id.clone().into(),
id: self.id.to_string(),
first: self.first,
});
@@ -558,7 +545,7 @@ impl query::QueryFn for FetchPullRequestFileTree {
pub(crate) struct FetchPullRequestTimeline {
pub(crate) id: Id,
pub(crate) first: i64,
pub(crate) after: Option<String>,
pub(crate) after: Option<Arc<str>>,
}
impl query::QueryFn for FetchPullRequestTimeline {
@@ -841,9 +828,9 @@ impl query::QueryFn for FetchPullRequestTimeline {
} else {
let gql =
PullRequestTimelineQuery::build_query(pull_request_timeline_query::Variables {
id: self.id.clone().into(),
id: self.id.to_string(),
first: self.first,
after: self.after.clone(),
after: self.after.as_ref().map(|it| it.to_string()),
});
let res = c.github_graphql_request(&gql)?.send().await?;
@@ -892,7 +879,7 @@ impl query::QueryFn for FetchPullRequestTimeline {
Ok(PullRequestTimeline {
items,
end_cursor: timeline.page_info.end_cursor,
end_cursor: timeline.page_info.end_cursor.map(|it| it.into()),
has_next_page: timeline.page_info.has_next_page,
})
}

View File

@@ -175,12 +175,12 @@ mod tests {
assert_eq!(merged.state, issues::PullRequestState::Merged);
assert!(merged.body.contains("| Stage | Owner | Status |"));
assert_eq!(
merged.author.as_ref().map(|author| author.login.as_str()),
merged.author.as_ref().map(|author| author.login.as_ref()),
Some("rorycraft")
);
assert_eq!(merged.base_branch_name.as_str(), "main");
assert_eq!(merged.base_branch_name.as_ref(), "main");
assert_eq!(
merged.head_branch_name.as_str(),
merged.head_branch_name.as_ref(),
"feat/release-handoff-checklist"
);
assert_eq!(
@@ -196,12 +196,12 @@ mod tests {
documented_failover
.author
.as_ref()
.map(|author| author.login.as_str()),
.map(|author| author.login.as_ref()),
Some("kennethnym")
);
assert_eq!(documented_failover.base_branch_name.as_str(), "main");
assert_eq!(documented_failover.base_branch_name.as_ref(), "main");
assert_eq!(
documented_failover.head_branch_name.as_str(),
documented_failover.head_branch_name.as_ref(),
"docs/manual-failover-steps"
);
assert_eq!(
@@ -209,17 +209,17 @@ mod tests {
Some(chrono::DateTime::parse_from_rfc3339("2026-04-24T06:40:00Z").unwrap())
);
assert!(dashboard_markdown.body.contains("```rust"));
assert_eq!(dashboard_markdown.base_branch_name.as_str(), "main");
assert_eq!(dashboard_markdown.base_branch_name.as_ref(), "main");
assert_eq!(
dashboard_markdown.head_branch_name.as_str(),
dashboard_markdown.head_branch_name.as_ref(),
"feat/cached-issue-pane"
);
assert_eq!(
dashboard_markdown.base_ref.as_str(),
dashboard_markdown.base_ref.as_ref(),
"5e8745bfcc0c90c226d3c6af84226d6d4a5ec2d1"
);
assert_eq!(
dashboard_markdown.head_ref.as_str(),
dashboard_markdown.head_ref.as_ref(),
"2bc41de7731b9ef48f7d64ee9f0d5f497dbe0a51"
);
assert_eq!(
@@ -230,20 +230,20 @@ mod tests {
cached_repo_picker
.author
.as_ref()
.map(|author| author.login.as_str()),
.map(|author| author.login.as_ref()),
Some("kennethnym")
);
assert_eq!(cached_repo_picker.base_branch_name.as_str(), "main");
assert_eq!(cached_repo_picker.base_branch_name.as_ref(), "main");
assert_eq!(
cached_repo_picker.head_branch_name.as_str(),
cached_repo_picker.head_branch_name.as_ref(),
"feat/cached-repo-picker"
);
assert_eq!(
cached_repo_picker.base_ref.as_str(),
cached_repo_picker.base_ref.as_ref(),
"5e8745bfcc0c90c226d3c6af84226d6d4a5ec2d1"
);
assert_eq!(
cached_repo_picker.head_ref.as_str(),
cached_repo_picker.head_ref.as_ref(),
"13af7d0b48a6ce0b22d48c9b6c1c78dfcd94e6a0"
);
assert_eq!(
@@ -254,12 +254,12 @@ mod tests {
worker_split
.author
.as_ref()
.map(|author| author.login.as_str()),
.map(|author| author.login.as_ref()),
Some("leaferiksen")
);
assert_eq!(worker_split.base_branch_name.as_str(), "main");
assert_eq!(worker_split.base_branch_name.as_ref(), "main");
assert_eq!(
worker_split.head_branch_name.as_str(),
worker_split.head_branch_name.as_ref(),
"feat/worker-context-envelope"
);
assert_eq!(
@@ -270,12 +270,12 @@ mod tests {
spacing_tokens
.author
.as_ref()
.map(|author| author.login.as_str()),
.map(|author| author.login.as_ref()),
Some("mariahops")
);
assert_eq!(spacing_tokens.base_branch_name.as_str(), "main");
assert_eq!(spacing_tokens.base_branch_name.as_ref(), "main");
assert_eq!(
spacing_tokens.head_branch_name.as_str(),
spacing_tokens.head_branch_name.as_ref(),
"chore/dashboard-spacing-scale"
);
assert_eq!(
@@ -294,13 +294,13 @@ mod tests {
let base_query = fetch_file_content(
"kennethnym/novem",
"src/query.rs",
Some(dashboard_markdown.base_ref.as_str()),
Some(dashboard_markdown.base_ref.as_ref()),
)
.expect("base query fixture should exist");
let head_query = fetch_file_content(
"kennethnym/novem",
"src/query.rs",
Some(dashboard_markdown.head_ref.as_str()),
Some(dashboard_markdown.head_ref.as_ref()),
)
.expect("head query fixture should exist");
let base_query = std::str::from_utf8(base_query.as_ref())
@@ -317,13 +317,13 @@ mod tests {
let base_repo = fetch_file_content(
"kennethnym/novem",
"src/api/repo.rs",
Some(cached_repo_picker.base_ref.as_str()),
Some(cached_repo_picker.base_ref.as_ref()),
)
.expect("base repo fixture should exist");
let head_repo = fetch_file_content(
"kennethnym/novem",
"src/api/repo.rs",
Some(cached_repo_picker.head_ref.as_str()),
Some(cached_repo_picker.head_ref.as_ref()),
)
.expect("head repo fixture should exist");
let base_repo =
@@ -364,15 +364,15 @@ mod tests {
for path in file_paths {
fetch_file_content(
dashboard_markdown.base_repo_slug.as_str(),
dashboard_markdown.base_repo_slug.as_ref(),
path,
Some(dashboard_markdown.base_ref.as_str()),
Some(dashboard_markdown.base_ref.as_ref()),
)
.unwrap_or_else(|_| panic!("base fixture should exist for {path}"));
fetch_file_content(
dashboard_markdown.head_repo_slug.as_str(),
dashboard_markdown.head_repo_slug.as_ref(),
path,
Some(dashboard_markdown.head_ref.as_str()),
Some(dashboard_markdown.head_ref.as_ref()),
)
.unwrap_or_else(|_| panic!("head fixture should exist for {path}"));
}
@@ -440,35 +440,29 @@ mod tests {
.expect("third timeline fixture json should parse");
let first_page_nodes = match first_page.node.as_ref() {
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => {
pull_request
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => pull_request
.timeline_items
.nodes
.as_ref()
.expect("first timeline fixture page should contain timeline nodes")
}
.expect("first timeline fixture page should contain timeline nodes"),
| _ => panic!("first timeline fixture page should resolve to a pull request node"),
};
let second_page_nodes = match second_page.node.as_ref() {
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => {
pull_request
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => pull_request
.timeline_items
.nodes
.as_ref()
.expect("second timeline fixture page should contain timeline nodes")
}
.expect("second timeline fixture page should contain timeline nodes"),
| _ => panic!("second timeline fixture page should resolve to a pull request node"),
};
let third_page_nodes = match third_page.node.as_ref() {
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => {
pull_request
| Some(issues::PullRequestTimelineResponseNode::PullRequest(pull_request)) => pull_request
.timeline_items
.nodes
.as_ref()
.expect("third timeline fixture page should contain timeline nodes")
}
.expect("third timeline fixture page should contain timeline nodes"),
| _ => panic!("third timeline fixture page should resolve to a pull request node"),
};

View File

@@ -1,11 +1,10 @@
use futures::{FutureExt, TryFutureExt};
use std::sync::Arc;
use reqwest::Method;
use serde::Deserialize;
use tokio::sync::OwnedRwLockReadGuard;
use crate::{
api,
query::{self, Query, fetch_query},
api, query,
util::{self, file},
};
@@ -31,9 +30,9 @@ pub struct Owner {
#[derive(Debug, Clone)]
pub struct FileRef {
pub repo_slug: String,
pub path: String,
pub reff: Option<String>,
pub repo_slug: Arc<str>,
pub path: Arc<str>,
pub reff: Option<Arc<str>>,
}
#[derive(Clone)]
@@ -67,9 +66,9 @@ impl query::QueryFn for List {
#[derive(Clone)]
pub struct FetchFileContent {
pub repo_slug: String,
pub path: String,
pub reff: Option<String>,
pub repo_slug: Arc<str>,
pub path: Arc<str>,
pub reff: Option<Arc<str>>,
}
impl query::QueryFn for FetchFileContent {

View File

@@ -1,4 +1,4 @@
use std::ops::Deref;
use std::{ops::Deref, sync::Arc};
use reqwest::Method;
use serde::{Deserialize, Serialize};
@@ -12,18 +12,18 @@ pub struct Id(u64);
#[derive(Debug, Deserialize)]
pub struct User {
pub login: String,
pub login: Arc<str>,
pub id: Id,
pub avatar_url: String,
pub html_url: String,
pub name: Option<String>,
pub email: Option<String>,
pub avatar_url: Arc<str>,
pub html_url: Arc<str>,
pub name: Option<Arc<str>>,
pub email: Option<Arc<str>>,
}
#[derive(Debug, Deserialize)]
pub(crate) struct Actor {
pub(crate) login: String,
pub(crate) avatar_url: String,
pub(crate) login: Arc<str>,
pub(crate) avatar_url: Arc<str>,
}
impl Deref for Id {

View File

@@ -1,6 +1,9 @@
// markdown treesitter playground: https://ikatyang.github.io/tree-sitter-markdown/
use std::{ops::Range, sync::LazyLock};
use std::{
ops::Range,
sync::{Arc, LazyLock},
};
use gpui::{AppContext, ParentElement, Refineable, Styled, div, px, relative, rems};
@@ -86,7 +89,7 @@ const MARKDOWN_KIND_ID_TABLE_CELL: u16 = 235;
const MARKDOWN_KIND_ID_TASK_LIST_ITEM_MARKER: u16 = 236;
pub(crate) struct MarkdownText {
content: gpui::SharedString,
content: Arc<str>,
blocks: Vec<ContentBlock>,
}
@@ -100,10 +103,7 @@ enum ContentBlock {
},
}
pub(crate) fn new(
content: gpui::SharedString,
cx: &mut gpui::Context<MarkdownText>,
) -> MarkdownText {
pub(crate) fn new(content: Arc<str>, cx: &mut gpui::Context<MarkdownText>) -> MarkdownText {
let mut view = MarkdownText {
content,
blocks: Vec::new(),
@@ -122,13 +122,13 @@ impl Styled for ContentBlock {
impl MarkdownText {
fn on_create(&mut self, cx: &gpui::Context<Self>) {
let content = self.content.clone();
let content = Arc::clone(&self.content);
let t = cx.background_spawn(async move {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(tree_sitter_markdown::language())
.expect("tree-sitter-markdown language should load");
parser.parse(content.as_str(), None)
parser.parse(content.as_bytes(), None)
});
cx.spawn(async |weak, cx| {
@@ -214,10 +214,8 @@ impl MarkdownText {
if cursor.goto_next_sibling()
&& let Ok(src) = cursor.node().utf8_text(content.as_bytes())
{
links.push((
node_range!(),
gpui::SharedString::from(String::from(src)),
));
links
.push((node_range!(), gpui::SharedString::from(String::from(src))));
} else {
// the link src is invalid, use an empty string as a fallback
// link on click handler will ignore empty string

View File

@@ -1,5 +1,3 @@
use std::ops::Deref;
use gpui::{
InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, div, list,
point, prelude::FluentBuilder, px,
@@ -13,6 +11,7 @@ use crate::{
text::text,
},
query::{self, QueryStatus, read_query, use_query},
util::str::ToSharedString,
};
pub(crate) struct IssueList {
@@ -20,7 +19,6 @@ pub(crate) struct IssueList {
list_state: gpui::ListState,
list_items: Vec<IssueListItem>,
selected_item: Option<(usize, gpui::SharedString)>,
}
pub(crate) enum Event {
@@ -29,7 +27,7 @@ pub(crate) enum Event {
#[derive(gpui::IntoElement, Clone)]
pub(crate) struct IssueListItem {
id: gpui::SharedString,
id: api::issues::Id,
repo_name: Option<gpui::SharedString>,
title: gpui::SharedString,
description: Option<gpui::SharedString>,
@@ -51,7 +49,6 @@ pub(crate) fn new(cx: &mut gpui::Context<IssueList>) -> IssueList {
list_state: gpui::ListState::new(0, gpui::ListAlignment::Top, px(100.)),
list_items: Vec::new(),
selected_item: None,
};
list.on_create(cx);
list
@@ -66,16 +63,12 @@ impl IssueList {
let new_len = res.items.len();
let new_items = res.items.iter().enumerate().map(|(i, it)| IssueListItem {
id: gpui::SharedString::from(it.id.deref()),
repo_name: Some(gpui::SharedString::new(it.repo_slug.as_str())),
title: gpui::SharedString::new(it.title.as_str()),
id: it.id.clone(),
repo_name: Some(it.repo_slug.to_shared_string()),
title: it.title.to_shared_string(),
description: None,
status: it.state,
is_selected: this
.selected_item
.as_ref()
.map(|(_, id)| id.as_str() == it.id.as_str())
.unwrap_or(false),
is_selected: false,
is_last: i == new_len - 1,
is_draft: it.is_draft,
});
@@ -95,7 +88,7 @@ impl IssueList {
item.is_selected = i == j;
}
cx.notify();
cx.emit(Event::ItemSelected(item_id.as_str().into()));
cx.emit(Event::ItemSelected(item_id));
}
}

View File

@@ -1,3 +1,5 @@
use std::sync::Arc;
use gpui::{
AppContext, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled,
div, img, prelude::FluentBuilder,
@@ -65,7 +67,7 @@ impl PullRequestView {
let maybe_content = {
let data = read_query(&query, cx);
if let QueryStatus::Loaded(pr) = data {
Some(gpui::SharedString::new(pr.body.as_str()))
Some(Arc::clone(&pr.body))
} else {
None
}
@@ -130,8 +132,8 @@ impl PullRequestView {
}
let merge_text = pr.author.as_ref().map(|author| {
let base_branch = pr.base_branch_name.as_str();
let head_branch = pr.head_branch_name.as_str();
let base_branch = &pr.base_branch_name;
let head_branch = &pr.head_branch_name;
let str = format!(
"{} requested to merge {} into {}",
author.login, head_branch, base_branch
@@ -172,6 +174,8 @@ impl PullRequestView {
)
});
let pr_title = gpui::SharedString::new(Arc::clone(&pr.title));
let metadata_line =
div()
.flex()
@@ -184,7 +188,7 @@ impl PullRequestView {
.flex_row()
.items_center()
.gap_1p5()
.child(img(author.avatar_url.clone()).size_4().rounded_full())
.child(img(author.avatar_url.as_ref()).size_4().rounded_full())
.child(
div()
.min_w_0()
@@ -222,7 +226,7 @@ impl PullRequestView {
.flex()
.flex_col()
.items_start()
.child(text(pr.title.clone()).w_full().text_xl().mb_1())
.child(text(pr_title).w_full().text_xl().mb_1())
.child(metadata_line),
)
.child(div().flex().flex_col().items_end().gap_1().when_some(

View File

@@ -1,4 +1,4 @@
use std::time::Duration;
use std::{sync::Arc, time::Duration};
use futures_lite::StreamExt;
use gpui::{
@@ -16,7 +16,7 @@ use crate::{
},
query::{self, QueryStatus, fetch_query, read_query, use_query},
storage,
util::timeout::set_timeout,
util::{str::ToSharedString, timeout::set_timeout},
};
pub(crate) struct GithubStepView {
@@ -83,7 +83,7 @@ impl GithubStepView {
_ = weak.update(cx, |this, cx| {
this.has_opened_link = true;
this.is_opening_link = false;
this.begin_auth_flow(&device_code, cx);
this.begin_auth_flow(device_code, cx);
cx.notify();
});
},
@@ -110,7 +110,7 @@ impl GithubStepView {
timer.clear();
} else {
let _ = this.update(cx, |this, cx| {
this.placeholder_code = this.generate_random_code(cx);
this.generate_random_code(cx);
cx.notify();
});
}
@@ -127,14 +127,13 @@ impl GithubStepView {
cx.open_url(api::auth::DEVICE_LOGIN_FLOW_URL);
}
fn generate_random_code(&mut self, cx: &mut gpui::Context<Self>) -> String {
fn generate_random_code(&mut self, cx: &mut gpui::Context<Self>) {
let rng = app::rng(cx);
(0..8)
.map(|_| {
self.placeholder_code.clear();
self.placeholder_code.extend((0..8).map(|_| {
let idx = rng.random_range(0..Self::CHAR_POOL.len());
Self::CHAR_POOL.chars().nth(idx).unwrap()
})
.collect()
}));
}
fn copy_user_code(&mut self, code: &str, cx: &mut gpui::Context<Self>) {
@@ -155,15 +154,10 @@ impl GithubStepView {
cx.notify();
}
fn begin_auth_flow(&mut self, device_code: &str, cx: &mut gpui::Context<Self>) {
fn begin_auth_flow(&mut self, device_code: Arc<str>, cx: &mut gpui::Context<Self>) {
GithubStepView::open_github_auth_page(cx);
let query = use_query(
api::auth::RequestAccessToken {
device_code: device_code.to_owned(),
},
cx,
);
let query = use_query(api::auth::RequestAccessToken { device_code }, cx);
cx.observe(&query, |this, _, cx| {
this.handle_access_token_query_response(cx);
@@ -263,7 +257,7 @@ impl GithubStepView {
let theme = app::current_theme(cx);
let (displayed_code, copyable_code) = match create_device_code_query {
| QueryStatus::Loaded(data) => (data.user_code.as_str(), Some(data.user_code.clone())),
| QueryStatus::Loaded(data) => (data.user_code.as_ref(), Some(data.user_code.clone())),
| _ => (self.placeholder_code.as_str(), None),
};
@@ -362,9 +356,7 @@ impl gpui::Render for GithubStepView {
| Some(ref q) => {
let user_query = read_query(q, cx);
match user_query {
| QueryStatus::Loaded(user) => {
(true, connected_header(), connected_body(user, cx))
}
| QueryStatus::Loaded(user) => (true, connected_header(), connected_body(user, cx)),
| _ => (false, self.header(), self.device_code_area(cx)),
}
}
@@ -417,7 +409,7 @@ fn connected_header() -> gpui::Div {
fn connected_body(user: &api::user::User, cx: &gpui::Context<GithubStepView>) -> gpui::Div {
let theme = app::current_theme(cx);
let display_name = user.name.as_deref().unwrap_or(&user.login).to_owned();
let display_name = user.name.as_ref().unwrap_or(&user.login).to_shared_string();
div()
.flex()
@@ -444,7 +436,7 @@ fn connected_body(user: &api::user::User, cx: &gpui::Context<GithubStepView>) ->
.flex_row()
.gap_4()
.items_center()
.child(img(user.avatar_url.clone()).size_12().rounded_full())
.child(img(user.avatar_url.as_ref()).size_12().rounded_full())
.child(
div()
.flex()
@@ -455,7 +447,7 @@ fn connected_body(user: &api::user::User, cx: &gpui::Context<GithubStepView>) ->
.text_xl()
.leading_tight(),
)
.child(text(user.login.clone()).text_sm().opacity(0.5)),
.child(text(user.login.to_shared_string()).text_sm().opacity(0.5)),
),
)
.child(

View File

@@ -34,15 +34,3 @@ pub(crate) fn classify_content(content: &[u8]) -> ContentType {
}
}
}
pub(crate) fn diff_content(old: &[u8], new: &[u8]) -> ContentDiff {
similar::TextDiff::from_lines::<[u8]>(old, new)
.iter_all_changes()
.map(|change| LineDiff {
old_line: change.old_index(),
old_content_range: change.old_range,
new_line: change.new_index(),
new_content_range: change.new_range,
})
.collect()
}

View File

@@ -1,3 +1,4 @@
pub(crate) mod diff;
pub(crate) mod file;
pub(crate) mod str;
pub(crate) mod timeout;

20
src/util/str.rs Normal file
View File

@@ -0,0 +1,20 @@
use std::sync::Arc;
use crate::api;
pub(crate) trait ToSharedString {
fn to_shared_string(&self) -> gpui::SharedString;
}
impl ToSharedString for Arc<str> {
/// converts into gpui SharedString cheaply with no allocation involved.
fn to_shared_string(&self) -> gpui::SharedString {
gpui::SharedString::new(Arc::clone(self))
}
}
impl Into<gpui::ElementId> for api::issues::Id {
fn into(self) -> gpui::ElementId {
gpui::ElementId::Name(gpui::SharedString::new(Arc::clone(&self.0)))
}
}