Skip to main content

git_editor/utils/
datetime.rs

1use crate::args::Args;
2use crate::utils::dates::parse_utc;
3use crate::utils::types::Result;
4use chrono::{Duration, NaiveDateTime};
5use rand::Rng;
6
7pub fn generate_timestamps(args: &Args) -> Result<Vec<NaiveDateTime>> {
8    let start_dt = parse_utc(args.start.as_deref().ok_or("Missing --begin")?)?;
9    let end_dt = parse_utc(args.end.as_deref().ok_or("Missing --end")?)?;
10
11    if start_dt >= end_dt {
12        return Err("Start datetime must be before end datetime".into());
13    }
14
15    let total_commits = count_commits(args.repo_path.as_ref().unwrap())?;
16    if total_commits == 0 {
17        return Err("No commits found in repository".into());
18    }
19
20    spread_timestamps(start_dt, end_dt, total_commits, args.skip_range_check)
21}
22
23/// Minimum gap between generated commits by default.
24const DEFAULT_GAP_SECS: i64 = 3 * 3600;
25/// Minimum gap with `--skip-range-check` when it fits.
26const PACKED_GAP_SECS: i64 = 5 * 60;
27
28/// `count` strictly increasing timestamps from `start` to exactly `end`.
29///
30/// Gaps are at least 3 hours (or, with `skip_range_check`, at least 5 minutes
31/// when that fits and otherwise as even as possible, but never below one second),
32/// with the remaining slack spread randomly. Everything is whole seconds, so the
33/// last timestamp is `end` exactly.
34pub fn spread_timestamps(
35    start: NaiveDateTime,
36    end: NaiveDateTime,
37    count: usize,
38    skip_range_check: bool,
39) -> Result<Vec<NaiveDateTime>> {
40    if count == 0 {
41        return Ok(Vec::new());
42    }
43    if count == 1 {
44        return Ok(vec![start]);
45    }
46    let gaps = (count - 1) as i64;
47    let span = (end - start).num_seconds();
48
49    let min_gap = if span >= DEFAULT_GAP_SECS * gaps {
50        DEFAULT_GAP_SECS
51    } else if !skip_range_check {
52        return Err(format!(
53            "Date range too small for {count} commits. Need at least {} hours between start and end dates.\n\
54            Tip: Pass --skip-range-check to skip this validation and distribute commits evenly across the given range.",
55            DEFAULT_GAP_SECS * gaps / 3600
56        )
57        .into());
58    } else if span >= PACKED_GAP_SECS * gaps {
59        PACKED_GAP_SECS
60    } else if span >= gaps {
61        // Too tight for random gaps: spread evenly, every gap at least one second.
62        let gap_lengths = even_split(span, gaps as usize);
63        return Ok(accumulate(start, &gap_lengths));
64    } else {
65        return Err(format!(
66            "Date range too small for {count} commits: need at least {gaps} seconds so every commit gets a distinct timestamp"
67        )
68        .into());
69    };
70
71    let slack = span - min_gap * gaps;
72    let mut rng = rand::rng();
73    let weights: Vec<f64> = (0..gaps)
74        .map(|_| rng.random::<f64>() + f64::EPSILON)
75        .collect();
76    let gap_lengths: Vec<i64> = random_split(slack, &weights)
77        .into_iter()
78        .map(|extra| extra + min_gap)
79        .collect();
80    Ok(accumulate(start, &gap_lengths))
81}
82
83/// Split `total` into `parts` integers that differ by at most one.
84fn even_split(total: i64, parts: usize) -> Vec<i64> {
85    let base = total / parts as i64;
86    let remainder = (total % parts as i64) as usize;
87    (0..parts)
88        .map(|i| base + i64::from(i < remainder))
89        .collect()
90}
91
92/// Split `total` proportionally to `weights` into integers that sum to `total` exactly.
93fn random_split(total: i64, weights: &[f64]) -> Vec<i64> {
94    let sum: f64 = weights.iter().sum();
95    let shares: Vec<f64> = weights.iter().map(|w| w / sum * total as f64).collect();
96    let mut parts: Vec<i64> = shares.iter().map(|s| s.floor() as i64).collect();
97    let mut missing = total - parts.iter().sum::<i64>();
98    // Hand out the rounding remainder to the largest fractional parts.
99    let mut order: Vec<usize> = (0..parts.len()).collect();
100    order.sort_by(|&a, &b| {
101        let fa = shares[a] - shares[a].floor();
102        let fb = shares[b] - shares[b].floor();
103        fb.partial_cmp(&fa).unwrap_or(std::cmp::Ordering::Equal)
104    });
105    for i in order {
106        if missing <= 0 {
107            break;
108        }
109        parts[i] += 1;
110        missing -= 1;
111    }
112    parts
113}
114
115fn accumulate(start: NaiveDateTime, gaps: &[i64]) -> Vec<NaiveDateTime> {
116    let mut current = start;
117    let mut out = Vec::with_capacity(gaps.len() + 1);
118    out.push(current);
119    for gap in gaps {
120        current += Duration::seconds(*gap);
121        out.push(current);
122    }
123    out
124}
125
126fn count_commits(repo_path: &str) -> Result<usize> {
127    let repo = git2::Repository::open(repo_path)?;
128    let mut revwalk = repo.revwalk()?;
129    revwalk.push_head()?;
130    revwalk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
131    Ok(revwalk.count())
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use std::fs;
138    use tempfile::TempDir;
139
140    fn create_test_repo() -> (TempDir, String) {
141        let temp_dir = TempDir::new().unwrap();
142        let repo_path = temp_dir.path().to_str().unwrap().to_string();
143
144        // Initialize git repo
145        let repo = git2::Repository::init(&repo_path).unwrap();
146
147        // Create a test file
148        let file_path = temp_dir.path().join("test.txt");
149        fs::write(&file_path, "test content").unwrap();
150
151        // Add and commit file
152        let mut index = repo.index().unwrap();
153        index.add_path(std::path::Path::new("test.txt")).unwrap();
154        index.write().unwrap();
155
156        let tree_id = index.write_tree().unwrap();
157        let tree = repo.find_tree(tree_id).unwrap();
158
159        let sig = git2::Signature::new(
160            "Test User",
161            "test@example.com",
162            &git2::Time::new(1234567890, 0),
163        )
164        .unwrap();
165        repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
166            .unwrap();
167
168        (temp_dir, repo_path)
169    }
170
171    #[test]
172    fn test_count_commits() {
173        let (_temp_dir, repo_path) = create_test_repo();
174        let count = count_commits(&repo_path).unwrap();
175        assert_eq!(count, 1);
176    }
177
178    #[test]
179    fn test_generate_timestamps_invalid_date_format() {
180        let (_temp_dir, repo_path) = create_test_repo();
181        let args = Args {
182            repo_path: Some(repo_path),
183            email: Some("test@example.com".to_string()),
184            name: Some("Test User".to_string()),
185            start: Some("invalid-date".to_string()),
186            end: Some("2023-01-02 00:00:00".to_string()),
187            ..Default::default()
188        };
189
190        let result = generate_timestamps(&args);
191        assert!(result.is_err());
192    }
193
194    #[test]
195    fn test_generate_timestamps_valid_range() {
196        let (_temp_dir, repo_path) = create_test_repo();
197        let args = Args {
198            repo_path: Some(repo_path),
199            email: Some("test@example.com".to_string()),
200            name: Some("Test User".to_string()),
201            start: Some("2023-01-01 00:00:00".to_string()),
202            end: Some("2023-01-10 00:00:00".to_string()),
203            ..Default::default()
204        };
205
206        let result = generate_timestamps(&args);
207        assert!(result.is_ok());
208
209        let timestamps = result.unwrap();
210        assert_eq!(timestamps.len(), 1); // One commit in test repo
211
212        let start_dt =
213            NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
214        let end_dt =
215            NaiveDateTime::parse_from_str("2023-01-10 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
216
217        assert!(timestamps[0] >= start_dt);
218        assert!(timestamps[0] <= end_dt);
219    }
220
221    #[test]
222    fn test_generate_timestamps_preserves_order() {
223        let (_temp_dir, repo_path) = create_test_repo();
224        let args = Args {
225            repo_path: Some(repo_path),
226            email: Some("test@example.com".to_string()),
227            name: Some("Test User".to_string()),
228            start: Some("2023-01-01 00:00:00".to_string()),
229            end: Some("2023-01-10 00:00:00".to_string()),
230            ..Default::default()
231        };
232
233        let result = generate_timestamps(&args);
234        assert!(result.is_ok());
235
236        let timestamps = result.unwrap();
237
238        // Check that timestamps are in ascending order
239        for i in 1..timestamps.len() {
240            assert!(timestamps[i] >= timestamps[i - 1]);
241        }
242    }
243
244    fn create_test_repo_with_n_commits(n: usize) -> (TempDir, String) {
245        let temp_dir = TempDir::new().unwrap();
246        let repo_path = temp_dir.path().to_str().unwrap().to_string();
247        let repo = git2::Repository::init(&repo_path).unwrap();
248
249        for i in 1..=n {
250            let file_path = temp_dir.path().join(format!("file{i}.txt"));
251            fs::write(&file_path, format!("content {i}")).unwrap();
252
253            let mut index = repo.index().unwrap();
254            index
255                .add_path(std::path::Path::new(&format!("file{i}.txt")))
256                .unwrap();
257            index.write().unwrap();
258
259            let tree_id = index.write_tree().unwrap();
260            let tree = repo.find_tree(tree_id).unwrap();
261
262            let sig = git2::Signature::new(
263                "Test User",
264                "test@example.com",
265                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
266            )
267            .unwrap();
268
269            let parents = if i == 1 {
270                vec![]
271            } else {
272                let head = repo.head().unwrap();
273                let parent_commit = head.peel_to_commit().unwrap();
274                vec![parent_commit]
275            };
276
277            repo.commit(
278                Some("HEAD"),
279                &sig,
280                &sig,
281                &format!("Commit {i}"),
282                &tree,
283                &parents.iter().collect::<Vec<_>>(),
284            )
285            .unwrap();
286        }
287
288        (temp_dir, repo_path)
289    }
290
291    #[test]
292    fn test_small_range_error_mentions_skip_flag() {
293        let (_temp_dir, repo_path) = create_test_repo_with_n_commits(5);
294        let args = Args {
295            repo_path: Some(repo_path),
296            email: Some("test@example.com".to_string()),
297            name: Some("Test User".to_string()),
298            start: Some("2023-01-01 00:00:00".to_string()),
299            end: Some("2023-01-01 01:00:00".to_string()), // 1 hour for 5 commits
300            ..Default::default()
301        };
302
303        let result = generate_timestamps(&args);
304        assert!(result.is_err());
305        let err_msg = result.unwrap_err().to_string();
306        assert!(
307            err_msg.contains("--skip-range-check"),
308            "Error message should mention --skip-range-check flag, got: {err_msg}"
309        );
310    }
311
312    #[test]
313    fn test_skip_range_check_produces_correct_count() {
314        let (_temp_dir, repo_path) = create_test_repo_with_n_commits(5);
315        let args = Args {
316            repo_path: Some(repo_path),
317            email: Some("test@example.com".to_string()),
318            name: Some("Test User".to_string()),
319            start: Some("2023-01-01 00:00:00".to_string()),
320            end: Some("2023-01-01 01:00:00".to_string()), // 1 hour for 5 commits
321            skip_range_check: true,
322            ..Default::default()
323        };
324
325        let result = generate_timestamps(&args);
326        assert!(
327            result.is_ok(),
328            "skip_range_check should succeed: {:?}",
329            result.err()
330        );
331
332        let timestamps = result.unwrap();
333        assert_eq!(timestamps.len(), 5);
334    }
335
336    #[test]
337    fn test_skip_range_check_respects_5min_gap_and_bounds() {
338        let (_temp_dir, repo_path) = create_test_repo_with_n_commits(3);
339        let args = Args {
340            repo_path: Some(repo_path),
341            email: Some("test@example.com".to_string()),
342            name: Some("Test User".to_string()),
343            start: Some("2023-01-01 00:00:00".to_string()),
344            end: Some("2023-01-01 02:00:00".to_string()), // 2 hours for 3 commits (enough for 5-min gaps)
345            skip_range_check: true,
346            ..Default::default()
347        };
348
349        let result = generate_timestamps(&args);
350        assert!(result.is_ok());
351
352        let timestamps = result.unwrap();
353        let start_dt =
354            NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
355        let end_dt =
356            NaiveDateTime::parse_from_str("2023-01-01 02:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
357
358        // All timestamps should be within bounds
359        for ts in &timestamps {
360            assert!(*ts >= start_dt, "Timestamp {ts} is before start");
361            assert!(*ts <= end_dt, "Timestamp {ts} is after end");
362        }
363
364        // Each consecutive gap should be >= 5 minutes
365        for i in 1..timestamps.len() {
366            let gap = timestamps[i] - timestamps[i - 1];
367            assert!(
368                gap >= Duration::minutes(5),
369                "Gap between timestamps[{i}] and [{prev}] is {gap_min} mins, expected >= 5",
370                prev = i - 1,
371                gap_min = gap.num_minutes()
372            );
373        }
374
375        // Timestamps should be in ascending order
376        for i in 1..timestamps.len() {
377            assert!(timestamps[i] >= timestamps[i - 1]);
378        }
379    }
380
381    #[test]
382    fn test_skip_range_check_single_commit() {
383        let (_temp_dir, repo_path) = create_test_repo(); // single commit
384        let args = Args {
385            repo_path: Some(repo_path),
386            email: Some("test@example.com".to_string()),
387            name: Some("Test User".to_string()),
388            start: Some("2023-01-01 00:00:00".to_string()),
389            end: Some("2023-01-01 00:01:00".to_string()), // 1 minute
390            skip_range_check: true,
391            ..Default::default()
392        };
393
394        let result = generate_timestamps(&args);
395        assert!(result.is_ok());
396
397        let timestamps = result.unwrap();
398        assert_eq!(timestamps.len(), 1);
399    }
400
401    fn dt(s: &str) -> NaiveDateTime {
402        NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").unwrap()
403    }
404
405    fn assert_strictly_increasing_within(
406        ts: &[NaiveDateTime],
407        start: NaiveDateTime,
408        end: NaiveDateTime,
409    ) {
410        assert_eq!(ts.first(), Some(&start));
411        assert_eq!(ts.last(), Some(&end));
412        assert!(ts.windows(2).all(|w| w[0] < w[1]), "{ts:?}");
413    }
414
415    #[test]
416    fn test_spread_hits_both_bounds_with_3h_gaps() {
417        let (start, end) = (dt("2024-01-01 00:00:00"), dt("2024-01-03 00:00:00"));
418        for _ in 0..50 {
419            let ts = spread_timestamps(start, end, 7, false).unwrap();
420            assert_strictly_increasing_within(&ts, start, end);
421            assert!(ts
422                .windows(2)
423                .all(|w| (w[1] - w[0]).num_seconds() >= 3 * 3600));
424        }
425    }
426
427    #[test]
428    fn test_spread_tiny_range_never_duplicates() {
429        let (start, end) = (dt("2024-01-01 00:00:00"), dt("2024-01-01 00:00:04"));
430        let ts = spread_timestamps(start, end, 5, true).unwrap();
431        assert_strictly_increasing_within(&ts, start, end);
432        assert!(spread_timestamps(start, end, 6, true).is_err());
433    }
434
435    #[test]
436    fn test_random_split_sums_exactly() {
437        let parts = random_split(1001, &[0.3, 0.3, 0.4]);
438        assert_eq!(parts.iter().sum::<i64>(), 1001);
439        assert_eq!(even_split(10, 3), vec![4, 3, 3]);
440    }
441}