Phabricator Link Copy

A Greasemonkey script to copy document links and titles on developer.blender.org

Blender developers use Phabricator to track tasks, bug reports, and patches. Often I need to create links to patch reviews, bug reports, etc. I got tired of manually typing those, so I created a little Greasemonkey script.

First download the GreaseMonkey add-on for your browser, then add the script. It should create two buttons in the top bar, “MD” and “WIKI”, for respectively MarkDown and MediaWiki syntax.

This is my 2nd GreaseMonkey script for Phabricator, the first one was to count things in lists.

// ==UserScript==
// @name     Phabricator Document Link
// @version  1
// @include  https://developer.blender.org/*
// @grant    GM.setClipboard
// ==/UserScript==

function add_document_links() {
  let page_name = find_page_name();
  if (page_name === "") return;

  let page_title = find_page_title();
  if (page_title === "") return;

  add_button("MD", "[" + page_name + ": " + page_title + "](" + window.location + ")");

  if (is_git_commit(page_name)) {
    let commit_id = window.location.pathname.substr(1, 14);
    add_button("WIKI (long)", "{{GitCommit|" + commit_id + "}}: " + page_title);
    add_button("WIKI (short)", "{{GitCommit|" + commit_id + "}}");
  } else {
    add_button("WIKI", "{{Phab|" + page_name + "}}: " + page_title);
  }
}

function add_button(button_text, clipboard_text) {
  let button = document.createElement('button');
  button.textContent = button_text;
  button.className = 'button button-grey';
  button.setAttribute("title", clipboard_text);
  button.addEventListener('click', function() {
    console.log('Clipboard:', clipboard_text);
    GM.setClipboard(clipboard_text);
  });

  let button_parent_elt = find_button_parent_element();
  button_parent_elt.appendChild(button);
}

function find_button_parent_element() {
  let elements = document.getElementsByClassName('phabricator-main-menu-alerts');
  if (elements.length == 0) return undefined;
  return elements[0];
}

function find_page_name_element() {
  let page_name_elts = document.getElementsByClassName('phui-crumb-name');
  if (page_name_elts.length == 0) return undefined;
  return page_name_elts[page_name_elts.length-1];
}

function find_page_name() {
  let page_name_elt = find_page_name_element();
  if (!page_name_elt) return "";
  return page_name_elt.textContent.trim();
}

function find_page_title() {
  let page_title_elts = document.getElementsByClassName('phui-header-header');
  if (page_title_elts.length == 0) return "";
  let page_title = page_title_elts[0].textContent;
  return page_title.trim();
}

function is_git_commit(page_name) {
  return page_name.length == 12 && /^[0-9A-Fa-f]{12}$/.test(page_name) && window.location.pathname.startsWith("/r")
}

window.setTimeout(add_document_links, 100);
dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer

Related