🔍 Code Extractor

function fix_file_dates

Maturity: 43

Normalizes all timestamp attributes (creation, modification, access) of a file to the oldest timestamp among them, with optional dry-run mode for preview.

File:
/tf/active/vicechatdev/mailsearch/fix_file_dates.py
Lines:
94 - 117
Complexity:
moderate

Purpose

This function is used to synchronize file timestamps by setting all date attributes (creation time, modification time, access time) to whichever timestamp is oldest. This is useful for maintaining consistent file metadata, preserving historical dates, or preparing files for archival. The function provides detailed output showing current timestamps and which one is oldest, and supports a dry-run mode to preview changes without applying them.

Source Code

def fix_file_dates(filepath, dry_run=False):
    """Fix all dates for a file by setting them to the oldest date"""
    times = get_file_times(filepath)
    
    # Find the oldest timestamp
    oldest_time = min(times.values())
    oldest_dt = datetime.fromtimestamp(oldest_time)
    
    # Check which timestamp is the oldest
    oldest_type = [k for k, v in times.items() if v == oldest_time][0]
    
    print(f"\n{filepath}")
    print(f"  Current times:")
    for time_type, timestamp in times.items():
        dt = datetime.fromtimestamp(timestamp)
        marker = " ← oldest" if timestamp == oldest_time else ""
        print(f"    {time_type:10}: {dt.strftime('%Y-%m-%d %H:%M:%S')}{marker}")
    
    if dry_run:
        print(f"  → Would set all dates to: {oldest_dt.strftime('%Y-%m-%d %H:%M:%S')}")
        return True
    else:
        print(f"  → Setting all dates to: {oldest_dt.strftime('%Y-%m-%d %H:%M:%S')}")
        return set_file_dates(filepath, oldest_time)

Parameters

Name Type Default Kind
filepath - - positional_or_keyword
dry_run - False positional_or_keyword

Parameter Details

filepath: String or Path object representing the path to the file whose timestamps should be normalized. Must be a valid path to an existing file with readable timestamp metadata.

dry_run: Boolean flag (default: False). When True, the function only displays what changes would be made without actually modifying the file. When False, the function applies the timestamp changes to the file.

Return Value

Returns a boolean value. In dry-run mode, always returns True to indicate successful preview. In normal mode, returns the result of set_file_dates() function, which likely returns True on successful timestamp modification or False on failure.

Dependencies

  • datetime
  • pathlib

Required Imports

from datetime import datetime
from pathlib import Path

Usage Example

from datetime import datetime
from pathlib import Path

# Preview changes without applying them
result = fix_file_dates('/path/to/file.txt', dry_run=True)
print(f"Dry run completed: {result}")

# Actually apply the timestamp changes
result = fix_file_dates('/path/to/file.txt', dry_run=False)
if result:
    print("File timestamps successfully normalized")
else:
    print("Failed to update file timestamps")

# Can also use Path objects
file_path = Path('/path/to/document.pdf')
fix_file_dates(file_path)

Best Practices

  • Always run with dry_run=True first to preview changes before applying them to important files
  • Ensure you have appropriate file system permissions before attempting to modify file timestamps
  • Be aware that this function depends on get_file_times() and set_file_dates() helper functions which must be available in scope
  • The function prints output to stdout, so consider redirecting or capturing output if using in automated scripts
  • Modifying file timestamps may affect backup systems, version control, or other tools that rely on file metadata
  • On some operating systems or file systems, certain timestamp types may not be modifiable or may have platform-specific behavior

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function set_file_dates 68.8% similar

    Sets all file timestamps (creation time, modification time, access time, and change time) to a specified Unix timestamp by directly modifying the file's inode using debugfs.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
  • function main_v112 66.2% similar

    Entry point function that parses command-line arguments to fix file timestamps by setting them to the oldest date found, either for a single file or recursively through a directory.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
  • function copy_file_with_date 60.7% similar

    Copies a file from source to destination and sets the file's modification and access times to match a provided datetime object.

    From: /tf/active/vicechatdev/mailsearch/copy_signed_documents.py
  • function get_file_times 57.1% similar

    Retrieves all available timestamps for a file, including modification time, access time, change time, and birth time (creation time) when available.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
  • function process_directory 51.4% similar

    Processes all files matching a specified pattern in a directory, applying date fixes to each file and providing a summary of results.

    From: /tf/active/vicechatdev/mailsearch/fix_file_dates.py
← Back to Browse