rehangit / GHA workflow_dispatch

// ==UserScript==
// @name         GHA workflow_dispatch
// @namespace    https://gist.github.com/rehangit/58409fc3cca4ec7630487ac13a055b27
// @version      0.1.1
// @description  Add missing info in workflow_dispatch actions
// @author       Rehan Ahmad
// @match        https://github.com/*/*/actions
// @grant        none
// @license      MIT
// ==/UserScript==

// ==OpenUserJs==
// @author       rehangit
// ==/OpenUserJs==

// Use with extension: Tampermonkey

let GITHUB_TOKEN = localStorage.getItem('GITHUB_TOKEN');
if (!GITHUB_TOKEN) {
  GITHUB_TOKEN = prompt(
    "Please enter your github token with 'repo' access",
    'Github Token'
  );
  localStorage.setItem('GITHUB_TOKEN', GITHUB_TOKEN);
}

const headers = { headers: { Authorization: `token ${GITHUB_TOKEN}` } };

const ghCacheStored = localStorage.getItem('GITHUB_API_CACHE');
const ghCache = (ghCacheStored && JSON.parse(ghCacheStored)) || {};
const getGH = async url => {
  if (!ghCache[url]) {
    ghCache[url] = await fetch(url, headers).then(res => res.json());
    localStorage.setItem('GITHUB_API_CACHE', JSON.stringify(ghCache));
  }
  return ghCache[url];
};

const render = event => {
  console.log('render fired', event);
  setTimeout(() => {
    document
      .querySelectorAll('.Box-row.js-socket-channel.js-updatable-content')
      .forEach(async node => {
        const middle = node.querySelector('.d-table-cell + .d-none');
        if (middle.innerText.trim() === '') {
          const link = node.querySelector('.Link--primary');
          const url = link.href.replace(
            '//github.com',
            '//api.github.com/repos'
          );
          const res = await getGH(url, headers);

          const branch = res.head_branch;
          const href = [res.repository.html_url, 'tree', branch].join('/');

          const sha = res.head_sha.slice(0, 7);
          const href_sha = [
            res.repository.html_url,
            'commit',
            res.head_sha,
          ].join('/');

          middle.innerHTML = `
            <div class="d-inline-block branch-name css-truncate css-truncate-target" style="max-width: 200px;">
              <a href="${href}" target="_blank">${branch}</a>
            </div> 
            <div style="padding: 2px 6px">
              <a class="d-block text-small color-fg-muted" href="${href_sha}" target="_blank">#${sha}</a>
            </div>
          `;
        }
      });
  }, 2000);
};

(() => {
  render();
  document.addEventListener('load', render);
  document.addEventListener('visibilitychange', render);
  document.addEventListener('readystatechange', render);
  window.addEventListener('hashchange', render);

  let lastUrl = location.href;
  new MutationObserver(() => {
    const url = location.href;
    if (url !== lastUrl) {
      lastUrl = url;
      render('mutation-observer');
    }
  }).observe(document, { subtree: true, childList: true });
})();