GitHub Repo Age

Displays repository creation date/time/age.

Από την 11/05/2025. Δείτε την τελευταία έκδοση.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey, το Greasemonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

You will need to install an extension such as Tampermonkey to install this script.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Userscripts για να εγκαταστήσετε αυτόν τον κώδικα.

You will need to install an extension such as Tampermonkey to install this script.

Θα χρειαστεί να εγκαταστήσετε μια επέκταση διαχείρισης κώδικα χρήστη για να εγκαταστήσετε αυτόν τον κώδικα.

(Έχω ήδη έναν διαχειριστή κώδικα χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

Advertisement:

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Έχω ήδη έναν διαχειριστή στυλ χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

Advertisement:

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

(function () {
    'use strict';

    const API_BASE_PROXY = 'https://api.codetabs.com/v1/proxy/?quest=https://api.github.com/repos/';
    const API_BASE_DIRECT = 'https://api.github.com/repos/';
    const CACHE_KEY_PREFIX = 'github_repo_created_';

    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: (user, repo) => `${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 } = JSON.parse(cachedData);
                return value;
            } catch (err) { return null; }
        },
        set: function(user, repo, value) {
            try {
                const key = this.getKey(user, repo);
                const data = { value: value };
                localStorage.setItem(key, JSON.stringify(data));
            } catch (err) { /* silently fail */ }
        }
    };

    async function getRepoCreationDate(user, repo) {
        const cachedDate = cache.get(user, repo);
        if (cachedDate) {
            return cachedDate;
        }

        function makeApiRequest(apiUrl, apiName) {
            return new Promise((resolve) => {
                GM_xmlhttpRequest({
                    method: 'GET', url: apiUrl,
                    onload: function(response) {
                        if (response.status === 403) {
                            resolve({ success: false, status: 403, rateLimited: true, apiName: apiName }); return;
                        }
                        if (response.status >= 200 && response.status < 300) {
                            try {
                                const data = JSON.parse(response.responseText);
                                const createdAt = data.created_at;
                                if (createdAt) {
                                    resolve({ success: true, data: createdAt, status: response.status, apiName: apiName });
                                } else {
                                    resolve({ success: false, status: response.status, error: 'missing_data', apiName: apiName });
                                }
                            } catch (e) {
                                resolve({ success: false, status: response.status, error: 'parse_error', apiName: apiName });
                            }
                        } else {
                            resolve({ success: false, status: response.status, error: 'http_error', apiName: apiName });
                        }
                    },
                    onerror: () => resolve({ success: false, status: 0, error: 'network_error', apiName: apiName }),
                    ontimeout: () => resolve({ success: false, status: 0, error: 'timeout_error', apiName: apiName })
                });
            });
        }

        let result = await makeApiRequest(`${API_BASE_DIRECT}${user}/${repo}`, 'Direct GitHub API');

        if (result.success) {
            cache.set(user, repo, result.data);
            return result.data;
        }

        if (result.status === 403 && result.rateLimited) {
            result = await makeApiRequest(`${API_BASE_PROXY}${user}/${repo}`, 'Proxy API');

            if (result.success) {
                cache.set(user, repo, result.data);
                return result.data;
            } else {
                return null;
            }
        }
        return null;
    }

    async function insertCreatedDate() {
        const match = window.location.pathname.match(/^\/([^\/]+)\/([^\/]+)/);
        if (!match || match[0].includes('/assets/') || match[0].includes('/blob/') || match[0].includes('/tree/')) {
            if (match) currentRepoPath = '';
            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++;
                    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) {
                 flexWrap.parentNode.insertBefore(p, flexWrap.nextSibling); return;
            }
            const dFlex = targetElement.querySelector('.d-flex.gap-2');
             if (dFlex && dFlex.parentNode) {
                dFlex.parentNode.insertBefore(p, dFlex.nextSibling); return;
            }
        }
        targetElement.insertBefore(p, targetElement.firstChild);
    }

    function checkAndInsertWithRetry(retryCount = 0, maxRetries = 3) {
        insertCreatedDate().then(inserted => {
            if (!inserted && retryCount < maxRetries) {
                const delay = Math.pow(2, retryCount) * 300;
                setTimeout(() => checkAndInsertWithRetry(retryCount + 1, maxRetries), delay);
            }
        });
    }

    function checkForRepoChange() {
        const match = window.location.pathname.match(/^\/([^\/]+)\/([^\/]+)/);
        let newRepoPath = '';
        if (match && !match[0].includes('/assets/') && !match[0].includes('/blob/') && !match[0].includes('/tree/')) {
            newRepoPath = `${match[1]}/${match[2]}`;
        }

        if (newRepoPath && newRepoPath !== currentRepoPath) {
            currentRepoPath = newRepoPath;
            checkAndInsertWithRetry();
        } else if (!newRepoPath && currentRepoPath) {
            document.querySelectorAll('.repo-created-date').forEach(el => el.remove());
            currentRepoPath = '';
        }
    }

    function init() {
        checkAndInsertWithRetry();
        observeDOM();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    const originalPushState = history.pushState;
    history.pushState = function() {
        originalPushState.apply(this, arguments);
        setTimeout(checkForRepoChange, 150);
    };
    const originalReplaceState = history.replaceState;
    history.replaceState = function() {
        originalReplaceState.apply(this, arguments);
        setTimeout(checkForRepoChange, 150);
    };
    window.addEventListener('popstate', () => setTimeout(checkForRepoChange, 150));

    function observeDOM() {
        const observer = new MutationObserver(() => {
            setTimeout(checkForRepoChange, 200);
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }
})();