use crate::{
git::{self, Opts},
history::{self, LogEntry},
input,
model::Config,
policy::{self, Op},
repo_state::{self, EntryKind, Head},
safety, screen,
ui::{self, Choice, Key},
};
use anyhow::{anyhow, bail, Result};
use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, Weekday};
const TITLE: &str = "Time travel";
const MAX_COMMITS: usize = 500;
const PREVIEW_ROWS: usize = 12;
#[derive(Debug, Clone)]
struct Commit {
oid: String,
raw: Vec<u8>,
author: (i64, String),
committer: (i64, String),
signed: bool,
subject: String,
}
#[derive(Debug, Clone)]
struct Range {
branch: String,
tip: String,
base: Option<String>,
commits: Vec<Commit>,
}
#[derive(Debug)]
struct Applied {
backup: String,
new_tip: String,
}
fn split_header(raw: &[u8]) -> (&[u8], &[u8]) {
let end = raw
.windows(2)
.position(|w| w == b"\n\n")
.map_or(raw.len(), |p| p + 1);
raw.split_at(end)
}
fn is_signature_header(line: &[u8]) -> bool {
line.starts_with(b"gpgsig ") || line.starts_with(b"gpgsig-sha256 ")
}
fn retime_line(line: &[u8], ts: i64, tz: &str) -> Vec<u8> {
let Some(gt) = line.iter().rposition(|&b| b == b'>') else {
return line.to_vec();
};
let mut out = line[..=gt].to_vec();
out.extend_from_slice(format!(" {ts} {tz}").as_bytes());
if line.ends_with(b"\r\n") {
out.extend_from_slice(b"\r\n");
} else if line.ends_with(b"\n") {
out.push(b'\n');
}
out
}
pub fn rewrite_commit_object(
raw: &[u8],
new_parent: Option<&str>,
author: (i64, &str),
committer: (i64, &str),
) -> Vec<u8> {
let (header, rest) = split_header(raw);
let mut out = Vec::with_capacity(raw.len() + 48);
let mut skipping = false;
let mut parent_done = false;
for line in header.split_inclusive(|&b| b == b'\n') {
if line.starts_with(b" ") {
if !skipping {
out.extend_from_slice(line);
}
continue;
}
skipping = false;
if line.starts_with(b"parent ") {
if !parent_done {
if let Some(parent) = new_parent {
out.extend_from_slice(format!("parent {parent}\n").as_bytes());
}
parent_done = true;
}
continue;
}
if !parent_done && !line.starts_with(b"tree ") {
if let Some(parent) = new_parent {
out.extend_from_slice(format!("parent {parent}\n").as_bytes());
}
parent_done = true;
}
if is_signature_header(line) {
skipping = true;
} else if line.starts_with(b"author ") {
out.extend(retime_line(line, author.0, author.1));
} else if line.starts_with(b"committer ") {
out.extend(retime_line(line, committer.0, committer.1));
} else {
out.extend_from_slice(line);
}
}
out.extend_from_slice(rest);
out
}
fn parse_signature(line: &[u8]) -> Result<(i64, String)> {
let gt = line
.iter()
.rposition(|&b| b == b'>')
.ok_or_else(|| anyhow!("malformed author/committer line"))?;
let tail = String::from_utf8_lossy(&line[gt + 1..]);
let mut parts = tail.split_whitespace();
let ts = parts
.next()
.and_then(|t| t.parse::<i64>().ok())
.ok_or_else(|| anyhow!("malformed timestamp in author/committer line"))?;
let tz = parts.next().unwrap_or("+0000").to_string();
Ok((ts, tz))
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedCommit {
parents: Vec<String>,
author: (i64, String),
committer: (i64, String),
signed: bool,
subject: String,
}
fn parse_commit(raw: &[u8]) -> Result<ParsedCommit> {
let (header, rest) = split_header(raw);
let (mut parents, mut author, mut committer, mut signed) = (Vec::new(), None, None, false);
for line in header.split_inclusive(|&b| b == b'\n') {
let trimmed = line.strip_suffix(b"\n").unwrap_or(line);
if let Some(p) = trimmed.strip_prefix(b"parent ") {
parents.push(String::from_utf8_lossy(p).trim().to_string());
} else if trimmed.starts_with(b"author ") {
author = Some(parse_signature(trimmed)?);
} else if trimmed.starts_with(b"committer ") {
committer = Some(parse_signature(trimmed)?);
} else if is_signature_header(line) {
signed = true;
}
}
let message = String::from_utf8_lossy(rest);
let subject = message
.trim_start()
.lines()
.next()
.unwrap_or("")
.trim_end()
.to_string();
Ok(ParsedCommit {
parents,
author: author.ok_or_else(|| anyhow!("commit has no author line"))?,
committer: committer.ok_or_else(|| anyhow!("commit has no committer line"))?,
signed,
subject,
})
}
fn tz_offset(tz: &str) -> Result<i64> {
let (sign, digits) = match tz.as_bytes().first() {
Some(b'+') => (1, &tz[1..]),
Some(b'-') => (-1, &tz[1..]),
_ => bail!("unknown time zone '{tz}'"),
};
if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
bail!("unknown time zone '{tz}'");
}
let hours: i64 = digits[..2].parse()?;
let minutes: i64 = digits[2..].parse()?;
Ok(sign * (hours * 3600 + minutes * 60))
}
fn to_local(ts: i64, tz: &str) -> Result<NaiveDateTime> {
ts.checked_add(tz_offset(tz)?)
.and_then(|t| DateTime::from_timestamp(t, 0))
.map(|d| d.naive_utc())
.ok_or_else(|| anyhow!("timestamp {ts} out of range"))
}
fn from_local(local: NaiveDateTime, tz: &str) -> Result<i64> {
local
.and_utc()
.timestamp()
.checked_sub(tz_offset(tz)?)
.ok_or_else(|| anyhow!("date {local} out of range"))
}
const MAX_TS: i64 = 253_402_300_799;
fn check_ts(ts: i64) -> Result<i64> {
if (0..=MAX_TS).contains(&ts) {
Ok(ts)
} else {
bail!(
"The new date ({}) is outside 1970-9999; git cannot store it.",
show_time(ts, "+0000")
)
}
}
fn shift_ts(ts: i64, delta: i64) -> Result<i64> {
check_ts(
ts.checked_add(delta)
.ok_or_else(|| anyhow!("The shifted date is out of range."))?,
)
}
fn show_time(ts: i64, tz: &str) -> String {
to_local(ts, tz).map_or_else(
|_| format!("@{ts} {tz}"),
|t| format!("{} {tz}", t.format("%Y-%m-%d %H:%M:%S")),
)
}
fn next_random(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
pub fn spread_dates(
n: usize,
start: NaiveDateTime,
end: NaiveDateTime,
hours: (u32, u32),
skip_weekends: bool,
seed: u64,
) -> Result<Vec<NaiveDateTime>> {
if hours.0 >= hours.1 || hours.1 > 24 {
bail!("Working hours must be like 09-18 (start before end, end at most 24).");
}
if start >= end {
bail!("The window must end after it starts.");
}
if (end - start).num_days() > 36_600 {
bail!("The window is longer than 100 years.");
}
let mut spans: Vec<(NaiveDateTime, i64)> = Vec::new();
let mut day = start.date();
while day <= end.date() {
let weekend = matches!(day.weekday(), Weekday::Sat | Weekday::Sun);
if !(skip_weekends && weekend) {
let midnight = day
.and_hms_opt(0, 0, 0)
.ok_or_else(|| anyhow!("bad date"))?;
let at = |h: u32| {
midnight
.checked_add_signed(Duration::hours(i64::from(h)))
.ok_or_else(|| anyhow!("date out of range"))
};
let open = at(hours.0)?.max(start);
let close = at(hours.1)?.min(end);
if close > open {
spans.push((open, (close - open).num_seconds()));
}
}
let Some(next) = day.succ_opt() else { break };
day = next;
}
let total: i64 = spans.iter().map(|s| s.1).sum();
if n == 0 {
return Ok(Vec::new());
}
if n as i64 > total {
bail!("Cannot fit {n} commits into the window: only {total} usable seconds.");
}
let mut state = seed;
let mut out = Vec::with_capacity(n);
for i in 0..n {
let lo = (i as i128 * total as i128 / n as i128) as i64;
let hi = ((i as i128 + 1) * total as i128 / n as i128) as i64;
let mut offset = lo + (next_random(&mut state) % (hi - lo) as u64) as i64;
let mut placed = None;
for (open, len) in &spans {
if offset < *len {
placed = open.checked_add_signed(Duration::seconds(offset));
break;
}
offset -= len;
}
out.push(placed.ok_or_else(|| anyhow!("internal error placing a date"))?);
}
Ok(out)
}
const MAX_DELTA: i64 = 36_600 * 86_400;
pub fn parse_delta(text: &str) -> Result<i64> {
let text = text.trim();
let (sign, rest) = match text.strip_prefix('-') {
Some(rest) => (-1, rest),
None => (1, text.strip_prefix('+').unwrap_or(text)),
};
let usage = "Use amounts like +2d, -3h or +1d 2h 30m (w d h m s).";
let (mut total, mut number, mut any) = (0i64, String::new(), false);
for ch in rest.chars() {
if ch.is_ascii_digit() {
number.push(ch);
} else if ch.is_whitespace() {
if !number.is_empty() {
bail!("Missing unit after {number}. {usage}");
}
} else {
let unit = match ch.to_ascii_lowercase() {
'w' => 604_800,
'd' => 86_400,
'h' => 3_600,
'm' => 60,
's' => 1,
_ => bail!("Unknown unit '{ch}'. {usage}"),
};
if number.is_empty() {
bail!("Missing number. {usage}");
}
let too_large = || anyhow!("Amount too large: at most 100 years (36600d).");
let value: i64 = number.parse().map_err(|_| too_large())?;
total = value
.checked_mul(unit)
.and_then(|v| total.checked_add(v))
.filter(|t| *t <= MAX_DELTA)
.ok_or_else(too_large)?;
number.clear();
any = true;
}
}
if !number.is_empty() || !any {
bail!("{usage}");
}
if total == 0 {
bail!("Shifting by zero changes nothing.");
}
Ok(sign * total)
}
fn parse_hours(text: &str) -> Result<(u32, u32)> {
let hour = |s: &str| -> Result<u32> {
let s = s.trim();
let s = s.strip_suffix(":00").unwrap_or(s);
s.parse()
.map_err(|_| anyhow!("Working hours must look like 09-18."))
};
let (a, b) = text
.split_once('-')
.ok_or_else(|| anyhow!("Working hours must look like 09-18."))?;
Ok((hour(a)?, hour(b)?))
}
fn plan_times(old: &[(i64, i64)], new_author: &[Option<i64>], sync: bool) -> Vec<(i64, i64)> {
old.iter()
.zip(new_author)
.map(|(&(a, c), new)| match new {
Some(t) => (*t, if sync { *t } else { c }),
None => (a, c),
})
.collect()
}
fn edit_one_times(
old_authors: &[i64],
new_time: i64,
shift_later: bool,
) -> Result<Vec<Option<i64>>> {
check_ts(new_time)?;
let first = old_authors.first().copied().unwrap_or(new_time);
let delta = new_time
.checked_sub(first)
.ok_or_else(|| anyhow!("The shift is out of range."))?;
old_authors
.iter()
.enumerate()
.map(|(i, &a)| match (i, shift_later) {
(0, _) => Ok(Some(new_time)),
(_, true) => shift_ts(a, delta).map(Some),
(_, false) => Ok(None),
})
.collect()
}
fn preview_rows(range: &Range, times: &[(i64, i64)]) -> Vec<String> {
range
.commits
.iter()
.zip(times)
.map(|(c, &(a, _))| {
let old = show_time(c.author.0, &c.author.1);
let new = if a == c.author.0 {
"(unchanged)".to_string()
} else {
show_time(a, &c.author.1)
};
format!("{} {old} -> {new} {}", short(&c.oid), c.subject)
})
.collect()
}
fn preview_warnings(
range: &Range,
times: &[(i64, i64)],
published: bool,
sync: bool,
) -> Vec<String> {
let mut out = Vec::new();
let signed = range.commits.iter().filter(|c| c.signed).count();
if signed > 0 {
out.push(screen::warning(format!(
"! {signed} signed commit(s): the signature is dropped (it would no longer be valid)."
)));
}
if published {
out.push(screen::warning(
"! Some of these commits are already pushed. You will need a force-with-lease push.",
));
}
if times.windows(2).any(|w| w[1].0 < w[0].0) {
out.push(screen::warning(
"! The new author dates are not in order (a commit is older than its parent).",
));
}
out.push(screen::muted(if sync {
"Committer date = author date."
} else {
"Only the author date changes; committer dates stay as they are."
}));
out
}
fn short(oid: &str) -> &str {
oid.get(..7).unwrap_or(oid)
}
fn preflight() -> Result<(String, String)> {
let state = repo_state::load()?;
let name = match state.branch.head {
Head::Branch { name, .. } => name,
Head::Detached { .. } => {
bail!("HEAD is detached. Switch to a branch first: time travel rewrites a branch.")
}
Head::Unborn { name } => bail!("Branch {name} has no commits yet."),
};
if let Some(op) = state.op {
bail!("A {op:?} is in progress. Finish or abort it first.");
}
if state
.entries
.iter()
.any(|e| !matches!(e.kind, EntryKind::Untracked | EntryKind::Ignored))
{
bail!("The working tree has uncommitted changes. Commit or stash them first.");
}
let tip = git::git_ok(
&["rev-parse", "--verify", &format!("refs/heads/{name}")],
&Opts::default(),
)?;
Ok((name, tip))
}
fn load_range(oldest: &str) -> Result<Range> {
let (branch, tip) = preflight()?;
if oldest.starts_with('-') {
bail!("'{oldest}' is not a commit.");
}
let quiet = |args: &[&str]| -> Result<Option<String>> {
let out = git::git_raw(args, &Opts::default())?;
Ok(out
.ok()
.then(|| out.text().trim().to_string())
.filter(|s| !s.is_empty()))
};
let oid = quiet(&[
"rev-parse",
"--verify",
"--quiet",
&format!("{oldest}^{{commit}}"),
])?
.ok_or_else(|| anyhow!("'{oldest}' is not a commit."))?;
if !git::git_raw(
&["merge-base", "--is-ancestor", &oid, &tip],
&Opts::default(),
)?
.ok()
{
bail!("Commit {} is not on branch {branch}.", short(&oid));
}
let base = quiet(&["rev-parse", "--verify", "--quiet", &format!("{oid}^")])?;
let spec = match &base {
Some(b) => format!("{b}..{tip}"),
None => tip.clone(),
};
let merges = git::git_ok(&["rev-list", "--merges", &spec], &Opts::default())?;
if !merges.trim().is_empty() {
bail!("The range contains merge commits. Time travel only rewrites linear history.");
}
let list = git::git_ok(
&["rev-list", "--reverse", "--parents", &spec],
&Opts::default(),
)?;
let rows: Vec<Vec<&str>> = list
.lines()
.map(|l| l.split_whitespace().collect())
.collect();
if rows.len() > MAX_COMMITS {
bail!(
"{} commits selected; at most {MAX_COMMITS} can be rewritten at once.",
rows.len()
);
}
let mut expected = base.clone();
for row in &rows {
let parent = row.get(1).map(|p| p.to_string());
if row.len() > 2 || parent != expected {
bail!("The range is not a simple line of commits. Time travel only rewrites linear history.");
}
expected = row.first().map(|o| o.to_string());
}
if rows.first().and_then(|r| r.first()) != Some(&oid.as_str())
|| expected.as_deref() != Some(tip.as_str())
{
bail!("Could not walk from {} to the branch tip.", short(&oid));
}
let oids: Vec<&str> = rows.iter().filter_map(|r| r.first().copied()).collect();
let commits = read_commits(&oids)?;
Ok(Range {
branch,
tip,
base,
commits,
})
}
fn read_commits(oids: &[&str]) -> Result<Vec<Commit>> {
let mut input = oids.join("\n").into_bytes();
input.push(b'\n');
let out = git::git_raw(
&["cat-file", "--batch"],
&Opts {
stdin: Some(&input),
..Opts::default()
},
)?;
if !out.ok() {
bail!("git cat-file failed: {}", out.stderr.trim());
}
let mut data = out.stdout.as_slice();
let mut commits = Vec::with_capacity(oids.len());
for oid in oids {
let nl = data
.iter()
.position(|&b| b == b'\n')
.ok_or_else(|| anyhow!("short cat-file output"))?;
let head = String::from_utf8_lossy(&data[..nl]).to_string();
let fields: Vec<&str> = head.split_whitespace().collect();
let [got, "commit", size] = fields[..] else {
bail!("cannot read commit {oid}: {head}");
};
let size: usize = size.parse()?;
if got != *oid || data.len() < nl + 1 + size {
bail!("unexpected cat-file output for {oid}");
}
let raw = data[nl + 1..nl + 1 + size].to_vec();
data = data.get(nl + 2 + size..).unwrap_or(&[]);
let p = parse_commit(&raw)?;
commits.push(Commit {
oid: oid.to_string(),
raw,
author: p.author,
committer: p.committer,
signed: p.signed,
subject: p.subject,
});
}
Ok(commits)
}
fn apply(range: &Range, times: &[(i64, i64)]) -> Result<Applied> {
if times.len() != range.commits.len() || range.commits.is_empty() {
bail!("internal error: plan does not match the range");
}
for (commit, &(a, c)) in range.commits.iter().zip(times) {
if a != commit.author.0 {
check_ts(a)?;
}
if c != commit.committer.0 {
check_ts(c)?;
}
}
let backup = safety::backup("timetravel", &range.tip)?;
let mut parent = range.base.clone();
for (commit, &(a, c)) in range.commits.iter().zip(times) {
let raw = rewrite_commit_object(
&commit.raw,
parent.as_deref(),
(a, &commit.author.1),
(c, &commit.committer.1),
);
let oid = git::git_ok(
&["hash-object", "-t", "commit", "-w", "--stdin"],
&Opts {
stdin: Some(&raw),
..Opts::default()
},
)?;
parent = Some(oid);
}
let new_tip = parent.ok_or_else(|| anyhow!("nothing was written"))?;
let tree =
|rev: &str| git::git_ok(&["rev-parse", &format!("{rev}^{{tree}}")], &Opts::default());
if tree(&new_tip)? != tree(&range.tip)? {
bail!("Safety check failed: the rewritten tip has a different tree. Nothing was changed.");
}
let refname = format!("refs/heads/{}", range.branch);
let out = git::git_raw(
&[
"update-ref",
"-m",
"gct timetravel",
&refname,
&new_tip,
&range.tip,
],
&Opts::default(),
)?;
if !out.ok() {
bail!(
"Branch {} moved since the plan was made, so nothing was changed. Try again. ({})",
range.branch,
out.stderr.trim()
);
}
Ok(Applied { backup, new_tip })
}
pub fn run(config: &mut Config) -> Result<()> {
loop {
if let Err(e) = preflight() {
return ui::notice(TITLE, &[screen::warning(e.to_string())]);
}
let mut context = vec![
"Change the dates of commits on this branch. Files and messages stay exactly the same."
.to_string(),
];
context.extend(ui::explain(
config,
&[
"Each commit is copied with new dates and the branch is moved to the copies.",
"A backup ref keeps the old commits, so this can be undone.",
],
));
let options = [
"Edit one commit's date",
"Spread commits across a time window",
"Shift a range of commits by a fixed amount",
"Back",
];
let result = match ui::choose(TITLE, &context, &options)? {
Some(0) => edit_one(config),
Some(1) => spread(config),
Some(2) => shift(config),
_ => return Ok(()),
};
if let Err(e) = result {
if e.to_string() == input::CANCELLED {
return Err(e);
}
ui::notice(TITLE, &[screen::danger(format!("x {e}"))])?;
}
}
}
fn recent() -> Result<Vec<LogEntry>> {
let format = format!("--format={}", history::LOG_FORMAT);
let text = git::git_ok(&["log", "-n", "300", &format, "HEAD"], &Opts::default())?;
Ok(history::parse_log(&text))
}
fn log_row(e: &LogEntry) -> String {
let date = e.author_date.replacen('T', " ", 1);
let date = date.get(..19).unwrap_or(&date);
let merge = if e.parents.len() > 1 { "[merge] " } else { "" };
format!("{} {date} {merge}{}", e.short, e.subject)
}
fn pick_commit(title: &str, range: bool) -> Result<Option<String>> {
let entries = recent()?;
if entries.is_empty() {
ui::notice(TITLE, &["No commits yet. Make a commit first.".into()])?;
return Ok(None);
}
let rows: Vec<String> = entries.iter().map(log_row).collect();
let header = vec![if range {
"Pick the OLDEST commit to change; it and every newer commit get new dates.".to_string()
} else {
"Pick the commit whose date you want to change.".to_string()
}];
let keys: &[Key] = if range {
&[Key {
key: 'n',
label: "last N commits",
}]
} else {
&[]
};
let mut index = 0usize;
loop {
match ui::action_list(title, &header, &rows, keys, &mut index)? {
Choice::Back => return Ok(None),
Choice::Open(i) if i < entries.len() => {
if !range {
return Ok(Some(entries[i].oid.clone()));
}
let choice = ui::choose(
title,
&[rows[i].clone()],
&[
"Change this commit and every newer one",
"Choose the last N commits instead",
"Back",
],
)?;
match choice {
Some(0) => return Ok(Some(entries[i].oid.clone())),
Some(1) => {
if let Some(oid) = ask_last_n(&entries)? {
return Ok(Some(oid));
}
}
_ => {}
}
}
Choice::Action('n', _) if range => {
if let Some(oid) = ask_last_n(&entries)? {
return Ok(Some(oid));
}
}
_ => {}
}
}
}
fn ask_last_n(entries: &[LogEntry]) -> Result<Option<String>> {
let max = entries.len().min(MAX_COMMITS);
let Some(answer) = ui::ask(&format!("How many recent commits? (1-{max}):"), "")? else {
return Ok(None);
};
match answer.trim().parse::<usize>() {
Ok(n) if (1..=max).contains(&n) => Ok(Some(entries[n - 1].oid.clone())),
_ => {
ui::notice(
TITLE,
&[screen::warning(format!("Enter a number from 1 to {max}."))],
)?;
Ok(None)
}
}
}
fn ask_date(prompt: &str, initial: NaiveDate) -> Result<NaiveDate> {
let text = input::masked(prompt, &initial.format("%Y-%m-%d").to_string(), true)?;
NaiveDate::parse_from_str(&text, "%Y-%m-%d").map_err(|_| anyhow!("'{text}' is not a date."))
}
fn edit_one(cfg: &mut Config) -> Result<()> {
let Some(oid) = pick_commit("Time travel: pick a commit", false)? else {
return Ok(());
};
let range = load_range(&oid)?;
let first = &range.commits[0];
let (ts, tz) = (first.author.0, first.author.1.clone());
let local = to_local(ts, &tz)?;
let date = ask_date("Commit date (YYYY-MM-DD):", local.date())?;
let time = input::masked(
"Commit time (HH:MM:SS):",
&local.format("%H:%M:%S").to_string(),
false,
)?;
let time = chrono::NaiveTime::parse_from_str(&time, "%H:%M:%S")
.map_err(|_| anyhow!("'{time}' is not a time."))?;
let new_time = from_local(date.and_time(time), &tz)?;
let later = range.commits.len() - 1;
let options = [
"Change only this commit".to_string(),
format!("Shift this commit and the {later} newer one(s) by the same amount"),
];
let refs: Vec<&str> = options.iter().map(String::as_str).collect();
let shift_later = match ui::choose(
TITLE,
&[format!(
"{} -> {}",
show_time(ts, &tz),
show_time(new_time, &tz)
)],
&refs,
)? {
Some(0) => false,
Some(1) => true,
_ => return Ok(()),
};
let authors: Vec<i64> = range.commits.iter().map(|c| c.author.0).collect();
finish(
cfg,
&range,
&edit_one_times(&authors, new_time, shift_later)?,
)
}
fn spread(cfg: &mut Config) -> Result<()> {
let Some(oid) = pick_commit("Time travel: commits to spread", true)? else {
return Ok(());
};
let range = load_range(&oid)?;
let first = &range.commits[0];
let start = ask_date(
"Window start date (YYYY-MM-DD):",
to_local(first.author.0, &first.author.1)?.date(),
)?;
let end = ask_date(
"Window end date (YYYY-MM-DD):",
chrono::Local::now().date_naive(),
)?;
let Some(hours) = ui::ask("Working hours (start-end, 24h clock):", "09-18")? else {
return Ok(());
};
let hours = parse_hours(&hours)?;
let skip_weekends = match ui::choose(
TITLE,
&[],
&["Skip weekends (Saturday and Sunday)", "Include weekends"],
)? {
Some(0) => true,
Some(1) => false,
_ => return Ok(()),
};
let Some(seed) = ui::ask(
"Jitter seed (any number; the same seed gives the same dates):",
"1",
)?
else {
return Ok(());
};
let seed: u64 = seed
.trim()
.parse()
.map_err(|_| anyhow!("The seed must be a whole number."))?;
let midnight = |d: NaiveDate| d.and_hms_opt(0, 0, 0).ok_or_else(|| anyhow!("bad date"));
let window_end = midnight(
end.succ_opt()
.ok_or_else(|| anyhow!("end date out of range"))?,
)?;
let dates = spread_dates(
range.commits.len(),
midnight(start)?,
window_end,
hours,
skip_weekends,
seed,
)?;
let new_author = range
.commits
.iter()
.zip(&dates)
.map(|(c, d)| from_local(*d, &c.author.1).and_then(check_ts).map(Some))
.collect::<Result<Vec<_>>>()?;
finish(cfg, &range, &new_author)
}
fn shift(cfg: &mut Config) -> Result<()> {
let Some(oid) = pick_commit("Time travel: commits to shift", true)? else {
return Ok(());
};
let range = load_range(&oid)?;
let Some(text) = ui::ask("Shift by (e.g. +2d, -3h, +1d 2h 30m):", "+1d")? else {
return Ok(());
};
let delta = parse_delta(&text)?;
finish(cfg, &range, &shift_times(&range.commits, delta)?)
}
fn shift_times(commits: &[Commit], delta: i64) -> Result<Vec<Option<i64>>> {
commits
.iter()
.map(|c| shift_ts(c.author.0, delta).map(Some))
.collect()
}
fn finish(cfg: &mut Config, range: &Range, new_author: &[Option<i64>]) -> Result<()> {
let sync = match ui::choose(
TITLE,
&["Git stores two dates per commit: author date and committer date.".into()],
&[
"Set committer date = author date (recommended)",
"Change only the author date",
],
)? {
Some(0) => true,
Some(1) => false,
_ => return Ok(()),
};
let old: Vec<(i64, i64)> = range
.commits
.iter()
.map(|c| (c.author.0, c.committer.0))
.collect();
let times = plan_times(&old, new_author, sync);
let published = safety::is_published(&range.commits[0].oid)?;
let rows = preview_rows(range, ×);
let warnings = preview_warnings(range, ×, published, sync);
let n = range.commits.len();
loop {
let mut context = vec![format!(
"{n} commit(s) on {} will get these author dates:",
range.branch
)];
context.extend(rows.iter().take(PREVIEW_ROWS).cloned());
if rows.len() > PREVIEW_ROWS {
context.push(screen::muted(format!(
"... and {} more",
rows.len() - PREVIEW_ROWS
)));
}
context.extend(warnings.iter().cloned());
match ui::choose(
"Preview",
&context,
&["Apply these dates", "Show the full preview", "Cancel"],
)? {
Some(0) => break,
Some(1) => {
let mut full = rows.clone();
full.push(String::new());
full.extend(warnings.iter().cloned());
ui::pager("Preview", &full, "")?;
}
_ => return Ok(()),
}
}
let refname = format!("refs/heads/{}", range.branch);
let command = format!(
"git hash-object -t commit -w --stdin (x{n}) && git update-ref -m \"gct timetravel\" {refname} <new tip> {}",
short(&range.tip)
);
let verdict = policy::check(
cfg,
&Op::RewriteHistory {
branch: &range.branch,
published,
},
);
let what = format!(
"Rewrite the dates of {n} commit(s) on {}.\nThe old tip {} is saved first as backup refs/gct/backup/<time>-timetravel (its exact name is shown afterwards; restore it from Undo & Rescue).",
range.branch,
short(&range.tip)
);
if !ui::gate(cfg, &verdict, &what, &command)? {
return Ok(());
}
let applied = ui::git_job("Rewriting commit dates", || apply(range, ×))?;
let mut lines = vec![
screen::success(format!(
"v Rewrote the dates of {n} commit(s) on {}.",
range.branch
)),
format!(
"$ git update-ref -m \"gct timetravel\" {refname} {} {}",
applied.new_tip, range.tip
),
format!("Backup of the old history: {}", applied.backup),
screen::muted(format!("Undo with: git reset --keep {}", applied.backup)),
];
if published {
lines.push(screen::warning(
"! This branch was already pushed. Publish the new history with Sync's force-with-lease push (gct never pushes for you).",
));
}
lines.extend(ui::explain(
cfg,
&[
"Only the dates changed: every file and message is the same as before.",
"The old commits still exist under the backup ref until you delete it.",
],
));
ui::notice(TITLE, &lines)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
const TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
const P1: &str = "1111111111111111111111111111111111111111";
const P2: &str = "2222222222222222222222222222222222222222";
fn dt(s: &str) -> NaiveDateTime {
NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").unwrap()
}
#[test]
fn rewrites_chain_commit_and_tz() {
let raw = format!(
"tree {TREE}\nparent {P1}\nauthor Ann <a@x.io> 1700000000 +0530\ncommitter Bob <b@x.io> 1700000100 -0800\n\nfix the parent pointer\n\nparent {P1} is mentioned here\n"
);
let out = rewrite_commit_object(
raw.as_bytes(),
Some(P2),
(1600000000, "+0530"),
(1600000005, "-0800"),
);
let expected = format!(
"tree {TREE}\nparent {P2}\nauthor Ann <a@x.io> 1600000000 +0530\ncommitter Bob <b@x.io> 1600000005 -0800\n\nfix the parent pointer\n\nparent {P1} is mentioned here\n"
);
assert_eq!(String::from_utf8(out).unwrap(), expected);
let p = parse_commit(raw.as_bytes()).unwrap();
assert_eq!(p.parents, [P1]);
assert_eq!(p.author, (1700000000, "+0530".into()));
assert_eq!(p.committer, (1700000100, "-0800".into()));
assert!(!p.signed);
assert_eq!(p.subject, "fix the parent pointer");
}
#[test]
fn rewrites_root_and_adds_or_removes_parent() {
let root =
format!("tree {TREE}\nauthor A <a@x> 1 +0000\ncommitter A <a@x> 2 +0000\n\nroot\n");
let same = rewrite_commit_object(root.as_bytes(), None, (1, "+0000"), (2, "+0000"));
assert_eq!(same, root.as_bytes());
let with_parent =
rewrite_commit_object(root.as_bytes(), Some(P1), (1, "+0000"), (2, "+0000"));
assert!(String::from_utf8(with_parent)
.unwrap()
.starts_with(&format!("tree {TREE}\nparent {P1}\nauthor ")));
let chain = format!(
"tree {TREE}\nparent {P1}\nauthor A <a@x> 1 +0000\ncommitter A <a@x> 2 +0000\n\nm\n"
);
let new_root = rewrite_commit_object(chain.as_bytes(), None, (1, "+0000"), (2, "+0000"));
assert_eq!(new_root, root.replace("root", "m").as_bytes());
}
#[test]
fn drops_signatures_keeps_encoding_and_crlf() {
let raw = format!(
"tree {TREE}\nparent {P1}\nauthor Zo\u{eb} <z@x> 1700000000 +0000\ncommitter Zo\u{eb} <z@x> 1700000000 +0000\nencoding ISO-8859-1\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n iQEzBAABCAAdFiEE\n -----END PGP SIGNATURE-----\ngpgsig-sha256 -----BEGIN SSH SIGNATURE-----\n abc\n -----END SSH SIGNATURE-----\nx-extra value\n continued\n\nsubject\r\n\r\nbody\r\n"
);
assert!(parse_commit(raw.as_bytes()).unwrap().signed);
let mut bytes = raw.into_bytes();
bytes.push(0xE9); let out = rewrite_commit_object(&bytes, Some(P1), (5, "+0000"), (6, "+0000"));
let mut expected = format!(
"tree {TREE}\nparent {P1}\nauthor Zo\u{eb} <z@x> 5 +0000\ncommitter Zo\u{eb} <z@x> 6 +0000\nencoding ISO-8859-1\nx-extra value\n continued\n\nsubject\r\n\r\nbody\r\n"
)
.into_bytes();
expected.push(0xE9);
assert_eq!(out, expected);
}
#[test]
fn timezones_and_shift_math() {
assert_eq!(tz_offset("+0530").unwrap(), 19800);
assert_eq!(tz_offset("-0800").unwrap(), -28800);
assert!(tz_offset("0800").is_err() && tz_offset("+08").is_err());
let local = dt("2024-03-10 01:30:00"); let ts = from_local(local, "-0800").unwrap();
assert_eq!(ts, 1710063000);
assert_eq!(
to_local(ts + 86_400, "-0800").unwrap(),
dt("2024-03-11 01:30:00")
);
assert_eq!(to_local(ts, "+0530").unwrap(), dt("2024-03-10 15:00:00"));
assert_eq!(parse_delta("+2d").unwrap(), 172_800);
assert_eq!(
parse_delta("-1d 2h 30m").unwrap(),
-(86_400 + 7_200 + 1_800)
);
assert_eq!(parse_delta("90m").unwrap(), 5_400);
assert_eq!(parse_delta("1W").unwrap(), 604_800);
for bad in ["", "+", "5", "2x", "d", "0h", "3 h"] {
assert!(parse_delta(bad).is_err(), "{bad}");
}
assert_eq!(parse_hours("09-18").unwrap(), (9, 18));
assert_eq!(parse_hours("9:00 - 17:00").unwrap(), (9, 17));
assert!(parse_hours("nine").is_err());
}
#[test]
fn plans_times() {
let old = [(100, 110), (200, 210), (300, 310)];
assert_eq!(
edit_one_times(&[100, 200, 300], 150, false).unwrap(),
[Some(150), None, None]
);
assert_eq!(
edit_one_times(&[100, 200, 300], 150, true).unwrap(),
[Some(150), Some(250), Some(350)]
);
let new = [Some(150), None, Some(350)];
assert_eq!(
plan_times(&old, &new, true),
[(150, 150), (200, 210), (350, 350)]
);
assert_eq!(
plan_times(&old, &new, false),
[(150, 110), (200, 210), (350, 310)]
);
}
#[test]
fn date_math_never_overflows() {
for bad in [
"+15000000000000w",
"-15000000000000w",
"+99999999999999999999s",
"36601d",
"+36600d 1s",
"5300w",
] {
let err = parse_delta(bad).unwrap_err().to_string();
assert!(err.contains("too large"), "{bad}: {err}");
}
assert_eq!(parse_delta("+36600d").unwrap(), MAX_DELTA);
assert_eq!(parse_delta("-36600d").unwrap(), -MAX_DELTA);
assert_eq!(tz_offset("+9959").unwrap(), 99 * 3600 + 59 * 60);
assert_eq!(tz_offset("-9959").unwrap(), -(99 * 3600 + 59 * 60));
assert!(to_local(i64::MAX, "+9959").is_err());
assert!(to_local(i64::MIN, "-9959").is_err());
assert!(to_local(i64::MAX - 10, "+0000").is_err());
assert_eq!(show_time(i64::MAX, "+0100"), format!("@{} +0100", i64::MAX));
assert!(from_local(dt("2024-01-01 00:00:00"), "-9959").is_ok());
assert!(from_local(NaiveDateTime::MAX, "-9959").is_ok());
let big = format!(
"tree {TREE}\nauthor A <a@x> {} +9959\ncommitter A <a@x> {} -9959\n\nm\n",
i64::MAX,
i64::MIN
);
let p = parse_commit(big.as_bytes()).unwrap();
assert_eq!((p.author.0, p.committer.0), (i64::MAX, i64::MIN));
assert!(parse_commit(format!("tree {TREE}\nauthor A <a@x> 99999999999999999999 +0000\ncommitter A <a@x> 1 +0000\n\nm\n").as_bytes()).is_err());
assert!(shift_ts(i64::MAX, 1).is_err());
assert!(shift_ts(i64::MIN, -1).is_err());
assert!(shift_ts(100, -101).is_err(), "before 1970");
assert!(shift_ts(MAX_TS, 1).is_err(), "after 9999");
assert_eq!(shift_ts(100, MAX_DELTA).unwrap(), 100 + MAX_DELTA);
let commit = |ts: i64| Commit {
oid: P1.into(),
raw: Vec::new(),
author: (ts, "+0000".into()),
committer: (ts, "+0000".into()),
signed: false,
subject: String::new(),
};
assert!(shift_times(&[commit(1_700_000_000), commit(i64::MAX)], 60).is_err());
assert_eq!(
shift_times(&[commit(1_700_000_000)], -60).unwrap(),
[Some(1_699_999_940)]
);
assert!(edit_one_times(&[i64::MIN, 5], 1_700_000_000, true).is_err());
assert!(edit_one_times(&[100, i64::MAX], 200, true).is_err());
assert_eq!(
edit_one_times(&[100, i64::MAX], 200, false).unwrap(),
[Some(200), None]
);
assert!(edit_one_times(&[100], -1, false).is_err());
let last = NaiveDateTime::MAX.date().and_hms_opt(0, 0, 0).unwrap();
assert!(spread_dates(1, last, NaiveDateTime::MAX, (0, 24), false, 0).is_err());
}
#[test]
fn apply_refuses_unstorable_dates() {
let repo = TempRepo::new(2);
let tip = repo.git(&["rev-parse", "HEAD"]);
repo.run(|| {
let range = load_range("HEAD").unwrap();
let c = &range.commits[0];
assert!(apply(&range, &[(-5, c.committer.0)]).is_err());
assert!(apply(&range, &[(c.author.0, MAX_TS + 1)]).is_err());
assert!(
safety::backups().unwrap().is_empty(),
"refused before any backup or write"
);
});
assert_eq!(repo.git(&["rev-parse", "HEAD"]), tip);
}
#[test]
fn spread_dates_properties() {
let (start, end) = (dt("2024-01-01 00:00:00"), dt("2024-01-15 00:00:00"));
for skip in [false, true] {
let dates = spread_dates(40, start, end, (9, 18), skip, 7).unwrap();
assert_eq!(dates.len(), 40);
assert!(dates.windows(2).all(|w| w[0] < w[1]), "strictly increasing");
for d in &dates {
assert!(*d >= start && *d < end);
let hour = chrono::Timelike::hour(d);
assert!((9..18).contains(&hour), "{d}");
if skip {
assert!(!matches!(d.weekday(), Weekday::Sat | Weekday::Sun), "{d}");
}
}
assert_eq!(
dates,
spread_dates(40, start, end, (9, 18), skip, 7).unwrap()
);
}
assert_ne!(
spread_dates(40, start, end, (9, 18), false, 1).unwrap(),
spread_dates(40, start, end, (9, 18), false, 2).unwrap()
);
let tight = spread_dates(
3,
dt("2024-01-02 10:00:00"),
dt("2024-01-02 10:00:03"),
(0, 24),
false,
0,
)
.unwrap();
assert_eq!(
tight,
[
dt("2024-01-02 10:00:00"),
dt("2024-01-02 10:00:01"),
dt("2024-01-02 10:00:02")
]
);
assert!(spread_dates(
4,
dt("2024-01-02 10:00:00"),
dt("2024-01-02 10:00:03"),
(0, 24),
false,
0
)
.is_err());
assert!(spread_dates(
1,
dt("2024-01-06 00:00:00"),
dt("2024-01-08 00:00:00"),
(9, 18),
true,
0
)
.is_err());
assert!(spread_dates(1, end, start, (9, 18), false, 0).is_err());
assert!(spread_dates(1, start, end, (18, 9), false, 0).is_err());
assert!(spread_dates(0, start, end, (9, 18), false, 0)
.unwrap()
.is_empty());
}
fn dates(repo: &TempRepo) -> Vec<String> {
repo.git(&["log", "--format=%at %ct"])
.lines()
.map(String::from)
.collect()
}
#[test]
fn redates_from_root() {
let repo = TempRepo::new(3).with_remote();
let old_tip = repo.git(&["rev-parse", "HEAD"]);
let old_trees = repo.git(&["log", "--format=%T %B"]);
let root = repo.git(&["rev-list", "--max-parents=0", "HEAD"]);
let applied = repo.run(|| {
let range = load_range(&root).unwrap();
assert_eq!(range.commits.len(), 3);
assert!(range.base.is_none());
assert!(safety::is_published(&root).unwrap());
let new = [
Some(1_800_000_000),
Some(1_800_000_100),
Some(1_800_000_200),
];
let old: Vec<(i64, i64)> = range
.commits
.iter()
.map(|c| (c.author.0, c.committer.0))
.collect();
apply(&range, &plan_times(&old, &new, true)).unwrap()
});
assert_eq!(repo.git(&["rev-parse", "HEAD"]), applied.new_tip);
assert_ne!(applied.new_tip, old_tip);
assert_eq!(repo.git(&["log", "--format=%T %B"]), old_trees);
assert_eq!(
dates(&repo),
[
"1800000200 1800000200",
"1800000100 1800000100",
"1800000000 1800000000"
]
);
assert_eq!(repo.git(&["rev-list", "--count", "HEAD"]), "3");
repo.git(&["fsck", "--no-dangling"]);
assert!(applied.backup.starts_with("refs/gct/backup/"));
assert_eq!(repo.git(&["rev-parse", &applied.backup]), old_tip);
assert_eq!(repo.git(&["status", "--porcelain"]), "");
}
#[test]
fn redates_suffix_keeps_older_commits() {
let repo = TempRepo::new(3);
let first = repo.git(&["rev-parse", "HEAD~2"]);
let applied = repo.run(|| {
let range = load_range("HEAD~1").unwrap();
assert_eq!(range.commits.len(), 2);
let old: Vec<(i64, i64)> = range
.commits
.iter()
.map(|c| (c.author.0, c.committer.0))
.collect();
let new: Vec<Option<i64>> = old.iter().map(|o| Some(o.0 + 3600)).collect();
apply(&range, &plan_times(&old, &new, false)).unwrap()
});
assert_eq!(repo.git(&["rev-parse", "HEAD~2"]), first);
assert_eq!(repo.git(&["rev-parse", "HEAD"]), applied.new_tip);
let base = 1_704_110_400;
assert_eq!(
dates(&repo),
[
format!("{} {}", base + 180 + 3600, base + 180),
format!("{} {}", base + 120 + 3600, base + 120),
format!("{} {}", base + 60, base + 60),
]
);
}
#[test]
fn refuses_merges_dirty_and_detached() {
let repo = TempRepo::new(2);
repo.git(&["checkout", "-q", "-b", "side"]);
repo.write("side.txt", "s\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "side"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("main.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "main"]);
repo.git(&["merge", "-q", "--no-ff", "-m", "merge", "side"]);
let err = repo.run(|| load_range("HEAD~1").unwrap_err().to_string());
assert!(err.contains("merge"), "{err}");
let err = repo.run(|| load_range("-x").unwrap_err().to_string());
assert!(err.contains("not a commit"), "{err}");
let repo = TempRepo::new(2);
repo.write("f1.txt", "changed\n");
let err = repo.run(|| load_range("HEAD").unwrap_err().to_string());
assert!(err.contains("uncommitted"), "{err}");
let repo = TempRepo::new(2);
repo.git(&["checkout", "-q", "--detach"]);
let err = repo.run(|| load_range("HEAD").unwrap_err().to_string());
assert!(err.contains("detached"), "{err}");
}
#[test]
fn cas_fails_safely_when_branch_moved() {
let repo = TempRepo::new(3);
let range = repo.run(|| load_range("HEAD~2").unwrap());
repo.write("late.txt", "late\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "late"]);
let moved = repo.git(&["rev-parse", "HEAD"]);
let old: Vec<(i64, i64)> = range
.commits
.iter()
.map(|c| (c.author.0 + 5, c.committer.0))
.collect();
let err = repo.run(|| apply(&range, &old).unwrap_err().to_string());
assert!(err.contains("moved"), "{err}");
assert_eq!(repo.git(&["rev-parse", "HEAD"]), moved);
assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "late");
}
}