History

Add ability to copy a permalink to a line (#7119)

This PR adds the ability to copy the permalink to a line from within Zed. This functionality is available through the `editor: copy permalink to line` action in the command palette: <img width="589" alt="Screenshot 2024-01-30 at 7 07 46 PM" src="https://github.com/zed-industries/zed/assets/1486634/332282cb-211f-4f16-9eb1-415bcfee9b7b"> Executing this action will create a permalink to the currently selected line(s) and copy it to the clipboard. Here is an example line: ``` https://github.com/maxdeviant/auk/blob/56c80e80112744740be1969c89fdd34db4be6f64/src/lib.rs#L25 ``` Currently, both GitHub and GitLab are supported. ### Notes and known limitations - In order to determine where to permalink to, we read the URL of the `origin` remote in Git. This feature will not work if the `origin` remote is not present. - Attempting to permalink to a ref that is not pushed to the origin will result in the link 404ing. - Attempting to permalink when Git is in a dirty state may not generate the right link. - For instance, modifying a file (e.g., adding new lines) and grabbing a permalink to it will result in incorrect line numbers. Release Notes: - Added the ability to copy a permalink to a line ([#6777](https://github.com/zed-industries/zed/issues/6777)). - Available via the `editor: copy permalink to line` action in the command palette.

Marshall Bowers committed 2 years ago

Commit 176f63e1 parent cbcaca413 files · +361 −5Browse files

Unified · Split

13 files
  1. Cargo.lock +1 −0
  2. Cargo.toml +1 −0
  3. crates/channel/Cargo.toml +1 −1
  4. crates/client/Cargo.toml +1 −1
  5. crates/editor/Cargo.toml +1 −0
  6. crates/editor/src/actions.rs +1 −0
  7. crates/editor/src/editor.rs +38 −1
  8. crates/editor/src/element.rs +1 −0
  9. crates/editor/src/git.rs +2 −0
  10. crates/editor/src/git/permalink.rs +288 −0
  11. crates/fs/src/repository.rs +24 −0
  12. crates/util/Cargo.toml +1 −1
  13. crates/zed/Cargo.toml +1 −1
Cargo.lock+1−0
@@ -2336,6 +2336,7 @@ dependencies = [ · 2335 unmodified lines
23362336 "tree-sitter-typescript",
23372337 "ui",
23382338 "unindent",
2339+ "url",
23392340 "util",
23402341 "workspace",
23412342 ]
Cargo.toml+1−0
@@ -132,6 +132,7 @@ tree-sitter = { version = "0.20" } · 131 unmodified lines
132132 unindent = { version = "0.1.7" }
133133 pretty_assertions = "1.3.0"
134134 git2 = { version = "0.15", default-features = false}
135+url = "2.2"
135136 uuid = { version = "1.1.2", features = ["v4"] }
136137
137138 tree-sitter-bash = { git = "https://github.com/tree-sitter/tree-sitter-bash", rev = "7331995b19b8f8aba2d5e26deb51d2195c18bc94" }
crates/channel/Cargo.toml+1−1
@@ -42,7 +42,7 @@ thiserror.workspace = true · 41 unmodified lines
4242 time.workspace = true
4343 tiny_http = "0.8"
4444 uuid.workspace = true
45−url = "2.2"
45+url.workspace = true
4646 serde.workspace = true
4747 serde_derive.workspace = true
4848 tempfile = "3"
crates/client/Cargo.toml+1−1
@@ -46,7 +46,7 @@ thiserror.workspace = true · 45 unmodified lines
4646 time.workspace = true
4747 tiny_http = "0.8"
4848 uuid.workspace = true
49−url = "2.2"
49+url.workspace = true
5050
5151 [dev-dependencies]
5252 collections = { path = "../collections", features = ["test-support"] }
crates/editor/Cargo.toml+1−0
@@ -67,6 +67,7 @@ serde_json.workspace = true · 66 unmodified lines
6767 serde_derive.workspace = true
6868 smallvec.workspace = true
6969 smol.workspace = true
70+url.workspace = true
7071
7172 tree-sitter-rust = { workspace = true, optional = true }
7273 tree-sitter-html = { workspace = true, optional = true }
crates/editor/src/actions.rs+1−0
@@ -110,6 +110,7 @@ gpui::actions!( · 109 unmodified lines
110110 Copy,
111111 CopyHighlightJson,
112112 CopyPath,
113+ CopyPermalinkToLine,
113114 CopyRelativePath,
114115 Cut,
115116 CutToEndOfLine,
crates/editor/src/editor.rs+38−1
@@ -117,7 +117,7 @@ use ui::{ · 116 unmodified lines
117117 h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
118118 Tooltip,
119119 };
120−use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
120+use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
121121 use workspace::{searchable::SearchEvent, ItemNavHistory, Pane, SplitDirection, ViewId, Workspace};
122122
123123 const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
@@ -8215,6 +8215,43 @@ impl Editor { · 8091 unmodified lines
82158215 }
82168216 }
82178217
8218+ pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
8219+ use git::permalink::{build_permalink, BuildPermalinkParams};
8220+
8221+ let permalink = maybe!({
8222+ let project = self.project.clone()?;
8223+ let project = project.read(cx);
8224+
8225+ let worktree = project.visible_worktrees(cx).next()?;
8226+
8227+ let mut cwd = worktree.read(cx).abs_path().to_path_buf();
8228+ cwd.push(".git");
8229+
8230+ let repo = project.fs().open_repo(&cwd)?;
8231+ let origin_url = repo.lock().remote_url("origin")?;
8232+ let sha = repo.lock().head_sha()?;
8233+
8234+ let buffer = self.buffer().read(cx).as_singleton()?;
8235+ let file = buffer.read(cx).file().and_then(|f| f.as_local())?;
8236+ let path = file.path().to_str().map(|path| path.to_string())?;
8237+
8238+ let selections = self.selections.all::<Point>(cx);
8239+ let selection = selections.iter().peekable().next();
8240+
8241+ build_permalink(BuildPermalinkParams {
8242+ remote_url: &origin_url,
8243+ sha: &sha,
8244+ path: &path,
8245+ selection: selection.map(|selection| selection.range()),
8246+ })
8247+ .log_err()
8248+ });
8249+
8250+ if let Some(permalink) = permalink {
8251+ cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
8252+ }
8253+ }
8254+
82188255 pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
82198256 self.highlighted_rows = rows;
82208257 }
crates/editor/src/element.rs+1−0
@@ -277,6 +277,7 @@ impl EditorElement { · 276 unmodified lines
277277 register_action(view, cx, Editor::copy_path);
278278 register_action(view, cx, Editor::copy_relative_path);
279279 register_action(view, cx, Editor::copy_highlight_json);
280+ register_action(view, cx, Editor::copy_permalink_to_line);
280281 register_action(view, cx, |editor, action, cx| {
281282 if let Some(task) = editor.format(action, cx) {
282283 task.detach_and_log_err(cx);
crates/editor/src/git.rs+2−0
@@ -1,3 +1,5 @@
1+pub mod permalink;
2+
13 use std::ops::Range;
24
35 use git::diff::{DiffHunk, DiffHunkStatus};
crates/editor/src/git/permalink.rs+288−0
@@ -0,0 +1,288 @@
1+use std::ops::Range;
2+
3+use anyhow::{anyhow, Result};
4+use language::Point;
5+use url::Url;
6+
7+enum GitHostingProvider {
8+ Github,
9+ Gitlab,
10+}
11+
12+impl GitHostingProvider {
13+ fn base_url(&self) -> Url {
14+ let base_url = match self {
15+ Self::Github => "https://github.com",
16+ Self::Gitlab => "https://gitlab.com",
17+ };
18+
19+ Url::parse(&base_url).unwrap()
20+ }
21+
22+ /// Returns the fragment portion of the URL for the selected lines in
23+ /// the representation the [`GitHostingProvider`] expects.
24+ fn line_fragment(&self, selection: &Range<Point>) -> String {
25+ if selection.start.row == selection.end.row {
26+ let line = selection.start.row + 1;
27+
28+ match self {
29+ Self::Github | Self::Gitlab => format!("L{}", line),
30+ }
31+ } else {
32+ let start_line = selection.start.row + 1;
33+ let end_line = selection.end.row + 1;
34+
35+ match self {
36+ Self::Github => format!("L{}-L{}", start_line, end_line),
37+ Self::Gitlab => format!("L{}-{}", start_line, end_line),
38+ }
39+ }
40+ }
41+}
42+
43+pub struct BuildPermalinkParams<'a> {
44+ pub remote_url: &'a str,
45+ pub sha: &'a str,
46+ pub path: &'a str,
47+ pub selection: Option<Range<Point>>,
48+}
49+
50+pub fn build_permalink(params: BuildPermalinkParams) -> Result<Url> {
51+ let BuildPermalinkParams {
52+ remote_url,
53+ sha,
54+ path,
55+ selection,
56+ } = params;
57+
58+ let ParsedGitRemote {
59+ provider,
60+ owner,
61+ repo,
62+ } = parse_git_remote_url(remote_url)
63+ .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
64+
65+ let path = match provider {
66+ GitHostingProvider::Github => format!("{owner}/{repo}/blob/{sha}/{path}"),
67+ GitHostingProvider::Gitlab => format!("{owner}/{repo}/-/blob/{sha}/{path}"),
68+ };
69+ let line_fragment = selection.map(|selection| provider.line_fragment(&selection));
70+
71+ let mut permalink = provider.base_url().join(&path).unwrap();
72+ permalink.set_fragment(line_fragment.as_deref());
73+
74+ Ok(permalink)
75+}
76+
77+struct ParsedGitRemote<'a> {
78+ pub provider: GitHostingProvider,
79+ pub owner: &'a str,
80+ pub repo: &'a str,
81+}
82+
83+fn parse_git_remote_url(url: &str) -> Option<ParsedGitRemote> {
84+ if url.starts_with("git@github.com:") || url.starts_with("https://github.com/") {
85+ let repo_with_owner = url
86+ .trim_start_matches("git@github.com:")
87+ .trim_start_matches("https://github.com/")
88+ .trim_end_matches(".git");
89+
90+ let (owner, repo) = repo_with_owner.split_once("/")?;
91+
92+ return Some(ParsedGitRemote {
93+ provider: GitHostingProvider::Github,
94+ owner,
95+ repo,
96+ });
97+ }
98+
99+ if url.starts_with("git@gitlab.com:") || url.starts_with("https://gitlab.com/") {
100+ let repo_with_owner = url
101+ .trim_start_matches("git@gitlab.com:")
102+ .trim_start_matches("https://gitlab.com/")
103+ .trim_end_matches(".git");
104+
105+ let (owner, repo) = repo_with_owner.split_once("/")?;
106+
107+ return Some(ParsedGitRemote {
108+ provider: GitHostingProvider::Gitlab,
109+ owner,
110+ repo,
111+ });
112+ }
113+
114+ None
115+}
116+
117+#[cfg(test)]
118+mod tests {
119+ use super::*;
120+
121+ #[test]
122+ fn test_build_github_permalink_from_ssh_url() {
123+ let permalink = build_permalink(BuildPermalinkParams {
124+ remote_url: "git@github.com:zed-industries/zed.git",
125+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
126+ path: "crates/editor/src/git/permalink.rs",
127+ selection: None,
128+ })
129+ .unwrap();
130+
131+ let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
132+ assert_eq!(permalink.to_string(), expected_url.to_string())
133+ }
134+
135+ #[test]
136+ fn test_build_github_permalink_from_ssh_url_single_line_selection() {
137+ let permalink = build_permalink(BuildPermalinkParams {
138+ remote_url: "git@github.com:zed-industries/zed.git",
139+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
140+ path: "crates/editor/src/git/permalink.rs",
141+ selection: Some(Point::new(6, 1)..Point::new(6, 10)),
142+ })
143+ .unwrap();
144+
145+ let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L7";
146+ assert_eq!(permalink.to_string(), expected_url.to_string())
147+ }
148+
149+ #[test]
150+ fn test_build_github_permalink_from_ssh_url_multi_line_selection() {
151+ let permalink = build_permalink(BuildPermalinkParams {
152+ remote_url: "git@github.com:zed-industries/zed.git",
153+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
154+ path: "crates/editor/src/git/permalink.rs",
155+ selection: Some(Point::new(23, 1)..Point::new(47, 10)),
156+ })
157+ .unwrap();
158+
159+ let expected_url = "https://github.com/zed-industries/zed/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L24-L48";
160+ assert_eq!(permalink.to_string(), expected_url.to_string())
161+ }
162+
163+ #[test]
164+ fn test_build_github_permalink_from_https_url() {
165+ let permalink = build_permalink(BuildPermalinkParams {
166+ remote_url: "https://github.com/zed-industries/zed.git",
167+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
168+ path: "crates/zed/src/main.rs",
169+ selection: None,
170+ })
171+ .unwrap();
172+
173+ let expected_url = "https://github.com/zed-industries/zed/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs";
174+ assert_eq!(permalink.to_string(), expected_url.to_string())
175+ }
176+
177+ #[test]
178+ fn test_build_github_permalink_from_https_url_single_line_selection() {
179+ let permalink = build_permalink(BuildPermalinkParams {
180+ remote_url: "https://github.com/zed-industries/zed.git",
181+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
182+ path: "crates/zed/src/main.rs",
183+ selection: Some(Point::new(6, 1)..Point::new(6, 10)),
184+ })
185+ .unwrap();
186+
187+ let expected_url = "https://github.com/zed-industries/zed/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs#L7";
188+ assert_eq!(permalink.to_string(), expected_url.to_string())
189+ }
190+
191+ #[test]
192+ fn test_build_github_permalink_from_https_url_multi_line_selection() {
193+ let permalink = build_permalink(BuildPermalinkParams {
194+ remote_url: "https://github.com/zed-industries/zed.git",
195+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
196+ path: "crates/zed/src/main.rs",
197+ selection: Some(Point::new(23, 1)..Point::new(47, 10)),
198+ })
199+ .unwrap();
200+
201+ let expected_url = "https://github.com/zed-industries/zed/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs#L24-L48";
202+ assert_eq!(permalink.to_string(), expected_url.to_string())
203+ }
204+
205+ #[test]
206+ fn test_build_gitlab_permalink_from_ssh_url() {
207+ let permalink = build_permalink(BuildPermalinkParams {
208+ remote_url: "git@gitlab.com:zed-industries/zed.git",
209+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
210+ path: "crates/editor/src/git/permalink.rs",
211+ selection: None,
212+ })
213+ .unwrap();
214+
215+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs";
216+ assert_eq!(permalink.to_string(), expected_url.to_string())
217+ }
218+
219+ #[test]
220+ fn test_build_gitlab_permalink_from_ssh_url_single_line_selection() {
221+ let permalink = build_permalink(BuildPermalinkParams {
222+ remote_url: "git@gitlab.com:zed-industries/zed.git",
223+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
224+ path: "crates/editor/src/git/permalink.rs",
225+ selection: Some(Point::new(6, 1)..Point::new(6, 10)),
226+ })
227+ .unwrap();
228+
229+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L7";
230+ assert_eq!(permalink.to_string(), expected_url.to_string())
231+ }
232+
233+ #[test]
234+ fn test_build_gitlab_permalink_from_ssh_url_multi_line_selection() {
235+ let permalink = build_permalink(BuildPermalinkParams {
236+ remote_url: "git@gitlab.com:zed-industries/zed.git",
237+ sha: "e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7",
238+ path: "crates/editor/src/git/permalink.rs",
239+ selection: Some(Point::new(23, 1)..Point::new(47, 10)),
240+ })
241+ .unwrap();
242+
243+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/e6ebe7974deb6bb6cc0e2595c8ec31f0c71084b7/crates/editor/src/git/permalink.rs#L24-48";
244+ assert_eq!(permalink.to_string(), expected_url.to_string())
245+ }
246+
247+ #[test]
248+ fn test_build_gitlab_permalink_from_https_url() {
249+ let permalink = build_permalink(BuildPermalinkParams {
250+ remote_url: "https://gitlab.com/zed-industries/zed.git",
251+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
252+ path: "crates/zed/src/main.rs",
253+ selection: None,
254+ })
255+ .unwrap();
256+
257+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs";
258+ assert_eq!(permalink.to_string(), expected_url.to_string())
259+ }
260+
261+ #[test]
262+ fn test_build_gitlab_permalink_from_https_url_single_line_selection() {
263+ let permalink = build_permalink(BuildPermalinkParams {
264+ remote_url: "https://gitlab.com/zed-industries/zed.git",
265+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
266+ path: "crates/zed/src/main.rs",
267+ selection: Some(Point::new(6, 1)..Point::new(6, 10)),
268+ })
269+ .unwrap();
270+
271+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs#L7";
272+ assert_eq!(permalink.to_string(), expected_url.to_string())
273+ }
274+
275+ #[test]
276+ fn test_build_gitlab_permalink_from_https_url_multi_line_selection() {
277+ let permalink = build_permalink(BuildPermalinkParams {
278+ remote_url: "https://gitlab.com/zed-industries/zed.git",
279+ sha: "b2efec9824c45fcc90c9a7eb107a50d1772a60aa",
280+ path: "crates/zed/src/main.rs",
281+ selection: Some(Point::new(23, 1)..Point::new(47, 10)),
282+ })
283+ .unwrap();
284+
285+ let expected_url = "https://gitlab.com/zed-industries/zed/-/blob/b2efec9824c45fcc90c9a7eb107a50d1772a60aa/crates/zed/src/main.rs#L24-48";
286+ assert_eq!(permalink.to_string(), expected_url.to_string())
287+ }
288+}
crates/fs/src/repository.rs+24−0
@@ -26,8 +26,14 @@ pub struct Branch { · 25 unmodified lines
2626 pub trait GitRepository: Send {
2727 fn reload_index(&self);
2828 fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
29+
30+ /// Returns the URL of the remote with the given name.
31+ fn remote_url(&self, name: &str) -> Option<String>;
2932 fn branch_name(&self) -> Option<String>;
3033
34+ /// Returns the SHA of the current HEAD.
35+ fn head_sha(&self) -> Option<String>;
36+
3137 /// Get the statuses of all of the files in the index that start with the given
3238 /// path and have changes with respect to the HEAD commit. This is fast because
3339 /// the index stores hashes of trees, so that unchanged directories can be skipped.
@@ -88,12 +94,22 @@ impl GitRepository for LibGitRepository { · 54 unmodified lines
8894 None
8995 }
9096
97+ fn remote_url(&self, name: &str) -> Option<String> {
98+ let remote = self.find_remote(name).ok()?;
99+ remote.url().map(|url| url.to_string())
100+ }
101+
91102 fn branch_name(&self) -> Option<String> {
92103 let head = self.head().log_err()?;
93104 let branch = String::from_utf8_lossy(head.shorthand_bytes());
94105 Some(branch.to_string())
95106 }
96107
108+ fn head_sha(&self) -> Option<String> {
109+ let head = self.head().ok()?;
110+ head.target().map(|oid| oid.to_string())
111+ }
112+
97113 fn staged_statuses(&self, path_prefix: &Path) -> TreeMap<RepoPath, GitFileStatus> {
98114 let mut map = TreeMap::default();
99115
@@ -255,11 +271,19 @@ impl GitRepository for FakeGitRepository { · 155 unmodified lines
255271 state.index_contents.get(path).cloned()
256272 }
257273
274+ fn remote_url(&self, _name: &str) -> Option<String> {
275+ None
276+ }
277+
258278 fn branch_name(&self) -> Option<String> {
259279 let state = self.state.lock();
260280 state.branch_name.clone()
261281 }
262282
283+ fn head_sha(&self) -> Option<String> {
284+ None
285+ }
286+
263287 fn staged_statuses(&self, path_prefix: &Path) -> TreeMap<RepoPath, GitFileStatus> {
264288 let mut map = TreeMap::default();
265289 let state = self.state.lock();
crates/util/Cargo.toml+1−1
@@ -21,7 +21,7 @@ lazy_static.workspace = true · 20 unmodified lines
2121 futures.workspace = true
2222 isahc.workspace = true
2323 smol.workspace = true
24−url = "2.2"
24+url.workspace = true
2525 rand.workspace = true
2626 rust-embed.workspace = true
2727 tempfile = { workspace = true, optional = true }
crates/zed/Cargo.toml+1−1
@@ -148,7 +148,7 @@ tree-sitter-vue.workspace = true · 147 unmodified lines
148148 tree-sitter-uiua.workspace = true
149149 tree-sitter-zig.workspace = true
150150
151−url = "2.2"
151+url.workspace = true
152152 urlencoding = "2.1.2"
153153 uuid.workspace = true
154154

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t