Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git: Add date format and per-view date style settings (#66533)

scarfe231594b6b88
diff --git a/Cargo.lock b/Cargo.lock
index dc88d66fe40..0e689367704 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7109,6 +7109,7 @@ dependencies = [
"tree-sitter-md",
"ui",
"ui_input",
+ "unicode-width 0.2.2",
"unindent",
"util",
"watch",
@@ -13927,6 +13928,7 @@ dependencies = [
"tempfile",
"terminal",
"text",
+ "time",
"toml 0.9.8",
"tracing",
"unindent",
diff --git a/assets/settings/default.json b/assets/settings/default.json
index 15686d81d15..ba46ed80a58 100644
--- a/assets/settings/default.json
+++ b/assets/settings/default.json
@@ -1083,7 +1083,13 @@
// Default width of the collaboration panel.
"default_width": 240,
},
+ "git_graph": {
+ // Show "absolute" or "relative" dates in graph rows.
+ "date_style": "absolute",
+ },
"git_panel": {
+ // Show "relative" or "absolute" dates in commit history.
+ "date_style": "relative",
// Whether to show the git panel button in the status bar.
"button": true,
// Where to dock the git panel. Can be 'left' or 'right'.
@@ -1827,6 +1833,9 @@
"read_only_files": [],
// Git gutter behavior configuration.
"git": {
+ // Format for absolute Git dates: "locale", "iso", or a strftime format
+ // such as "%Y-%m-%d %H:%M". Tooltips and commit views always show absolute dates.
+ "date_format": "locale",
// Global switch to enable or disable all git integration features.
// If set to true, disables all git integration features.
// If set to false, individual git integration features below will be independently enabled or disabled.
@@ -1848,6 +1857,8 @@
// Control whether the git blame information is shown for the currently
// focused line, and where it is rendered.
"inline_blame": {
+ // Show "relative" or "absolute" dates inline and in the status bar.
+ "date_style": "relative",
"enabled": true,
// Sets a delay after which the inline blame information is shown.
// Delay is restarted with every cursor movement.
@@ -1863,12 +1874,21 @@
"min_column": 0,
},
"blame": {
+ // Show "relative" or "absolute" dates in the blame gutter.
+ "date_style": "relative",
"show_avatar": true,
},
// Control which information is shown in the branch picker.
"branch_picker": {
+ // Show "relative" or "absolute" dates in the branch picker.
+ "date_style": "relative",
"show_author_name": true,
},
+ // Control which information is shown in the stash picker.
+ "stash_picker": {
+ // Show "relative" or "absolute" dates in the stash picker.
+ "date_style": "relative",
+ },
"file_diff": {
// Whether newly opened file diffs show the full file instead of changes only.
"show_full_file": true,
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 1be08b38ffe..335a6c48fa1 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -111,7 +111,7 @@ pub use element::{
CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
file_status_label_color, render_breadcrumb_text,
};
-pub use git::blame::{BlameRenderer, GitBlame};
+pub use git::blame::{BlameRenderer, GitBlame, MAX_RELATIVE_TIMESTAMP};
pub use git::{
DefaultDiffHunkRenderer, DiffHunkRenderer, HiddenDiffHunkRenderer,
HiddenUnstagedDiffHunkRenderer, render_diff_hunk_controls, set_blame_renderer,
@@ -12547,11 +12547,10 @@ impl EditorSnapshot {
self.git_blame_gutter_max_author_length
.map(|max_author_length| {
let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
- const MAX_RELATIVE_TIMESTAMP: &str = "2 years, 11 months ago";
let max_char_count = max_author_length.min(renderer.max_author_length())
+ ::git::SHORT_SHA_LENGTH
- + MAX_RELATIVE_TIMESTAMP.len();
+ + renderer.max_timestamp_width(cx);
ch_advance * max_char_count
+ renderer.blame_entry_non_text_width(window, cx)
diff --git a/crates/editor/src/git/blame.rs b/crates/editor/src/git/blame.rs
index b79395d3f2c..e3f5ea224a6 100644
--- a/crates/editor/src/git/blame.rs
+++ b/crates/editor/src/git/blame.rs
@@ -106,9 +106,15 @@ pub struct GitBlame {
kind: GitBlameKind,
}
+pub const MAX_RELATIVE_TIMESTAMP: &str = "2 years, 11 months ago";
+
pub trait BlameRenderer {
fn max_author_length(&self) -> usize;
+ fn max_timestamp_width(&self, _: &App) -> usize {
+ MAX_RELATIVE_TIMESTAMP.len()
+ }
+
fn blame_entry_non_text_width(&self, _: &Window, _: &App) -> Pixels {
Pixels::ZERO
}
diff --git a/crates/git_ui/Cargo.toml b/crates/git_ui/Cargo.toml
index 4ea810d6410..eab8d74e5cc 100644
--- a/crates/git_ui/Cargo.toml
+++ b/crates/git_ui/Cargo.toml
@@ -67,6 +67,7 @@ time_format.workspace = true
tracing.workspace = true
ui.workspace = true
ui_input.workspace = true
+unicode-width.workspace = true
util.workspace = true
watch.workspace = true
workspace.workspace = true
diff --git a/crates/git_ui/src/blame_ui.rs b/crates/git_ui/src/blame_ui.rs
index 90e1d780bd8..0002d990149 100644
--- a/crates/git_ui/src/blame_ui.rs
+++ b/crates/git_ui/src/blame_ui.rs
@@ -1,5 +1,8 @@
use crate::{
- commit_tooltip::{CommitAvatar, CommitTooltip, commit_tag_chips, shallow_boundary_notice},
+ commit_tooltip::{
+ CommitAvatar, CommitTooltip, blame_entry_timestamp, commit_tag_chips,
+ shallow_boundary_notice,
+ },
commit_view::{CommitView, GitBlob, build_buffer, worktree_id_for_repo_path},
};
use anyhow::Context as _;
@@ -34,8 +37,8 @@ const GIT_BLAME_AVATAR_SIZE: Rems = rems(1.);
pub struct GitBlameRenderer;
-fn format_blame_text(blame_entry: &BlameEntry, cx: &App) -> String {
- let relative_timestamp = blame_entry_relative_timestamp(blame_entry);
+fn format_blame_text(blame_entry: &BlameEntry, style: settings::GitDateStyle, cx: &App) -> String {
+ let timestamp = blame_entry_timestamp(blame_entry, style, cx);
let author = blame_entry.author.as_deref().unwrap_or_default();
let summary_enabled = ProjectSettings::get_global(cx)
.git
@@ -44,15 +47,15 @@ fn format_blame_text(blame_entry: &BlameEntry, cx: &App) -> String {
match blame_entry.summary.as_ref() {
Some(summary) if summary_enabled => {
- format!("{author}, {relative_timestamp} - {summary}")
+ format!("{author}, {timestamp} - {summary}")
}
- _ => format!("{author}, {relative_timestamp}"),
+ _ => format!("{author}, {timestamp}"),
}
}
#[derive(Default)]
pub struct GitBlameStatus {
- text: Option<SharedString>,
+ text: Option<(SharedString, SharedString)>,
active_editor: Option<Entity<Editor>>,
_subscriptions: Vec<Subscription>,
}
@@ -64,7 +67,13 @@ impl GitBlameStatus {
if inline_blame.enabled && inline_blame.location == InlineBlameLocation::StatusBar {
editor
.update(cx, |editor, cx| editor.active_git_blame_entry(cx))
- .map(|blame_entry| SharedString::from(format_blame_text(&blame_entry, cx)))
+ .map(|blame_entry| {
+ (
+ format_blame_text(&blame_entry, inline_blame.date_style, cx).into(),
+ format_blame_text(&blame_entry, settings::GitDateStyle::Absolute, cx)
+ .into(),
+ )
+ })
} else {
None
};
@@ -83,9 +92,9 @@ impl Render for GitBlameStatus {
return div();
}
- div().when_some(self.text.clone(), |el, text| {
+ div().when_some(self.text.clone(), |el, (text, tooltip)| {
el.child(
- Button::new("git-blame-status", text.clone())
+ Button::new("git-blame-status", text)
.label_size(LabelSize::Small)
.start_icon(
Icon::new(IconName::FileGit)
@@ -102,7 +111,7 @@ impl Render for GitBlameStatus {
);
}
}))
- .tooltip(ui::Tooltip::text(text)),
+ .tooltip(ui::Tooltip::text(tooltip)),
)
})
}
@@ -137,6 +146,18 @@ impl BlameRenderer for GitBlameRenderer {
GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED
}
+ fn max_timestamp_width(&self, cx: &App) -> usize {
+ if ProjectSettings::get_global(cx).git.blame.date_style == settings::GitDateStyle::Relative
+ {
+ return editor::MAX_RELATIVE_TIMESTAMP.len();
+ }
+ crate::git_timestamp::longest_git_dates(cx)
+ .iter()
+ .map(|date| unicode_width::UnicodeWidthStr::width(date.as_str()))
+ .max()
+ .unwrap_or_default()
+ }
+
fn blame_entry_non_text_width(&self, window: &Window, cx: &App) -> Pixels {
let show_avatar = ProjectSettings::get_global(cx).git.blame.show_avatar;
let gap_count = if show_avatar { 3. } else { 2. };
@@ -164,7 +185,11 @@ impl BlameRenderer for GitBlameRenderer {
window: &mut Window,
cx: &mut App,
) -> Option<AnyElement> {
- let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
+ let timestamp = blame_entry_timestamp(
+ &blame_entry,
+ ProjectSettings::get_global(cx).git.blame.date_style,
+ cx,
+ );
let short_commit_id = blame_entry.sha.display_short();
let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
@@ -217,7 +242,7 @@ impl BlameRenderer for GitBlameRenderer {
.children(avatar)
.child(name),
)
- .child(relative_timestamp)
+ .child(timestamp)
.hover(|style| style.bg(cx.theme().colors().element_hover))
.cursor_pointer()
.on_mouse_down(MouseButton::Right, {
@@ -283,7 +308,11 @@ impl BlameRenderer for GitBlameRenderer {
blame_entry: BlameEntry,
cx: &mut App,
) -> Option<AnyElement> {
- let text = format_blame_text(&blame_entry, cx);
+ let text = format_blame_text(
+ &blame_entry,
+ ProjectSettings::get_global(cx).git.inline_blame.date_style,
+ cx,
+ );
Some(
h_flex()
@@ -342,12 +371,10 @@ impl BlameRenderer for GitBlameRenderer {
.get(..git::SHORT_SHA_LENGTH)
.map(|sha| sha.to_string().into())
.unwrap_or_else(|| sha.clone());
- let local_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
- let absolute_timestamp = time_format::format_localized_timestamp(
+ let absolute_timestamp = crate::git_timestamp::format_git_timestamp(
commit_time,
- OffsetDateTime::now_utc(),
- local_offset,
time_format::TimestampFormat::MediumAbsolute,
+ cx,
);
let link_color = cx.theme().colors().text_accent;
let markdown_style = {
@@ -758,19 +785,3 @@ fn existing_blame_editor(
(blob.path == *path).then_some(editor)
})
}
-
-fn blame_entry_relative_timestamp(blame_entry: &BlameEntry) -> String {
- match blame_entry.author_offset_date_time() {
- Ok(timestamp) => {
- let local_offset =
- time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
- time_format::format_localized_timestamp(
- timestamp,
- time::OffsetDateTime::now_utc(),
- local_offset,
- time_format::TimestampFormat::Relative,
- )
- }
- Err(_) => "Error parsing date".to_string(),
- }
-}
diff --git a/crates/git_ui/src/branch_picker.rs b/crates/git_ui/src/branch_picker.rs
index c47331731a6..832e672300d 100644
--- a/crates/git_ui/src/branch_picker.rs
+++ b/crates/git_ui/src/branch_picker.rs
@@ -1683,19 +1683,15 @@ impl PickerDelegate for BranchListDelegate {
let subject = commit.subject.clone();
let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
.unwrap_or_else(|_| OffsetDateTime::now_utc());
- let local_offset =
- time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
- let formatted_time = time_format::format_localized_timestamp(
+ let formatted_time = crate::git_timestamp::format_git_date(
commit_time,
- OffsetDateTime::now_utc(),
- local_offset,
- time_format::TimestampFormat::Relative,
+ ProjectSettings::get_global(cx).git.branch_picker.date_style,
+ cx,
);
- let absolute_time = time_format::format_localized_timestamp(
+ let absolute_time = crate::git_timestamp::format_git_timestamp(
commit_time,
- OffsetDateTime::now_utc(),
- local_offset,
time_format::TimestampFormat::EnhancedAbsolute,
+ cx,
);
let author = commit.author_name.clone();
(
diff --git a/crates/git_ui/src/commit_tooltip.rs b/crates/git_ui/src/commit_tooltip.rs
index bca86047b0d..8bd9dc11510 100644
--- a/crates/git_ui/src/commit_tooltip.rs
+++ b/crates/git_ui/src/commit_tooltip.rs
@@ -18,7 +18,7 @@ use project::git_store::{Repository, UnshallowState};
use settings::Settings;
use std::hash::Hash;
use theme_settings::ThemeSettings;
-use time::{OffsetDateTime, UtcOffset};
+use time::OffsetDateTime;
use ui::{Avatar, Chip, CopyButton, Divider, Tooltip, prelude::*, tooltip_container};
use workspace::Workspace;
@@ -299,12 +299,10 @@ impl Render for CommitTooltip {
.map(|sha| sha.to_string().into())
.unwrap_or_else(|| self.commit.sha.clone());
let full_sha = self.commit.sha.to_string();
- let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
- let absolute_timestamp = time_format::format_localized_timestamp(
+ let absolute_timestamp = crate::git_timestamp::format_git_timestamp(
self.commit.commit_time,
- OffsetDateTime::now_utc(),
- local_offset,
time_format::TimestampFormat::MediumAbsolute,
+ cx,
);
let markdown_style = {
let style = hover_markdown_style(window, cx);
@@ -469,25 +467,17 @@ impl Render for CommitTooltip {
}
}
-fn blame_entry_timestamp(blame_entry: &BlameEntry, format: time_format::TimestampFormat) -> String {
+pub(crate) fn blame_entry_timestamp(
+ blame_entry: &BlameEntry,
+ style: settings::GitDateStyle,
+ cx: &App,
+) -> String {
match blame_entry.author_offset_date_time() {
- Ok(timestamp) => {
- let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
- time_format::format_localized_timestamp(
- timestamp,
- time::OffsetDateTime::now_utc(),
- local_offset,
- format,
- )
- }
+ Ok(timestamp) => crate::git_timestamp::format_git_date(timestamp, style, cx),
Err(_) => "Error parsing date".to_string(),
}
}
-pub fn blame_entry_relative_timestamp(blame_entry: &BlameEntry) -> String {
- blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative)
-}
-
pub(crate) fn shallow_boundary_notice(
repository: Entity<Repository>,
workspace: WeakEntity<Workspace>,
diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rs
index 1b79b38e86a..dfcae247f3e 100644
--- a/crates/git_ui/src/commit_view.rs
+++ b/crates/git_ui/src/commit_view.rs
@@ -721,12 +721,10 @@ impl CommitView {
let commit_sha = commit.sha.clone();
let commit_date = time::OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
.unwrap_or_else(|_| time::OffsetDateTime::now_utc());
- let local_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
- let date_string = time_format::format_localized_timestamp(
+ let date_string = crate::git_timestamp::format_git_timestamp(
commit_date,
- time::OffsetDateTime::now_utc(),
- local_offset,
time_format::TimestampFormat::MediumAbsolute,
+ cx,
);
let avatar_size = rems_from_px(40_f32);
diff --git a/crates/git_ui/src/git_graph.rs b/crates/git_ui/src/git_graph.rs
index 5d978382670..f0323950311 100644
--- a/crates/git_ui/src/git_graph.rs
+++ b/crates/git_ui/src/git_graph.rs
@@ -7,6 +7,7 @@ use crate::{
commit_tooltip::CommitAvatar,
commit_view::CommitView,
git_status_icon,
+ git_timestamp::format_git_timestamp,
};
use collections::{BTreeMap, HashMap, IndexSet};
use editor::Editor;
@@ -29,6 +30,7 @@ use language::line_diff;
use markdown::{Markdown, MarkdownElement};
use menu::{Cancel, SelectFirst, SelectLast, SelectNext, SelectPrevious};
use picker::{Picker, PickerDelegate};
+use project::project_settings::ProjectSettings;
use project::{
ProjectPath, TaskSourceKind,
git_store::{
@@ -36,6 +38,7 @@ use project::{
GraphDataResponse, Repository, RepositoryEvent, RepositoryId,
},
};
+use settings::{GitDateStyle, RegisterSetting, Settings};
use smallvec::{SmallVec, smallvec};
use std::{
cell::Cell,
@@ -615,17 +618,39 @@ fn timestamp_format() -> &'static [BorrowedFormatItem<'static>] {
})
}
-fn format_timestamp(timestamp: i64) -> String {
+#[derive(Clone, Debug, RegisterSetting)]
+pub(crate) struct GitGraphSettings {
+ pub date_style: GitDateStyle,
+}
+
+impl Settings for GitGraphSettings {
+ fn from_settings(content: &settings::SettingsContent) -> Self {
+ Self {
+ date_style: content.git_graph.as_ref().unwrap().date_style.unwrap(),
+ }
+ }
+}
+
+fn format_timestamp(timestamp: i64, date_style: GitDateStyle, cx: &App) -> String {
let Ok(datetime) = OffsetDateTime::from_unix_timestamp(timestamp) else {
return "Unknown".to_string();
};
+ if date_style == GitDateStyle::Relative {
+ return format_git_timestamp(datetime, time_format::TimestampFormat::Relative, cx);
+ }
let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
let local_datetime = datetime.to_offset(local_offset);
- local_datetime
- .format(timestamp_format())
- .unwrap_or_default()
+ ProjectSettings::get_global(cx)
+ .git
+ .date_format
+ .format(local_datetime)
+ .unwrap_or_else(|| {
+ local_datetime
+ .format(timestamp_format())
+ .unwrap_or_default()
+ })
}
fn accent_colors_count(accents: &AccentColors) -> usize {
@@ -1678,8 +1703,17 @@ impl GitGraph {
},
);
let mut row_height = Self::row_height(window, cx);
+ let mut was_date_style = GitGraphSettings::get_global(cx).date_style;
+ let mut was_date_format = ProjectSettings::get_global(cx).git.date_format.clone();
cx.observe_global_in::<settings::SettingsStore>(window, move |this, window, cx| {
+ let date_style = GitGraphSettings::get_global(cx).date_style;
+ let date_format = &ProjectSettings::get_global(cx).git.date_format;
+ if date_style != was_date_style || *date_format != was_date_format {
+ was_date_style = date_style;
+ was_date_format = date_format.clone();
+ cx.notify();
+ }
let new_row_height = Self::row_height(window, cx);
if new_row_height != row_height {
// The `uniform_list` powering the table caches the item size
@@ -2053,7 +2087,11 @@ impl GitGraph {
author_name = data.author_name.clone();
author_email =
(!data.author_email.is_empty()).then(|| data.author_email.clone());
- formatted_time = format_timestamp(data.commit_timestamp);
+ formatted_time = format_timestamp(
+ data.commit_timestamp,
+ GitGraphSettings::get_global(cx).date_style,
+ cx,
+ );
} else {
subject = "Loading…".into();
author_name = SharedString::default();
@@ -3043,7 +3081,9 @@ impl GitGraph {
CommitDataState::Loading(_) => ("Loading…".into(), "".into(), None),
};
- let date_string = commit_timestamp.map(format_timestamp).unwrap_or_default();
+ let date_string = commit_timestamp
+ .map(|timestamp| format_timestamp(timestamp, GitDateStyle::Absolute, cx))
+ .unwrap_or_default();
let remote = repository.update(cx, |repo, cx| {
let remote_url = repo.default_remote_url()?;
@@ -5390,6 +5430,24 @@ mod tests {
use std::path::Path;
use std::sync::{Arc, Mutex};
+ #[gpui::test]
+ fn test_graph_dates_use_date_format(cx: &mut App) {
+ let store = SettingsStore::test(cx);
+ cx.set_global(store);
+ ProjectSettings::register(cx);
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |content| {
+ content.git.get_or_insert_default().date_format = Some("%Y".into());
+ });
+ });
+ let timestamp = time::macros::datetime!(2024-06-08 12:34 UTC).unix_timestamp();
+ assert!(format_timestamp(timestamp, GitDateStyle::Relative, cx).ends_with(" ago"));
+ assert_eq!(
+ format_timestamp(timestamp, GitDateStyle::Absolute, cx),
+ "2024"
+ );
+ }
+
fn init_test(cx: &mut TestAppContext) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs
index 688e49413a8..2775eaaccf3 100644
--- a/crates/git_ui/src/git_panel.rs
+++ b/crates/git_ui/src/git_panel.rs
@@ -1516,6 +1516,8 @@ impl GitPanel {
let mut was_folder_indicator = GitPanelSettings::get_global(cx).folder_indicator;
let mut was_diff_stats = GitPanelSettings::get_global(cx).diff_stats;
let mut was_commit_editor = GitPanelSettings::get_global(cx).commit_editor;
+ let mut was_date_style = GitPanelSettings::get_global(cx).date_style;
+ let mut was_date_format = ProjectSettings::get_global(cx).git.date_format.clone();
cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
let settings = GitPanelSettings::get_global(cx);
let sort_by = settings.sort_by;
@@ -1525,6 +1527,8 @@ impl GitPanel {
let folder_indicator = settings.folder_indicator;
let diff_stats = settings.diff_stats;
let commit_editor = settings.commit_editor;
+ let date_style = settings.date_style;
+ let date_format = ProjectSettings::get_global(cx).git.date_format.clone();
// Changing the setting is an explicit request, so it wins over
// whatever this workspace last persisted.
if commit_editor != was_commit_editor {
@@ -1558,7 +1562,11 @@ impl GitPanel {
if (diff_stats != was_diff_stats) || update_entries {
this.update_visible_entries(window, cx);
}
- if file_icons != was_file_icons || folder_indicator != was_folder_indicator {
+ if file_icons != was_file_icons
+ || folder_indicator != was_folder_indicator
+ || date_style != was_date_style
+ || date_format != was_date_format
+ {
cx.notify();
}
was_sort_by = sort_by;
@@ -1568,6 +1576,8 @@ impl GitPanel {
was_folder_indicator = folder_indicator;
was_diff_stats = diff_stats;
was_commit_editor = commit_editor;
+ was_date_style = date_style;
+ was_date_format = date_format;
})
.detach();
@@ -8128,10 +8138,7 @@ impl GitPanel {
let repo_weak = repo_weak;
let git_panel = cx.weak_entity();
move |range, window, cx| {
- let local_offset = time::UtcOffset::current_local_offset()
- .unwrap_or(time::UtcOffset::UTC);
- let now = time::OffsetDateTime::now_utc();
-
+ let date_style = GitPanelSettings::get_global(cx).date_style;
let visible_data: Vec<Option<Arc<CommitData>>> = repo_weak
.update(cx, |repository, cx| {
entries[range.clone()]
@@ -8174,16 +8181,13 @@ impl GitPanel {
None => ("Loading…".into(), "".into(), None, None),
};
- let relative_time: SharedString = timestamp
+ let formatted_time: SharedString = timestamp
.and_then(|ts| {
time::OffsetDateTime::from_unix_timestamp(ts).ok()
})
.map(|dt| {
- time_format::format_localized_timestamp(
- dt,
- now,
- local_offset,
- time_format::TimestampFormat::Relative,
+ crate::git_timestamp::format_git_date(
+ dt, date_style, cx,
)
.into()
})
@@ -8335,9 +8339,9 @@ impl GitPanel {
)
.child(dot_separator())
})
- .when(!relative_time.is_empty(), |this| {
+ .when(!formatted_time.is_empty(), |this| {
this.child(
- Label::new(relative_time)
+ Label::new(formatted_time)
.size(LabelSize::Small)
.color(Color::Muted)
.flex_none(),
diff --git a/crates/git_ui/src/git_panel_settings.rs b/crates/git_ui/src/git_panel_settings.rs
index d0193c05884..cf66f116362 100644
--- a/crates/git_ui/src/git_panel_settings.rs
+++ b/crates/git_ui/src/git_panel_settings.rs
@@ -16,6 +16,7 @@ pub struct ScrollbarSettings {
#[derive(Debug, Clone, PartialEq, RegisterSetting)]
pub struct GitPanelSettings {
+ pub date_style: settings::GitDateStyle,
pub button: bool,
pub dock: DockPosition,
pub default_width: Pixels,
@@ -60,6 +61,7 @@ impl Settings for GitPanelSettings {
fn from_settings(content: &settings::SettingsContent) -> Self {
let git_panel = content.git_panel.clone().unwrap();
Self {
+ date_style: git_panel.date_style.unwrap(),
button: git_panel.button.unwrap(),
dock: git_panel.dock.unwrap().into(),
default_width: git_panel.default_width.unwrap().into_gpui(),
diff --git a/crates/git_ui/src/git_timestamp.rs b/crates/git_ui/src/git_timestamp.rs
new file mode 100644
index 00000000000..c0d12c74fb2
--- /dev/null
+++ b/crates/git_ui/src/git_timestamp.rs
@@ -0,0 +1,217 @@
+use gpui::App;
+use project::project_settings::{GitDateFormat, ProjectSettings};
+use settings::{GitDateStyle, Settings};
+use time::{OffsetDateTime, UtcOffset};
+use time_format::TimestampFormat;
+
+pub(crate) fn format_git_timestamp(
+ timestamp: OffsetDateTime,
+ format: TimestampFormat,
+ cx: &App,
+) -> String {
+ format_timestamp(
+ timestamp,
+ OffsetDateTime::now_utc(),
+ UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC),
+ format,
+ &ProjectSettings::get_global(cx).git.date_format,
+ )
+}
+
+pub(crate) fn format_git_date(timestamp: OffsetDateTime, style: GitDateStyle, cx: &App) -> String {
+ let format = match style {
+ GitDateStyle::Relative => TimestampFormat::Relative,
+ GitDateStyle::Absolute => TimestampFormat::EnhancedAbsolute,
+ };
+ format_git_timestamp(timestamp, format, cx)
+}
+
+pub(crate) fn longest_git_dates(cx: &App) -> [String; 3] {
+ let offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
+ let now = OffsetDateTime::now_utc();
+ // Wednesday, September 25 at 23:59:59 has the longest weekday, month name, day, and time.
+ let september = time::macros::datetime!(2024-09-25 23:59:59).assume_offset(offset);
+ // December 25 is also a Wednesday and has the longest unpadded month number.
+ let december = time::macros::datetime!(2024-12-25 23:59:59).assume_offset(offset);
+ // The locale format shows recent commits as "Yesterday at 11:59 PM", which is wider than
+ // an older date.
+ [
+ (september, now),
+ (december, now),
+ (september, september + time::Duration::days(1)),
+ ]
+ .map(|(sample, reference)| {
+ format_timestamp(
+ sample,
+ reference,
+ offset,
+ TimestampFormat::EnhancedAbsolute,
+ &ProjectSettings::get_global(cx).git.date_format,
+ )
+ })
+}
+
+fn format_timestamp(
+ timestamp: OffsetDateTime,
+ reference: OffsetDateTime,
+ offset: UtcOffset,
+ format: TimestampFormat,
+ date_format: &GitDateFormat,
+) -> String {
+ if !matches!(format, TimestampFormat::Relative)
+ && let Some(timestamp) = date_format.format(timestamp.to_offset(offset))
+ {
+ return timestamp;
+ }
+ time_format::format_localized_timestamp(timestamp, reference, offset, format)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::blame_ui::GitBlameRenderer;
+ use editor::BlameRenderer;
+ use gpui::UpdateGlobal;
+ use settings::SettingsStore;
+ use time::macros::{datetime, offset};
+ use unicode_width::UnicodeWidthStr;
+
+ #[test]
+ fn absolute_formats_use_local_time() {
+ let timestamp = datetime!(2024-06-08 23:45:12 UTC);
+ for (format, expected) in [
+ ("iso", "2024-06-09 08:45"),
+ ("%Y-%m-%d %H:%M:%S %z", "2024-06-09 08:45:12 +0900"),
+ ("%a %b %d %%", "Sun Jun 09 %"),
+ ] {
+ for fallback in [
+ TimestampFormat::Absolute,
+ TimestampFormat::EnhancedAbsolute,
+ TimestampFormat::MediumAbsolute,
+ ] {
+ assert_eq!(
+ format_timestamp(
+ timestamp,
+ timestamp,
+ offset!(+9),
+ fallback,
+ &GitDateFormat::parse(format)
+ ),
+ expected
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn relative_dates_ignore_absolute_format() {
+ let timestamp = datetime!(2024-06-08 23:45:12 UTC);
+ let reference = timestamp + time::Duration::days(3);
+ let expected = time_format::format_localized_timestamp(
+ timestamp,
+ reference,
+ UtcOffset::UTC,
+ TimestampFormat::Relative,
+ );
+ for format in ["locale", "iso", "%Y", "", "%Q"] {
+ assert_eq!(
+ format_timestamp(
+ timestamp,
+ reference,
+ UtcOffset::UTC,
+ TimestampFormat::Relative,
+ &GitDateFormat::parse(format)
+ ),
+ expected
+ );
+ }
+ }
+
+ #[test]
+ fn locale_and_invalid_formats_preserve_surface_defaults() {
+ let timestamp = datetime!(2024-06-08 23:45:12 UTC);
+ let reference = timestamp + time::Duration::days(3);
+ for format in ["locale", "", " ", "%Q", "%"] {
+ assert!(matches!(
+ GitDateFormat::parse(format),
+ GitDateFormat::Locale
+ ));
+ for fallback in [
+ TimestampFormat::Absolute,
+ TimestampFormat::EnhancedAbsolute,
+ TimestampFormat::MediumAbsolute,
+ ] {
+ assert_eq!(
+ format_timestamp(
+ timestamp,
+ reference,
+ UtcOffset::UTC,
+ fallback,
+ &GitDateFormat::parse(format)
+ ),
+ time_format::format_localized_timestamp(
+ timestamp,
+ reference,
+ UtcOffset::UTC,
+ fallback
+ )
+ );
+ }
+ }
+ }
+
+ fn init(cx: &mut App) {
+ let store = SettingsStore::test(cx);
+ cx.set_global(store);
+ ProjectSettings::register(cx);
+ }
+
+ fn set_blame_date_format(format: &str, cx: &mut App) {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |content| {
+ let git = content.git.get_or_insert_default();
+ git.date_format = Some(format.into());
+ git.blame.get_or_insert_default().date_style = Some(GitDateStyle::Absolute);
+ });
+ });
+ }
+
+ #[gpui::test]
+ fn blame_gutter_width_fits_longest_date(cx: &mut App) {
+ init(cx);
+ assert_eq!(
+ GitBlameRenderer.max_timestamp_width(cx),
+ editor::MAX_RELATIVE_TIMESTAMP.len()
+ );
+
+ for (format, width) in [
+ ("iso", "2024-09-25 23:59".len()),
+ ("%d", "25".len()),
+ ("%B %Y", "September 2024".len()),
+ ("%A %H:%M", "Wednesday 23:59".len()),
+ ("%-m/%-d/%Y", "12/25/2024".len()),
+ ("%H:%M:%-S", "23:59:59".len()),
+ ("%Y年%m月", 10),
+ ] {
+ set_blame_date_format(format, cx);
+ assert_eq!(GitBlameRenderer.max_timestamp_width(cx), width, "{format}");
+ }
+
+ set_blame_date_format("locale", cx);
+ let locale_dates = longest_git_dates(cx);
+ assert!(
+ locale_dates
+ .iter()
+ .any(|date| date.starts_with("Yesterday at ")),
+ "{locale_dates:?}"
+ );
+ assert_eq!(
+ GitBlameRenderer.max_timestamp_width(cx),
+ locale_dates
+ .iter()
+ .map(|date| UnicodeWidthStr::width(date.as_str()))
+ .max()
+ .unwrap_or(0)
+ );
+ }
+}
diff --git a/crates/git_ui/src/git_ui.rs b/crates/git_ui/src/git_ui.rs
index db20f4f2a9d..32da5941710 100644
--- a/crates/git_ui/src/git_ui.rs
+++ b/crates/git_ui/src/git_ui.rs
@@ -49,6 +49,7 @@ pub mod git_panel;
mod git_panel_settings;
pub mod git_picker;
mod git_runtime_diagnostics;
+mod git_timestamp;
pub mod multi_diff_view;
pub mod picker_prompt;
pub mod project_diff;
diff --git a/crates/git_ui/src/stash_picker.rs b/crates/git_ui/src/stash_picker.rs
index bdd8e0a03e1..799806abd2a 100644
--- a/crates/git_ui/src/stash_picker.rs
+++ b/crates/git_ui/src/stash_picker.rs
@@ -1,3 +1,4 @@
+use crate::git_timestamp::format_git_timestamp;
use fuzzy::StringMatchCandidate;
use git::stash::StashEntry;
@@ -8,8 +9,9 @@ use gpui::{
};
use picker::{Picker, PickerDelegate};
use project::git_store::{Repository, RepositoryEvent};
+use settings::Settings;
use std::sync::Arc;
-use time::{OffsetDateTime, UtcOffset};
+use time::OffsetDateTime;
use time_format;
use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
use util::ResultExt;
@@ -229,8 +231,6 @@ impl Render for StashList {
struct StashEntryMatch {
entry: StashEntry,
positions: Vec<usize>,
- formatted_timestamp: String,
- formatted_absolute_timestamp: String,
}
pub struct StashListDelegate {
@@ -242,7 +242,6 @@ pub struct StashListDelegate {
last_query: String,
modifiers: Modifiers,
focus_handle: FocusHandle,
- timezone: UtcOffset,
show_footer: bool,
}
@@ -253,8 +252,6 @@ impl StashListDelegate {
_window: &mut Window,
cx: &mut Context<StashList>,
) -> Self {
- let timezone = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
-
Self {
matches: vec![],
repo,
@@ -264,7 +261,6 @@ impl StashListDelegate {
last_query: Default::default(),
modifiers: Default::default(),
focus_handle: cx.focus_handle(),
- timezone,
show_footer: false,
}
}
@@ -273,28 +269,6 @@ impl StashListDelegate {
format!("#{}: {}", ix, message)
}
- fn format_timestamp(timestamp: i64, timezone: UtcOffset) -> String {
- let timestamp =
- OffsetDateTime::from_unix_timestamp(timestamp).unwrap_or(OffsetDateTime::now_utc());
- time_format::format_localized_timestamp(
- timestamp,
- OffsetDateTime::now_utc(),
- timezone,
- time_format::TimestampFormat::Relative,
- )
- }
-
- fn format_absolute_timestamp(timestamp: i64, timezone: UtcOffset) -> String {
- let timestamp =
- OffsetDateTime::from_unix_timestamp(timestamp).unwrap_or(OffsetDateTime::now_utc());
- time_format::format_localized_timestamp(
- timestamp,
- OffsetDateTime::now_utc(),
- timezone,
- time_format::TimestampFormat::EnhancedAbsolute,
- )
- }
-
fn drop_stash_at(&self, ix: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
let Some(entry_match) = self.matches.get(ix) else {
return;
@@ -405,23 +379,13 @@ impl PickerDelegate for StashListDelegate {
return Task::ready(());
};
- let timezone = self.timezone;
-
cx.spawn_in(window, async move |picker, cx| {
let matches: Vec<StashEntryMatch> = if query.is_empty() {
all_stash_entries
.into_iter()
- .map(|entry| {
- let formatted_timestamp = Self::format_timestamp(entry.timestamp, timezone);
- let formatted_absolute_timestamp =
- Self::format_absolute_timestamp(entry.timestamp, timezone);
-
- StashEntryMatch {
- entry,
- positions: Vec::new(),
- formatted_timestamp,
- formatted_absolute_timestamp,
- }
+ .map(|entry| StashEntryMatch {
+ entry,
+ positions: Vec::new(),
})
.collect()
} else {
@@ -448,15 +412,9 @@ impl PickerDelegate for StashListDelegate {
.into_iter()
.map(|candidate| {
let entry = all_stash_entries[candidate.candidate_id].clone();
- let formatted_timestamp = Self::format_timestamp(entry.timestamp, timezone);
- let formatted_absolute_timestamp =
- Self::format_absolute_timestamp(entry.timestamp, timezone);
-
StashEntryMatch {
entry,
positions: candidate.positions,
- formatted_timestamp,
- formatted_absolute_timestamp,
}
})
.collect()
@@ -502,6 +460,8 @@ impl PickerDelegate for StashListDelegate {
cx: &mut Context<Picker<Self>>,
) -> Option<Self::ListItem> {
let entry_match = &self.matches[ix];
+ let timestamp = OffsetDateTime::from_unix_timestamp(entry_match.entry.timestamp)
+ .unwrap_or_else(|_| OffsetDateTime::now_utc());
let stash_message =
Self::format_message(entry_match.entry.index, &entry_match.entry.message);
@@ -527,9 +487,16 @@ impl PickerDelegate for StashListDelegate {
.size(LabelSize::Small),
)
.child(
- Label::new(entry_match.formatted_timestamp.clone())
- .color(Color::Muted)
- .size(LabelSize::Small),
+ Label::new(crate::git_timestamp::format_git_date(
+ timestamp,
+ project::project_settings::ProjectSettings::get_global(cx)
+ .git
+ .stash_picker
+ .date_style,
+ cx,
+ ))
+ .color(Color::Muted)
+ .size(LabelSize::Small),
);
let view_button = {
@@ -595,16 +562,17 @@ impl PickerDelegate for StashListDelegate {
entry_match.entry.index,
&entry_match.entry.message,
);
- let absolute_timestamp =
- entry_match.formatted_absolute_timestamp.clone();
-
- Tooltip::element(move |_, _| {
+ Tooltip::element(move |_, cx| {
v_flex()
.child(Label::new(stash_message.clone()))
.child(
- Label::new(absolute_timestamp.clone())
- .size(LabelSize::Small)
- .color(Color::Muted),
+ Label::new(format_git_timestamp(
+ timestamp,
+ time_format::TimestampFormat::EnhancedAbsolute,
+ cx,
+ ))
+ .size(LabelSize::Small)
+ .color(Color::Muted),
)
.into_any_element()
})
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 585f5ce5787..eb7e0ba9c44 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -85,6 +85,7 @@ semver.workspace = true
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
+time.workspace = true
sha2.workspace = true
shellexpand.workspace = true
smallvec.workspace = true
diff --git a/crates/project/src/project_settings.rs b/crates/project/src/project_settings.rs
index 51f9ec0a8cf..bc9af3bee90 100644
--- a/crates/project/src/project_settings.rs
+++ b/crates/project/src/project_settings.rs
@@ -457,6 +457,10 @@ impl GoToDiagnosticSeverityFilter {
#[derive(Clone, Debug)]
pub struct GitSettings {
+ /// How absolute dates are shown across Git views.
+ ///
+ /// Default: locale
+ pub date_format: GitDateFormat,
/// Whether or not git integration is enabled.
///
/// Default: true
@@ -480,6 +484,8 @@ pub struct GitSettings {
///
/// Default: on
pub branch_picker: BranchPickerSettings,
+ /// Stash picker configuration.
+ pub stash_picker: StashPickerSettings,
/// How hunks are displayed visually in the editor.
///
/// Default: staged_hollow
@@ -566,6 +572,10 @@ impl From<settings::InlineBlameLocation> for InlineBlameLocation {
#[derive(Clone, Copy, Debug)]
pub struct InlineBlameSettings {
+ /// Whether dates are shown as relative or absolute.
+ ///
+ /// Default: relative
+ pub date_style: settings::GitDateStyle,
/// Whether or not to show git blame data inline in
/// the currently focused line.
///
@@ -597,12 +607,60 @@ pub struct InlineBlameSettings {
#[derive(Clone, Copy, Debug)]
pub struct BlameSettings {
+ /// Whether dates are shown as relative or absolute.
+ ///
+ /// Default: relative
+ pub date_style: settings::GitDateStyle,
/// Whether to show the avatar of the author of the commit.
///
/// Default: true
pub show_avatar: bool,
}
+#[derive(Clone, Copy, Debug)]
+pub struct StashPickerSettings {
+ /// Whether dates are shown as relative or absolute.
+ ///
+ /// Default: relative
+ pub date_style: settings::GitDateStyle,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub enum GitDateFormat {
+ #[default]
+ Locale,
+ Iso,
+ Custom(Arc<time::format_description::OwnedFormatItem>),
+}
+
+impl GitDateFormat {
+ pub fn parse(format: &str) -> Self {
+ match format {
+ "locale" => Self::Locale,
+ format if format.trim().is_empty() => Self::Locale,
+ "iso" => Self::Iso,
+ format => match time::format_description::parse_strftime_owned(format) {
+ Ok(format) => Self::Custom(Arc::new(format)),
+ Err(error) => {
+ log::warn!("Invalid git.date_format: {error}");
+ Self::Locale
+ }
+ },
+ }
+ }
+
+ pub fn format(&self, timestamp: time::OffsetDateTime) -> Option<String> {
+ let result = match self {
+ Self::Locale => return None,
+ Self::Iso => timestamp.format(time::macros::format_description!(
+ "[year]-[month]-[day] [hour]:[minute]"
+ )),
+ Self::Custom(format) => timestamp.format(format.as_ref()),
+ };
+ result.log_err()
+ }
+}
+
impl GitSettings {
pub fn inline_blame_delay(&self) -> Option<Duration> {
if self.inline_blame.delay_ms.0 > 0 {
@@ -616,6 +674,11 @@ impl GitSettings {
#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct BranchPickerSettings {
+ #[serde(default)]
+ /// Whether dates are shown as relative or absolute.
+ ///
+ /// Default: relative
+ pub date_style: settings::GitDateStyle,
/// Whether to show author name as part of the commit information.
///
/// Default: false
@@ -627,6 +690,7 @@ impl Default for BranchPickerSettings {
fn default() -> Self {
Self {
show_author_name: true,
+ date_style: settings::GitDateStyle::Relative,
}
}
}
@@ -700,12 +764,14 @@ impl Settings for ProjectSettings {
}
};
let git_settings = GitSettings {
+ date_format: GitDateFormat::parse(git.date_format.as_deref().unwrap()),
enabled: git_enabled,
git_gutter: git.git_gutter.unwrap(),
gutter_debounce: git.gutter_debounce.unwrap_or_default(),
inline_blame: {
let inline = git.inline_blame.unwrap();
InlineBlameSettings {
+ date_style: inline.date_style.unwrap(),
enabled: inline.enabled.unwrap(),
delay_ms: inline.delay_ms.unwrap(),
location: inline.location.unwrap().into(),
@@ -717,15 +783,20 @@ impl Settings for ProjectSettings {
blame: {
let blame = git.blame.unwrap();
BlameSettings {
+ date_style: blame.date_style.unwrap(),
show_avatar: blame.show_avatar.unwrap(),
}
},
branch_picker: {
let branch_picker = git.branch_picker.unwrap();
BranchPickerSettings {
+ date_style: branch_picker.date_style.unwrap(),
show_author_name: branch_picker.show_author_name.unwrap(),
}
},
+ stash_picker: StashPickerSettings {
+ date_style: git.stash_picker.unwrap().date_style.unwrap(),
+ },
hunk_style: git.hunk_style.unwrap(),
diff_base: git.diff_base.unwrap_or_default(),
path_style: git.path_style.unwrap().into(),
diff --git a/crates/settings/src/vscode_import.rs b/crates/settings/src/vscode_import.rs
index 3cc073635e9..60dece06bd5 100644
--- a/crates/settings/src/vscode_import.rs
+++ b/crates/settings/src/vscode_import.rs
@@ -203,6 +203,7 @@ impl VsCodeSettings {
file_finder: None,
git: self.git_settings_content(),
git_panel: self.git_panel_settings_content(),
+ git_graph: None,
global_lsp_settings: skip_default(GlobalLspSettingsContent {
semantic_token_rules: self.semantic_token_rules(),
..GlobalLspSettingsContent::default()
diff --git a/crates/settings_content/src/project.rs b/crates/settings_content/src/project.rs
index 582cb7219a6..05be8098bb8 100644
--- a/crates/settings_content/src/project.rs
+++ b/crates/settings_content/src/project.rs
@@ -631,6 +631,12 @@ impl std::fmt::Debug for ContextServerCommand {
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct GitSettings {
+ /// Format for absolute Git dates: "locale", "iso", or a strftime format
+ /// such as "%Y-%m-%d %H:%M" or "%b %d, %Y". Invalid formats fall back to "locale".
+ ///
+ /// Default: locale
+ #[schemars(extend("examples" = ["locale", "iso", "%Y-%m-%d %H:%M", "%b %d, %Y"]))]
+ pub date_format: Option<String>,
/// Whether or not to enable git integration.
///
/// Default: true
@@ -655,6 +661,8 @@ pub struct GitSettings {
///
/// Default: on
pub branch_picker: Option<BranchPickerSettingsContent>,
+ /// Stash picker settings.
+ pub stash_picker: Option<StashPickerSettings>,
/// File diff settings.
pub file_diff: Option<FileDiffSettingsContent>,
/// How hunks are displayed visually in the editor.
@@ -780,6 +788,10 @@ pub enum InlineBlameLocation {
#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "snake_case")]
pub struct InlineBlameSettings {
+ /// Whether to show relative or absolute dates.
+ ///
+ /// Default: relative
+ pub date_style: Option<GitDateStyle>,
/// Whether or not to show git blame data inline in
/// the currently focused line.
///
@@ -813,6 +825,10 @@ pub struct InlineBlameSettings {
#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "snake_case")]
pub struct BlameSettings {
+ /// Whether to show relative or absolute dates in the blame gutter.
+ ///
+ /// Default: relative
+ pub date_style: Option<GitDateStyle>,
/// Whether to show the avatar of the author of the commit.
///
/// Default: true
@@ -823,12 +839,46 @@ pub struct BlameSettings {
#[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "snake_case")]
pub struct BranchPickerSettingsContent {
+ /// Whether to show relative or absolute dates.
+ ///
+ /// Default: relative
+ pub date_style: Option<GitDateStyle>,
/// Whether to show author name as part of the commit information.
///
/// Default: false
pub show_author_name: Option<bool>,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Default,
+ Serialize,
+ Deserialize,
+ JsonSchema,
+ MergeFrom,
+ strum::VariantArray,
+ strum::VariantNames,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum GitDateStyle {
+ #[default]
+ Relative,
+ Absolute,
+}
+
+#[with_fallible_options]
+#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
+pub struct StashPickerSettings {
+ /// Whether to show relative or absolute dates.
+ ///
+ /// Default: relative
+ pub date_style: Option<GitDateStyle>,
+}
+
#[with_fallible_options]
#[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "snake_case")]
diff --git a/crates/settings_content/src/settings_content.rs b/crates/settings_content/src/settings_content.rs
index 65e018d9591..70c642d2610 100644
--- a/crates/settings_content/src/settings_content.rs
+++ b/crates/settings_content/src/settings_content.rs
@@ -199,6 +199,7 @@ pub struct SettingsContent {
pub call_hierarchy: Option<CallHierarchySettingsContent>,
pub git_panel: Option<GitPanelSettingsContent>,
+ pub git_graph: Option<GitGraphSettingsContent>,
pub tabs: Option<ItemSettingsContent>,
pub tab_bar: Option<TabBarSettingsContent>,
@@ -405,7 +406,7 @@ impl SettingsContent {
fallible_options::flattened_deserialize!(SettingsContent {
sections: { project, theme, extension, workspace, editor, remote },
options: {
- call_hierarchy, command_palette, file_finder, git_panel, tabs, tab_bar, tab_switcher, status_bar, preview_tabs, agent,
+ call_hierarchy, command_palette, file_finder, git_panel, git_graph, tabs, tab_bar, tab_switcher, status_bar, preview_tabs, agent,
agent_servers, audio, auto_update, base_keymap, collaboration_panel, debugger, diagnostics,
git,
global_lsp_settings, image_viewer, markdown_preview, repl, helix_mode, hide_mouse,
@@ -739,6 +740,10 @@ pub struct CallSettingsContent {
#[with_fallible_options]
#[derive(Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom, Debug)]
pub struct GitPanelSettingsContent {
+ /// Whether to show relative or absolute dates in commit history.
+ ///
+ /// Default: relative
+ pub date_style: Option<GitDateStyle>,
/// Whether to show the panel button in the status bar.
///
/// Default: true
@@ -829,6 +834,15 @@ pub struct GitPanelSettingsContent {
pub commit_editor: Option<GitPanelCommitEditor>,
}
+#[with_fallible_options]
+#[derive(Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom, Debug)]
+pub struct GitGraphSettingsContent {
+ /// Whether to show relative or absolute dates in graph rows.
+ ///
+ /// Default: absolute
+ pub date_style: Option<GitDateStyle>,
+}
+
#[derive(
Copy,
Clone,
diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs
index 2d886462363..790de77746d 100644
--- a/crates/settings_ui/src/page_data.rs
+++ b/crates/settings_ui/src/page_data.rs
@@ -6554,9 +6554,23 @@ fn panels_page() -> SettingsPage {
]
}
- fn git_panel_section() -> [SettingsPageItem; 19] {
+ fn git_panel_section() -> [SettingsPageItem; 20] {
[
SettingsPageItem::SectionHeader("Git Panel"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates in commit history.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git_panel.date_style"),
+ pick: |content| content.git_panel.as_ref()?.date_style.as_ref(),
+ write: |content, value, _| {
+ content.git_panel.get_or_insert_default().date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Git Panel Button",
description: "Show the Git panel button in the status bar.",
@@ -8193,9 +8207,23 @@ fn terminal_page() -> SettingsPage {
}
fn version_control_page() -> SettingsPage {
- fn git_integration_section() -> [SettingsPageItem; 3] {
+ fn git_integration_section() -> [SettingsPageItem; 4] {
[
SettingsPageItem::SectionHeader("Git Integration"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Format",
+ description: "Format absolute dates using locale, iso (YYYY-MM-DD HH:MM), or a strftime format such as %Y-%m-%d %H:%M.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git.date_format"),
+ pick: |content| content.git.as_ref()?.date_format.as_ref(),
+ write: |content, value, _| {
+ content.git.get_or_insert_default().date_format = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::DynamicItem(DynamicItem {
discriminant: SettingItem {
files: USER,
@@ -8404,9 +8432,36 @@ fn version_control_page() -> SettingsPage {
]
}
- fn inline_git_blame_section() -> [SettingsPageItem; 6] {
+ fn inline_git_blame_section() -> [SettingsPageItem; 7] {
[
SettingsPageItem::SectionHeader("Inline Git Blame"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates inline and in the status bar.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git.inline_blame.date_style"),
+ pick: |content| {
+ content
+ .git
+ .as_ref()?
+ .inline_blame
+ .as_ref()?
+ .date_style
+ .as_ref()
+ },
+ write: |content, value, _| {
+ content
+ .git
+ .get_or_insert_default()
+ .inline_blame
+ .get_or_insert_default()
+ .date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::DynamicItem(DynamicItem {
discriminant: SettingItem {
title: "Enabled",
@@ -8588,9 +8643,28 @@ fn version_control_page() -> SettingsPage {
]
}
- fn git_blame_view_section() -> [SettingsPageItem; 2] {
+ fn git_blame_view_section() -> [SettingsPageItem; 3] {
[
SettingsPageItem::SectionHeader("Git Blame View"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates in the blame gutter.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git.blame.date_style"),
+ pick: |content| content.git.as_ref()?.blame.as_ref()?.date_style.as_ref(),
+ write: |content, value, _| {
+ content
+ .git
+ .get_or_insert_default()
+ .blame
+ .get_or_insert_default()
+ .date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Show Avatar",
description: "Show the avatar of the author of the commit.",
@@ -8621,9 +8695,36 @@ fn version_control_page() -> SettingsPage {
]
}
- fn branch_picker_section() -> [SettingsPageItem; 2] {
+ fn branch_picker_section() -> [SettingsPageItem; 3] {
[
SettingsPageItem::SectionHeader("Branch Picker"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates in the branch picker.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git.branch_picker.date_style"),
+ pick: |content| {
+ content
+ .git
+ .as_ref()?
+ .branch_picker
+ .as_ref()?
+ .date_style
+ .as_ref()
+ },
+ write: |content, value, _| {
+ content
+ .git
+ .get_or_insert_default()
+ .branch_picker
+ .get_or_insert_default()
+ .date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Show Author Name",
description: "Show author name as part of the commit information in branch picker.",
@@ -8654,6 +8755,59 @@ fn version_control_page() -> SettingsPage {
]
}
+ fn stash_picker_section() -> [SettingsPageItem; 2] {
+ [
+ SettingsPageItem::SectionHeader("Stash Picker"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates in the stash picker.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git.stash_picker.date_style"),
+ pick: |content| {
+ content
+ .git
+ .as_ref()?
+ .stash_picker
+ .as_ref()?
+ .date_style
+ .as_ref()
+ },
+ write: |content, value, _| {
+ content
+ .git
+ .get_or_insert_default()
+ .stash_picker
+ .get_or_insert_default()
+ .date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
+ ]
+ }
+
+ fn git_graph_section() -> [SettingsPageItem; 2] {
+ [
+ SettingsPageItem::SectionHeader("Git Graph"),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Date Style",
+ description: "Show relative or absolute dates in graph rows.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("git_graph.date_style"),
+ pick: |content| content.git_graph.as_ref()?.date_style.as_ref(),
+ write: |content, value, _| {
+ content.git_graph.get_or_insert_default().date_style = value
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
+ ]
+ }
+
fn git_hunks_section() -> [SettingsPageItem; 5] {
[
SettingsPageItem::SectionHeader("Git Hunks"),
@@ -8766,6 +8920,8 @@ fn version_control_page() -> SettingsPage {
inline_git_blame_section(),
git_blame_view_section(),
branch_picker_section(),
+ stash_picker_section(),
+ git_graph_section(),
file_diff_section(),
git_hunks_section(),
],
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 7e637cf8229..e167c5cc7e2 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -580,6 +580,7 @@ fn init_renderers(cx: &mut App) {
.add_basic_renderer::<settings::DockPosition>(render_dropdown)
.add_basic_renderer::<settings::SidebarDockPosition>(render_dropdown)
.add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
+ .add_basic_renderer::<settings::GitDateStyle>(render_dropdown)
.add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
.add_basic_renderer::<settings::GitDiffBaseSetting>(render_dropdown)
.add_basic_renderer::<settings::GitPathStyle>(render_dropdown)
diff --git a/docs/src/reference/all-settings.md b/docs/src/reference/all-settings.md
index a4de136a36c..5de21223ed6 100644
--- a/docs/src/reference/all-settings.md
+++ b/docs/src/reference/all-settings.md
@@ -3187,6 +3187,41 @@ These settings belong inside the `git` object.
| `path_style` | `"file_name_first"` | Use `"file_name_first"` or `"file_path_first"` in Git views. |
| `show_stage_restore_buttons` | `true` | Show stage and restore buttons on diff hunks. |
+### Git Dates
+
+In the Settings Editor, open **Version Control** to set **Date Format** and each
+view's **Date Style**. The Git Panel's date style is under **Panels**.
+
+`git.date_format` controls absolute dates across Git views:
+
+- `"locale"` (default): keep each view's existing date format.
+- `"iso"`: `YYYY-MM-DD HH:MM`.
+- A [strftime format](https://man7.org/linux/man-pages/man3/strftime.3.html), such as
+ `"%Y-%m-%d %H:%M:%S %z"`.
+
+Dates use your local time zone. Empty or invalid formats fall back to `"locale"`.
+Hovers, tooltips, and commit views always show absolute dates using this format.
+
+Each view has its own `date_style`, either `"relative"` or `"absolute"`. The default
+is `"relative"` for blame, inline blame (including the status bar), branch and stash
+pickers, and Git Panel history. Git Graph rows default to `"absolute"`.
+
+Or add this to your settings.json:
+
+```json [settings]
+{
+ "git": {
+ "date_format": "%Y-%m-%d %H:%M",
+ "blame": { "date_style": "relative" },
+ "inline_blame": { "date_style": "relative" },
+ "branch_picker": { "date_style": "relative" },
+ "stash_picker": { "date_style": "relative" }
+ },
+ "git_panel": { "date_style": "relative" },
+ "git_graph": { "date_style": "absolute" }
+}
+```
+
### Git Gutter
- Description: Whether or not to show the git gutter.