-- GitHub, through the gh CLI, which signs in as it's set up to, so the extension never sees a -- token. "gh" offers Repos, Pull requests and Reviews: "gh toolshed" (or "gh repos toolshed") -- finds the repos you can reach, Enter opening one you've cloned, with the command the Open with -- setting names or in Finder, or cloning it in the background, saying when it's done; "gh prs" -- lists your open pull requests with how their checks and reviews stand, and "gh reviews" those -- you're asked to review; Enter opens one on GitHub. Within 15 seconds, reviews.lua says when -- you're asked to review one, and every minute checks.lua when the checks of yours pass or fail. Its text is in -- locales/. local home = os.getenv("HOME") local cache = toolshed.cache_dir() local repos_file = cache .. "/repos.tsv" -- Listing every repo takes GitHub a few seconds a hundred, so it's done in the background once -- what's known is this old, searches using it meanwhile. local stale_seconds = 6 * 3600 -- Pull requests change by the minute but not by the keystroke: asked again once this old. local prs_seconds = 30 -- Looking through the repo folders for clones is cheap, but not on every keystroke. local clones_seconds = 10 -- Search shows at most this many, as a launcher list shows no more. local most = 40 -- Where repos are usually kept, as lazysecrets looks for them: those that hold repos are the -- folders setting's default. local usual_folders = { "git", "repo", "repos", "projects", "code", "source", "src" } local quoted = toolshed.shell_quote local modified = toolshed.file.modified local read = toolshed.file.read local function reason(err) return (tostring(err):gsub("^.-gh: ", ""):gsub("%s+", " ")) end local function problem(text) return { title = text, icon = "info", actions = {} } end local function copy(text) toolshed.clipboard.copy(text) return toolshed.t("copied", { text = text }) end local function ago(iso) local y, mo, d, h, mi, s = (iso or ""):match("^(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)") if not y then return "" end -- GitHub's times are UTC; os.time reads a table as local time, so the difference is put back. local utc = os.time({ year = y, month = mo, day = d, hour = h, min = mi, sec = s }) local offset = os.time() - os.time(os.date("!*t")) local seconds = math.max(0, os.time() - (utc + offset)) if seconds < 3600 then return toolshed.t("ago.minutes", { count = math.floor(seconds / 60) }) end if seconds < 86400 then return toolshed.t("ago.hours", { count = math.floor(seconds / 3600) }) end return toolshed.t("ago.days", { count = math.floor(seconds / 86400) }) end -- Repo folders --------------------------------------------------------------------------------- -- holds_repos says a folder has a repo one or two levels down, as repos are kept. local function holds_repos(path) local ok, out = pcall(toolshed.exec, { "find", path, "-mindepth", "2", "-maxdepth", "3", "-name", ".git", "-print", "-quit" }) return ok and out:find("%S") ~= nil end -- detected are the usual folders that hold repos, as ~/git, found as the extension loads so the -- setting starts out with them rather than empty. local function detected() local found = {} for _, name in ipairs(usual_folders) do if holds_repos(home .. "/" .. name) then table.insert(found, "~/" .. name) end end return found end -- folders are where repos are kept: those the setting names, or else those found. A clone goes -- into the first. local function folders(settings) local chosen = {} local named = settings.folders or {} if #named == 0 then named = detected() end for _, f in ipairs(named) do table.insert(chosen, (f:gsub("^~", home))) end if #chosen == 0 then chosen = { home .. "/git" } end return chosen end local clones_known, clones_at = nil, 0 -- github_name is the "owner/name" a remote's address points to on GitHub: git@github.com:o/n.git, -- https://github.com/o/n or a host alias of GitHub's in ~/.ssh/config (github.com-work:o/n). local function github_name(url) local rest = url:gsub("^[%w+.-]+://", ""):gsub("^[^@/]*@", "") local host, path = rest:match("^([^/:]+)[:/]+(.+)$") if not host or not host:lower():find("github") then return nil end local owner, name = path:gsub("%.git$", ""):gsub("/$", ""):match("^([^/]+)/([^/]+)$") return owner and (owner .. "/" .. name):lower() end -- origin is the address of a clone's origin remote, read from its .git/config. local function origin(path) local config = read(path .. "/.git/config") if not config then return nil end local section = config:match('%[remote "origin"%]([^%[]*)') return section and section:match("\n%s*url%s*=%s*(%S+)") end -- clones are the repos in the folders, one or two levels down, by the GitHub repo their origin -- remote points to: a folder named like a repo but cloned from elsewhere isn't its clone. local function clones(settings) if clones_known and os.time() - clones_at < clones_seconds then return clones_known end local found = {} for _, root in ipairs(folders(settings)) do local ok, out = pcall(toolshed.exec, { "find", root, "-mindepth", "2", "-maxdepth", "3", "-name", ".git" }) if ok then for git in out:gmatch("[^\n]+") do local path = git:gsub("/%.git$", "") local name = github_name(origin(path) or "") if name and not found[name] then found[name] = path end end end end clones_known, clones_at = found, os.time() return found end local function clone_of(settings, full_name) return clones(settings)[full_name:lower()] end -- Repos ---------------------------------------------------------------------------------------- local function index_in_background() local jq = '.[] | [.full_name, (.description // "" | gsub("\\\\s+"; " ")), .language // "", .private, .fork, .archived, .pushed_at] | @tsv' toolshed.activities.set { key = "index", title = toolshed.t("jobs.index.title"), description = toolshed.t("jobs.index.description"), quiet = true, timeout = 300, run = { "sh", "-c", "gh api " .. quoted("user/repos?per_page=100&affiliation=owner,collaborator,organization_member") .. " --paginate --jq " .. quoted(jq) .. " > " .. quoted(repos_file .. ".tmp") .. " && mv " .. quoted(repos_file .. ".tmp") .. " " .. quoted(repos_file) } } end local repos_known = { at = nil, list = {} } -- repos are those you can reach, or nil and what to say instead: that they're being listed, or -- why that failed. local function repos() local at = modified(repos_file) if not at then local last = toolshed.activities.get("index") if last and (last.state == "failed" or last.state == "timed-out") then return nil, toolshed.t("error.repos", { reason = reason(last.reason) }) end index_in_background() return nil, toolshed.t("listing") end if os.time() - at > stale_seconds then index_in_background() end if repos_known.at == at then return repos_known.list end local list = {} for line in (read(repos_file) or ""):gmatch("[^\n]+") do local name, description, language, private, fork, archived, pushed = line:match("^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t?(.*)$") if name then table.insert(list, { name = name, description = description, language = language, private = private == "true", fork = fork == "true", archived = archived == "true", pushed = pushed }) end end repos_known = { at = at, list = list } return list end local function repo_jig(settings, r) local path = clone_of(settings, r.name) local tags = {} if path then table.insert(tags, { text = toolshed.t("tag.cloned"), tint = "green", icon = "circle-check" }) end if r.private then table.insert(tags, { text = toolshed.t("tag.private"), icon = "lock" }) end if r.fork then table.insert(tags, { text = toolshed.t("tag.fork"), icon = "git-branch" }) end if r.archived then table.insert(tags, { text = toolshed.t("tag.archived"), tint = "orange" }) end local about = {} if r.description ~= "" then table.insert(about, r.description) end if r.language ~= "" then table.insert(about, r.language) end -- Enter opens what's cloned and clones what isn't. local actions = path and { "open", "web", "copy-ssh", "copy-https", "finder", "copy-path" } or { "clone", "web", "copy-ssh", "copy-https" } if not path and #folders(settings) > 1 then table.insert(actions, 2, "clone-into") end return { key = r.name, title = r.name:match("([^/]+)$"), subtitle = (r.name:match("^([^/]+)") .. " · " .. table.concat(about, " · ")):gsub(" · $", ""), tags = tags, tool = "repo", action = actions[1], actions = actions, data = { name = r.name, path = path }, } end local function repo_rows(settings, typed) local list, why = repos() if not list then return { problem(why) } end local matched = {} for _, r in ipairs(list) do local score = typed == "" and 0.5 or toolshed.match(typed, r.name) if score > 0 then -- What's cloned is what you work on, so it's first among equals; what's archived, last. if clone_of(settings, r.name) then score = score + 0.05 end if r.archived then score = score - 0.1 end table.insert(matched, { score = score, r = r }) end end table.sort(matched, function(a, b) if a.score ~= b.score then return a.score > b.score end return (a.r.pushed or "") > (b.r.pushed or "") end) local jigs = {} for i = 1, math.min(#matched, most) do table.insert(jigs, repo_jig(settings, matched[i].r)) end return jigs end -- with fills a command from the settings in for a repo's folder: "code {path}". local function with(command, path) return (command:gsub("{path}", function() return quoted(path) end)) end -- target_of is where a repo is cloned: by its name in the folder, or under its owner there when -- that name is taken, by another repo of the name cloned from elsewhere. local function target_of(settings, name, into) local folder = into or folders(settings)[1] local target = folder .. "/" .. name:match("([^/]+)$") if modified(target) then target = folder .. "/" .. name end return target end local function shown(path) return (path:gsub("^" .. home:gsub("%p", "%%%0"), "~")) end -- clone clones a repo in the background, shown while it runs and saying when it's done or why -- it failed, then runs the After cloning command. GIT_TERMINAL_PROMPT=0 makes git fail rather -- than wait for a password no one can type. local function clone(ctx, into) local name = ctx.data.name local target = target_of(ctx.settings, name, into) local said = { repo = name, path = shown(target) } toolshed.activities.set { key = "clone-" .. name:lower():gsub("[^%w_-]", "-"), tool = "repo", title = toolshed.t("cloning", said), icon = "download", run = { "env", "GIT_TERMINAL_PROMPT=0", "gh", "repo", "clone", name, target, "--", "--progress" }, timeout = 3600, ending = { done = toolshed.t("cloned", said), failed = toolshed.t("error.clone", said) }, after = { action = "cloned", data = { name = name, path = target } }, } return toolshed.t("cloning", said) end -- cloned runs as a clone ends: what's cloned is looked for again, and After cloning runs. local function cloned(ctx) clones_known = nil local after = (ctx.settings.after_clone or ""):gsub("^%s+", ""):gsub("%s+$", "") if ctx.data.activity.state == "done" and after ~= "" then toolshed.exec({ "sh", "-c", with(after, ctx.data.path) .. " >/dev/null 2>&1 &" }) end end -- open_clone opens a cloned repo with the Open with setting's command, or in Finder. local function open_clone(settings, path) local command = (settings.open_with or ""):gsub("^%s+", ""):gsub("%s+$", "") if command == "" then toolshed.open(path) else toolshed.exec({ "sh", "-c", with(command, path) }) end end -- Pull requests -------------------------------------------------------------------------------- local pr_query = [[ query($q: String!) { search(query: $q, type: ISSUE, first: 50) { nodes { ... on PullRequest { number title url isDraft updatedAt mergeable reviewDecision author { login } repository { nameWithOwner } commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } } } } }]] local searches = { prs = "is:open is:pr author:@me archived:false sort:updated-desc", reviews = "is:open is:pr review-requested:@me archived:false sort:updated-desc", } local prs_known = {} local function pull_requests(which) local known = prs_known[which] if known and os.time() - known.at < prs_seconds then return known.list end local out = toolshed.json.decode(toolshed.exec({ "gh", "api", "graphql", "-F", "q=" .. searches[which], "-f", "query=" .. pr_query })) local list = {} for _, pr in ipairs(((out.data or {}).search or {}).nodes or {}) do if pr.number then table.insert(list, pr) end end prs_known[which] = { at = os.time(), list = list } return list end -- checks says how a pull request's checks went, as a word and a tint. local function checks(pr) local commit = (((pr.commits or {}).nodes or {})[1] or {}).commit or {} local state = (commit.statusCheckRollup or {}).state if state == "SUCCESS" then return "passing", "green" end if state == "FAILURE" or state == "ERROR" then return "failing", "red" end if state == "PENDING" or state == "EXPECTED" then return "running", "orange" end return nil end local review_tints = { APPROVED = "green", CHANGES_REQUESTED = "red", REVIEW_REQUIRED = "gray" } local function pr_tags(pr) local tags = {} local how, tint = checks(pr) if how then table.insert(tags, { text = toolshed.t("checks." .. how), tint = tint }) end if review_tints[pr.reviewDecision] then table.insert(tags, { text = toolshed.t("review." .. pr.reviewDecision), tint = review_tints[pr.reviewDecision] }) end if pr.isDraft then table.insert(tags, { text = toolshed.t("tag.draft") }) end if pr.mergeable == "CONFLICTING" then table.insert(tags, { text = toolshed.t("tag.conflicts"), tint = "red" }) end return tags end -- pr_jig is a pull request as a row, which opens on GitHub: its tags say how it stands. local function pr_jig(pr, by) local about = { pr.repository.nameWithOwner .. "#" .. math.floor(pr.number), ago(pr.updatedAt) } if by and pr.author then table.insert(about, 2, pr.author.login) end return { key = pr.url, title = pr.title, subtitle = table.concat(about, " · "), icon = "git-pull-request", tags = pr_tags(pr), tool = "pr", action = "web", actions = { "web", "copy-url", "checkout" }, data = { repo = pr.repository.nameWithOwner, number = tostring(math.floor(pr.number)), url = pr.url }, } end -- The words that filter pull requests by how they stand. local pr_words = { failing = function(pr) return checks(pr) == "failing" end, passing = function(pr) return checks(pr) == "passing" end, running = function(pr) return checks(pr) == "running" end, draft = function(pr) return pr.isDraft end, approved = function(pr) return pr.reviewDecision == "APPROVED" end, changes = function(pr) return pr.reviewDecision == "CHANGES_REQUESTED" end, conflicts = function(pr) return pr.mergeable == "CONFLICTING" end, } local function pr_rows(which, typed) local ok, list = pcall(pull_requests, which) if not ok then return { problem(toolshed.t("error.prs", { reason = reason(list) })) } end local only, words = {}, {} for word in typed:lower():gmatch("%S+") do if pr_words[word] then table.insert(only, pr_words[word]) else table.insert(words, word) end end local named = table.concat(words, " ") local jigs = {} for _, pr in ipairs(list) do local fits = named == "" or toolshed.match(named, pr.repository.nameWithOwner .. " " .. pr.title) > 0 for _, keep in ipairs(only) do fits = fits and keep(pr) end if fits then table.insert(jigs, pr_jig(pr, which == "reviews")) end end if #jigs == 0 then table.insert(jigs, problem(toolshed.t(#list == 0 and ("none." .. which) or "none.like"))) end return jigs end -- gh ------------------------------------------------------------------------------------------- local verbs = { { name = "repos", icon = "git-branch" }, { name = "prs", icon = "git-pull-request" }, { name = "reviews", icon = "eye" }, } -- The other names the verbs go by, as gh's own commands are named. local aliases = { repo = "repos", pr = "prs", pull = "prs", pulls = "prs", review = "reviews" } local function verb_rows(word) local rows = {} for _, v in ipairs(verbs) do local fits = v.name:sub(1, #word) == word for alias, of in pairs(aliases) do if of == v.name and alias:sub(1, #word) == word then fits = true end end if fits then table.insert(rows, { key = v.name, title = toolshed.t("verb." .. v.name .. ".title"), subtitle = toolshed.t("verb." .. v.name .. ".description"), icon = v.icon, prefix = v.name .. " ", actions = {}, }) end end return rows end -- listed is what's typed after gh: a verb and what to look for, or straight away a repo. A word -- on its own also offers the verbs it could become ("pr" → prs). local function listed(rest, settings) local word, typed = rest:match("^(%S+)%s*(.-)%s*$") if not word then return verb_rows("") end word = word:lower() local verb = aliases[word] or word if verb == "repos" then return repo_rows(settings, typed) end if verb == "prs" or verb == "reviews" then return pr_rows(verb, typed) end local rows = typed == "" and verb_rows(word) or {} for _, row in ipairs(repo_rows(settings, rest:match("^%s*(.-)%s*$"))) do table.insert(rows, row) end return rows end return toolshed.toolbox { key = "github", title = "GitHub", description = "i18n:toolbox.description", icon = "assets/github.svg", tint = "gray", requires = { { command = "gh" } }, settings = { { key = "folders", title = "i18n:setting.folders.title", description = "i18n:setting.folders.description", type = "folders", default = detected(), }, { key = "open_with", title = "i18n:setting.open_with.title", description = "i18n:setting.open_with.description", type = "text", default = "", placeholder = "code {path}", }, { key = "after_clone", title = "i18n:setting.after_clone.title", description = "i18n:setting.after_clone.description", type = "text", default = "", placeholder = "code {path}", }, }, background_jobs = { { file = "reviews.lua", title = "i18n:jobs.reviews.title", description = "i18n:jobs.reviews.description", icon = "bell-ring", every = 15 }, { file = "checks.lua", title = "i18n:jobs.checks.title", description = "i18n:jobs.checks.description", icon = "circle-check", every = 60 }, }, -- Made from the settings, so Clone Into lists the repo folders as they're set. tools = function(settings) local into = {} for _, folder in ipairs(folders(settings)) do table.insert(into, { title = (folder:gsub("^" .. home:gsub("%p", "%%%0"), "~")), value = folder }) end local repo_actions = { { key = "open", title = "i18n:action.open", icon = "folder-open", run = function(ctx) local path = ctx.data.path or clone_of(ctx.settings, ctx.data.name) if not path then error(toolshed.t("error.not-cloned", { repo = ctx.data.name })) end open_clone(ctx.settings, path) end }, { key = "clone", title = "i18n:action.clone", icon = "download", run = function(ctx) return clone(ctx) end }, { key = "cloned", title = "i18n:action.cloned", run = cloned }, { key = "web", title = "i18n:action.web", icon = "external-link", run = function(ctx) toolshed.open("https://github.com/" .. ctx.data.name) end }, { key = "copy-ssh", title = "i18n:action.copy-ssh", icon = "copy", run = function(ctx) return copy("git@github.com:" .. ctx.data.name .. ".git") end }, { key = "copy-https", title = "i18n:action.copy-https", icon = "copy", run = function(ctx) return copy("https://github.com/" .. ctx.data.name .. ".git") end }, { key = "finder", title = "i18n:action.finder", icon = "folder-open", run = function(ctx) toolshed.open(clone_of(ctx.settings, ctx.data.name) or ctx.data.path) end }, { key = "copy-path", title = "i18n:action.copy-path", icon = "copy", run = function(ctx) return copy(ctx.data.path or clone_of(ctx.settings, ctx.data.name)) end }, } -- With one repo folder, Clone puts it there already. if #into > 1 then table.insert(repo_actions, 3, { key = "clone-into", title = "i18n:action.clone-into", icon = "download", variants = into, run = function(ctx) return clone(ctx, ctx.variant) end }) end return { { key = "search", title = "i18n:tool.search.title", description = "i18n:tool.search.description", words = { "gh", "github" }, keywords = { "github", "repo", "clone", "pull request", "review" }, examples = { "gh toolshed", "gh prs", "gh prs failing", "gh reviews" }, items = true, search = function(rest, settings) return listed(rest, settings) end, -- Its rows are the other tools' (a repo, a pull request), which do what they're chosen for. actions = { { key = "none", title = "i18n:tool.search.title", run = function() end } }, }, { key = "repo", title = "i18n:tool.repo.title", hidden = true, items = true, actions = repo_actions, }, { key = "pr", title = "i18n:tool.pr.title", hidden = true, items = true, actions = { { key = "web", title = "i18n:action.web", icon = "external-link", run = function(ctx) toolshed.open(ctx.data.url) end }, { key = "copy-url", title = "i18n:action.copy-url", icon = "copy", run = function(ctx) return copy(ctx.data.url) end }, { key = "checkout", title = "i18n:action.checkout", icon = "git-branch", run = function(ctx) local path = clone_of(ctx.settings, ctx.data.repo) if not path then error(toolshed.t("error.not-cloned", { repo = ctx.data.repo })) end toolshed.exec({ "sh", "-c", "cd " .. quoted(path) .. " && gh pr checkout " .. quoted(ctx.data.number) }) return toolshed.t("checked-out", { number = ctx.data.number, repo = ctx.data.repo }) end }, }, }, } end, }