summaryrefslogtreecommitdiff
path: root/page_action.js
blob: 8efa274de7e8d4dff71a3dbb2f15948b1741f53c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function onResponse(response) {
  console.log(`Received ${response}`);
}

function onError(error) {
  console.log(`Error: ${error}`);
}

async function handleClick(tab) {
  const gldata = await parsetab(tab.id);
  browser.runtime.sendNativeMessage("ping_pong", gldata)
    .then(onResponse, onError);
}

async function parsetab(tabId) {
  const tab = browser.tabs.get(tabId);
  var data = {
    host: null,
    repo: null,
    file: null,
    branch: null
  };

  // try to find the Clone button to determine if we're in a root repo
  // <span class="js-clone-dropdown-label">Clone</span>
  const hasClone = await tab.then(async function(tab) {
    const txt = await browser.tabs.executeScript(tab.id, {
      code: 'document.querySelector(".js-clone-dropdown-label").innerText'
    }).then(function(result) {
      if (!result) { throw new Error("No result"); }
      return result[0];
    }).catch(function() {
      return '';
    });

    if (txt && txt === 'Clone ') {
      return true;
    }
    return false;
  });

  // try to find the Blame button to determine if we're in a file inside a repo
  const hasBlame = await tab.then(async function(tab) {
    const txt = await browser.tabs.executeScript(tab.id, {
      code: 'document.querySelector(".js-blob-blame-link").innerText'
    }).then(function(result) {
      if (!result) { throw new Error("No result"); }
      return result[0];
    }).catch(function() {
      return '';
    });

    if (txt && txt === 'Blame') {
      return true;
    }
    return false;
  });

  // if we're not in a repo, or file within a repo, bail out
  if (!hasClone && !hasBlame) {
    return data;
  }

  const url = await tab.then(function(tab) { return new URL(tab.url); });
  data.host = url.hostname;

  // if we're in a root repo, the repo path should be the original url removing
  // the hostname and leading slash
  if (hasClone && !hasBlame) {
    data.repo = url.pathname.substring(1);
    // if we're in a file, resort to a regex match
  } else if (!hasClone && hasBlame) {
    data.repo = url.pathname.match(/^\/(.*)\/-/)[1];
    data.branch = url.pathname.match(/^\/.*\/-\/blob\/(.*)\//)[1];
    data.file = url.pathname.match(/^^\/.*\/-\/blob\/.*\/(.*)(\?)?/)[1];
    if (!data.repo) { throw new Error("Could not find repo"); }
    else if (!data.branch) { throw new Error("Could not find branch"); }
    else if (!data.file) { throw new Error("Could not find file"); }
  } else {
    throw new Error("Unknown state");
  }

  return data;
}

browser.pageAction.onClicked.addListener(handleClick);