GitHub Repo Age

Displays repository creation date/time/age.

当前为 2025-05-11 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         GitHub Repo Age
// @description  Displays repository creation date/time/age.
// @icon         https://github.githubassets.com/favicons/favicon-dark.svg
// @version      1.1
// @author       afkarxyz
// @namespace    https://github.com/afkarxyz/userscripts/
// @supportURL   https://github.com/afkarxyz/userscripts/issues
// @license      MIT
// @match        https://github.com/*/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    const apiBase = 'https://api.github.com/repos/';
    const CACHE_KEY_PREFIX = 'github_repo_created_';
    const CACHE_EXPIRY = 7 * 24 * 60 * 60 * 1000;
    
    const selectors = {
        desktop: [
            '.BorderGrid-cell .hide-sm.hide-md .f4.my-3',
            '.BorderGrid-cell'
        ],
        mobile: [
            '.d-block.d-md-none.mb-2.px-3.px-md-4.px-lg-5 .f4.mb-3.color-fg-muted',
            '.d-block.d-md-none.mb-2.px-3.px-md-4.px-lg-5 .d-flex.gap-2.mt-n3.mb-3.flex-wrap',
            '.d-block.d-md-none.mb-2.px-3.px-md-4.px-lg-5'
        ]
    };
    
    let currentRepoPath = '';
    
    function formatDate(isoDateStr) {
        const createdDate = new Date(isoDateStr);
        const now = new Date();
        const diffTime = Math.abs(now - createdDate);
        
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        const diffHours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const diffMinutes = Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60));
        
        const diffMonths = Math.floor(diffDays / 30.44);
        const diffYears = Math.floor(diffMonths / 12);
        const remainingMonths = diffMonths % 12;
        const remainingDays = Math.floor(diffDays % 30.44);
        
        const datePart = createdDate.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
        
        const timePart = createdDate.toLocaleTimeString('en-GB', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        });
        
        let ageText = '';
        
        if (diffYears > 0) {
            ageText = `${diffYears} year${diffYears !== 1 ? 's' : ''}`;
            if (remainingMonths > 0) {
                ageText += ` ${remainingMonths} month${remainingMonths !== 1 ? 's' : ''}`;
            }
        } else if (diffMonths > 0) {
            ageText = `${diffMonths} month${diffMonths !== 1 ? 's' : ''}`;
            if (remainingDays > 0) {
                ageText += ` ${remainingDays} day${remainingDays !== 1 ? 's' : ''}`;
            }
        } else if (diffDays > 0) {
            ageText = `${diffDays} day${diffDays !== 1 ? 's' : ''}`;
            if (diffHours > 0) {
                ageText += ` ${diffHours} hour${diffHours !== 1 ? 's' : ''}`;
            }
        } else if (diffHours > 0) {
            ageText = `${diffHours} hour${diffHours !== 1 ? 's' : ''}`;
            if (diffMinutes > 0) {
                ageText += ` ${diffMinutes} minute${diffMinutes !== 1 ? 's' : ''}`;
            }
        } else {
            ageText = `${diffMinutes} minute${diffMinutes !== 1 ? 's' : ''}`;
        }
        
        return `${datePart} - ${timePart} (${ageText} ago)`;
    }
    
    const cache = {
        getKey: function(user, repo) {
            return `${CACHE_KEY_PREFIX}${user}_${repo}`;
        },
        
        get: function(user, repo) {
            try {
                const key = this.getKey(user, repo);
                const cachedData = localStorage.getItem(key);
                
                if (!cachedData) return null;
                
                const { value, expiry } = JSON.parse(cachedData);
                
                if (expiry && expiry < Date.now()) {
                    console.log('Cache expired, removing item');
                    localStorage.removeItem(key);
                    return null;
                }
                
                console.log('Using cached data for ' + user + '/' + repo);
                return value;
            } catch (err) {
                console.error('Error reading from cache:', err);
                return null;
            }
        },
        
        set: function(user, repo, value) {
            try {
                const key = this.getKey(user, repo);
                const data = {
                    value: value,
                    expiry: Date.now() + CACHE_EXPIRY
                };
                
                localStorage.setItem(key, JSON.stringify(data));
                console.log('Saved to cache: ' + user + '/' + repo);
            } catch (err) {
                console.error('Error writing to cache:', err);
            }
        },
        
        cleanup: function() {
            try {
                const now = Date.now();
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    
                    if (key && key.startsWith(CACHE_KEY_PREFIX)) {
                        try {
                            const data = JSON.parse(localStorage.getItem(key));
                            if (data.expiry && data.expiry < now) {
                                localStorage.removeItem(key);
                                console.log('Cleaned up expired cache item:', key);
                            }
                        } catch (e) {
                            localStorage.removeItem(key);
                        }
                    }
                }
            } catch (err) {
                console.error('Error cleaning cache:', err);
            }
        }
    };
    
    async function getRepoCreationDate(user, repo) {
        const cachedDate = cache.get(user, repo);
        if (cachedDate) {
            return cachedDate;
        }
        
        const apiUrl = `${apiBase}${user}/${repo}`;
        
        try {
            const res = await fetch(apiUrl);
            
            if (res.status === 403) {
                console.warn('GitHub API rate limit exceeded. Try again later.');
                return null;
            }
            
            if (!res.ok) {
                console.error(`API error: ${res.status} - ${res.statusText}`);
                return null;
            }
            
            const data = await res.json();
            const createdAt = data.created_at;
            
            if (createdAt) {
                cache.set(user, repo, createdAt);
                return createdAt;
            }
            
            return null;
        } catch (err) {
            console.error('Failed to fetch repo creation date:', err);
            return null;
        }
    }
    
    async function insertCreatedDate() {
        const match = window.location.pathname.match(/^\/([^\/]+)\/([^\/]+)/);
        if (!match) return false;
        
        const [_, user, repo] = match;
        const repoPath = `${user}/${repo}`;
        
        currentRepoPath = repoPath;
        
        const createdAt = await getRepoCreationDate(user, repo);
        if (!createdAt) return false;
        
        const formattedDate = formatDate(createdAt);
        let insertedCount = 0;
        
        document.querySelectorAll('.repo-created-date').forEach(el => el.remove());
        
        for (const [view, selectorsList] of Object.entries(selectors)) {
            for (const selector of selectorsList) {
                const element = document.querySelector(selector);
                if (element && !element.querySelector(`.repo-created-${view}`)) {
                    insertDateElement(element, formattedDate, view);
                    insertedCount++;
                    console.log(`Added creation date to ${view} view using selector: ${selector}`);
                    break;
                }
            }
        }
        
        return insertedCount > 0;
    }
    
    function insertDateElement(targetElement, formattedDate, view) {
        const p = document.createElement('p');
        p.className = `f6 color-fg-muted repo-created-date repo-created-${view}`;
        p.style.marginTop = '4px';
        p.style.marginBottom = '8px';
        p.innerHTML = `<strong>Created</strong> ${formattedDate}`;
        
        if (view === 'mobile') {
            const flexWrap = targetElement.querySelector('.flex-wrap');
            if (flexWrap) {
                flexWrap.parentNode.insertBefore(p, flexWrap.nextSibling);
                return;
            }
            
            const dFlex = targetElement.querySelector('.d-flex');
            if (dFlex) {
                dFlex.parentNode.insertBefore(p, dFlex.nextSibling);
                return;
            }
        }
        
        targetElement.insertBefore(p, targetElement.firstChild);
    }
    
    function checkAndInsertWithRetry(retryCount = 0, maxRetries = 5) {
        insertCreatedDate().then(inserted => {
            if (!inserted && retryCount < maxRetries) {
                const delay = Math.pow(2, retryCount) * 500;
                console.log(`Retrying in ${delay}ms (attempt ${retryCount + 1}/${maxRetries})`);
                setTimeout(() => checkAndInsertWithRetry(retryCount + 1, maxRetries), delay);
            }
        });
    }
    
    function checkForRepoChange() {
        const match = window.location.pathname.match(/^\/([^\/]+)\/([^\/]+)/);
        if (!match) return;
        
        const [_, user, repo] = match;
        const repoPath = `${user}/${repo}`;
        
        if (repoPath !== currentRepoPath) {
            console.log(`Repository changed: ${currentRepoPath} -> ${repoPath}`);
            checkAndInsertWithRetry();
        }
    }
    
    cache.cleanup();
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => checkAndInsertWithRetry());
    } else {
        checkAndInsertWithRetry();
    }
    
    const originalPushState = history.pushState;
    history.pushState = function() {
        originalPushState.apply(this, arguments);
        setTimeout(checkForRepoChange, 100);
    };
    
    const originalReplaceState = history.replaceState;
    history.replaceState = function() {
        originalReplaceState.apply(this, arguments);
        setTimeout(checkForRepoChange, 100);
    };
    
    window.addEventListener('popstate', () => {
        setTimeout(checkForRepoChange, 100);
    });
    
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.type === 'childList' && 
                (mutation.target.id === 'js-repo-pjax-container' || 
                 mutation.target.id === 'repository-container-header')) {
                setTimeout(checkForRepoChange, 100);
                break;
            }
        }
    });
    
    observer.observe(document.body, { childList: true, subtree: true });
})();