Resulting output:
[`octocat/Hello-World #1053`](https://github.com/octocat/Hello-World/issues/1053)
example token contents |
<% tp.user.insertGitHubLink(tp, ['octocat/Hello-World']) %>
const fs = require('fs'); | |
const path = require('path'); | |
// Authored by Jacob Levernier, 2021 | |
// Released under a CC0 1.0 Universal Public Domain Dedication | |
// Fetch multiple URLs asynchronously | |
// For an explanation, see, e.g., the tutorial at | |
// https://www.shawntabrizi.com/code/programmatically-fetch-multiple-apis-parallel-using-async-await-javascript/ | |
async function fetchAll(urls, api_token) { | |
try { | |
const data = await Promise.all( | |
urls.map( | |
url => | |
fetch( | |
url, { | |
method: 'GET', | |
headers: new Headers({ | |
'Authorization': `Bearer ${api_token}`, | |
'Content-Type': 'application/json', | |
'Accept': 'application/vnd.github.v3+json' | |
}) | |
}).then( | |
(response) => response.json() | |
))); | |
return (data) | |
} catch (error) { | |
console.log(error) | |
throw (error) | |
} | |
} | |
async function insertGitHubLink( | |
tp, | |
repos = [], | |
max_n = 750, | |
// GitHub Token file (by default, in a file at ~/.obsidian-github-key). | |
// You can create a token at https://github.com/settings/tokens. It may need | |
// the following scopes to be able to see private issues: | |
// admin:org | |
// read:enterprise | |
// repo | |
api_key_file = path.join(process.env.HOME, '.obsidian-github-key'), | |
) { | |
let api_key = '' | |
try { | |
api_key = fs.readFileSync(api_key_file, 'utf8'); | |
} catch (e) { | |
console.log('Error reading GitHub API key:', e.stack); | |
return | |
} | |
let issuesList = await ( | |
await fetchAll( | |
repos.map(repo => `https://api.github.com/repos/${repo}/issues`), api_key | |
)) | |
.reduce((a, b) => a.concat(b)) | |
.sort((a, b) => a.updated_at - b.updated_at); | |
if (issuesList.length > max_n) { | |
issuesList = issuesList.slice(0, max_n); | |
} | |
// console.log(issuesList); | |
const selection = await tp.system.suggester( | |
issuesList.map(issue => `[${issue.state}] ${issue.repository_url.replace('https://api.github.com/repos/', '')}#${issue.number} "${issue.title || '[Untitled]'}" (Assignee: ${issue.assignee?.login || '[None]'}) (Milestone: ${issue.milestone?.title || '[None]'}) (Labels: ${issue.labels?.map(label => label.name).join(', ') || '[None]'})`), | |
[...Array(issuesList.length).keys()], | |
true, | |
"Select an issue" | |
); | |
return `[\`${issuesList[selection].repository_url.replace('https://api.github.com/repos/', '')} #${issuesList[selection].number}\`](${issuesList[selection].html_url})` | |
} | |
module.exports = insertGitHubLink; |