From 21ce48d6f085f3500e46057ef0bf958706561738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl-Einar=20Bergstr=C3=B8m?= Date: Thu, 26 Nov 2026 11:05:42 +0100 Subject: [PATCH] =?UTF-8?q?The=20extensions=20that=20were=20in=20Toolshed'?= =?UTF-8?q?s=20own=20repository,=20a=20folder=20each:=20brreg,=20dashboard?= =?UTF-8?q?-icons,=20databricks,=20docker,=20github,=20homebrew,=20norway,?= =?UTF-8?q?=20projects,=20scripts,=20secrets,=20wikipedia=20and=20yr.=20To?= =?UTF-8?q?olshed=20installs=20them=20from=20here,=20in=20Settings=20?= =?UTF-8?q?=E2=86=92=20Extensions=20=E2=86=92=20From=20a=20repository,=20a?= =?UTF-8?q?nd=20the=20README=20says=20how?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 33 +- brreg/init.lua | 293 ++++++++++++ brreg/locales/en.toml | 140 ++++++ brreg/locales/nb.toml | 140 ++++++ dashboard-icons/init.lua | 145 ++++++ dashboard-icons/locales/en.toml | 44 ++ dashboard-icons/locales/nb.toml | 44 ++ databricks/assets/databricks.svg | 1 + databricks/index.sh | 41 ++ databricks/init.lua | 629 +++++++++++++++++++++++++ databricks/locales/en.toml | 209 +++++++++ databricks/locales/nb.toml | 209 +++++++++ docker/init.lua | 782 +++++++++++++++++++++++++++++++ docker/locales/en.toml | 311 ++++++++++++ docker/locales/nb.toml | 311 ++++++++++++ github/assets/github.svg | 1 + github/checks.lua | 45 ++ github/init.lua | 495 +++++++++++++++++++ github/locales/en.toml | 194 ++++++++ github/locales/nb.toml | 194 ++++++++ github/reviews.lua | 34 ++ homebrew/init.lua | 674 ++++++++++++++++++++++++++ homebrew/locales/en.toml | 299 ++++++++++++ homebrew/locales/nb.toml | 299 ++++++++++++ norway/assets/flag.svg | 1 + norway/init.lua | 304 ++++++++++++ norway/locales/en.toml | 137 ++++++ norway/locales/nb.toml | 137 ++++++ norway/name_days.lua | 368 +++++++++++++++ projects/init.lua | 178 +++++++ projects/locales/en.toml | 47 ++ projects/locales/nb.toml | 47 ++ scripts/init.lua | 41 ++ scripts/locales/en.toml | 20 + scripts/locales/nb.toml | 20 + secrets/init.lua | 93 ++++ secrets/locales/en.toml | 23 + secrets/locales/nb.toml | 23 + wikipedia/init.lua | 133 ++++++ wikipedia/locales/en.toml | 32 ++ wikipedia/locales/nb.toml | 32 ++ yr/init.lua | 250 ++++++++++ yr/locales/en.toml | 263 +++++++++++ yr/locales/nb.toml | 263 +++++++++++ 44 files changed, 7978 insertions(+), 1 deletion(-) create mode 100644 brreg/init.lua create mode 100644 brreg/locales/en.toml create mode 100644 brreg/locales/nb.toml create mode 100644 dashboard-icons/init.lua create mode 100644 dashboard-icons/locales/en.toml create mode 100644 dashboard-icons/locales/nb.toml create mode 100644 databricks/assets/databricks.svg create mode 100644 databricks/index.sh create mode 100644 databricks/init.lua create mode 100644 databricks/locales/en.toml create mode 100644 databricks/locales/nb.toml create mode 100644 docker/init.lua create mode 100644 docker/locales/en.toml create mode 100644 docker/locales/nb.toml create mode 100644 github/assets/github.svg create mode 100644 github/checks.lua create mode 100644 github/init.lua create mode 100644 github/locales/en.toml create mode 100644 github/locales/nb.toml create mode 100644 github/reviews.lua create mode 100644 homebrew/init.lua create mode 100644 homebrew/locales/en.toml create mode 100644 homebrew/locales/nb.toml create mode 100644 norway/assets/flag.svg create mode 100644 norway/init.lua create mode 100644 norway/locales/en.toml create mode 100644 norway/locales/nb.toml create mode 100644 norway/name_days.lua create mode 100644 projects/init.lua create mode 100644 projects/locales/en.toml create mode 100644 projects/locales/nb.toml create mode 100644 scripts/init.lua create mode 100644 scripts/locales/en.toml create mode 100644 scripts/locales/nb.toml create mode 100644 secrets/init.lua create mode 100644 secrets/locales/en.toml create mode 100644 secrets/locales/nb.toml create mode 100644 wikipedia/init.lua create mode 100644 wikipedia/locales/en.toml create mode 100644 wikipedia/locales/nb.toml create mode 100644 yr/init.lua create mode 100644 yr/locales/en.toml create mode 100644 yr/locales/nb.toml diff --git a/README.md b/README.md index bd0cc32..40d3755 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,34 @@ # toolshed-extensions -Extensions for toolshed \ No newline at end of file +Extensions for [Toolshed](https://git.kebcloud.no/keb/toolshed): each folder is one, a toolbox written in Lua that starts from its `init.lua`. + +## Installing + +In Toolshed, open Settings → Extensions → From a repository, add this repository's address and install the ones you want: + +``` +https://git.kebcloud.no/keb/toolshed-extensions +``` + +Toolshed asks for updates once a day and installs one only when you accept it, after showing what it changes. Extensions run with your permissions, so read one before you install it. + +## The extensions + +| Folder | What it does | +| --- | --- | +| `brreg` | Finds Norwegian companies by name or organisation number: `brreg equinor` | +| `dashboard-icons` | Finds icons for self-hosted apps on dashboardicons.com: `di plex` | +| `databricks` | Searches Unity Catalog and shows job runs and jobs through the Databricks CLI: `dbx sales` | +| `docker` | Handles containers and compose projects, with logs, live stats and pruning: `docker web` | +| `github` | Finds your repos to open or clone and shows your pull requests and reviews through the gh CLI: `gh prs` | +| `homebrew` | Installs, upgrades and removes Homebrew packages: `brew install jq` | +| `norway` | Norway's public holidays, flag days and name days, offline: `helligdager 2027` | +| `projects` | Opens repos with the `dev` command: `p toolshed` | +| `scripts` | A place for your own small commands, each a tool with a hotkey | +| `secrets` | Searches lazysecrets: `s db-password` | +| `wikipedia` | Finds articles and shows their summaries: `wiki rust` | +| `yr` | The weather from yr.no: `yr bergen` | + +## Writing one + +An extension is a folder with an `init.lua` that returns `toolshed.toolbox { … }`; Toolshed's `docs/extensions.md` describes all of it. Open `init.lua` with a comment that says what the extension does: Toolshed shows it where the extension is offered. diff --git a/brreg/init.lua b/brreg/init.lua new file mode 100644 index 0000000..63bf67c --- /dev/null +++ b/brreg/init.lua @@ -0,0 +1,293 @@ +-- Brønnøysundregistrene: "brreg equinor" finds companies by name, "brreg 923 609 016" by +-- organisation number, sub-units (avdelinger) too, and "brreg" alone a number selected in the app +-- Toolshed was opened from; a number selected or copied is offered under Suggested. Enter shows +-- what the Central Coordinating Register knows, with the unit it's part of and a company's +-- sub-units under it, each shown in turn; ⌘K opens it on brreg.no or copies its number, name or +-- address. Its text is in locales/; what the register says (forms, industries) is in Norwegian, +-- as it gives it. + +local api = "https://data.brreg.no/enhetsregisteret/api/" + +local encode = toolshed.url_encode + +local escape = toolshed.escape + +local function get(path, max_seconds) + return toolshed.json.decode(toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), api .. path })) +end + +-- 923609016 reads as 923 609 016, as brreg.no writes it. +local function spaced(number) + return (number:gsub("^(%d%d%d)(%d%d%d)(%d%d%d)$", "%1 %2 %3")) +end + +-- The register writes names and places in capitals; "STAVANGER" reads better as "Stavanger". +-- Lua's lower and upper know only ASCII, so Æ, Ø and Å are handled by hand; Lua 5.1 has no \x +-- escapes, so their first byte is written in decimal. +local function titled(s) + local text = tostring(s or ""):lower():gsub("Æ", "æ"):gsub("Ø", "ø"):gsub("Å", "å") + local upper = { ["æ"] = "Æ", ["ø"] = "Ø", ["å"] = "Å" } + return (text:gsub("[^%s%-]+", function(word) + local first = word:match("^[\195][\128-\191]") or word:sub(1, 1) + return (upper[first] or first:upper()) .. word:sub(#first + 1) + end)) +end + +local function address(a) + if not a then return nil end + local parts = {} + for _, line in ipairs(a.adresse or {}) do table.insert(parts, line) end + local place = table.concat({ a.postnummer or "", titled(a.poststed) }, " "):match("^%s*(.-)%s*$") + if place ~= "" then table.insert(parts, place) end + if a.landkode and a.landkode ~= "NO" and a.land then table.insert(parts, a.land) end + return #parts > 0 and table.concat(parts, ", ") or nil +end + +-- A sub-unit is where a company works (a shop, an office), found under its own path. +local function location(unit) + return unit.forretningsadresse or unit.beliggenhetsadresse +end + +local function status(unit) + if unit.slettedato then return toolshed.t("status.deleted", { date = unit.slettedato }) end + if unit.konkurs then return toolshed.t("status.bankrupt") end + if unit.underTvangsavviklingEllerTvangsopplosning then return toolshed.t("status.dissolved") end + if unit.underAvvikling then return toolshed.t("status.wound-up") end + return nil +end + +local function jig(unit, kind) + local subtitle = { spaced(unit.organisasjonsnummer) } + if unit.organisasjonsform then table.insert(subtitle, unit.organisasjonsform.kode) end + local where = location(unit) + if where and where.poststed then table.insert(subtitle, titled(where.poststed)) end + table.insert(subtitle, status(unit)) + return { + title = unit.navn, + subtitle = table.concat(subtitle, " · "), + data = { number = unit.organisasjonsnummer, kind = kind, name = unit.navn, address = address(location(unit)) }, + } +end + +-- by_number looks a number up as a company first, then as a sub-unit; nil when it's neither. +local function by_number(number, max_seconds) + for _, kind in ipairs({ "enheter", "underenheter" }) do + local ok, unit = pcall(get, kind .. "/" .. number, max_seconds) + if ok then return unit, kind end + end + return nil +end + +local function page_address(data) + return toolshed.t("link") .. data.kind .. "/" .. data.number +end + +local function tile(icon) + return '' +end + +local function card(title, icon, tint, facts) + local rows = {} + for _, f in ipairs(facts) do + if f[2] and f[2] ~= "" then table.insert(rows, "
" .. escape(toolshed.t(f[1])) .. "
" .. f[2] .. "
") end + end + if #rows == 0 then return "" end + return '
' .. tile(icon) .. escape(toolshed.t(title)) .. + '
' .. table.concat(rows) .. "
" +end + +local function industries(unit) + local out = {} + for i = 1, 3 do + local code = unit["naeringskode" .. i] + if code then table.insert(out, escape(code.beskrivelse) .. ' ' .. escape(code.kode) .. "") end + end + return table.concat(out, "
") +end + +-- details is a unit's page, and the jigs it draws: the unit it's part of, in Part of, and what's +-- under a company in lines under its cards, each kind under its own heading. +local function details(unit, kind, parent_unit, under) + local jigs = {} + local trouble = status(unit) + local state = '' .. escape(trouble or toolshed.t("status.active")) + local form = unit.organisasjonsform + local parent = unit.overordnetEnhet and escape(spaced(unit.overordnetEnhet)) + if parent and parent_unit then + table.insert(jigs, jig(parent_unit, "enheter")) + parent = '' .. escape(parent_unit.navn) .. ' ' .. parent .. "" + end + local registered = {} + if unit.registrertIForetaksregisteret then table.insert(registered, toolshed.t("register.business")) end + if unit.registrertIMvaregisteret then table.insert(registered, toolshed.t("register.vat")) end + if unit.registrertIStiftelsesregisteret then table.insert(registered, toolshed.t("register.foundations")) end + if unit.registrertIFrivillighetsregisteret then table.insert(registered, toolshed.t("register.non-profit")) end + local employees = unit.harRegistrertAntallAnsatte and unit.antallAnsatte and tostring(unit.antallAnsatte) or nil + local site = unit.hjemmeside + local cards = { + card(kind == "underenheter" and "card.sub-unit" or "card.company", "building", "sand", { + { "fact.number", escape(spaced(unit.organisasjonsnummer)) }, + { "fact.form", form and (escape(form.beskrivelse) .. ' ' .. escape(form.kode) .. "") }, + { "fact.status", state }, + { "fact.part-of", parent }, + { "fact.founded", escape(unit.stiftelsesdato or unit.oppstartsdato) }, + { "fact.registered", escape(unit.registreringsdatoEnhetsregisteret) }, + }), + card("card.business", "briefcase", "purple", { + { "fact.industry", industries(unit) }, + { "fact.employees", employees and escape(employees) }, + { "fact.sector", unit.institusjonellSektorkode and escape(unit.institusjonellSektorkode.beskrivelse) }, + { "fact.registers", escape(table.concat(registered, ", ")) }, + }), + card("card.address", "map-pin", "orange", { + { kind == "underenheter" and "fact.location" or "fact.business-address", escape(address(location(unit))) }, + { "fact.postal", escape(address(unit.postadresse)) }, + { "fact.municipality", location(unit) and location(unit).kommune and escape(titled(location(unit).kommune)) }, + { "fact.website", site and escape(site) }, + }), + } + -- What's under it are rows the launcher draws where the page puts them, under their heading. + local lists = {} + for _, group in ipairs(under) do + local heading = toolshed.t(group.heading, { count = group.total }) + for _, u in ipairs(group.units) do + local row = jig(u, group.kind) + row.section = heading + table.insert(jigs, row) + end + if group.total > #group.units then + table.insert(jigs, { + title = toolshed.t("all-" .. group.heading, { count = group.total }), icon = "external-link", action = "open", section = heading, + data = { number = unit.organisasjonsnummer, kind = "enheter" }, + }) + end + table.insert(lists, '
') + end + return '
' .. table.concat(cards) .. "
" .. table.concat(lists) .. "
", jigs +end + +-- most_under is how many of each kind under a company its page lists; the rest are on brreg.no. +local most_under = 49 + +-- A company has two kinds under it: units of their own that are part of it, like the +-- directorates under a ministry, and its sub-units, the places where it does business. +local kinds_under = { + { kind = "enheter", heading = "units-under" }, + { kind = "underenheter", heading = "sub-units" }, +} + +-- related fetches the unit a unit is part of, and what's under a company, each kind with how many +-- there are. What can't be fetched is left out, so the page still shows. +local function related(unit, kind) + local parent, under = nil, {} + if unit.overordnetEnhet then + local ok, found = pcall(get, "enheter/" .. unit.overordnetEnhet, 5) + if ok then parent = found end + end + if kind == "enheter" then + for _, k in ipairs(kinds_under) do + local ok, found = pcall(get, k.kind .. "?size=" .. most_under .. "&overordnetEnhet=" .. unit.organisasjonsnummer, 5) + if ok and found._embedded and found._embedded[k.kind] then + table.insert(under, { kind = k.kind, heading = k.heading, units = found._embedded[k.kind], total = found.page and found.page.totalElements or 0 }) + end + end + end + return parent, under +end + +return toolshed.toolbox { + key = "brreg", + title = "i18n:toolbox.title", + description = "i18n:toolbox.description", + icon = "building", + tint = "sand", + + tools = { + { + key = "search", + title = "i18n:tool.search.title", + words = { "brreg" }, + examples = { "brreg equinor", "brreg 923 609 016" }, + keywords = { "company", "organisation number", "orgnr", "enhetsregisteret", "foretak", "bedrift", "organisasjonsnummer" }, + items = true, + -- brreg.no is asked once typing pauses, not for every letter on the way. + debounce = true, + + -- Nine digits are offered as a number to look up; nothing is asked of brreg.no until Enter. + suggest = function(text) + local number = text:gsub("[%s%.]", "") + if not number:match("^%d%d%d%d%d%d%d%d%d$") then return nil end + return { + title = toolshed.t("suggest", { number = spaced(number) }), + data = { number = number }, actions = { "details" }, + } + end, + + search = function(rest, settings) + -- "brreg" on its own looks up an organisation number selected where Toolshed was opened + -- from; other selected text is left alone, as it may be anything. + if rest == "" then + local selected = (toolshed.selection() or ""):gsub("[%s%.]", "") + if not selected:match("^%d%d%d%d%d%d%d%d%d$") then return {} end + rest = selected + end + local number = rest:gsub("[%s%.]", "") + if number:match("^%d+$") then + if #number ~= 9 then return {} end + local unit, kind = by_number(number, 1.5) + return unit and { jig(unit, kind) } or {} + end + local ok, found = pcall(get, "enheter?size=15&navn=" .. encode(rest), 1.5) + local jigs = {} + for _, unit in ipairs(ok and found._embedded and found._embedded.enheter or {}) do + table.insert(jigs, jig(unit, "enheter")) + end + return jigs + end, + + actions = { + { + key = "details", title = "i18n:action.search.details", icon = "info", + run = function(ctx) + local unit, kind + if ctx.data.kind then + unit, kind = get(ctx.data.kind .. "/" .. ctx.data.number, 10), ctx.data.kind + else + -- A suggested number, not yet looked up: a company or a sub-unit. + unit, kind = by_number(ctx.data.number, 10) + if not unit then error(toolshed.t("not-found", { number = spaced(ctx.data.number) })) end + end + local html, jigs = details(unit, kind, related(unit, kind)) + return { html = html, jigs = jigs } + end, + }, + { + key = "open", title = "i18n:action.search.open", icon = "external-link", shortcut = "cmd+enter", + run = function(ctx) toolshed.open(page_address(ctx.data)) end, + }, + { + key = "copy-number", title = "i18n:action.search.copy-number", icon = "hash", shortcut = "cmd+shift+c", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.number) + return toolshed.t("number-copied") + end, + }, + { + key = "copy-name", title = "i18n:action.search.copy-name", icon = "copy", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.name) + return toolshed.t("name-copied") + end, + }, + { + key = "copy-address", title = "i18n:action.search.copy-address", icon = "map-pin", + run = function(ctx) + if not ctx.data.address then error(toolshed.t("no-address")) end + toolshed.clipboard.copy(ctx.data.address) + return toolshed.t("address-copied") + end, + }, + }, + }, + }, +} diff --git a/brreg/locales/en.toml b/brreg/locales/en.toml new file mode 100644 index 0000000..b2f38ad --- /dev/null +++ b/brreg/locales/en.toml @@ -0,0 +1,140 @@ +[toolbox.title] +other = "Brønnøysund Registers" + +[toolbox.description] +other = "Finds Norwegian companies by name or organisation number" + +[tool.search.title] +other = "Search Brønnøysund Registers" + +[action.search.details] +other = "Show Details" + +[action.search.open] +other = "Open on brreg.no" + +[action.search.copy-number] +other = "Copy Organisation Number" + +[action.search.copy-name] +other = "Copy Name" + +[action.search.copy-address] +other = "Copy Address" + +[number-copied] +other = "Organisation number copied" + +[name-copied] +other = "Name copied" + +[address-copied] +other = "Address copied" + +[no-address] +other = "No address registered" + +[link] +other = "https://virksomhet.brreg.no/en/oppslag/" + +[status.active] +other = "Active" + +[status.deleted] +other = "Deleted {{.date}}" + +[status.bankrupt] +other = "Bankrupt" + +[status.dissolved] +other = "Being dissolved by force" + +[status.wound-up] +other = "Being wound up" + +[register.business] +other = "Register of Business Enterprises" + +[register.vat] +other = "VAT Register" + +[register.foundations] +other = "Register of Foundations" + +[register.non-profit] +other = "Register of Non-Profit Organisations" + +[card.company] +other = "Company" + +[card.sub-unit] +other = "Sub-unit" + +[card.business] +other = "Business" + +[card.address] +other = "Address" + +[fact.number] +other = "Number" + +[fact.form] +other = "Form" + +[fact.status] +other = "Status" + +[fact.part-of] +other = "Part of" + +[fact.founded] +other = "Founded" + +[fact.registered] +other = "Registered" + +[fact.industry] +other = "Industry" + +[fact.employees] +other = "Employees" + +[fact.sector] +other = "Sector" + +[fact.registers] +other = "Registers" + +[fact.location] +other = "Location" + +[fact.business-address] +other = "Business" + +[fact.postal] +other = "Postal" + +[fact.municipality] +other = "Municipality" + +[fact.website] +other = "Website" + +[units-under] +other = "Units under it ({{.count}})" + +[all-units-under] +other = "All {{.count}} units under it on brreg.no" + +[sub-units] +other = "Sub-units ({{.count}})" + +[all-sub-units] +other = "All {{.count}} sub-units on brreg.no" + +[suggest] +other = "Look up {{.number}} in the Brønnøysund Registers" + +[not-found] +other = "No unit has the number {{.number}}" diff --git a/brreg/locales/nb.toml b/brreg/locales/nb.toml new file mode 100644 index 0000000..72a0b7e --- /dev/null +++ b/brreg/locales/nb.toml @@ -0,0 +1,140 @@ +[toolbox.title] +other = "Brønnøysundregistrene" + +[toolbox.description] +other = "Finner norske virksomheter på navn eller organisasjonsnummer" + +[tool.search.title] +other = "Søk i Brønnøysundregistrene" + +[action.search.details] +other = "Vis detaljer" + +[action.search.open] +other = "Åpne på brreg.no" + +[action.search.copy-number] +other = "Kopier organisasjonsnummer" + +[action.search.copy-name] +other = "Kopier navn" + +[action.search.copy-address] +other = "Kopier adresse" + +[number-copied] +other = "Organisasjonsnummer kopiert" + +[name-copied] +other = "Navn kopiert" + +[address-copied] +other = "Adresse kopiert" + +[no-address] +other = "Ingen adresse registrert" + +[link] +other = "https://virksomhet.brreg.no/nb/oppslag/" + +[status.active] +other = "Aktiv" + +[status.deleted] +other = "Slettet {{.date}}" + +[status.bankrupt] +other = "Konkurs" + +[status.dissolved] +other = "Under tvangsavvikling" + +[status.wound-up] +other = "Under avvikling" + +[register.business] +other = "Foretaksregisteret" + +[register.vat] +other = "Merverdiavgiftsregisteret" + +[register.foundations] +other = "Stiftelsesregisteret" + +[register.non-profit] +other = "Frivillighetsregisteret" + +[card.company] +other = "Hovedenhet" + +[card.sub-unit] +other = "Underenhet" + +[card.business] +other = "Virksomhet" + +[card.address] +other = "Adresse" + +[fact.number] +other = "Org.nr." + +[fact.form] +other = "Form" + +[fact.status] +other = "Status" + +[fact.part-of] +other = "Del av" + +[fact.founded] +other = "Stiftet" + +[fact.registered] +other = "Registrert" + +[fact.industry] +other = "Næring" + +[fact.employees] +other = "Ansatte" + +[fact.sector] +other = "Sektor" + +[fact.registers] +other = "Registre" + +[fact.location] +other = "Beliggenhet" + +[fact.business-address] +other = "Forretning" + +[fact.postal] +other = "Post" + +[fact.municipality] +other = "Kommune" + +[fact.website] +other = "Nettside" + +[units-under] +other = "Enheter under ({{.count}})" + +[all-units-under] +other = "Alle {{.count}} enhetene under på brreg.no" + +[sub-units] +other = "Underenheter ({{.count}})" + +[all-sub-units] +other = "Alle {{.count}} underenhetene på brreg.no" + +[suggest] +other = "Slå opp {{.number}} i Brønnøysundregistrene" + +[not-found] +other = "Ingen enhet har nummeret {{.number}}" diff --git a/dashboard-icons/init.lua b/dashboard-icons/init.lua new file mode 100644 index 0000000..f10aa94 --- /dev/null +++ b/dashboard-icons/init.lua @@ -0,0 +1,145 @@ +-- Icons for self-hosted apps from dashboardicons.com: "di plex" shows them as tiles. Enter copies +-- the icon's address, its SVG when it has one, for a dashboard like Homarr or Homepage; ⌘K copies +-- the SVG or PNG address, its name or the picture, or opens it on the site. + +local cdn = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/" +local list_file = toolshed.cache_dir() .. "/metadata.json" +-- New icons arrive every few days; a week-old list still finds nearly all of them. +local refresh_seconds = 7 * 24 * 3600 + +local modified = toolshed.file.modified + +local function download(max_seconds) + local tmp = list_file .. ".download" + toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), "-o", tmp, cdn .. "metadata.json" }) + assert(os.rename(tmp, list_file)) +end + +-- refresh downloads a stale list again in the background, quietly, so no search waits for it: +-- once a run of Toolshed, at its first search, as the list read then is kept. +local refreshed = false +local function refresh() + if refreshed then return end + refreshed = true + local changed = modified(list_file) + if changed and os.time() - changed > refresh_seconds then + toolshed.activities.set { + key = "refresh", title = toolshed.t("jobs.refresh.title"), description = toolshed.t("jobs.refresh.description"), quiet = true, timeout = 120, + run = { "sh", "-c", 'curl -sSfL --max-time 60 -o "$0.download" "$1" && mv "$0.download" "$0"', list_file, cdn .. "metadata.json" }, + } + end +end + +local icons +local function load() + refresh() + if icons then return icons end + if not modified(list_file) then download(1.5) end -- the first search ever has to wait + local f = assert(io.open(list_file, "r")) + local metadata = toolshed.json.decode(f:read("*a")) + f:close() + icons = {} + for name, meta in pairs(metadata) do + table.insert(icons, { + name = name, + base = meta.base, + aliases = table.concat(meta.aliases or {}, " "), + categories = table.concat(meta.categories or {}, ", "), + }) + end + table.sort(icons, function(a, b) return a.name < b.name end) + return icons +end + +local function address(ctx, format) + return cdn .. format .. "/" .. ctx.data.name .. "." .. format +end + +return toolshed.toolbox { + key = "dashboard-icons", + title = "Dashboard Icons", + description = "i18n:toolbox.description", + icon = "image", + tint = "blue", + grid = true, + + tools = { { + key = "search", + title = "Dashboard Icons", + words = { "di" }, + examples = { "di plex", "di home assistant" }, + keywords = { "ikoner" }, + items = true, + + search = function(rest) + local found = {} + for _, icon in ipairs(load()) do + local score = math.max( + toolshed.match(rest, icon.name), + toolshed.match(rest, icon.aliases), + toolshed.match(rest, icon.categories) * 0.8) + if score > 0 then table.insert(found, { icon = icon, score = score }) end + end + table.sort(found, function(a, b) + if a.score ~= b.score then return a.score > b.score end + return a.icon.name < b.icon.name + end) + local items = {} + for i = 1, math.min(#found, 50) do + local icon = found[i].icon + table.insert(items, { + title = icon.name, + subtitle = icon.categories, + -- The original: an SVG is mostly a tenth of the PNG's size, and some PNGs made from SVGs + -- came out blank, like jellyglance's. + image = cdn .. icon.base .. "/" .. icon.name .. "." .. icon.base, + data = { name = icon.name, base = icon.base }, + }) + end + return items + end, + + actions = { + { + key = "copy-address", title = "i18n:action.search.copy-address", + run = function(ctx) + toolshed.clipboard.copy(address(ctx, ctx.data.base)) + return toolshed.t(ctx.data.base == "svg" and "svg-copied" or "png-copied-no-svg") + end, + }, + { + key = "copy-svg-address", title = "i18n:action.search.copy-svg-address", + run = function(ctx) + if ctx.data.base ~= "svg" then error(toolshed.t("no-svg")) end + toolshed.clipboard.copy(address(ctx, "svg")) + return toolshed.t("svg-copied") + end, + }, + { + key = "copy-png-address", title = "i18n:action.search.copy-png-address", + run = function(ctx) + toolshed.clipboard.copy(address(ctx, "png")) + return toolshed.t("png-copied") + end, + }, + { + key = "copy-image", title = "i18n:action.search.copy-image", + run = function(ctx) + toolshed.clipboard.copy_image(address(ctx, "png")) + return toolshed.t("image-copied") + end, + }, + { + key = "copy-name", title = "i18n:action.search.copy-name", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.name) + return toolshed.t("name-copied") + end, + }, + { + key = "open", title = "i18n:action.search.open", + run = function(ctx) toolshed.open("https://dashboardicons.com/icons/" .. ctx.data.name) end, + }, + }, + } }, +} diff --git a/dashboard-icons/locales/en.toml b/dashboard-icons/locales/en.toml new file mode 100644 index 0000000..5c47294 --- /dev/null +++ b/dashboard-icons/locales/en.toml @@ -0,0 +1,44 @@ +[toolbox.description] +other = "Finds icons for self-hosted apps on dashboardicons.com" + +[action.search.copy-address] +other = "Copy Address" + +[action.search.copy-svg-address] +other = "Copy SVG Address" + +[action.search.copy-png-address] +other = "Copy PNG Address" + +[action.search.copy-image] +other = "Copy Image" + +[action.search.copy-name] +other = "Copy Name" + +[action.search.open] +other = "Open on dashboardicons.com" + +[svg-copied] +other = "SVG address copied" + +[png-copied] +other = "PNG address copied" + +[png-copied-no-svg] +other = "PNG address copied: this icon has no SVG" + +[no-svg] +other = "This icon has no SVG, only a PNG" + +[image-copied] +other = "Image copied" + +[name-copied] +other = "Name copied" + +[jobs.refresh.title] +other = "Downloads the icon list" + +[jobs.refresh.description] +other = "Keeps the icon list up to date" diff --git a/dashboard-icons/locales/nb.toml b/dashboard-icons/locales/nb.toml new file mode 100644 index 0000000..46a0fd2 --- /dev/null +++ b/dashboard-icons/locales/nb.toml @@ -0,0 +1,44 @@ +[toolbox.description] +other = "Finner ikoner for selvhostede apper på dashboardicons.com" + +[action.search.copy-address] +other = "Kopier adresse" + +[action.search.copy-svg-address] +other = "Kopier SVG-adresse" + +[action.search.copy-png-address] +other = "Kopier PNG-adresse" + +[action.search.copy-image] +other = "Kopier bilde" + +[action.search.copy-name] +other = "Kopier navn" + +[action.search.open] +other = "Åpne på dashboardicons.com" + +[svg-copied] +other = "SVG-adresse kopiert" + +[png-copied] +other = "PNG-adresse kopiert" + +[png-copied-no-svg] +other = "PNG-adresse kopiert: dette ikonet har ingen SVG" + +[no-svg] +other = "Dette ikonet har ingen SVG, bare PNG" + +[image-copied] +other = "Bilde kopiert" + +[name-copied] +other = "Navn kopiert" + +[jobs.refresh.title] +other = "Laster ned ikonlisten" + +[jobs.refresh.description] +other = "Holder ikonlisten oppdatert" diff --git a/databricks/assets/databricks.svg b/databricks/assets/databricks.svg new file mode 100644 index 0000000..4163340 --- /dev/null +++ b/databricks/assets/databricks.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/databricks/index.sh b/databricks/index.sh new file mode 100644 index 0000000..046c444 --- /dev/null +++ b/databricks/index.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# index.sh PROFILE OUT writes what a workspace has to OUT, a line each, tab-separated: its kind +# (catalog, schema, table, volume or job), its name, its type (a job's: its id) and comment. +# Unity Catalog has no call that lists everything, so it's walked a catalog, then a schema, at a +# time, several at once; the jobs take a call of their own. OUT is swapped in whole when done, so +# a search never reads half of it; a failure says why on stderr. +P="$1" +OUT="$2" +T="$OUT.parts" +export P T +rm -rf "$T" +mkdir -p "$T" +trap 'rm -rf "$T"' EXIT + +# Every catalog has an information_schema of the same forty views, which would bury the rest. +if ! databricks catalogs list -p "$P" -o json 2>"$T/error" | + jq -r '.[] | select(.name != "__databricks_internal") | [.name, .catalog_type // "", (.comment // "" | gsub("\\s+"; " "))] | @tsv' >"$T/catalogs"; then + grep -v "aitools" "$T/error" >&2 + exit 1 +fi +awk -F'\t' '{ print "catalog\t" $1 "\t" $2 "\t" $3 }' "$T/catalogs" >"$T/a" + +cut -f1 "$T/catalogs" | xargs -P 8 -I{} sh -c ' + databricks schemas list "$1" -p "$P" -o json 2>/dev/null | + jq -r ".[] | select(.name != \"information_schema\") | [\"schema\", .full_name, \"\", (.comment // \"\" | gsub(\"\\\\s+\"; \" \"))] | @tsv" >"$T/s.$1" + databricks tables list-summaries "$1" -p "$P" -o json 2>/dev/null | + jq -r ".[] | select(.full_name | contains(\".information_schema.\") | not) | [\"table\", .full_name, .table_type // \"\", \"\"] | @tsv" >"$T/t.$1" +' sh {} + +# Volumes are listed a schema at a time, and only managed catalogs have them. +awk -F'\t' '$2 == "MANAGED_CATALOG" { print $1 }' "$T/catalogs" >"$T/managed" +cat "$T"/s.* 2>/dev/null | awk -F'\t' 'NR == FNR { m[$1] = 1; next } { split($2, n, "."); if (m[n[1]]) print $2 }' "$T/managed" - | + xargs -P 8 -I{} sh -c ' + databricks volumes list "${1%%.*}" "${1#*.}" -p "$P" -o json 2>/dev/null | + jq -r ".[]? | [\"volume\", .full_name, .volume_type // \"\", (.comment // \"\" | gsub(\"\\\\s+\"; \" \"))] | @tsv" >"$T/v.$1" + ' sh {} + +databricks jobs list -p "$P" -o json 2>/dev/null | + jq -r '.[] | ["job", .settings.name // "", (.job_id | tostring), ""] | @tsv' >"$T/jobs" + +cat "$T/a" "$T"/s.* "$T"/t.* "$T"/v.* "$T/jobs" 2>/dev/null >"$OUT.tmp" && mv "$OUT.tmp" "$OUT" diff --git a/databricks/init.lua b/databricks/init.lua new file mode 100644 index 0000000..81efc67 --- /dev/null +++ b/databricks/init.lua @@ -0,0 +1,629 @@ +-- Databricks, through its CLI, which reads ~/.databrickscfg and signs in as it's set up to, so +-- the extension never sees a token. "dbx" offers Search, Runs and Jobs: "dbx search sales" (or +-- just "dbx sales") finds catalogs, schemas, tables and volumes, "dbx runs" the latest job runs, +-- newest first ("dbx runs failed", "dbx runs ingest" filter them), and "dbx jobs" the jobs. Enter +-- shows one: a table's columns, a schema's tables, a run's tasks, a job's runs; ⌘K opens it in +-- Databricks or copies its name. Which workspaces it searches is a setting, the profiles in +-- ~/.databrickscfg to choose from. Its text is in locales/. + +local cache = toolshed.cache_dir() +-- index.sh beside this file walks a workspace, as no one call lists what's in it. +local folder = package.path:match("^(.-)/%?%.lua") +-- The index is walked again in the background once it's this old, searches using it meanwhile. +local stale_seconds = 24 * 3600 +-- Runs change by the minute but not by the keystroke: asked again once they're this old. +local runs_seconds = 20 +-- Search shows at most this many, as a launcher list shows no more. +local most = 40 + +local escape = toolshed.escape + +local quoted = toolshed.shell_quote + +local modified = toolshed.file.modified + +local read = toolshed.file.read + +-- The CLI nags on stderr about skills of its own, which says nothing about what went wrong. +local function reason(err) + local lines = {} + for line in tostring(err):gmatch("[^\n]+") do + if not line:find("aitools") then table.insert(lines, line) end + end + return (table.concat(lines, " "):gsub("^.-databricks: ", "")) +end + +-- workspaces are the profiles in ~/.databrickscfg that are a workspace, not an account: name +-- and address, in the file's order. +local function workspaces() + local list, current = {}, nil + for line in (read(os.getenv("HOME") .. "/.databrickscfg") or ""):gmatch("[^\n]+") do + local name = line:match("^%s*%[(.-)%]") + if name then + current = { name = name } + table.insert(list, current) + elseif current then + local key, value = line:match("^%s*([%w_]+)%s*=%s*(.-)%s*$") + if key then current[key] = value end + end + end + local found = {} + for _, p in ipairs(list) do + if p.host and not p.account_id then + local host = p.host:gsub("/+$", "") + if not host:find("^https?://") then host = "https://" .. host end + table.insert(found, { name = p.name, host = host, id = host:match("adb%-(%d+)%.") }) + end + end + return found +end + +local function workspace(name) + for _, w in ipairs(workspaces()) do + if w.name == name then return w end + end + error(toolshed.t("error.no-profile", { profile = name })) +end + +-- chosen are the workspaces the setting names: one, or all of them. +local function chosen(settings) + local all = workspaces() + if settings.workspace == "*" then return all end + for _, w in ipairs(all) do + if w.name == settings.workspace then return { w } end + end + return {} +end + +local function cli(profile, ...) + local args = { "databricks", ... } + table.insert(args, "-p") + table.insert(args, profile) + table.insert(args, "-o") + table.insert(args, "json") + return toolshed.json.decode(toolshed.exec(args)) +end + +-- address is where Databricks shows a thing, with the workspace's id so the right one opens. +local function address(w, path) + return w.host .. path .. (w.id and ("?o=" .. w.id) or "") +end + +local function problem(text) + return { title = text, icon = "info", actions = {} } +end + +-- The index ------------------------------------------------------------------------------------ + +local function index_file(profile) return cache .. "/index-" .. profile:gsub("[^%w%-_]", "_") .. ".tsv" end + +local function index_key(profile) return "index-" .. profile:lower():gsub("[^%w_-]", "-") end + +-- index_in_background walks the workspace again, quietly, unless that's already under way. +local function index_in_background(profile) + toolshed.activities.set { + key = index_key(profile), title = toolshed.t("jobs.index.title", { workspace = profile }), description = toolshed.t("jobs.index.description"), quiet = true, timeout = 1800, + run = { "sh", folder .. "/index.sh", profile, index_file(profile) }, + } +end + +local indexes = {} -- by profile: what's read from its file, and when + +-- index is what's known of a workspace, its entries { kind, name, detail, comment }, or nil and +-- what to say instead: that it's being walked, or why that failed. +local function index(profile) + local file = index_file(profile) + local at = modified(file) + if not at then + local last = toolshed.activities.get(index_key(profile)) + if last and (last.state == "failed" or last.state == "timed-out") then + return nil, toolshed.t("error.index", { reason = reason(last.reason) }) + end + index_in_background(profile) + return nil, toolshed.t("indexing", { workspace = profile }) + end + if os.time() - at > stale_seconds then index_in_background(profile) end + local known = indexes[profile] + if known and known.at == at then return known.entries end + local entries = {} + for line in (read(file) or ""):gmatch("[^\n]+") do + local kind, name, detail, comment = line:match("^([^\t]*)\t([^\t]*)\t([^\t]*)\t?(.*)$") + if kind then table.insert(entries, { kind = kind, name = name, detail = detail, comment = comment }) end + end + indexes[profile] = { at = at, entries = entries } + return entries +end + +local kind_icons = { catalog = "database", schema = "layers", table = "table-2", volume = "hard-drive", job = "workflow" } + +-- A catalog, schema, table or volume as a row: its name, what it is, and where. +local function item_jig(w, e, several) + local kind = e.kind + if kind == "table" and (e.detail == "VIEW" or e.detail == "MATERIALIZED_VIEW") then kind = "view" end + local tags = { { text = toolshed.t("kind." .. kind) } } + if several then table.insert(tags, { text = w.name, tint = "blue" }) end + local short = e.name:match("([^.]+)$") + local within = e.name:match("^(.*)%.[^.]+$") + local about = {} + if within then table.insert(about, within) end + if e.comment ~= "" then table.insert(about, e.comment) end + local actions = { "show", "open", "copy-name" } + if e.kind == "table" then table.insert(actions, "copy-select") end + if e.kind == "volume" then table.insert(actions, "copy-path") end + return { + key = w.name .. ":" .. e.name, title = short, subtitle = table.concat(about, " · "), icon = kind_icons[e.kind], + tags = tags, tool = "item", actions = actions, + data = { profile = w.name, kind = e.kind, name = e.name }, + } +end + +local function job_jig(w, e, several) + local tags = several and { { text = w.name, tint = "blue" } } or nil + return { + key = w.name .. ":job:" .. e.detail, title = e.name, subtitle = toolshed.t("job-id", { id = e.detail }), icon = "workflow", + tags = tags, tool = "job", data = { profile = w.name, id = e.detail, name = e.name }, + } +end + +-- found are the index's entries of these kinds that match what's typed, best first. +local function found(settings, typed, kinds, as_jig) + local wanted = {} + for _, k in ipairs(kinds) do wanted[k] = true end + local list, said = {}, {} + local ws = chosen(settings) + if #ws == 0 then return { problem(toolshed.t("error.no-workspace")) } end + for _, w in ipairs(ws) do + local entries, why = index(w.name) + if not entries then + table.insert(said, problem(why)) + else + for _, e in ipairs(entries) do + if wanted[e.kind] then + local score = toolshed.match(typed, e.name) + if score > 0 then table.insert(list, { score = score, w = w, e = e }) end + end + end + end + end + table.sort(list, function(a, b) + if a.score ~= b.score then return a.score > b.score end + return a.e.name < b.e.name + end) + local jigs = said + for i = 1, math.min(#list, most) do table.insert(jigs, as_jig(list[i].w, list[i].e, #ws > 1)) end + return jigs +end + +-- Runs ----------------------------------------------------------------------------------------- + +local runs_known = {} -- by profile: the latest runs, and when they were asked for + +local function latest_runs(profile) + local known = runs_known[profile] + if known and os.time() - known.at < runs_seconds then return known.runs end + local runs = cli(profile, "jobs", "list-runs", "--limit", "50") + runs_known[profile] = { at = os.time(), runs = runs } + return runs +end + +-- status is how a run or task went, as a word and a tint. +local function status(state) + state = state or {} + local life, result = state.life_cycle_state, state.result_state + if life == "RUNNING" or life == "PENDING" or life == "QUEUED" or life == "TERMINATING" or life == "BLOCKED" or life == "WAITING_FOR_RETRY" then + return "running", "blue" + end + if result == "SUCCESS" then return "succeeded", "green" end + if result == "SUCCESS_WITH_FAILURES" then return "partly", "orange" end + if result == "CANCELED" or result == "UPSTREAM_CANCELED" then return "cancelled", "gray" end + if result == "SKIPPED" or result == "EXCLUDED" or life == "SKIPPED" then return "skipped", "gray" end + if result or life == "INTERNAL_ERROR" then return "failed", "red" end + return "running", "blue" +end + +-- The words that filter runs by how they went, in the languages Toolshed speaks. +local status_words = { + failed = "failed", fail = "failed", failing = "failed", feilet = "failed", feil = "failed", + running = "running", ["kjører"] = "running", active = "running", + succeeded = "succeeded", success = "succeeded", ok = "succeeded", vellykket = "succeeded", + cancelled = "cancelled", canceled = "cancelled", avbrutt = "cancelled", skipped = "skipped", +} + +local function duration(ms) + local s = math.floor((ms or 0) / 1000) + if s < 60 then return s .. " s" end + if s < 3600 then return math.floor(s / 60) .. " m " .. s % 60 .. " s" end + return math.floor(s / 3600) .. " h " .. math.floor(s % 3600 / 60) .. " m" +end + +local function ago(ms) + local s = math.max(0, os.time() - math.floor((ms or 0) / 1000)) + if s < 60 then return toolshed.t("ago.now") end + if s < 3600 then return toolshed.t("ago.minutes", { count = math.floor(s / 60) }) end + if s < 86400 then return toolshed.t("ago.hours", { count = math.floor(s / 3600) }) end + return toolshed.t("ago.days", { count = math.floor(s / 86400) }) +end + +local function when(ms) + return os.date("%Y-%m-%d %H:%M", math.floor((ms or 0) / 1000)) +end + +local function run_length(run) + if run.run_duration and run.run_duration > 0 then return run.run_duration end + local ended = run.end_time and run.end_time > 0 and run.end_time or os.time() * 1000 + return ended - (run.start_time or ended) +end + +local function run_jig(w, run, several) + local how, tint = status(run.state) + local tags = { { text = toolshed.t("status." .. how), tint = tint } } + if several then table.insert(tags, { text = w.name, tint = "blue" }) end + return { + key = w.name .. ":run:" .. tostring(run.run_id), title = run.run_name or toolshed.t("run"), icon = "play", + subtitle = ago(run.start_time) .. " · " .. duration(run_length(run)), tags = tags, tool = "run", + data = { profile = w.name, id = string.format("%.0f", run.run_id), url = run.run_page_url }, + } +end + +-- run_rows are the latest runs of the chosen workspaces, newest first, those that are of how +-- typed says they went and named like the rest of it. +local function run_rows(settings, typed) + local only, words = nil, {} + for word in typed:lower():gmatch("%S+") do + if status_words[word] then only = status_words[word] else table.insert(words, word) end + end + local named = table.concat(words, " ") + local list, jigs = {}, {} + local ws = chosen(settings) + if #ws == 0 then return { problem(toolshed.t("error.no-workspace")) } end + for _, w in ipairs(ws) do + local ok, runs = pcall(latest_runs, w.name) + if not ok then + table.insert(jigs, problem(toolshed.t("error.runs", { workspace = w.name, reason = reason(runs) }))) + else + for _, run in ipairs(runs) do + if (not only or status(run.state) == only) and (named == "" or toolshed.match(named, run.run_name or "") > 0) then + table.insert(list, { w = w, run = run }) + end + end + end + end + table.sort(list, function(a, b) return (a.run.start_time or 0) > (b.run.start_time or 0) end) + for i = 1, math.min(#list, most) do table.insert(jigs, run_jig(list[i].w, list[i].run, #ws > 1)) end + if #jigs == 0 then table.insert(jigs, problem(toolshed.t("no-runs"))) end + return jigs +end + +-- Pages ---------------------------------------------------------------------------------------- + +local function card(title, icon, tint, facts) + local rows = {} + for _, f in ipairs(facts) do + if f[2] and f[2] ~= "" then table.insert(rows, "
" .. escape(toolshed.t(f[1])) .. "
" .. f[2] .. "
") end + end + return '
' .. escape(title) .. '
' .. table.concat(rows) .. "
" +end + +local function page(html) return '
' .. html .. "
" end + +local function rows_at(section) return '
' end + +local function tag(text, tint) + return '' .. escape(text) .. "" +end + +-- within lists what the index has directly inside a catalog or schema, as rows of the page. +local function within(w, name, section, jigs) + local entries = index(w.name) or {} + local depth = select(2, name:gsub("%.", "")) + 1 + local inside = {} + for _, e in ipairs(entries) do + if e.kind ~= "job" and e.name:sub(1, #name + 1) == name .. "." and select(2, e.name:gsub("%.", "")) == depth then + table.insert(inside, e) + end + end + table.sort(inside, function(a, b) return a.name < b.name end) + for _, e in ipairs(inside) do + local row = item_jig(w, e, false) + row.section = section + table.insert(jigs, row) + end + return #inside +end + +-- type_icons show a column's type at a glance, by Unity Catalog's type_name: numbers, text, +-- yes or no, dates and times, and what holds other values. +local type_icons = { + BYTE = { "hash", "blue" }, SHORT = { "hash", "blue" }, INT = { "hash", "blue" }, LONG = { "hash", "blue" }, + FLOAT = { "hash", "blue" }, DOUBLE = { "hash", "blue" }, DECIMAL = { "hash", "blue" }, + STRING = { "type", "green" }, CHAR = { "type", "green" }, BINARY = { "binary", "gray" }, + BOOLEAN = { "toggle-right", "purple" }, + DATE = { "calendar", "orange" }, TIMESTAMP = { "calendar-clock", "orange" }, TIMESTAMP_NTZ = { "calendar-clock", "orange" }, + INTERVAL = { "timer", "orange" }, + ARRAY = { "brackets", "teal" }, STRUCT = { "braces", "teal" }, MAP = { "braces", "teal" }, VARIANT = { "braces", "teal" }, + GEOGRAPHY = { "map-pin", "pink" }, GEOMETRY = { "map-pin", "pink" }, +} + +local function type_tile(type_name) + local icon = type_icons[type_name] or { "circle", "gray" } + return '' +end + +local function item_page(ctx) + local d = ctx.data + local w = workspace(d.profile) + -- html is the card; below, what's under it across the page: a table's columns, a schema's tables. + local jigs, html, below = {}, "", "" + if d.kind == "table" then + local t = cli(w.name, "tables", "get", d.name) + html = card(t.full_name, "table-2", "red", { + { "fact.type", escape(t.table_type) .. (t.data_source_format and (" · " .. escape(t.data_source_format)) or "") }, + { "fact.comment", t.comment and escape(t.comment) }, + { "fact.owner", escape(t.owner) }, + { "fact.created", t.created_at and escape(when(t.created_at) .. " · " .. (t.created_by or "")) }, + { "fact.updated", t.updated_at and escape(when(t.updated_at) .. " · " .. (t.updated_by or "")) }, + { "fact.location", t.storage_location and escape(t.storage_location) }, + }) + -- Keys are tagged on their columns; the tables foreign keys point to are rows to open. + local primary, foreign, references = {}, {}, {} + for _, constraint in ipairs(t.table_constraints or {}) do + for _, name in ipairs((constraint.primary_key_constraint or {}).child_columns or {}) do primary[name] = true end + local fk = constraint.foreign_key_constraint + if fk then + for i, name in ipairs(fk.child_columns or {}) do + foreign[name] = fk.parent_table .. "." .. ((fk.parent_columns or {})[i] or "") + end + if not references[fk.parent_table] then + references[fk.parent_table] = true + local row = item_jig(w, { kind = "table", name = fk.parent_table, detail = "", comment = "" }, false) + row.section, row.subtitle = toolshed.t("references"), table.concat(fk.child_columns or {}, ", ") .. " → " .. fk.parent_table + table.insert(jigs, row) + end + end + end + -- The columns are facts to read, nothing to open, so they're a table rather than rows. + local lines = {} + for _, c in ipairs(t.columns or {}) do + local keys = "" + if primary[c.name] then keys = keys .. ' PK' end + if foreign[c.name] then + keys = keys .. ' FK' + end + table.insert(lines, '
' .. escape(c.name) .. "" .. keys .. + '
' .. type_tile(c.type_name) .. '' .. escape(c.type_text or c.type_name) .. + '
' .. escape(c.comment) .. "
") + end + if #lines > 0 then + below = '
' .. + escape(toolshed.t("columns", { count = #lines })) .. "
" .. escape(toolshed.t("fact.type")) .. "
" .. + escape(toolshed.t("fact.comment")) .. "
" .. table.concat(lines) .. "
" + end + if #jigs > 0 then below = below .. rows_at(toolshed.t("references")) end + elseif d.kind == "volume" then + local v = cli(w.name, "volumes", "read", d.name) + html = card(v.full_name, "hard-drive", "red", { + { "fact.type", escape(v.volume_type) }, + { "fact.path", escape("/Volumes/" .. d.name:gsub("%.", "/")) }, + { "fact.comment", v.comment and escape(v.comment) }, + { "fact.owner", escape(v.owner) }, + { "fact.created", v.created_at and escape(when(v.created_at)) }, + { "fact.location", v.storage_location and escape(v.storage_location) }, + }) + else + local what = d.kind == "schema" and cli(w.name, "schemas", "get", d.name) or cli(w.name, "catalogs", "get", d.name) + html = card(d.name, kind_icons[d.kind], "red", { + { "fact.type", d.kind == "catalog" and what.catalog_type and escape(what.catalog_type) }, + { "fact.comment", what.comment and escape(what.comment) }, + { "fact.owner", escape(what.owner) }, + { "fact.created", what.created_at and escape(when(what.created_at)) }, + { "fact.location", what.storage_root and escape(what.storage_root) }, + }) + local section = toolshed.t(d.kind == "schema" and "inside.schema" or "inside.catalog") + if within(w, d.name, section, jigs) > 0 then below = rows_at(section) end + end + return { html = page('
' .. html .. "
" .. below), jigs = jigs } +end + +local function explorer(w, d) + if d.kind == "volume" then return address(w, "/explore/data/volumes/" .. d.name:gsub("%.", "/")) end + return address(w, "/explore/data/" .. d.name:gsub("%.", "/")) +end + +local function task_jig(w, task, section) + local how, tint = status(task.state) + local about = { duration(run_length(task)) } + -- A task tried again is listed once a try, so they're told apart. + if (task.attempt_number or 0) > 0 then table.insert(about, 1, toolshed.t("retry", { count = task.attempt_number })) end + local message = (task.state or {}).state_message + if message and message ~= "" then table.insert(about, message) end + return { + title = task.task_key, subtitle = table.concat(about, " · "), + icon = "play", section = section, tags = { { text = toolshed.t("status." .. how), tint = tint } }, + tool = "run", action = "open", data = { profile = w.name, url = task.run_page_url }, + } +end + +local function run_page(ctx) + local w = workspace(ctx.data.profile) + local run = cli(w.name, "jobs", "get-run", ctx.data.id) + local how, tint = status(run.state) + local figures = '
' .. + '
' .. + escape(toolshed.t("status." .. how)) .. '
' .. escape(toolshed.t("fact.status")) .. "
" .. + '
' .. + escape(when(run.start_time)) .. '
' .. escape(ago(run.start_time)) .. "
" .. + '
' .. + escape(duration(run_length(run))) .. '
' .. escape(toolshed.t("fact.duration")) .. "
" + local message = (run.state or {}).state_message + local note = message and message ~= "" and ('
' .. escape(message) .. "
") or "" + -- A failed run says only to see the output, so the last failed task's error is fetched. + local failed + for _, task in ipairs(run.tasks or {}) do + if status(task.state) == "failed" then failed = task end + end + if failed then + local ok, out = pcall(cli, w.name, "jobs", "get-run-output", string.format("%.0f", failed.run_id)) + if ok and out.error and out.error ~= "" then + note = note .. '
' .. escape(toolshed.t("error-in", { task = failed.task_key })) .. '
' .. + escape(out.error) .. "
" + end + end + local jigs = {} + local section = toolshed.t("tasks", { count = #(run.tasks or {}) }) + for _, task in ipairs(run.tasks or {}) do table.insert(jigs, task_jig(w, task, section)) end + table.insert(jigs, 1, { + title = toolshed.t("action.open-job"), icon = "workflow", tool = "job", + data = { profile = w.name, id = string.format("%.0f", run.job_id), name = run.run_name }, + }) + return { + html = page(figures .. note .. (#jigs > 1 and rows_at(section) or "")), + jigs = jigs, refresh = how == "running" and 10 or nil, + } +end + +local function job_page(ctx) + local w = workspace(ctx.data.profile) + local job = cli(w.name, "jobs", "get", ctx.data.id) + local s = job.settings or {} + local schedule = s.schedule and (s.schedule.quartz_cron_expression .. " · " .. (s.schedule.timezone_id or "") .. + (s.schedule.pause_status == "PAUSED" and (" " .. tag(toolshed.t("paused"), "gray")) or "")) or nil + local html = card(s.name or ctx.data.name, "workflow", "red", { + { "fact.id", escape(ctx.data.id) }, + { "fact.schedule", schedule and escape(schedule) }, + { "fact.tasks", s.tasks and tostring(#s.tasks) }, + { "fact.created", job.created_time and escape(when(job.created_time)) }, + }) + local runs = cli(w.name, "jobs", "list-runs", "--job-id", ctx.data.id, "--limit", "25") + table.sort(runs, function(a, b) return (a.start_time or 0) > (b.start_time or 0) end) + local section = toolshed.t("recent-runs") + local jigs = {} + for _, run in ipairs(runs) do + local row = run_jig(w, run, false) + row.section = section + table.insert(jigs, row) + end + return { html = page('
' .. html .. "
" .. (#jigs > 0 and rows_at(section) or "")), jigs = jigs } +end + +-- dbx ------------------------------------------------------------------------------------------ + +local verbs = { + { name = "search", icon = "search" }, + { name = "runs", icon = "play" }, + { name = "jobs", icon = "workflow" }, +} + +-- verb_rows are the verbs what's typed could become, all of them for nothing: each types itself +-- after dbx, to go on from there. +local function verb_rows(word) + local rows = {} + for _, v in ipairs(verbs) do + if v.name:sub(1, #word) == word 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 + +local function catalog_rows(settings, typed) + if typed == "" then return { problem(toolshed.t("search-hint")) } end + return found(settings, typed, { "catalog", "schema", "table", "volume" }, item_jig) +end + +-- listed is what's typed after dbx: a verb and what to look for, or straight away what to find +-- in the catalogs. A word on its own also offers the verbs it could become ("ru" → runs). +local function listed(rest, settings) + local word, typed = rest:match("^(%S+)%s*(.-)%s*$") + if not word then return verb_rows("") end + word = word:lower() + if word == "search" then return catalog_rows(settings, typed) end + if word == "runs" or word == "run" then return run_rows(settings, typed) end + if word == "jobs" or word == "job" then + return found(settings, typed, { "job" }, job_jig) + end + local rows = typed == "" and verb_rows(word) or {} + for _, row in ipairs(catalog_rows(settings, rest:match("^%s*(.-)%s*$"))) do table.insert(rows, row) end + return rows +end + +local function copy(text) + toolshed.clipboard.copy(text) + return toolshed.t("copied", { text = text }) +end + +return toolshed.toolbox { + key = "databricks", + title = "Databricks", + description = "i18n:toolbox.description", + icon = "assets/databricks.svg", + tint = "red", + requires = { { command = "databricks" }, { command = "jq" }, { path = "~/.databrickscfg" } }, + settings = { + { + key = "workspace", title = "i18n:setting.workspace.title", description = "i18n:setting.workspace.description", + type = "choice", default = "DEFAULT", + options_from = function() + local options = {} + for _, w in ipairs(workspaces()) do + table.insert(options, { value = w.name, title = w.name .. " · " .. w.host:gsub("^https://", "") }) + end + table.insert(options, { value = "*", title = toolshed.t("setting.workspace.all") }) + return options + end, + }, + }, + tools = { + { + key = "search", + title = "i18n:tool.search.title", + description = "i18n:tool.search.description", + words = { "dbx", "databricks" }, + keywords = { "databricks", "unity catalog", "catalog", "table", "schema", "volume", "job", "runs" }, + examples = { "dbx sales", "dbx runs", "dbx runs failed", "dbx jobs ingest" }, + items = true, + search = function(rest, settings) return listed(rest, settings) end, + -- Its rows are the other tools' (a table, a run, a job), which do what they're chosen for. + actions = { { key = "none", title = "i18n:tool.search.title", run = function() end } }, + }, + { + key = "item", title = "i18n:tool.item.title", hidden = true, items = true, + actions = { + { key = "show", title = "i18n:action.show", icon = "info", run = item_page }, + { key = "open", title = "i18n:action.open", icon = "external-link", run = function(ctx) + toolshed.open(explorer(workspace(ctx.data.profile), ctx.data)) + end }, + { key = "copy-name", title = "i18n:action.copy-name", icon = "copy", shortcut = "cmd+shift+c", run = function(ctx) + return copy(ctx.data.name) + end }, + { key = "copy-select", title = "i18n:action.copy-select", icon = "copy", run = function(ctx) + return copy("SELECT * FROM " .. ctx.data.name .. " LIMIT 100") + end }, + { key = "copy-path", title = "i18n:action.copy-path", icon = "copy", run = function(ctx) + return copy("/Volumes/" .. ctx.data.name:gsub("%.", "/")) + end }, + }, + }, + { + key = "run", title = "i18n:tool.run.title", hidden = true, items = true, + actions = { + { key = "show", title = "i18n:action.show", icon = "info", run = run_page }, + { key = "open", title = "i18n:action.open", 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 = "job", title = "i18n:tool.job.title", hidden = true, items = true, + actions = { + { key = "show", title = "i18n:action.show", icon = "info", run = job_page }, + { key = "open", title = "i18n:action.open", icon = "external-link", run = function(ctx) + toolshed.open(address(workspace(ctx.data.profile), "/jobs/" .. ctx.data.id)) + end }, + { key = "copy-name", title = "i18n:action.copy-name", icon = "copy", run = function(ctx) return copy(ctx.data.name) end }, + }, + }, + }, +} diff --git a/databricks/locales/en.toml b/databricks/locales/en.toml new file mode 100644 index 0000000..53b52d8 --- /dev/null +++ b/databricks/locales/en.toml @@ -0,0 +1,209 @@ +[toolbox.description] +other = "Search Unity Catalog's catalogs, schemas, tables and volumes, and see the latest job runs and the jobs, through the Databricks CLI." + +[setting.workspace.title] +other = "Workspace" + +[setting.workspace.description] +other = "Which profile in ~/.databrickscfg to search, or all of them." + +[setting.workspace.all] +other = "All workspaces" + +[tool.search.title] +other = "Databricks" + +[tool.search.description] +other = "Search, Runs and Jobs: dbx sales finds tables, dbx runs lists the latest runs, newest first." + +[tool.item.title] +other = "Unity Catalog" + +[tool.run.title] +other = "Job Run" + +[tool.job.title] +other = "Job" + +[action.show] +other = "Show Details" + +[action.open] +other = "Open in Databricks" + +[action.copy-name] +other = "Copy Name" + +[action.copy-select] +other = "Copy SELECT" + +[action.copy-path] +other = "Copy Path" + +[action.copy-url] +other = "Copy Link" + +[action.open-job] +other = "Open the Job" + +[verb.search.title] +other = "Search" + +[verb.search.description] +other = "Catalogs, schemas, tables and volumes" + +[verb.runs.title] +other = "Runs" + +[verb.runs.description] +other = "The latest job runs, newest first; failed or running filters them" + +[verb.jobs.title] +other = "Jobs" + +[verb.jobs.description] +other = "The jobs, and each one's runs" + +[search-hint] +other = "Type part of a name, like sales or bronze.orders" + +[indexing] +other = "Reading what's in {{.workspace}}, which takes a minute the first time" + +[error.index] +other = "Couldn't read the workspace: {{.reason}}" + +[error.no-profile] +other = "There's no profile {{.profile}} in ~/.databrickscfg" + +[error.no-workspace] +other = "Choose a workspace in Settings" + +[error.runs] +other = "Couldn't get the runs of {{.workspace}}: {{.reason}}" + +[no-runs] +other = "No runs like that among the latest" + +[kind.catalog] +other = "Catalog" + +[kind.schema] +other = "Schema" + +[kind.table] +other = "Table" + +[kind.view] +other = "View" + +[kind.volume] +other = "Volume" + +[job-id] +other = "Job {{.id}}" + +[status.running] +other = "Running" + +[status.succeeded] +other = "Succeeded" + +[status.partly] +other = "Partly failed" + +[status.cancelled] +other = "Cancelled" + +[status.skipped] +other = "Skipped" + +[status.failed] +other = "Failed" + +[ago.now] +other = "Just now" + +[ago.minutes] +other = "{{.count}} min ago" + +[ago.hours] +other = "{{.count}} h ago" + +[ago.days] +other = "{{.count}} d ago" + +[run] +other = "Run" + +[fact.type] +other = "Type" + +[fact.comment] +other = "Comment" + +[fact.owner] +other = "Owner" + +[fact.created] +other = "Created" + +[fact.updated] +other = "Updated" + +[fact.location] +other = "Location" + +[fact.path] +other = "Path" + +[fact.status] +other = "Status" + +[fact.duration] +other = "Duration" + +[fact.id] +other = "ID" + +[fact.schedule] +other = "Schedule" + +[fact.tasks] +other = "Tasks" + +[columns] +other = "Columns ({{.count}})" + +[inside.schema] +other = "Tables and volumes" + +[inside.catalog] +other = "Schemas" + +[tasks] +other = "Tasks ({{.count}})" + +[recent-runs] +other = "Latest runs" + +[paused] +other = "Paused" + +[copied] +other = "Copied {{.text}}" + +[retry] +other = "Retry {{.count}}" + +[error-in] +other = "The error in {{.task}}" + +[references] +other = "References" + +[jobs.index.title] +other = "Indexes {{.workspace}}" + +[jobs.index.description] +other = "Walks the workspace's catalogs, tables and jobs for search" diff --git a/databricks/locales/nb.toml b/databricks/locales/nb.toml new file mode 100644 index 0000000..2002352 --- /dev/null +++ b/databricks/locales/nb.toml @@ -0,0 +1,209 @@ +[toolbox.description] +other = "Søk i Unity Catalogs kataloger, skjemaer, tabeller og volumer, og se de siste jobbkjøringene og jobbene, gjennom Databricks CLI." + +[setting.workspace.title] +other = "Arbeidsområde" + +[setting.workspace.description] +other = "Hvilken profil i ~/.databrickscfg det skal søkes i, eller alle." + +[setting.workspace.all] +other = "Alle arbeidsområder" + +[tool.search.title] +other = "Databricks" + +[tool.search.description] +other = "Søk, kjøringer og jobber: dbx salg finner tabeller, dbx runs viser de siste kjøringene, nyeste først." + +[tool.item.title] +other = "Unity Catalog" + +[tool.run.title] +other = "Jobbkjøring" + +[tool.job.title] +other = "Jobb" + +[action.show] +other = "Vis detaljer" + +[action.open] +other = "Åpne i Databricks" + +[action.copy-name] +other = "Kopier navn" + +[action.copy-select] +other = "Kopier SELECT" + +[action.copy-path] +other = "Kopier sti" + +[action.copy-url] +other = "Kopier lenke" + +[action.open-job] +other = "Åpne jobben" + +[verb.search.title] +other = "Søk" + +[verb.search.description] +other = "Kataloger, skjemaer, tabeller og volumer" + +[verb.runs.title] +other = "Kjøringer" + +[verb.runs.description] +other = "De siste jobbkjøringene, nyeste først; feilet eller kjører filtrerer dem" + +[verb.jobs.title] +other = "Jobber" + +[verb.jobs.description] +other = "Jobbene, og kjøringene til hver" + +[search-hint] +other = "Skriv en del av et navn, som salg eller bronze.orders" + +[indexing] +other = "Leser hva som finnes i {{.workspace}}, som tar et minutt første gang" + +[error.index] +other = "Klarte ikke å lese arbeidsområdet: {{.reason}}" + +[error.no-profile] +other = "Det finnes ingen profil {{.profile}} i ~/.databrickscfg" + +[error.no-workspace] +other = "Velg et arbeidsområde i Innstillinger" + +[error.runs] +other = "Klarte ikke å hente kjøringene i {{.workspace}}: {{.reason}}" + +[no-runs] +other = "Ingen slike kjøringer blant de siste" + +[kind.catalog] +other = "Katalog" + +[kind.schema] +other = "Skjema" + +[kind.table] +other = "Tabell" + +[kind.view] +other = "Visning" + +[kind.volume] +other = "Volum" + +[job-id] +other = "Jobb {{.id}}" + +[status.running] +other = "Kjører" + +[status.succeeded] +other = "Vellykket" + +[status.partly] +other = "Delvis feilet" + +[status.cancelled] +other = "Avbrutt" + +[status.skipped] +other = "Hoppet over" + +[status.failed] +other = "Feilet" + +[ago.now] +other = "Akkurat nå" + +[ago.minutes] +other = "for {{.count}} min siden" + +[ago.hours] +other = "for {{.count}} t siden" + +[ago.days] +other = "for {{.count}} d siden" + +[run] +other = "Kjøring" + +[fact.type] +other = "Type" + +[fact.comment] +other = "Kommentar" + +[fact.owner] +other = "Eier" + +[fact.created] +other = "Opprettet" + +[fact.updated] +other = "Endret" + +[fact.location] +other = "Lagring" + +[fact.path] +other = "Sti" + +[fact.status] +other = "Status" + +[fact.duration] +other = "Varighet" + +[fact.id] +other = "ID" + +[fact.schedule] +other = "Tidsplan" + +[fact.tasks] +other = "Oppgaver" + +[columns] +other = "Kolonner ({{.count}})" + +[inside.schema] +other = "Tabeller og volumer" + +[inside.catalog] +other = "Skjemaer" + +[tasks] +other = "Oppgaver ({{.count}})" + +[recent-runs] +other = "Siste kjøringer" + +[paused] +other = "Pauset" + +[copied] +other = "Kopierte {{.text}}" + +[retry] +other = "Forsøk {{.count}}" + +[error-in] +other = "Feilen i {{.task}}" + +[references] +other = "Refererer til" + +[jobs.index.title] +other = "Indekserer {{.workspace}}" + +[jobs.index.description] +other = "Går gjennom arbeidsområdets kataloger, tabeller og jobber for søk" diff --git a/docker/init.lua b/docker/init.lua new file mode 100644 index 0000000..dd4be94 --- /dev/null +++ b/docker/init.lua @@ -0,0 +1,782 @@ +-- Docker: "docker" lists compose projects and containers, "docker web" finds them by name, image, +-- project or service. A container's details, logs and stats are pages a level down; Docker +-- Dashboard shows every container, with what the running ones use, updating as it goes; Docker +-- Prune frees space, saying how much each kind would free first. Everything goes through the docker command, so Podman or Colima +-- work too, by setting their command. Its text is in locales/. + +local function docker(settings) + local command = settings.command + return (command and command ~= "") and command or "docker" +end + +local function run(settings, ...) + return toolshed.exec({ docker(settings), ... }) +end + +local function lines(text) + local out = {} + for line in text:gmatch("[^\n]+") do table.insert(out, line) end + return out +end + +-- Each line docker prints with --format '{{json .}}' is one JSON object. +local function json_lines(text) + local out = {} + for _, line in ipairs(lines(text)) do table.insert(out, toolshed.json.decode(line)) end + return out +end + +local escape = toolshed.escape + +-- Numbers worked out here are written as the language writes them: 1.5 in English, 1,5 in Norwegian. +local function localised(text) + return (text:gsub("%.", toolshed.t("decimal"))) +end + +-- A compose label's value. Labels are "k=v,k=v", and only these, whose values hold no commas, are read. +local function label(labels, key) + return (labels or ""):match("com%.docker%.compose%." .. key:gsub("%.", "%%.") .. "=([^,]*)") +end + +-- The ports a container publishes on this Mac, once each: "0.0.0.0:3000->3000/tcp, :::3000->3000/tcp". +local function published(ports) + local out, seen = {}, {} + for host, inside, proto in (ports or ""):gmatch(":(%d+)%->(%d+)/(%a+)") do + if not seen[host] then + seen[host] = true + table.insert(out, { host = host, inside = inside, proto = proto }) + end + end + return out +end + +local function containers(settings) + local out = {} + for _, c in ipairs(json_lines(run(settings, "ps", "-a", "--no-trunc", "--format", "{{json .}}"))) do + table.insert(out, { + id = c.ID:sub(1, 12), name = c.Names, image = c.Image, state = c.State, status = c.Status, + ports = published(c.Ports), + project = label(c.Labels, "project"), service = label(c.Labels, "service"), + folder = label(c.Labels, "project.working_dir"), + }) + end + table.sort(out, function(a, b) + if (a.state == "running") ~= (b.state == "running") then return a.state == "running" end + return a.name < b.name + end) + return out +end + +local function projects(list) + local out, by = {}, {} + for _, c in ipairs(list) do + if c.project then + local p = by[c.project] + if not p then + p = { name = c.project, folder = c.folder, containers = {}, running = 0 } + by[c.project] = p + table.insert(out, p) + end + table.insert(p.containers, c) + if c.state == "running" then p.running = p.running + 1 end + end + end + table.sort(out, function(a, b) return a.name < b.name end) + return out +end + +local function ports_text(c) + local out = {} + for _, p in ipairs(c.ports) do table.insert(out, ":" .. p.host) end + return table.concat(out, " ") +end + +-- The jig for a container, offering the actions that fit its state. +local function container_jig(c) + local actions = { "details", "logs", "copy-id", "remove" } + if c.state == "running" then + for _, a in ipairs({ "shell", "stop", "restart", "follow-logs" }) do table.insert(actions, a) end + if #c.ports > 0 then table.insert(actions, "open-port") end + else + table.insert(actions, "start") + end + local where = c.project and (toolshed.t("service-in", { service = c.service, project = c.project }) .. ", ") or "" + local ports = ports_text(c) + return { + title = c.name, icon = "container", tool = "containers", actions = actions, + subtitle = where .. c.status .. (ports ~= "" and (" " .. ports) or ""), + data = { id = c.id, name = c.name }, + } +end + +local function project_jig(p) + return { + title = p.name, icon = "boxes", tool = "project", + subtitle = toolshed.t("running-of", { running = p.running, total = #p.containers }), + data = { name = p.name, folder = p.folder }, + } +end + +-- What to show when docker can't be asked: usually Docker Desktop isn't running. +local function unavailable(err) + local reason = tostring(err):match("[^\n]+") or "" + return { + title = toolshed.t("not-running"), icon = "container", tool = "desktop", + subtitle = reason ~= "" and reason or toolshed.t("open-desktop"), + } +end + +-- Opens a Terminal window running command: a .command file, which macOS opens in Terminal +-- without asking for permission to control it. +local function in_terminal(name, command) + local path = toolshed.cache_dir() .. "/" .. name:gsub("[^%w%-_]", "_") .. ".command" + local f = assert(io.open(path, "w")) + f:write("#!/bin/sh\nclear\nexec " .. command .. "\n") + f:close() + toolshed.exec({ "chmod", "+x", path }) + toolshed.open(path) +end + +local quoted = toolshed.shell_quote + +-- Runs a docker command that may take longer than an action may (pulling images), and returns +-- straight away: it shows in Active while it runs, titled as said, and says why if it fails; +-- Docker shows the outcome in the list. +local function compose_key(project) return "compose-" .. project:lower():gsub("[^%w_-]", "-") end + +local function in_background(settings, key, title, ...) + toolshed.activities.set { + key = key, title = title, icon = "container", timeout = 1800, + run = { docker(settings), ... }, ending = { failed = title }, + } +end + +-- Sizes as docker prints them ("20.5MiB", "1.2GB") in bytes, to add them up. +local units = { B = 1, kB = 1e3, KB = 1e3, MB = 1e6, GB = 1e9, TB = 1e12, KiB = 1024, MiB = 1024 ^ 2, GiB = 1024 ^ 3, TiB = 1024 ^ 4 } +local function bytes(text) + local n, unit = (text or ""):match("([%d%.]+)%s*(%a+)") + return (tonumber(n or "") or 0) * (units[unit or ""] or 0) +end + +-- decimal writes bytes as docker does: "1.2GB", "300MB". +local function decimal(n) + for _, u in ipairs({ { "TB", 1e12 }, { "GB", 1e9 }, { "MB", 1e6 }, { "kB", 1e3 } }) do + if n >= u[2] then return localised(string.format("%.3g", n / u[2])) .. u[1] end + end + return string.format("%dB", n) +end + +-- What dangling images take, the ones no tag points to. +local function dangling_images(settings) + local total = 0 + local ok, out = pcall(run, settings, "images", "-f", "dangling=true", "--format", "{{.Size}}") + for _, line in ipairs(ok and lines(out) or {}) do total = total + bytes(line) end + return total +end + +local function size(n) + for _, u in ipairs({ { "GiB", 1024 ^ 3 }, { "MiB", 1024 ^ 2 }, { "KiB", 1024 } }) do + if n >= u[2] then return localised(string.format("%.1f %s", n / u[2], u[1])) end + end + return string.format("%d B", n) +end + +-- Pages are drawn in the launcher's own terms: its type sizes, colours and rounded rows, no +-- Pages use the launcher's page classes (docs/extensions.md), so they look like the rest of the +-- app: its icons by name, its tints, sparklines drawn from their values. +local function page(body) + return '
' .. body .. "
" +end + +local function tile(icon, small) + return '' +end + +-- sparkline is how values went, the latest last; percentages are drawn from zero. +local function sparkline(values, from_zero) + if not values or #values < 2 then return "" end + local text = {} + for _, v in ipairs(values) do table.insert(text, string.format("%.4g", v)) end + return '" +end + +-- split shows how many of a whole are on: a segment each, lit for those running. +local function split(on, total) + local out = {} + for i = 1, math.min(total, 40) do table.insert(out, i <= on and '' or "") end + return '
' .. table.concat(out) .. "
" +end + +-- figures are the numbers at the top of a page, each { label, value, icon, tint, history }; the +-- value is HTML, for a quieter part like "of 4". +local function figures(list) + local out = {} + for _, f in ipairs(list) do + table.insert(out, '
' .. tile(f[3]) .. '
' .. f[2] .. + '
' .. escape(f[1]) .. "
" .. (f.under or sparkline(f[5], f.from_zero)) .. "
") + end + return '
' .. table.concat(out) .. "
" +end + +local function dot(state) + return '' +end + +local function meter(part) + return '' +end + +-- The columns of the container lines: name, CPU, memory, network, ports. +local columns = "minmax(0, 1fr) 96px 104px 108px 92px" + +-- Docker takes a second or two to measure what containers use, so it measures in the background +-- and pages show the latest measurement, at most one refresh old. +local stats_file = toolshed.cache_dir() .. "/stats.json" + +local modified = toolshed.file.modified + +local function measure(settings) + toolshed.activities.set { + key = "stats", title = toolshed.t("jobs.stats.title"), description = toolshed.t("jobs.stats.description"), quiet = true, timeout = 30, + run = { "sh", "-c", '"$0" stats --no-stream --format "{{json .}}" > "$1.part" && mv "$1.part" "$1"', docker(settings), stats_file }, + } +end + +local function percent(text) + return tonumber((text or ""):match("([%d%.]+)") or "") or 0 +end + +-- What was measured lately, a minute's worth, by what it's of ("cpu", or a container's +-- "cpu:"), to draw how it changed. A measurement counts once, however often it's read; +-- without one (at), these only read what's kept. +local history = {} +local function remember(key, at, value) + local h = history[key] or { values = {} } + history[key] = h + if at and h.at ~= at then + h.at = at + table.insert(h.values, value) + if #h.values > 20 then table.remove(h.values, 1) end + end + return h.values +end + +-- rates are how fast a growing total went, per second, between the measurements remembered. +local totals = {} +local function rates(key, at, total) + local h = totals[key] or {} + totals[key] = h + if at and (#h == 0 or h[#h].at ~= at) then + table.insert(h, { at = at, total = total }) + if #h > 21 then table.remove(h, 1) end + end + local out = {} + for i = 2, #h do + local seconds = h[i].at - h[i - 1].at + if seconds > 0 then table.insert(out, math.max(h[i].total - h[i - 1].total, 0) / seconds) end + end + return out +end + +-- in_and_out is what docker's "1.2MB / 3.4MB" adds up to. +local function in_and_out(text) + local a, b = (text or ""):match("^(.-)%s*/%s*(.-)$") + return bytes(a) + bytes(b) +end + +-- latest_stats is what running containers used when last measured, by ID, and whether that's +-- recent enough to show. It starts the next measurement. +local function latest_stats(settings) + measure(settings) + local by = {} + local at = modified(stats_file) + if not at or os.time() - at > 60 then return by, false end + local f = io.open(stats_file, "r") + if not f then return by, false end + local text = f:read("*a") + f:close() + local ok, list = pcall(json_lines, text) + local cpu, memory = 0, 0 + for _, s in ipairs(ok and list or {}) do + local id = s.ID:sub(1, 12) + by[id] = s + -- Kept for every container, so a page opened later already has the last minute to draw. + remember("cpu:" .. id, at, percent(s.CPUPerc)) + remember("memory:" .. id, at, bytes(s.MemUsage)) + rates("net:" .. id, at, in_and_out(s.NetIO)) + cpu, memory = cpu + percent(s.CPUPerc), memory + bytes(s.MemUsage) + end + remember("cpu", at, cpu) + remember("memory", at, memory) + return by, true, at +end + + +local function find(settings, id) + for _, c in ipairs(containers(settings)) do + if c.id == id then return c end + end + error(toolshed.t("gone")) +end + +local function port_jigs(c) + local out = {} + for _, p in ipairs(c.ports) do + table.insert(out, { + title = toolshed.t("open-localhost", { port = p.host }), icon = "external-link", tool = "port", + subtitle = toolshed.t("port-inside", { port = p.inside, proto = p.proto }), data = { port = p.host }, + }) + end + return out +end + +local function logs_page(title, text) + local tail = {} + local all = lines(text) + for i = math.max(1, #all - 199), #all do table.insert(tail, all[i]) end + if #tail == 0 then return page('
' .. escape(toolshed.t("no-logs")) .. "
") end + -- Starts scrolled to the end, where the newest lines are. + return page('
' .. escape(toolshed.t("last-lines", { count = #tail })) .. '
' .. escape(table.concat(tail, "\n")) ..
+    '
') +end + +-- overview draws containers as Docker Dashboard does: figures for what runs, with how CPU and +-- memory went (the histories), then a line each, projects with their services hanging from them. +-- Each line is a jig the page draws itself, selected and run as the list's are. The Dashboard +-- shows every container; a project's page only its own, and is about it: its line does what's +-- done with the project, where showing its services again would only open this page. +local function overview(list, settings, cpu_history, memory_history, about) + local stats, measured = latest_stats(settings) + local function usage(c) + local s = stats[c.id] or { CPUPerc = "…", MemUsage = "…", MemPerc = "0", NetIO = "…" } + c.cpu, c.memory, c.stats = percent(s.CPUPerc), bytes(s.MemUsage), s + end + -- Running first, the busiest first; stopped ones after, by name, to start again. + local function order(a, b) + local ar, br = a.state == "running", b.state == "running" + if ar ~= br then return ar end + if ar and a.cpu ~= b.cpu then return a.cpu > b.cpu end + return a.name < b.name + end + -- Containers outside a project first, then each project with its services under it, as + -- Docker Desktop shows them. + local alone, cpu, memory, count = {}, 0, 0, 0 + for _, c in ipairs(list) do + c.cpu, c.memory = 0, 0 + if c.state == "running" then + usage(c) + cpu, memory, count = cpu + c.cpu, memory + c.memory, count + 1 + end + if not c.project then table.insert(alone, c) end + end + table.sort(alone, order) + local measure = function(text) return measured and text or "…" end + local function metric(text, part) + return measure('
' .. meter(part) .. "" .. text .. "
") + end + local lines, jigs, folder = {}, {}, nil + -- Each line is a jig the page draws itself (data-jig), selected and run as the list's are. + -- A stopped one uses nothing, so it shows a dash where the numbers go. + local function add(jig, class, running, name, extra, cpu_text, cpu, memory, part, net, ports) + table.insert(jigs, jig) + local none = '—' + local classes = ("line " .. class .. (running and "" or " muted")):gsub("%s+", " ") + table.insert(lines, '
' .. dot(running and "running" or "stopped") .. '' .. name .. "" .. extra .. + '
' .. (running and metric(cpu_text, cpu) or none) .. + '
' .. (running and metric(size(memory), part) or none) .. + '
' .. (running and net or none) .. '
' .. ports .. "
") + end + local function container(c, class, name) + local running = c.state == "running" + add(container_jig(c), class, running, escape(name), "", running and escape(c.stats.CPUPerc), c.cpu, c.memory, + running and percent(c.stats.MemPerc), running and measure(escape(c.stats.NetIO)), escape(ports_text(c))) + end + for _, c in ipairs(alone) do container(c, "", c.name) end + for _, p in ipairs(projects(list)) do + local services, pcpu, pmemory, part = {}, 0, 0, 0 + for _, c in ipairs(p.containers) do + table.insert(services, c) + if c.state == "running" then + pcpu, pmemory, part = pcpu + c.cpu, pmemory + c.memory, part + percent(c.stats.MemPerc) + end + end + table.sort(services, order) + local jig, extra = project_jig(p), '' .. escape(toolshed.t("count-of", { running = p.running, total = #p.containers })) .. "" + if p.name == about then + jig.action, jig.actions = "logs", { "logs", "restart", "up", "down", "open-folder", "copy-name" } + folder = p.folder + end + add(jig, "parent", p.running > 0, escape(p.name), extra, localised(string.format("%.2f%%", pcpu)), pcpu, pmemory, part, "", "") + for i, c in ipairs(services) do + -- Under its project a container is its service: "db", not "shop-db-1". + container(c, i == #services and "child last" or "child", c.service or c.name) + end + end + if #list == 0 then return { html = page('
' .. escape(toolshed.t("no-containers")) .. "
"), refresh = 3 } end + local top = figures({ + { toolshed.t("running"), count .. (#list > count and (" " .. escape(toolshed.t("of", { total = #list })) .. "") or ""), "container", "green", under = split(count, #list) }, + { toolshed.t("cpu"), measured and localised(string.format("%.1f%%", cpu)) or "…", "cpu", "blue", measured and cpu_history, from_zero = true }, + { toolshed.t("memory"), measured and size(memory) or "…", "memory-stick", "purple", measured and memory_history }, + }) + local head = '
' .. escape(toolshed.t("name")) .. '
' .. escape(toolshed.t("cpu")) .. + '
' .. escape(toolshed.t("memory")) .. '
' .. escape(toolshed.t("net-in-out")) .. + "
" .. escape(toolshed.t("ports")) .. "
" + -- A project's folder has a line of its own: in its line it would crowd out the name. + local home = os.getenv("HOME") or "" + local place = (folder and folder ~= "") and ('
' .. tile("folder", true) .. "" .. + escape(home ~= "" and folder:sub(1, #home) == home and ("~" .. folder:sub(#home + 1)) or folder) .. "
") or "" + return { + html = page(top .. place .. '
' .. head .. table.concat(lines) .. "
"), + jigs = jigs, refresh = measured and 3 or 1, + } +end + +-- Each prune's title and question are in locales/, under its key. +local prunes = { + { key = "containers", args = { "container", "prune", "-f" } }, + { key = "dangling", args = { "image", "prune", "-f" } }, + { key = "images", args = { "image", "prune", "-a", "-f" } }, + { key = "volumes", args = { "volume", "prune", "-a", "-f" } }, + { key = "cache", args = { "builder", "prune", "-f" } }, + { key = "everything", args = { "system", "prune", "-f" } }, +} + +-- The kinds of space docker system df reports, each a jig whose Enter runs its own prune; ⌘K +-- offers the others that fit it, and Everything, which covers them all. +local kinds = { + ["Images"] = { key = "images", icon = "layers", prunes = { "dangling", "images" } }, + ["Containers"] = { key = "containers", icon = "container", prunes = { "containers" } }, + ["Local Volumes"] = { key = "volumes", icon = "hard-drive", prunes = { "volumes" } }, + ["Build Cache"] = { key = "cache", icon = "boxes", prunes = { "cache" } }, +} + +local show_space = { + { + key = "show", title = "i18n:action.prune.show", icon = "hard-drive", + run = function(ctx) + local dangling = dangling_images(ctx.settings) + -- What Everything frees: stopped containers, dangling images and the build cache. Unused + -- networks take no space to speak of. + local everything = dangling + local jigs = {} + for _, d in ipairs(json_lines(run(ctx.settings, "system", "df", "--format", "{{json .}}"))) do + local kind = kinds[d.Type] + if kind then + local actions = { unpack(kind.prunes) } + table.insert(actions, "everything") + -- Only what its prunes would remove: what stays isn't the question here. + local reclaimable = bytes(d.Reclaimable) + local unused = (tonumber(d.TotalCount) or 0) - (tonumber(d.Active) or 0) + local freed + if d.Type == "Images" then + -- df counts every unused image; Enter on Images prunes only the dangling ones. + freed = (dangling + reclaimable > 0) and toolshed.t("free-images", { dangling = decimal(dangling), unused = decimal(reclaimable) }) + elseif reclaimable > 0 then + local counted = ({ ["Containers"] = "free-stopped", ["Local Volumes"] = "free-unused" })[d.Type] or "free" + freed = toolshed.t(counted, { count = unused, size = decimal(reclaimable) }) + end + if d.Type == "Containers" or d.Type == "Build Cache" then everything = everything + reclaimable end + table.insert(jigs, { + title = toolshed.t("kind." .. kind.key), icon = kind.icon, tool = "space", action = kind.prunes[1], actions = actions, + subtitle = freed or toolshed.t("nothing-to-free"), + }) + end + end + table.insert(jigs, 1, { + title = toolshed.t("kind.everything"), icon = "eraser", tool = "space", action = "everything", actions = { "everything" }, + subtitle = toolshed.t("free-everything", { size = decimal(everything) }), + }) + return { jigs = jigs } + end, + }, +} +local function prune_action(p) + return { + key = p.key, title = "i18n:action.space." .. p.key, icon = "eraser", confirm = "i18n:confirm.space." .. p.key, never_default = true, + run = function(ctx) + local out = run(ctx.settings, unpack(p.args)) + local freed = out:match("Total reclaimed space:%s*([^\n]+)") or "0B" + return toolshed.t("freed", { size = freed }) + end, + } +end + +-- The prunes are the actions of a kind of space, not of Docker Prune, which shows them. +local prune_actions = {} +for _, p in ipairs(prunes) do table.insert(prune_actions, prune_action(p)) end + +return toolshed.toolbox { + key = "docker", + title = "Docker", + description = "i18n:toolbox.description", + icon = "container", + tint = "blue", + + settings = { + { key = "command", title = "i18n:setting.command.title", description = "i18n:setting.command.description", + type = "text", default = "docker", placeholder = "docker" }, + }, + requires = { { command = "docker", setting = "command" } }, + + tools = { + { + key = "containers", + title = "Docker", + description = "i18n:tool.containers.description", + words = { "docker" }, + examples = { "docker", "docker web" }, + keywords = { "containers", "compose", "containere" }, + items = true, + + search = function(rest, settings) + local ok, list = pcall(containers, settings) + if not ok then return { unavailable(list) } end + local jigs = {} + for _, p in ipairs(projects(list)) do + if toolshed.match(rest, p.name) > 0 then table.insert(jigs, project_jig(p)) end + end + for _, c in ipairs(list) do + local text = table.concat({ c.name, c.image, c.project or "", c.service or "" }, " ") + -- Without a search, a project's containers are found inside it rather than listed again. + if (rest ~= "" or not c.project) and toolshed.match(rest, text) > 0 then + table.insert(jigs, container_jig(c)) + end + end + return jigs + end, + + actions = { + { + key = "details", title = "i18n:action.containers.details", icon = "info", + run = function(ctx) + local c = find(ctx.settings, ctx.data.id) + local running = c.state == "running" + local s, at + if running then + local by, _, measured_at = latest_stats(ctx.settings) + s, at = by[c.id], measured_at + end + local top = "" + if running then + local cpu, memory, network = remember("cpu:" .. c.id), remember("memory:" .. c.id), rates("net:" .. c.id) + top = figures({ + { toolshed.t("cpu"), s and escape(s.CPUPerc) or "…", "cpu", "blue", cpu, from_zero = true }, + { toolshed.t("memory"), s and size(bytes(s.MemUsage)) or "…", "memory-stick", "purple", memory }, + { toolshed.t("network"), #network > 0 and (decimal(network[#network]) .. "/s") or "…", "network", "teal", network, from_zero = true }, + }) + end + local function card(title, icon, tint, facts, wide) + local rows = {} + for _, f in ipairs(facts) do table.insert(rows, "
" .. escape(toolshed.t(f[1])) .. "
" .. f[2] .. "
") end + return '
' .. + tile(icon, true) .. escape(toolshed.t(title)) .. '
' .. table.concat(rows) .. "
" + end + local long = function(text) return '' .. escape(text) .. "" end + local split_io = function(text) return (text or ""):match("^(.-)%s*/%s*(.-)$") end + -- Titles and labels are keys in locales/. + local cards = { card("container", "info", "gray", { + { "state", dot(c.state) .. escape(c.status) }, { "image", long(c.image) }, { "id", escape(c.id) }, + }, not c.project) } + if c.project then + table.insert(cards, card("compose", "boxes", "orange", { { "project", escape(c.project) }, { "service", escape(c.service or "") } })) + end + local received, sent = split_io(s and s.NetIO) + local net = { { "ports", #c.ports > 0 and escape(ports_text(c)) or escape(toolshed.t("none-published")) } } + if s then + table.insert(net, { "received", escape(received) }) + table.insert(net, { "sent", escape(sent) }) + end + table.insert(cards, card("network", "network", "teal", net, not s)) + if s then + local read, written = split_io(s.BlockIO) + table.insert(cards, card("storage", "hard-drive", "yellow", { { "read", escape(read) }, { "written", escape(written) } })) + end + -- What to do with the container is in ⌘K: a page without jigs of its own is about the + -- jig that opened it. + return { + html = page(top .. '
' .. table.concat(cards) .. "
"), + refresh = (running and not s) and 1 or 5, + } + end, + }, + { + key = "logs", title = "i18n:action.containers.logs", icon = "scroll-text", + run = function(ctx) + -- Containers log to stderr as often as stdout, so both are read. + local text = toolshed.exec({ "sh", "-c", '"$0" logs --tail 200 "$1" 2>&1', docker(ctx.settings), ctx.data.id }) + return { html = logs_page(ctx.data.name, text), refresh = 2 } + end, + }, + { + key = "open-port", title = "i18n:action.containers.open-port", icon = "external-link", + run = function(ctx) + local c = find(ctx.settings, ctx.data.id) + if #c.ports == 0 then error(toolshed.t("no-ports", { name = c.name })) end + if #c.ports == 1 then + toolshed.open("http://localhost:" .. c.ports[1].host) + return + end + return { jigs = port_jigs(c) } + end, + }, + { + key = "shell", title = "i18n:action.containers.shell", icon = "terminal", + run = function(ctx) + in_terminal("shell-" .. ctx.data.name, quoted(docker(ctx.settings)) .. " exec -it " .. quoted(ctx.data.id) .. + " sh -c 'command -v bash >/dev/null && exec bash || exec sh'") + end, + }, + { + key = "follow-logs", title = "i18n:action.containers.follow-logs", icon = "scroll-text", + run = function(ctx) + in_terminal("logs-" .. ctx.data.name, quoted(docker(ctx.settings)) .. " logs -f --tail 100 " .. quoted(ctx.data.id)) + end, + }, + { key = "start", title = "i18n:action.containers.start", icon = "play", run = function(ctx) run(ctx.settings, "start", ctx.data.id); return toolshed.t("started", { name = ctx.data.name }) end }, + { key = "stop", title = "i18n:action.containers.stop", icon = "square", run = function(ctx) run(ctx.settings, "stop", ctx.data.id); return toolshed.t("stopped", { name = ctx.data.name }) end }, + { key = "restart", title = "i18n:action.containers.restart", icon = "rotate-cw", run = function(ctx) run(ctx.settings, "restart", ctx.data.id); return toolshed.t("restarted", { name = ctx.data.name }) end }, + { + key = "remove", title = "i18n:action.containers.remove", icon = "trash-2", never_default = true, + confirm = "i18n:confirm.containers.remove", + run = function(ctx) run(ctx.settings, "rm", "-f", ctx.data.id); return toolshed.t("removed", { name = ctx.data.name }) end, + }, + { + key = "copy-id", title = "i18n:action.containers.copy-id", icon = "copy", + run = function(ctx) toolshed.clipboard.copy(ctx.data.id); return toolshed.t("copied", { text = ctx.data.id }) end, + }, + }, + }, + { + key = "project", + title = "i18n:tool.project.title", + hidden = true, + items = true, + actions = { + { + key = "details", title = "i18n:action.project.details", icon = "boxes", + run = function(ctx) + local list = {} + for _, c in ipairs(containers(ctx.settings)) do + if c.project == ctx.data.name then table.insert(list, c) end + end + -- Its figures' lines add up what its containers did, measurement by measurement. + local function summed(what) + local out = {} + for _, c in ipairs(list) do + local values = remember(what .. ":" .. c.id) + for i = 1, #values do + local at = #out - #values + i + if at < 1 then table.insert(out, 1, 0); at = 1 end + out[at] = out[at] + values[i] + end + end + return out + end + return overview(list, ctx.settings, summed("cpu"), summed("memory"), ctx.data.name) + end, + }, + { + key = "logs", title = "i18n:action.project.logs", icon = "scroll-text", + run = function(ctx) + local text = toolshed.exec({ "sh", "-c", '"$0" compose -p "$1" logs --tail 200 --no-color 2>&1', docker(ctx.settings), ctx.data.name }) + return { html = logs_page(ctx.data.name, text), refresh = 2 } + end, + }, + { + key = "up", title = "i18n:action.project.up", icon = "play", + run = function(ctx) + if not ctx.data.folder or ctx.data.folder == "" then error(toolshed.t("no-folder", { name = ctx.data.name })) end + local said = toolshed.t("starting", { name = ctx.data.name }) + in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "--project-directory", ctx.data.folder, "up", "-d") + return said + end, + }, + { + key = "restart", title = "i18n:action.project.restart", icon = "rotate-cw", + run = function(ctx) + local said = toolshed.t("restarting", { name = ctx.data.name }) + in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "restart") + return said + end, + }, + { + key = "down", title = "i18n:action.project.down", icon = "square", never_default = true, + confirm = "i18n:confirm.project.down", + run = function(ctx) + local said = toolshed.t("taking-down", { name = ctx.data.name }) + in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "down") + return said + end, + }, + { + key = "open-folder", title = "i18n:action.project.open-folder", icon = "folder-open", + run = function(ctx) + if not ctx.data.folder or ctx.data.folder == "" then error(toolshed.t("no-folder", { name = ctx.data.name })) end + toolshed.open(ctx.data.folder) + end, + }, + { + key = "copy-name", title = "i18n:action.project.copy-name", icon = "copy", + run = function(ctx) toolshed.clipboard.copy(ctx.data.name); return toolshed.t("copied", { text = ctx.data.name }) end, + }, + }, + }, + { + key = "port", + title = "i18n:tool.port.title", + hidden = true, + items = true, + actions = { + { key = "open", title = "i18n:action.port.open", icon = "external-link", run = function(ctx) toolshed.open("http://localhost:" .. ctx.data.port) end }, + { + key = "copy-address", title = "i18n:action.port.copy-address", icon = "copy", + run = function(ctx) + toolshed.clipboard.copy("http://localhost:" .. ctx.data.port) + return toolshed.t("copied", { text = "localhost:" .. ctx.data.port }) + end, + }, + }, + }, + { + key = "desktop", + title = "Docker Desktop", + hidden = true, + actions = { + { key = "open", title = "i18n:action.desktop.open", icon = "container", run = function() toolshed.exec({ "open", "-a", "Docker" }) end }, + }, + }, + { + key = "dashboard", + title = "i18n:tool.dashboard.title", + description = "i18n:tool.dashboard.description", + icon = "gauge", + keywords = { "docker", "containers", "stats", "cpu", "memory", "usage", "overview", "oversikt", "minne" }, + actions = { + { + key = "show", title = "i18n:action.dashboard.show", icon = "gauge", + run = function(ctx) + local ok, list = pcall(containers, ctx.settings) + if not ok then return { jigs = { unavailable(list) } } end + return overview(list, ctx.settings, remember("cpu"), remember("memory")) + end, + }, + }, + }, + { + key = "prune", + title = "i18n:tool.prune.title", + description = "i18n:tool.prune.description", + icon = "eraser", + keywords = { "docker", "clean", "space", "disk", "remove", "rydd", "plass" }, + actions = show_space, + }, + { + key = "space", + title = "i18n:tool.space.title", + hidden = true, + items = true, + actions = prune_actions, + }, + }, +} diff --git a/docker/locales/en.toml b/docker/locales/en.toml new file mode 100644 index 0000000..abb08a5 --- /dev/null +++ b/docker/locales/en.toml @@ -0,0 +1,311 @@ +[toolbox.description] +other = "Containers and compose projects: start, stop, logs, shells, live stats and pruning" + +[setting.command.title] +other = "Docker command" + +[setting.command.description] +other = "The docker command to run, or a compatible one like podman" + +[tool.containers.description] +other = "Finds containers and compose projects by name, image, project or service" + +[tool.project.title] +other = "Compose Project" + +[tool.port.title] +other = "Container Port" + +[tool.dashboard.title] +other = "Docker Dashboard" + +[tool.dashboard.description] +other = "Every container and compose project, with what the running ones use, updating as it goes" + +[tool.prune.title] +other = "Docker Prune" + +[tool.prune.description] +other = "Frees space: stopped containers, unused images and volumes, the build cache" + +[tool.space.title] +other = "Docker Space" + +[action.containers.details] +other = "Show Details" + +[action.containers.logs] +other = "Show Logs" + +[action.containers.open-port] +other = "Open Port" + +[action.containers.shell] +other = "Open Shell" + +[action.containers.follow-logs] +other = "Follow Logs in Terminal" + +[action.containers.start] +other = "Start" + +[action.containers.stop] +other = "Stop" + +[action.containers.restart] +other = "Restart" + +[action.containers.remove] +other = "Remove" + +[action.containers.copy-id] +other = "Copy ID" + +[confirm.containers.remove] +other = "Remove this container? What it keeps outside a volume is lost." + +[action.project.details] +other = "Show Services" + +[action.project.logs] +other = "Show Logs" + +[action.project.up] +other = "Up" + +[action.project.restart] +other = "Restart" + +[action.project.down] +other = "Down" + +[confirm.project.down] +other = "Stop and remove this project's containers?" + +[action.project.open-folder] +other = "Open Folder" + +[action.project.copy-name] +other = "Copy Name" + +[action.port.open] +other = "Open in Browser" + +[action.port.copy-address] +other = "Copy Address" + +[action.desktop.open] +other = "Open Docker Desktop" + +[action.dashboard.show] +other = "Show Dashboard" + +[action.prune.show] +other = "Show Space Used" + +[action.space.containers] +other = "Prune Stopped Containers" + +[action.space.dangling] +other = "Prune Dangling Images" + +[action.space.images] +other = "Prune All Unused Images" + +[action.space.volumes] +other = "Prune Unused Volumes" + +[action.space.cache] +other = "Prune Build Cache" + +[action.space.everything] +other = "Prune Everything" + +[confirm.space.containers] +other = "Remove every stopped container?" + +[confirm.space.dangling] +other = "Remove images no tag points to?" + +[confirm.space.images] +other = "Remove every image no container uses? They're downloaded or built again when needed." + +[confirm.space.volumes] +other = "Remove every volume no container uses, with the data in it?" + +[confirm.space.cache] +other = "Clear the build cache? Builds take longer until it fills again." + +[confirm.space.everything] +other = "Remove stopped containers, unused networks, dangling images and the build cache?" + +[decimal] +other = "." + +[service-in] +other = "{{.service}} in {{.project}}" + +[running-of] +other = "{{.running}} of {{.total}} running" + +[count-of] +other = "{{.running}} of {{.total}}" + +[of] +other = "of {{.total}}" + +[not-running] +other = "Docker isn't running" + +[open-desktop] +other = "Open Docker Desktop" + +[gone] +other = "That container is gone" + +[open-localhost] +other = "Open localhost:{{.port}}" + +[port-inside] +other = "{{.port}}/{{.proto}} inside" + +[no-logs] +other = "No logs yet" + +[last-lines] +other = "Last {{.count}} lines" + +[no-containers] +other = "No containers" + +[running] +other = "Running" + +[cpu] +other = "CPU" + +[memory] +other = "Memory" + +[network] +other = "Network" + +[storage] +other = "Storage" + +[container] +other = "Container" + +[compose] +other = "Compose" + +[name] +other = "Name" + +[net-in-out] +other = "Net in / out" + +[ports] +other = "Ports" + +[state] +other = "State" + +[image] +other = "Image" + +[id] +other = "ID" + +[project] +other = "Project" + +[service] +other = "Service" + +[none-published] +other = "None published" + +[received] +other = "Received" + +[sent] +other = "Sent" + +[read] +other = "Read" + +[written] +other = "Written" + +[no-ports] +other = "{{.name}} publishes no ports" + +[no-folder] +other = "Docker doesn't say where {{.name}} lives" + +[started] +other = "Started {{.name}}" + +[stopped] +other = "Stopped {{.name}}" + +[restarted] +other = "Restarted {{.name}}" + +[removed] +other = "Removed {{.name}}" + +[copied] +other = "Copied {{.text}}" + +[starting] +other = "Starting {{.name}}" + +[restarting] +other = "Restarting {{.name}}" + +[taking-down] +other = "Taking {{.name}} down" + +[kind.images] +other = "Images" + +[kind.containers] +other = "Containers" + +[kind.volumes] +other = "Local Volumes" + +[kind.cache] +other = "Build Cache" + +[kind.everything] +other = "Everything" + +[free-images] +other = "{{.dangling}} dangling and {{.unused}} unused can be freed" + +[free-stopped] +other = "{{.count}} stopped, {{.size}} can be freed" + +[free-unused] +other = "{{.count}} unused, {{.size}} can be freed" + +[free] +other = "{{.size}} can be freed" + +[nothing-to-free] +other = "Nothing to free" + +[free-everything] +other = "Stopped containers, dangling images, build cache, {{.size}} can be freed" + +[freed] +other = "Freed {{.size}}" + +[jobs.stats.title] +other = "Measures containers" + +[jobs.stats.description] +other = "Measures what each container uses" diff --git a/docker/locales/nb.toml b/docker/locales/nb.toml new file mode 100644 index 0000000..523f34c --- /dev/null +++ b/docker/locales/nb.toml @@ -0,0 +1,311 @@ +[toolbox.description] +other = "Containere og compose-prosjekter: start, stopp, logger, skall, live statistikk og opprydding" + +[setting.command.title] +other = "Docker-kommando" + +[setting.command.description] +other = "Docker-kommandoen som kjøres, eller en kompatibel en som podman" + +[tool.containers.description] +other = "Finner containere og compose-prosjekter etter navn, image, prosjekt eller tjeneste" + +[tool.project.title] +other = "Compose-prosjekt" + +[tool.port.title] +other = "Containerport" + +[tool.dashboard.title] +other = "Docker-dashbord" + +[tool.dashboard.description] +other = "Alle containere og compose-prosjekter, med hva de som kjører bruker, oppdatert fortløpende" + +[tool.prune.title] +other = "Rydd opp i Docker" + +[tool.prune.description] +other = "Frigjør plass: stoppede containere, ubrukte images og volumer, byggecachen" + +[tool.space.title] +other = "Docker-plass" + +[action.containers.details] +other = "Vis detaljer" + +[action.containers.logs] +other = "Vis logger" + +[action.containers.open-port] +other = "Åpne port" + +[action.containers.shell] +other = "Åpne skall" + +[action.containers.follow-logs] +other = "Følg logger i Terminal" + +[action.containers.start] +other = "Start" + +[action.containers.stop] +other = "Stopp" + +[action.containers.restart] +other = "Start på nytt" + +[action.containers.remove] +other = "Fjern" + +[action.containers.copy-id] +other = "Kopier ID" + +[confirm.containers.remove] +other = "Fjerne denne containeren? Det den har lagret utenfor et volum, går tapt." + +[action.project.details] +other = "Vis tjenester" + +[action.project.logs] +other = "Vis logger" + +[action.project.up] +other = "Start (up)" + +[action.project.restart] +other = "Start på nytt" + +[action.project.down] +other = "Ta ned (down)" + +[confirm.project.down] +other = "Stoppe og fjerne containerne i dette prosjektet?" + +[action.project.open-folder] +other = "Åpne mappe" + +[action.project.copy-name] +other = "Kopier navn" + +[action.port.open] +other = "Åpne i nettleser" + +[action.port.copy-address] +other = "Kopier adresse" + +[action.desktop.open] +other = "Åpne Docker Desktop" + +[action.dashboard.show] +other = "Vis dashbord" + +[action.prune.show] +other = "Vis plassbruk" + +[action.space.containers] +other = "Fjern stoppede containere" + +[action.space.dangling] +other = "Fjern images uten tag" + +[action.space.images] +other = "Fjern alle ubrukte images" + +[action.space.volumes] +other = "Fjern ubrukte volumer" + +[action.space.cache] +other = "Tøm byggecachen" + +[action.space.everything] +other = "Rydd opp i alt" + +[confirm.space.containers] +other = "Fjerne alle stoppede containere?" + +[confirm.space.dangling] +other = "Fjerne images som ingen tag peker på?" + +[confirm.space.images] +other = "Fjerne alle images som ingen container bruker? De lastes ned eller bygges på nytt ved behov." + +[confirm.space.volumes] +other = "Fjerne alle volumer som ingen container bruker, med dataene i dem?" + +[confirm.space.cache] +other = "Tømme byggecachen? Bygg tar lengre tid til den er fylt opp igjen." + +[confirm.space.everything] +other = "Fjerne stoppede containere, ubrukte nettverk, images uten tag og byggecachen?" + +[decimal] +other = "," + +[service-in] +other = "{{.service}} i {{.project}}" + +[running-of] +other = "{{.running}} av {{.total}} kjører" + +[count-of] +other = "{{.running}} av {{.total}}" + +[of] +other = "av {{.total}}" + +[not-running] +other = "Docker kjører ikke" + +[open-desktop] +other = "Åpne Docker Desktop" + +[gone] +other = "Den containeren finnes ikke lenger" + +[open-localhost] +other = "Åpne localhost:{{.port}}" + +[port-inside] +other = "{{.port}}/{{.proto}} inni" + +[no-logs] +other = "Ingen logger ennå" + +[last-lines] +other = "Siste {{.count}} linjer" + +[no-containers] +other = "Ingen containere" + +[running] +other = "Kjører" + +[cpu] +other = "CPU" + +[memory] +other = "Minne" + +[network] +other = "Nettverk" + +[storage] +other = "Lagring" + +[container] +other = "Container" + +[compose] +other = "Compose" + +[name] +other = "Navn" + +[net-in-out] +other = "Nett inn / ut" + +[ports] +other = "Porter" + +[state] +other = "Tilstand" + +[image] +other = "Image" + +[id] +other = "ID" + +[project] +other = "Prosjekt" + +[service] +other = "Tjeneste" + +[none-published] +other = "Ingen publisert" + +[received] +other = "Mottatt" + +[sent] +other = "Sendt" + +[read] +other = "Lest" + +[written] +other = "Skrevet" + +[no-ports] +other = "{{.name}} publiserer ingen porter" + +[no-folder] +other = "Docker sier ikke hvor {{.name}} ligger" + +[started] +other = "Startet {{.name}}" + +[stopped] +other = "Stoppet {{.name}}" + +[restarted] +other = "Startet {{.name}} på nytt" + +[removed] +other = "Fjernet {{.name}}" + +[copied] +other = "Kopierte {{.text}}" + +[starting] +other = "Starter {{.name}}" + +[restarting] +other = "Starter {{.name}} på nytt" + +[taking-down] +other = "Tar ned {{.name}}" + +[kind.images] +other = "Images" + +[kind.containers] +other = "Containere" + +[kind.volumes] +other = "Lokale volumer" + +[kind.cache] +other = "Byggecache" + +[kind.everything] +other = "Alt" + +[free-images] +other = "{{.dangling}} uten tag og {{.unused}} ubrukt kan frigjøres" + +[free-stopped] +other = "{{.count}} stoppet, {{.size}} kan frigjøres" + +[free-unused] +other = "{{.count}} ubrukt, {{.size}} kan frigjøres" + +[free] +other = "{{.size}} kan frigjøres" + +[nothing-to-free] +other = "Ingenting å frigjøre" + +[free-everything] +other = "Stoppede containere, images uten tag, byggecache, {{.size}} kan frigjøres" + +[freed] +other = "Frigjorde {{.size}}" + +[jobs.stats.title] +other = "Måler containerne" + +[jobs.stats.description] +other = "Måler hva hver container bruker" diff --git a/github/assets/github.svg b/github/assets/github.svg new file mode 100644 index 0000000..7914685 --- /dev/null +++ b/github/assets/github.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/github/checks.lua b/github/checks.lua new file mode 100644 index 0000000..696d48c --- /dev/null +++ b/github/checks.lua @@ -0,0 +1,45 @@ +-- Says when the checks of a pull request of yours pass or fail, through gh. Toolshed runs it +-- every minute, while it's turned on. What's been said is remembered, a commit's checks said once; +-- the first time it runs, what's there already is noted. + +local query = [[ +query { + viewer { + pullRequests(states: OPEN, first: 50) { + nodes { + number title url + repository { nameWithOwner } + commits(last: 1) { nodes { commit { oid statusCheckRollup { state } } } } + } + } + } +}]] + +-- The checks' states that are an end, as GitHub names them. +local ended = { SUCCESS = "say.passed", FAILURE = "say.failed", ERROR = "say.failed" } + +local seen = toolshed.memory() +local first = seen == nil +seen = seen or {} + +-- A failure ends this run; Toolshed runs it again a while later. +local data = toolshed.json.decode(toolshed.exec({ "gh", "api", "graphql", "-f", "query=" .. query })).data + +local now = {} +for _, pr in ipairs(data.viewer.pullRequests.nodes) do + local commit = pr.commits.nodes[1] and pr.commits.nodes[1].commit + local state = commit and commit.statusCheckRollup and commit.statusCheckRollup.state + if state then + local was = seen[pr.url] + now[pr.url] = { oid = commit.oid, state = state } + local changed = not was or was.oid ~= commit.oid or was.state ~= state + if not first and changed and ended[state] then + local said = { repo = pr.repository.nameWithOwner, number = pr.number, title = pr.title } + local data = { repo = pr.repository.nameWithOwner, number = tostring(math.floor(pr.number)), url = pr.url .. "/checks" } + toolshed.notify(toolshed.t(ended[state], said), { tool = "pr", stay = state ~= "SUCCESS", actions = { + { title = toolshed.t("action.web"), action = "web", data = data }, + } }) + end + end +end +toolshed.remember(now) diff --git a/github/init.lua b/github/init.lua new file mode 100644 index 0000000..f5a87c0 --- /dev/null +++ b/github/init.lua @@ -0,0 +1,495 @@ +-- 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, +} diff --git a/github/locales/en.toml b/github/locales/en.toml new file mode 100644 index 0000000..ebead88 --- /dev/null +++ b/github/locales/en.toml @@ -0,0 +1,194 @@ +[toolbox.description] +other = "Your GitHub repos, to open or clone, your pull requests and those you're asked to review, with how their checks and reviews stand, through the gh CLI." + +[setting.folders.title] +other = "Repo folders" + +[setting.folders.description] +other = "Where your repos are, one or two levels down; a clone goes into the first. To start with, those of ~/git, ~/repos, ~/projects, ~/code, ~/source and ~/src that hold repos." + +[tool.search.title] +other = "GitHub" + +[tool.search.description] +other = "Repos, Pull requests and Reviews: gh toolshed finds a repo, gh prs your pull requests, gh reviews those you're asked to review." + +[tool.repo.title] +other = "Repo" + +[tool.pr.title] +other = "Pull Request" + +[verb.repos.title] +other = "Repos" + +[verb.repos.description] +other = "The repos you can reach, to open or clone" + +[verb.prs.title] +other = "Pull requests" + +[verb.prs.description] +other = "Your open pull requests; failing, draft or approved filters them" + +[verb.reviews.title] +other = "Reviews" + +[verb.reviews.description] +other = "Pull requests you're asked to review" + +[action.open] +other = "Open" + +[action.web] +other = "Open on GitHub" + +[action.copy-ssh] +other = "Copy SSH Address" + +[action.copy-https] +other = "Copy HTTPS Address" + +[action.finder] +other = "Show in Finder" + +[action.copy-url] +other = "Copy Link" + +[action.checkout] +other = "Check Out" + +[listing] +other = "Listing your repos, which takes a few seconds the first time" + +[error.repos] +other = "Couldn't list your repos: {{.reason}}" + +[error.prs] +other = "Couldn't get the pull requests: {{.reason}}" + +[error.not-cloned] +other = "{{.repo}} isn't cloned" + +[tag.cloned] +other = "Cloned" + +[tag.private] +other = "Private" + +[tag.fork] +other = "Fork" + +[tag.archived] +other = "Archived" + +[tag.draft] +other = "Draft" + +[tag.conflicts] +other = "Conflicts" + +[checks.passing] +other = "Checks pass" + +[checks.failing] +other = "Checks fail" + +[checks.running] +other = "Checks running" + +[checks.skipped] +other = "Skipped" + +[review.APPROVED] +other = "Approved" + +[review.CHANGES_REQUESTED] +other = "Changes requested" + +[review.REVIEW_REQUIRED] +other = "Review required" + +[ago.minutes] +other = "{{.count}} min ago" + +[ago.hours] +other = "{{.count}} h ago" + +[ago.days] +other = "{{.count}} d ago" + +[copied] +other = "Copied {{.text}}" + +[checked-out] +other = "Checked out #{{.number}} in {{.repo}}" + +[action.clone] +other = "Clone" + +[action.clone-into] +other = "Clone Into" + +[setting.open_with.title] +other = "Open with" + +[setting.open_with.description] +other = "A command that opens a cloned repo, {path} being its folder: code {path}. Empty, Finder opens it." + +[setting.after_clone.title] +other = "After cloning" + +[setting.after_clone.description] +other = "A command run when a clone is done, {path} being its folder: code {path}. Empty, nothing runs." + +[action.copy-path] +other = "Copy Path" + +[action.cloned] +other = "Cloned" + +[cloning] +other = "Cloning {{.repo}} into {{.path}}" + +[cloned] +other = "Cloned {{.repo}} into {{.path}}" + +[error.clone] +other = "Couldn't clone {{.repo}}" + +[none.prs] +other = "You have no open pull requests" + +[none.reviews] +other = "No one is waiting for your review" + +[none.like] +other = "No pull requests like that" + +[say.review] +other = "Review requested: {{.repo}}#{{.number}} {{.title}}" + +[say.passed] +other = "Checks passed: {{.repo}}#{{.number}} {{.title}}" + +[say.failed] +other = "Checks failed: {{.repo}}#{{.number}} {{.title}}" + +[jobs.index.title] +other = "Lists your repos" + +[jobs.index.description] +other = "Keeps the list of repos you can reach up to date" + +[jobs.reviews.title] +other = "Review requests" + +[jobs.reviews.description] +other = "Says when you're asked to review a pull request" + +[jobs.checks.title] +other = "Checks" + +[jobs.checks.description] +other = "Says when the checks of your pull requests pass or fail" diff --git a/github/locales/nb.toml b/github/locales/nb.toml new file mode 100644 index 0000000..5543d0d --- /dev/null +++ b/github/locales/nb.toml @@ -0,0 +1,194 @@ +[toolbox.description] +other = "Repoene dine på GitHub, å åpne eller klone, pull requestene dine og dem du er bedt om å se gjennom, med hvordan sjekker og gjennomganger står, gjennom gh CLI." + +[setting.folders.title] +other = "Repomapper" + +[setting.folders.description] +other = "Hvor repoene dine ligger, ett eller to nivåer ned; en klone havner i den første. Til å begynne med: de av ~/git, ~/repos, ~/projects, ~/code, ~/source og ~/src som har repoer." + +[tool.search.title] +other = "GitHub" + +[tool.search.description] +other = "Repoer, pull requester og gjennomganger: gh toolshed finner et repo, gh prs pull requestene dine, gh reviews dem du er bedt om å se gjennom." + +[tool.repo.title] +other = "Repo" + +[tool.pr.title] +other = "Pull request" + +[verb.repos.title] +other = "Repoer" + +[verb.repos.description] +other = "Repoene du har tilgang til, å åpne eller klone" + +[verb.prs.title] +other = "Pull requester" + +[verb.prs.description] +other = "Dine åpne pull requester; failing, draft eller approved filtrerer dem" + +[verb.reviews.title] +other = "Gjennomganger" + +[verb.reviews.description] +other = "Pull requester du er bedt om å se gjennom" + +[action.open] +other = "Åpne" + +[action.web] +other = "Åpne på GitHub" + +[action.copy-ssh] +other = "Kopier SSH-adresse" + +[action.copy-https] +other = "Kopier HTTPS-adresse" + +[action.finder] +other = "Vis i Finder" + +[action.copy-url] +other = "Kopier lenke" + +[action.checkout] +other = "Sjekk ut" + +[listing] +other = "Henter repoene dine, som tar noen sekunder første gang" + +[error.repos] +other = "Klarte ikke å hente repoene: {{.reason}}" + +[error.prs] +other = "Klarte ikke å hente pull requestene: {{.reason}}" + +[error.not-cloned] +other = "{{.repo}} er ikke klonet" + +[tag.cloned] +other = "Klonet" + +[tag.private] +other = "Privat" + +[tag.fork] +other = "Fork" + +[tag.archived] +other = "Arkivert" + +[tag.draft] +other = "Utkast" + +[tag.conflicts] +other = "Konflikter" + +[checks.passing] +other = "Sjekker OK" + +[checks.failing] +other = "Sjekker feiler" + +[checks.running] +other = "Sjekker kjører" + +[checks.skipped] +other = "Hoppet over" + +[review.APPROVED] +other = "Godkjent" + +[review.CHANGES_REQUESTED] +other = "Endringer ønsket" + +[review.REVIEW_REQUIRED] +other = "Trenger gjennomgang" + +[ago.minutes] +other = "for {{.count}} min siden" + +[ago.hours] +other = "for {{.count}} t siden" + +[ago.days] +other = "for {{.count}} d siden" + +[copied] +other = "Kopierte {{.text}}" + +[checked-out] +other = "Sjekket ut #{{.number}} i {{.repo}}" + +[action.clone] +other = "Klon" + +[action.clone-into] +other = "Klon til" + +[setting.open_with.title] +other = "Åpne med" + +[setting.open_with.description] +other = "En kommando som åpner et klonet repo, der {path} er mappen: code {path}. Tom: Finder åpner det." + +[setting.after_clone.title] +other = "Etter kloning" + +[setting.after_clone.description] +other = "En kommando som kjøres når en kloning er ferdig, der {path} er mappen: code {path}. Tom: ingenting kjøres." + +[action.copy-path] +other = "Kopier sti" + +[action.cloned] +other = "Klonet" + +[cloning] +other = "Kloner {{.repo}} til {{.path}}" + +[cloned] +other = "Klonet {{.repo}} til {{.path}}" + +[error.clone] +other = "Klarte ikke å klone {{.repo}}" + +[none.prs] +other = "Du har ingen åpne pull requester" + +[none.reviews] +other = "Ingen venter på at du skal se gjennom" + +[none.like] +other = "Ingen slike pull requester" + +[say.review] +other = "Ber om gjennomgang: {{.repo}}#{{.number}} {{.title}}" + +[say.passed] +other = "Sjekkene gikk gjennom: {{.repo}}#{{.number}} {{.title}}" + +[say.failed] +other = "Sjekkene feilet: {{.repo}}#{{.number}} {{.title}}" + +[jobs.index.title] +other = "Lister repoene dine" + +[jobs.index.description] +other = "Holder listen over repoene du har tilgang til oppdatert" + +[jobs.reviews.title] +other = "Forespørsler om gjennomgang" + +[jobs.reviews.description] +other = "Sier fra når du blir bedt om å se gjennom en pull request" + +[jobs.checks.title] +other = "Sjekker" + +[jobs.checks.description] +other = "Sier fra når sjekkene til pull requestene dine går gjennom eller feiler" diff --git a/github/reviews.lua b/github/reviews.lua new file mode 100644 index 0000000..4bb69f0 --- /dev/null +++ b/github/reviews.lua @@ -0,0 +1,34 @@ +-- Says when you're asked to review a pull request, through gh. Toolshed runs it every 15 seconds, +-- while it's turned on: GitHub can't push to a Mac, and a search that often uses a fraction of +-- what GraphQL allows an hour. What's been said is remembered, so nothing is said twice; the first time +-- it runs, what's there already is noted. + +local query = [[ +query { + search(query: "is:pr is:open review-requested:@me", type: ISSUE, first: 50) { + nodes { ... on PullRequest { number title url repository { nameWithOwner } } } + } +}]] + +local seen = toolshed.memory() +local first = seen == nil +seen = seen or {} + +-- A failure ends this run; Toolshed runs it again a while later. +local data = toolshed.json.decode(toolshed.exec({ "gh", "api", "graphql", "-f", "query=" .. query })).data + +local now = {} +for _, pr in ipairs(data.search.nodes) do + if pr.url then + now[pr.url] = true + if not first and not seen[pr.url] then + local said = { repo = pr.repository.nameWithOwner, number = pr.number, title = pr.title } + local data = { repo = pr.repository.nameWithOwner, number = tostring(math.floor(pr.number)), url = pr.url } + toolshed.notify(toolshed.t("say.review", said), { tool = "pr", stay = true, actions = { + { title = toolshed.t("action.web"), action = "web", data = data }, + { title = toolshed.t("action.copy-url"), action = "copy-url", data = data }, + } }) + end + end +end +toolshed.remember(now) diff --git a/homebrew/init.lua b/homebrew/init.lua new file mode 100644 index 0000000..f36df6c --- /dev/null +++ b/homebrew/init.lua @@ -0,0 +1,674 @@ +-- Homebrew, as on the command line: "brew install jq" lists what you could install and Enter +-- installs it, "brew uninstall jq" what's installed, "brew upgrade" what has an update, "brew +-- list" what you installed, "brew services" the services; "brew info jq" finds everything by +-- name, saying what's installed and what has an update, and Enter shows a package's details +-- there. ⌘K installs, upgrades, uninstalls or pins a package, or opens it on formulae.brew.sh. +-- "brew" alone offers the verbs, and a verb half typed ("brew un") those it could become: Enter +-- types it ("brew uninstall "), to go on from there. A whole name ("brew jq") is that package. +-- "brew upgrade" lists what's outdated, Upgrade all first; "brew update", "brew cleanup" and +-- "brew doctor" take nothing more, so choosing them runs them. What changes what's installed +-- runs in the background, one at a time, shown in Active while it does and saying when it's +-- done, a page showing what Homebrew says as it goes; one that needs a password can be run in +-- Terminal instead, where it can ask for it. Its text is in locales/. + +local cache = toolshed.cache_dir() +local installed_file = cache .. "/installed.json" +-- Asking brew what's installed takes a second, so it's asked in the background when what's +-- known is older than this, and searches use what's known meanwhile. +local refresh_seconds = 60 +-- Search finds at most this many, as a launcher list shows no more. +local most = 40 + +local quoted = toolshed.shell_quote + +local escape = toolshed.escape + +local function trim(s) + return (tostring(s or ""):gsub("^%s+", ""):gsub("%s+$", "")) +end + +local modified = toolshed.file.modified + +-- brew is found once, by the shell's PATH, so Terminal runs the same one whatever its own PATH. +local brew_path +local function brew() + if not brew_path then brew_path = trim(toolshed.exec({ "sh", "-c", "command -v brew" })) end + return brew_path +end + +-- quiet runs brew without it updating itself first, which only installing and upgrading need. +local function quiet(...) + return toolshed.exec({ "env", "HOMEBREW_NO_AUTO_UPDATE=1", brew(), ... }) +end + +-- installed_command writes what's installed to the file, swapped in whole so a search never +-- reads half of it. +local function installed_command() + return "HOMEBREW_NO_AUTO_UPDATE=1 " .. quoted(brew()) .. " info --json=v2 --installed > " .. + quoted(installed_file .. ".tmp") .. " 2>/dev/null && mv " .. quoted(installed_file .. ".tmp") .. " " .. quoted(installed_file) +end + +-- refresh_in_background asks brew what's installed, quietly, once at a time. +local function refresh_in_background() + toolshed.activities.set { key = "refresh", title = toolshed.t("jobs.refresh.title"), description = toolshed.t("jobs.refresh.description"), quiet = true, run = { "sh", "-c", installed_command() }, timeout = 120 } +end + +-- in_terminal runs a brew command in Terminal, as a .command file macOS opens without asking +-- for permission to control it, then writes down what's installed now: for one that failed in +-- the background, as it needs a password, which Terminal can ask for. +local function in_terminal(name, args) + local words = { quoted(brew()) } + for _, a in ipairs(args) do table.insert(words, quoted(a)) end + local path = cache .. "/" .. name:gsub("[^%w%-_]", "_") .. ".command" + local f = assert(io.open(path, "w")) + f:write("#!/bin/sh\nclear\n" .. table.concat(words, " ") .. "\nstatus=$?\n" .. installed_command() .. "\nexit $status\n") + f:close() + toolshed.exec({ "chmod", "+x", path }) + toolshed.open(path) +end + +-- A brew command runs in the background as an activity, shown while it runs and saying when +-- it's done or why it failed, one at a time as Homebrew needs. One that ended less than this +-- ago is the one the page is showing; older, running it again starts afresh. +local done_seconds = 30 + +-- output is the last lines of what brew said, its colours taken out. +local function output(text, most_lines) + local lines = {} + for line in (text or ""):gsub("\27%[[%d;]*%a", ""):gmatch("[^\n]+") do table.insert(lines, line) end + return table.concat(lines, "\n", math.max(1, #lines - most_lines + 1)) +end + +-- brew_page runs a brew command, unless it's under way, and shows how it goes: what brew says +-- while it runs, all of it once done, and on a failure, a way to run it in Terminal, where it +-- can ask for a password. What's installed is read again afterwards. +local function brew_page(name, args) + local typed = "brew " .. table.concat(args, " ") + local key = "run-" .. name:lower():gsub("[^%w_-]", "-") + local now = toolshed.activities.get(key) + if not now or (now.ended and os.time() - now.ended >= done_seconds) then + local command = { "env", "HOMEBREW_NO_COLOR=1", "HOMEBREW_NO_EMOJI=1", "HOMEBREW_NO_ENV_HINTS=1", brew() } + for _, a in ipairs(args) do table.insert(command, a) end + now = toolshed.activities.set { + key = key, tool = "brew", title = toolshed.t("run.running", { command = typed }), icon = "package", + run = command, queue = "brew", timeout = 3600, + ending = { done = toolshed.t("run.done", { command = typed }), failed = toolshed.t("run.failed", { command = typed }) }, + after = { action = "ran" }, + } + end + local running = now.state == "waiting" or now.state == "running" + local heading = toolshed.t(running and "run.running" or now.state == "done" and "run.done" or "run.failed", { command = typed }) + local html = '
' .. escape(heading) .. '
' .. + escape(output(now.output, running and 12 or 400)) .. "
" + if running then return { html = html, refresh = 1 } end + if now.state == "done" then return { html = html } end + return { html = html, jigs = { { + title = toolshed.t("run.in-terminal"), subtitle = typed, icon = "terminal", tool = "terminal", action = "run", + data = { name = name, args = args }, + } } } +end + +-- A package as the extension keeps it: what's needed to list it, not all brew says. +local function slim(p, kind) + if kind == "cask" then + return { + name = p.token, kind = "cask", desc = p.desc, homepage = p.homepage, latest = p.version, + version = p.installed, on_request = true, pinned = false, + -- Casks that update themselves aren't upgraded by brew upgrade, so brew doesn't count them. + outdated = p.outdated and not p.auto_updates, + } + end + local last = p.installed and p.installed[#p.installed] or {} + -- A new build of the same version is a revision, which the installed version names too: + -- 9.12_1 after 9.12. + local latest = p.versions and p.versions.stable + if latest and (p.revision or 0) > 0 then latest = latest .. "_" .. p.revision end + return { + name = p.name, kind = "formula", desc = p.desc, homepage = p.homepage, + latest = latest, version = last.version, + on_request = last.installed_on_request, pinned = p.pinned, outdated = p.outdated, + } +end + +local known, known_at = nil, 0 + +-- installed is what's installed, as last written down: the first time it's asked now, and when +-- it's older than refresh_seconds it's asked again in the background. +local function installed() + local at = modified(installed_file) + if not at then + local out = quiet("info", "--json=v2", "--installed") + local f = assert(io.open(installed_file, "w")) + f:write(out) + f:close() + at = modified(installed_file) + elseif os.time() - at > refresh_seconds then + refresh_in_background() + end + if known and known_at == at then return known end + local f = io.open(installed_file) + local data = f and toolshed.json.decode(f:read("*a")) or {} + if f then f:close() end + local list = {} + for _, p in ipairs(data.formulae or {}) do table.insert(list, slim(p, "formula")) end + for _, p in ipairs(data.casks or {}) do table.insert(list, slim(p, "cask")) end + known, known_at = list, at + return list +end + +-- Every formula and cask there is, as brew formulae and brew casks list them, written down +-- and asked again in the background when older than names_seconds: brew's own files for them +-- change as Homebrew does. +local names_file = cache .. "/names.txt" +local names_seconds = 6 * 3600 + +local function names_command() + local b = quoted(brew()) + return "(" .. b .. " formulae 2>/dev/null | sed 's/^/formula /'; " .. b .. " casks 2>/dev/null | sed 's/^/cask /') > " .. + quoted(names_file .. ".tmp") .. " && mv " .. quoted(names_file .. ".tmp") .. " " .. quoted(names_file) +end + +local names, names_at = nil, 0 +local function every_name() + local at = modified(names_file) + if not at then + toolshed.exec({ "sh", "-c", "export HOMEBREW_NO_AUTO_UPDATE=1; " .. names_command() }) + at = modified(names_file) + elseif os.time() - at > names_seconds then + toolshed.activities.set { key = "names", title = toolshed.t("jobs.names.title"), description = toolshed.t("jobs.names.description"), quiet = true, run = { "sh", "-c", "export HOMEBREW_NO_AUTO_UPDATE=1; " .. names_command() }, timeout = 300 } + end + if names and names_at == at then return names end + names = {} + local f = io.open(names_file) + if f then + for line in f:lines() do + local kind, name = line:match("^(%a+) (.+)$") + if name then table.insert(names, { name = name, kind = kind }) end + end + f:close() + end + names_at = at + return names +end + +local function key(name, kind) return kind .. ":" .. name end + +-- jig is a package as a row: its state and what it's for, and the actions that fit it. +-- Its tags say at a glance whether it's installed, has an update or is pinned; the subtitle +-- says which version, and what it's for. +local function jig(p) + local state, tags = toolshed.t(p.kind == "cask" and "kind.cask" or "kind.formula"), {} + if p.version then + table.insert(tags, { text = toolshed.t("tag.installed"), tint = "green", icon = "circle-check" }) + if p.pinned then + table.insert(tags, { text = toolshed.t("tag.pinned"), tint = "gray", icon = "pin" }) + elseif p.outdated then + table.insert(tags, { text = toolshed.t("tag.update"), tint = "orange", icon = "circle-arrow-up" }) + end + state = p.outdated and (p.version .. " → " .. (p.latest or "?")) or p.version + end + local actions = { "info" } + if p.version then + if p.outdated and not p.pinned then table.insert(actions, "upgrade") end + table.insert(actions, "uninstall") + if p.kind == "formula" then table.insert(actions, p.pinned and "unpin" or "pin") end + else + table.insert(actions, "install") + end + table.insert(actions, "open-site") + table.insert(actions, "copy-name") + return { + title = p.name, subtitle = state .. ((p.desc and p.desc ~= "") and (" · " .. p.desc) or ""), tags = tags, + icon = p.kind == "cask" and "app-window" or "package", tool = "search", actions = actions, + data = { name = p.name, kind = p.kind }, + } +end + +-- mine is what's installed that keep allows, updates first. +local function mine(keep) + local list = {} + for _, p in ipairs(installed()) do + if keep(p) then table.insert(list, p) end + end + table.sort(list, function(a, b) + if (a.outdated or false) ~= (b.outdated or false) then return a.outdated end + return a.name < b.name + end) + return list +end + +-- find is the packages whose name has what's typed, those keep allows: the name itself first, +-- then those starting with it, then the rest; within each, what's installed first, then the +-- shortest. Only what's installed is looked through when that's all keep allows. +local function find(typed, keep, installed_only) + local q = typed:lower() + local have = {} + for _, p in ipairs(installed()) do have[key(p.name, p.kind)] = p end + local found = {} + local function consider(name, kind) + local at = name:lower():find(q, 1, true) + if not at then return end + local k = key(name, kind) + local p = have[k] or { name = name, kind = kind } + if found[k] or not keep(p) then return end + found[k] = { p = p, rank = (name:lower() == q and 0) or (at == 1 and 1) or 2 } + end + for _, p in ipairs(installed()) do consider(p.name, p.kind) end + if not installed_only then + for _, n in ipairs(every_name()) do consider(n.name, n.kind) end + end + local list = {} + for _, f in pairs(found) do table.insert(list, f) end + table.sort(list, function(a, b) + if a.rank ~= b.rank then return a.rank < b.rank end + if (a.p.version ~= nil) ~= (b.p.version ~= nil) then return a.p.version ~= nil end + if #a.p.name ~= #b.p.name then return #a.p.name < #b.p.name end + return a.p.name < b.p.name + end) + local out = {} + for i = 1, math.min(#list, most) do table.insert(out, list[i].p) end + return out +end + +local function page(body) return '
' .. body .. "
" end +local function tile(icon) return '' end + +local function card(title, icon, tint, facts, wide) + local rows = {} + for _, f in ipairs(facts) do + if f[2] and f[2] ~= "" then table.insert(rows, "
" .. escape(toolshed.t(f[1])) .. "
" .. f[2] .. "
") end + end + if #rows == 0 then return "" end + return '
' .. tile(icon) .. + escape(toolshed.t(title)) .. '
' .. table.concat(rows) .. "
" +end + +local function site(data) + return "https://formulae.brew.sh/" .. data.kind .. "/" .. data.name +end + +-- details is a package's page, from what brew says about it now. +local function details(data) + local info = toolshed.json.decode(quiet("info", "--json=v2", data.kind == "cask" and "--cask" or "--formula", data.name)) + local raw = (data.kind == "cask" and info.casks or info.formulae)[1] + if not raw then error(toolshed.t("not-found", { name = data.name })) end + local p = slim(raw, data.kind) + local status + if not p.version then + status = toolshed.t("status.not-installed") + elseif p.outdated then + status = '' .. escape(toolshed.t("status.update", { latest = p.latest or "?" })) + else + status = '' .. escape(toolshed.t(p.pinned and "status.pinned" or "status.current")) + end + local link = p.homepage and ('' .. escape(p.homepage) .. "") + local cards = { + card("card.package", data.kind == "cask" and "app-window" or "package", "yellow", { + { "fact.description", escape(p.desc) }, + { "fact.kind", escape(toolshed.t(data.kind == "cask" and "kind.cask" or "kind.formula")) }, + { "fact.tap", escape(raw.tap) }, + { "fact.license", escape(raw.license) }, + { "fact.homepage", link }, + }), + card("card.version", "download", "green", { + { "fact.latest", escape(p.latest) }, + { "fact.installed", escape(p.version or toolshed.t("none")) }, + { "fact.status", status }, + }), + } + local deps = raw.dependencies + if data.kind == "formula" and deps and #deps > 0 then + table.insert(cards, card("card.dependencies", "boxes", "teal", { { "fact.needs", escape(table.concat(deps, ", ")) } }, true)) + end + local caveats = raw.caveats and raw.caveats ~= "" and + ('
' .. escape(toolshed.t("caveats")) .. '
' .. escape(raw.caveats) .. "
") or "" + return page('
' .. table.concat(cards) .. "
" .. caveats) +end + +-- updates is what's outdated as a page: how many, and a line each, to upgrade. + +-- services are brew's background services, as rows to start, stop or restart. +local function services() + local list = toolshed.json.decode(quiet("services", "list", "--json")) or {} + local jigs = {} + for _, s in ipairs(list) do + local running = s.status == "started" or s.status == "scheduled" + table.insert(jigs, { + title = s.name, subtitle = toolshed.t("service." .. (s.status or "none")), tool = "service", + icon = running and "play" or "circle-stop", actions = running and { "stop", "restart" } or { "start" }, + data = { name = s.name }, + }) + end + if #jigs == 0 then error(toolshed.t("no-services")) end + return { jigs = jigs } +end + +-- A tap's name is user/repo; on GitHub it's github.com/user/homebrew-repo, unless an address +-- is given for it. +local function tap_page(name) + local user, repo = name:match("^([^/]+)/(.+)$") + return "https://github.com/" .. user .. "/homebrew-" .. repo +end + +-- Asking brew about its taps takes a second, so what it says is kept for a minute, and +-- forgotten when a tap is added, removed or trusted. +local tap_info, tap_info_at = nil, 0 +local function forget_taps() tap_info = nil end + +-- installed_taps are the third-party taps brew has: Homebrew's own aren't listed, as brew tap +-- doesn't list them. +local function installed_taps() + if not tap_info or os.time() - tap_info_at > 60 then + tap_info, tap_info_at = {}, os.time() + for _, t in ipairs(toolshed.json.decode(quiet("tap-info", "--json", "--installed")) or {}) do + if not t.official then table.insert(tap_info, t) end + end + end + return tap_info +end + +-- tap_status says what a tap holds and when it last changed; whether Homebrew trusts it, as it +-- loads nothing from one it doesn't, is its tag. +local function tap_status(t) + local parts = {} + local formulae, casks = #(t.formula_names or {}), #(t.cask_tokens or {}) + if formulae > 0 then table.insert(parts, toolshed.t("tap.formulae", { count = formulae })) end + if casks > 0 then table.insert(parts, toolshed.t("tap.casks", { count = casks })) end + if t.private then table.insert(parts, toolshed.t("tap.private")) end + if t.last_commit then table.insert(parts, toolshed.t("tap.updated", { when = t.last_commit })) end + return table.concat(parts, " · ") +end + +-- taps are the third-party repositories brew has, those whose name has what's typed, with how +-- each is; and when what's typed is a tap brew doesn't have yet ("user/repo", maybe with an +-- address after it), a row first to add it. +local function taps(typed) + local name, address = typed:match("^(%S+)%s*(.-)$") + local q = (name or ""):lower() + local jigs, have = {}, false + for _, t in ipairs(installed_taps()) do + if t.name:lower() == q then have = true end + if q == "" or t.name:lower():find(q, 1, true) then + table.insert(jigs, { + title = t.name, subtitle = tap_status(t), icon = "git-branch", tool = "tap", + tags = { t.trusted and { text = toolshed.t("tap.trusted"), tint = "green", icon = "shield-check" } + or { text = toolshed.t("tap.untrusted"), tint = "orange", icon = "shield-check" } }, + actions = { "open-tap", t.trusted and "untrust" or "trust", "untap" }, + data = { name = t.name, page = t.remote or tap_page(t.name) }, + }) + end + end + if name and not have and name:match("^[%w_.-]+/[%w_.-]+$") then + table.insert(jigs, 1, { + title = toolshed.t("tap.add", { name = name }), + subtitle = address ~= "" and address or tap_page(name):gsub("^https://", ""), + icon = "download", tool = "tap", action = "tap", actions = { "tap" }, data = { name = name, address = address }, + }) + end + return jigs +end + +-- run_row runs a brew command that takes nothing more, like doctor, showing how it goes. +local function run_row(key, title, subtitle, icon, args) + return { key = key, title = title, subtitle = subtitle, icon = icon, tool = "brew", action = "run", data = { name = key, args = args } } +end + +local function any() return true end +local function absent(p) return p.version == nil end +local function present(p) return p.version ~= nil end +local function updatable(p) return p.version ~= nil and p.outdated and not p.pinned end +local function yours(p) return p.on_request end + +-- verbs are what can follow brew, as on the command line, in the order they're offered: each +-- lists what it fits, and Enter does it. installed means only what's installed can fit; all is +-- what it lists with nothing more typed: for uninstall what you installed, not what came along +-- with it. acts_on is what Enter does it to, when it lists more: install shows what's installed +-- too, saying so, and Enter shows its details. services and tap list what they're about instead. +local order = { "install", "uninstall", "upgrade", "list", "info", "services", "tap", "update", "cleanup", "doctor" } +local verbs = { + install = { icon = "download", keep = any, action = "install", acts_on = absent }, + uninstall = { icon = "trash-2", keep = present, action = "uninstall", installed = true, all = yours }, + upgrade = { icon = "circle-arrow-up", keep = updatable, action = "upgrade", installed = true, all = updatable }, + list = { icon = "package", keep = yours, installed = true, all = yours }, + info = { icon = "info", keep = any }, + services = { icon = "server", rows = function() + local ok, found = pcall(services) + return ok and found.jigs or {} + end }, + tap = { icon = "git-branch", rows = taps }, + -- These take nothing more, so choosing them runs them. + update = { icon = "refresh-cw", runs = { "update" } }, + cleanup = { icon = "sparkles", runs = { "cleanup" } }, + doctor = { icon = "stethoscope", runs = { "doctor" } }, +} +-- The other names brew knows them by. +local aliases = { remove = "uninstall", rm = "uninstall", ls = "list", taps = "tap", outdated = "upgrade", updates = "upgrade" } + +-- verb_rows are the verbs what's typed could become ("un" → uninstall), all of them for +-- nothing: a row each, saying what it does, that types it after brew, to go on from there. +local function verb_rows(word) + local rows = {} + for _, name in ipairs(order) do + local fits = name:sub(1, #word) == word + for alias, of in pairs(aliases) do + if of == name and alias:sub(1, #word) == word then fits = true end + end + if fits then + local title, about, v = toolshed.t("verb." .. name .. ".title"), toolshed.t("verb." .. name .. ".description"), verbs[name] + if v.runs then + table.insert(rows, run_row(name, title, about, v.icon, v.runs)) + else + table.insert(rows, { title = title, subtitle = about, icon = v.icon, prefix = name .. " ", actions = {} }) + end + end + end + return rows +end + +-- listed is what's typed after brew: a verb, then what to look for. While a verb is typed, +-- the verbs it could become are offered, and a package of exactly that name after them ("brew +-- jq"); brew on its own offers every verb. +local function listed(rest) + local word, typed = rest:match("^(%S+)%s*(.-)%s*$") + if not word then return verb_rows("") end + word = word:lower() + local v = verbs[aliases[word] or word] + if not v then + if typed ~= "" then return {} end + local rows = verb_rows(word) + for _, p in ipairs(find(word, function(p) return p.name:lower() == word end)) do table.insert(rows, jig(p)) end + return rows + end + if v.rows then return v.rows(typed) end + if v.runs then + local name = aliases[word] or word + return { run_row(name, toolshed.t("verb." .. name .. ".title"), toolshed.t("verb." .. name .. ".description"), v.icon, v.runs) } + end + local list + if typed ~= "" then + list = find(typed, v.keep, v.installed) + elseif v.all then + list = mine(v.all) + else + return {} + end + local jigs = {} + if v == verbs.upgrade and typed == "" and #list > 0 then + table.insert(jigs, run_row("upgrade-all", toolshed.t("action.upgrade-all"), toolshed.t("upgrade-all.about", { count = #list }), + "circle-arrow-up", { "upgrade" })) + end + for _, p in ipairs(list) do + local row = jig(p) + if not v.acts_on or v.acts_on(p) then row.action = v.action end + table.insert(jigs, row) + end + return jigs +end + +return toolshed.toolbox { + key = "homebrew", + title = "Homebrew", + description = "i18n:toolbox.description", + icon = "beer", + tint = "yellow", + requires = { { command = "brew" } }, + + tools = { + { + key = "search", + title = "i18n:tool.search.title", + description = "i18n:tool.search.description", + words = { "brew", "homebrew" }, + examples = { "brew install jq", "brew upgrade", "brew uninstall jq", "brew list", "brew services", "brew info jq" }, + keywords = { "homebrew", "install", "package", "formula", "cask", "installer", "pakke", "outdated", "doctor", "cleanup" }, + items = true, + + search = function(rest) return listed(rest) end, + + actions = { + { + key = "info", title = "i18n:action.info", icon = "info", + run = function(ctx) return { html = details(ctx.data) } end, + }, + { + key = "install", title = "i18n:action.install", icon = "download", shortcut = "cmd+enter", + run = function(ctx) + return brew_page("install-" .. ctx.data.name, { "install", "--" .. ctx.data.kind, ctx.data.name }) + end, + }, + { + key = "upgrade", title = "i18n:action.upgrade", icon = "circle-arrow-up", + run = function(ctx) + return brew_page("upgrade-" .. ctx.data.name, { "upgrade", "--" .. ctx.data.kind, ctx.data.name }) + end, + }, + { + key = "uninstall", title = "i18n:action.uninstall", icon = "trash-2", confirm = "i18n:confirm.uninstall", + never_default = true, + run = function(ctx) + return brew_page("uninstall-" .. ctx.data.name, { "uninstall", "--" .. ctx.data.kind, ctx.data.name }) + end, + }, + { + key = "pin", title = "i18n:action.pin", icon = "pin", never_default = true, + run = function(ctx) + quiet("pin", ctx.data.name) + refresh_in_background() + return toolshed.t("pinned", { name = ctx.data.name }) + end, + }, + { + key = "unpin", title = "i18n:action.unpin", icon = "pin-off", never_default = true, + run = function(ctx) + quiet("unpin", ctx.data.name) + refresh_in_background() + return toolshed.t("unpinned", { name = ctx.data.name }) + end, + }, + { + key = "open-site", title = "i18n:action.open-site", icon = "external-link", + run = function(ctx) toolshed.open(site(ctx.data)) end, + }, + { + key = "copy-name", title = "i18n:action.copy-name", icon = "copy", shortcut = "cmd+shift+c", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.name) + return toolshed.t("name-copied") + end, + }, + }, + }, + { + key = "tap", + title = "i18n:tool.tap.title", + hidden = true, + items = true, + actions = { + { + key = "open-tap", title = "i18n:action.open-tap", icon = "external-link", + run = function(ctx) toolshed.open(ctx.data.page) end, + }, + { + key = "tap", title = "i18n:action.tap", icon = "download", + run = function(ctx) + local args = { "tap", ctx.data.name } + if ctx.data.address and ctx.data.address ~= "" then table.insert(args, ctx.data.address) end + forget_taps() + return brew_page("tap-" .. ctx.data.name, args) + end, + }, + { + key = "trust", title = "i18n:action.trust", icon = "shield-check", + run = function(ctx) + quiet("trust", "--tap", ctx.data.name) + forget_taps() + return toolshed.t("trusted", { name = ctx.data.name }) + end, + }, + { + key = "untrust", title = "i18n:action.untrust", icon = "shield-check", never_default = true, + run = function(ctx) + quiet("untrust", "--tap", ctx.data.name) + forget_taps() + return toolshed.t("untrusted", { name = ctx.data.name }) + end, + }, + { + key = "untap", title = "i18n:action.untap", icon = "trash-2", confirm = "i18n:confirm.untap", never_default = true, + run = function(ctx) + forget_taps() + return brew_page("untap-" .. ctx.data.name, { "untap", ctx.data.name }) + end, + }, + }, + }, + { + key = "service", + title = "i18n:tool.service.title", + hidden = true, + items = true, + actions = { + { + key = "start", title = "i18n:action.start", icon = "play", + run = function(ctx) + quiet("services", "start", ctx.data.name) + return toolshed.t("started", { name = ctx.data.name }) + end, + }, + { + key = "stop", title = "i18n:action.stop", icon = "circle-stop", + run = function(ctx) + quiet("services", "stop", ctx.data.name) + return toolshed.t("stopped", { name = ctx.data.name }) + end, + }, + { + key = "restart", title = "i18n:action.restart", icon = "rotate-cw", + run = function(ctx) + quiet("services", "restart", ctx.data.name) + return toolshed.t("restarted", { name = ctx.data.name }) + end, + }, + }, + }, + { + -- What a verb that takes nothing more runs, like doctor. + key = "brew", title = "i18n:tool.brew.title", hidden = true, + actions = { { + key = "run", title = "i18n:tool.brew.title", icon = "terminal", + run = function(ctx) return brew_page(ctx.data.name, ctx.data.args) end, + }, { + -- Run as a brew command ends: what's installed is asked again. + key = "ran", title = "i18n:tool.brew.title", run = function() refresh_in_background() end, + } }, + }, + { + -- Reached from a command that failed in the background: runs it in Terminal instead. + key = "terminal", title = "i18n:run.in-terminal", hidden = true, + actions = { { + key = "run", title = "i18n:run.in-terminal", icon = "terminal", + run = function(ctx) in_terminal(ctx.data.name, ctx.data.args) end, + } }, + }, + }, +} diff --git a/homebrew/locales/en.toml b/homebrew/locales/en.toml new file mode 100644 index 0000000..b46630c --- /dev/null +++ b/homebrew/locales/en.toml @@ -0,0 +1,299 @@ +[toolbox.description] +other = "Find, install, upgrade and remove Homebrew formulae and casks, see what has updates, and start and stop brew's services." + +[tool.search.title] +other = "Homebrew" + +[tool.search.description] +other = "Install, uninstall, upgrade and find packages, and start and stop services, as on the command line: brew install jq." + +[tool.service.title] +other = "Homebrew Service" + +[action.info] +other = "Show Details" + +[action.install] +other = "Install" + +[action.upgrade] +other = "Upgrade" + +[action.uninstall] +other = "Uninstall" + +[action.pin] +other = "Pin Version" + +[action.unpin] +other = "Unpin Version" + +[action.open-site] +other = "Open on formulae.brew.sh" + +[action.copy-name] +other = "Copy Name" + +[action.upgrade-all] +other = "Upgrade All" + +[action.start] +other = "Start" + +[action.stop] +other = "Stop" + +[action.restart] +other = "Restart" + +[confirm.uninstall] +other = "Uninstall it? Homebrew removes it in Terminal." + +[kind.formula] +other = "Formula" + +[kind.cask] +other = "Cask" + +[status.not-installed] +other = "Not installed" + +[status.update] +other = "Update to {{.latest}}" + +[status.current] +other = "Up to date" + +[status.pinned] +other = "Pinned" + +[none] +other = "None" + +[not-found] +other = "Homebrew doesn't know {{.name}}" + +[card.package] +other = "Package" + +[card.version] +other = "Version" + +[card.dependencies] +other = "Dependencies" + +[fact.description] +other = "About" + +[fact.kind] +other = "Kind" + +[fact.tap] +other = "Tap" + +[fact.license] +other = "License" + +[fact.homepage] +other = "Homepage" + +[fact.latest] +other = "Latest" + +[fact.installed] +other = "Installed" + +[fact.status] +other = "Status" + +[fact.needs] +other = "Needs" + +[caveats] +other = "Caveats" + +[service.started] +other = "Running" + +[service.scheduled] +other = "Scheduled" + +[service.stopped] +other = "Stopped" + +[service.none] +other = "Not running" + +[service.error] +other = "Failed" + +[service.unknown] +other = "Unknown" + +[no-services] +other = "No installed package has a service" + +[started] +other = "Started {{.name}}" + +[stopped] +other = "Stopped {{.name}}" + +[restarted] +other = "Restarted {{.name}}" + +[pinned] +other = "Pinned {{.name}}" + +[unpinned] +other = "Unpinned {{.name}}" + +[name-copied] +other = "Name copied" + +[verb.install.title] +other = "Install" + +[verb.install.description] +other = "A formula or a cask you don't have yet" + +[verb.uninstall.title] +other = "Uninstall" + +[verb.uninstall.description] +other = "Something you installed" + +[verb.upgrade.title] +other = "Upgrade" + +[verb.upgrade.description] +other = "What has a newer version" + +[verb.list.title] +other = "List" + +[verb.list.description] +other = "What you installed" + +[verb.info.title] +other = "Info" + +[verb.info.description] +other = "Any formula or cask, installed or not" + +[verb.services.title] +other = "Services" + +[verb.services.description] +other = "Start and stop brew's background services" + +[verb.tap.title] +other = "Tap" + +[verb.tap.description] +other = "Your taps and how they are, or add one: brew tap user/repo" + +[tool.tap.title] +other = "Homebrew Tap" + +[tap.add] +other = "Tap {{.name}}" + +[tap.trusted] +other = "Trusted" + +[tap.untrusted] +other = "Not trusted" + +[tap.formulae] +other = "Formulae: {{.count}}" + +[tap.casks] +other = "Casks: {{.count}}" + +[tap.private] +other = "Private" + +[tap.updated] +other = "Updated {{.when}}" + +[action.open-tap] +other = "Open Tap" + +[action.tap] +other = "Tap" + +[action.trust] +other = "Trust" + +[action.untrust] +other = "Stop Trusting" + +[action.untap] +other = "Untap" + +[confirm.untap] +other = "Untap it? Homebrew removes it in Terminal; it won't if something installed comes from it." + +[trusted] +other = "Trusting {{.name}}" + +[untrusted] +other = "No longer trusting {{.name}}" + +[tag.installed] +other = "Installed" + +[tag.update] +other = "Update" + +[tag.pinned] +other = "Pinned" + +[run.running] +other = "Running {{.command}}" + +[run.done] +other = "Done: {{.command}}" + +[run.failed] +other = "Failed: {{.command}}" + +[run.in-terminal] +other = "Run in Terminal" + +[verb.update.title] +other = "Update" + +[verb.update.description] +other = "Fetch the newest Homebrew and lists of packages" + +[verb.cleanup.title] +other = "Clean Up" + +[verb.cleanup.description] +other = "Remove old versions and downloads, saying how much it freed" + +[verb.doctor.title] +other = "Doctor" + +[verb.doctor.description] +other = "Check Homebrew for problems" + +[tool.brew.title] +other = "Run brew" + +[upgrade-all.about] +other = "Upgrade the {{.count}} below" + +[jobs.refresh.title] +other = "Reads what's installed" + +[jobs.names.title] +other = "Lists Homebrew's packages" + +[jobs.refresh.description] +other = "Keeps the list of what's installed up to date" + +[jobs.names.description] +other = "Keeps the names you can install up to date" diff --git a/homebrew/locales/nb.toml b/homebrew/locales/nb.toml new file mode 100644 index 0000000..ce3f8a1 --- /dev/null +++ b/homebrew/locales/nb.toml @@ -0,0 +1,299 @@ +[toolbox.description] +other = "Finn, installer, oppgrader og fjern Homebrew-formler og -casks, se hva som har oppdateringer, og start og stopp brew sine tjenester." + +[tool.search.title] +other = "Homebrew" + +[tool.search.description] +other = "Installer, avinstaller, oppgrader og finn pakker, og start og stopp tjenester, som på kommandolinjen: brew install jq." + +[tool.service.title] +other = "Homebrew-tjeneste" + +[action.info] +other = "Vis detaljer" + +[action.install] +other = "Installer" + +[action.upgrade] +other = "Oppgrader" + +[action.uninstall] +other = "Avinstaller" + +[action.pin] +other = "Lås versjon" + +[action.unpin] +other = "Lås opp versjon" + +[action.open-site] +other = "Åpne på formulae.brew.sh" + +[action.copy-name] +other = "Kopier navn" + +[action.upgrade-all] +other = "Oppgrader alle" + +[action.start] +other = "Start" + +[action.stop] +other = "Stopp" + +[action.restart] +other = "Start på nytt" + +[confirm.uninstall] +other = "Avinstallere den? Homebrew fjerner den i Terminal." + +[kind.formula] +other = "Formel" + +[kind.cask] +other = "Cask" + +[status.not-installed] +other = "Ikke installert" + +[status.update] +other = "Oppdatering til {{.latest}}" + +[status.current] +other = "Oppdatert" + +[status.pinned] +other = "Låst" + +[none] +other = "Ingen" + +[not-found] +other = "Homebrew kjenner ikke {{.name}}" + +[card.package] +other = "Pakke" + +[card.version] +other = "Versjon" + +[card.dependencies] +other = "Avhengigheter" + +[fact.description] +other = "Om" + +[fact.kind] +other = "Type" + +[fact.tap] +other = "Tap" + +[fact.license] +other = "Lisens" + +[fact.homepage] +other = "Nettside" + +[fact.latest] +other = "Nyeste" + +[fact.installed] +other = "Installert" + +[fact.status] +other = "Status" + +[fact.needs] +other = "Trenger" + +[caveats] +other = "Merknader" + +[service.started] +other = "Kjører" + +[service.scheduled] +other = "Planlagt" + +[service.stopped] +other = "Stoppet" + +[service.none] +other = "Kjører ikke" + +[service.error] +other = "Feilet" + +[service.unknown] +other = "Ukjent" + +[no-services] +other = "Ingen installert pakke har en tjeneste" + +[started] +other = "Startet {{.name}}" + +[stopped] +other = "Stoppet {{.name}}" + +[restarted] +other = "Startet {{.name}} på nytt" + +[pinned] +other = "Låste {{.name}}" + +[unpinned] +other = "Låste opp {{.name}}" + +[name-copied] +other = "Navn kopiert" + +[verb.install.title] +other = "Installer" + +[verb.install.description] +other = "En formel eller cask du ikke har ennå" + +[verb.uninstall.title] +other = "Avinstaller" + +[verb.uninstall.description] +other = "Noe du har installert" + +[verb.upgrade.title] +other = "Oppgrader" + +[verb.upgrade.description] +other = "Det som har en nyere versjon" + +[verb.list.title] +other = "Vis installerte" + +[verb.list.description] +other = "Det du har installert" + +[verb.info.title] +other = "Info" + +[verb.info.description] +other = "En hvilken som helst formel eller cask, installert eller ikke" + +[verb.services.title] +other = "Tjenester" + +[verb.services.description] +other = "Start og stopp brew sine bakgrunnstjenester" + +[verb.tap.title] +other = "Tap" + +[verb.tap.description] +other = "Dine taps og hvordan de står til, eller legg til et: brew tap bruker/repo" + +[tool.tap.title] +other = "Homebrew-tap" + +[tap.add] +other = "Legg til {{.name}}" + +[tap.trusted] +other = "Klarert" + +[tap.untrusted] +other = "Ikke klarert" + +[tap.formulae] +other = "Formler: {{.count}}" + +[tap.casks] +other = "Casks: {{.count}}" + +[tap.private] +other = "Privat" + +[tap.updated] +other = "Oppdatert {{.when}}" + +[action.open-tap] +other = "Åpne tap" + +[action.tap] +other = "Legg til" + +[action.trust] +other = "Klarer" + +[action.untrust] +other = "Slutt å klarere" + +[action.untap] +other = "Fjern tap" + +[confirm.untap] +other = "Fjerne den? Homebrew fjerner den i Terminal; det går ikke hvis noe installert kommer fra den." + +[trusted] +other = "Klarerer {{.name}}" + +[untrusted] +other = "Klarerer ikke lenger {{.name}}" + +[tag.installed] +other = "Installert" + +[tag.update] +other = "Oppdatering" + +[tag.pinned] +other = "Låst" + +[run.running] +other = "Kjører {{.command}}" + +[run.done] +other = "Ferdig: {{.command}}" + +[run.failed] +other = "Feilet: {{.command}}" + +[run.in-terminal] +other = "Kjør i Terminal" + +[verb.update.title] +other = "Oppdater" + +[verb.update.description] +other = "Hent nyeste Homebrew og pakkelister" + +[verb.cleanup.title] +other = "Rydd opp" + +[verb.cleanup.description] +other = "Fjern gamle versjoner og nedlastinger, og si hvor mye som ble frigjort" + +[verb.doctor.title] +other = "Doctor" + +[verb.doctor.description] +other = "Sjekk Homebrew for problemer" + +[tool.brew.title] +other = "Kjør brew" + +[upgrade-all.about] +other = "Oppgrader de {{.count}} nedenfor" + +[jobs.refresh.title] +other = "Leser hva som er installert" + +[jobs.names.title] +other = "Lister Homebrews pakker" + +[jobs.refresh.description] +other = "Holder listen over det som er installert oppdatert" + +[jobs.names.description] +other = "Holder navnene du kan installere oppdatert" diff --git a/norway/assets/flag.svg b/norway/assets/flag.svg new file mode 100644 index 0000000..7bbf590 --- /dev/null +++ b/norway/assets/flag.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/norway/init.lua b/norway/init.lua new file mode 100644 index 0000000..d1916e6 --- /dev/null +++ b/norway/init.lua @@ -0,0 +1,304 @@ +-- Norway: public holidays, flag days, other days people mark and name days, for any year, with no +-- network. +-- Every date is worked out from its rule, Easter's by calculation, so nothing is downloaded or +-- kept. + +-- Dates are days since 1970-01-01, so adding days is adding numbers and no time zone gets in the +-- way. These are Howard Hinnant's days_from_civil and civil_from_days. +local function day_number(y, m, d) + if m <= 2 then y = y - 1 end + local era = math.floor(y / 400) + local yoe = y - era * 400 + local doy = math.floor((153 * (m > 2 and m - 3 or m + 9) + 2) / 5) + d - 1 + return era * 146097 + yoe * 365 + math.floor(yoe / 4) - math.floor(yoe / 100) + doy - 719468 +end + +local function civil(n) + local z = n + 719468 + local era = math.floor(z / 146097) + local doe = z - era * 146097 + local yoe = math.floor((doe - math.floor(doe / 1460) + math.floor(doe / 36524) - math.floor(doe / 146096)) / 365) + local doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100)) + local mp = math.floor((5 * doy + 2) / 153) + local d = doy - math.floor((153 * mp + 2) / 5) + 1 + local m = mp < 10 and mp + 3 or mp - 9 + return yoe + era * 400 + (m <= 2 and 1 or 0), m, d +end + +-- weekday is 0 for Sunday: 1 January 1970 was a Thursday. +local function weekday(n) return (n + 4) % 7 end + +-- easter is Easter Sunday in the Gregorian calendar, by the Meeus/Jones/Butcher algorithm. +local function easter(y) + local a, b, c = y % 19, math.floor(y / 100), y % 100 + local d, e = math.floor(b / 4), b % 4 + local f = math.floor((b + 8) / 25) + local g = math.floor((b - f + 1) / 3) + local h = (19 * a + b - d - g + 15) % 30 + local i, k = math.floor(c / 4), c % 4 + local l = (32 + 2 * e + 2 * i - h - k) % 7 + local m = math.floor((a + 11 * h + 22 * l) / 451) + local n = h + l - 7 * m + 114 + return day_number(y, math.floor(n / 31), n % 31 + 1) +end + +local function fixed(m, d) return function(y) return day_number(y, m, d) end end +local function from_easter(days) return function(y) return easter(y) + days end end + +-- sunday is the nth Sunday of a month, or with a negative n, counted from its end: -1 is the last. +local function sunday(m, n) + return function(y) + if n < 0 then + local last = (m == 12 and day_number(y + 1, 1, 1) or day_number(y, m + 1, 1)) - 1 + return last - weekday(last) + 7 * (n + 1) + end + local first = day_number(y, m, 1) + return first + (7 - weekday(first)) % 7 + 7 * (n - 1) + end +end + +-- advent is the nth Sunday of Advent: the fourth is the last Sunday before Christmas Day. +local function advent(n) + return function(y) + local christmas = day_number(y, 12, 25) + local back = weekday(christmas) + if back == 0 then back = 7 end + return christmas - back - 7 * (4 - n) + end +end + +local HOLIDAY, FLAG, NOTABLE = "holiday", "flag", "notable" + +-- days are the public holidays (lov om helligdager, and 1 and 17 May), the official flag days +-- (flaggforskriften § 4), and other days people mark, as flaggdager.no lists them, with a few +-- more. The royal family is named as it is since Kong Harald V died on 28 August 2026 and Haakon +-- became king; flaggforskriften, last changed in 2005, hasn't caught up yet. `through` is the +-- last year a day is marked, `born` a royal's year, for the age a birthday is. +local days = { + { "1. nyttårsdag", { HOLIDAY, FLAG }, fixed(1, 1) }, + { "Kronprinsesse Ingrid Alexandra", { FLAG }, fixed(1, 21), born = 2004 }, + { "Samefolkets dag", { FLAG }, fixed(2, 6) }, + { "Morsdag", { NOTABLE }, sunday(2, 2) }, + { "Valentinsdag", { NOTABLE }, fixed(2, 14) }, + { "Kong Harald V", { FLAG }, fixed(2, 21), born = 1937, through = 2026 }, + { "Fastelavnssøndag", { NOTABLE }, from_easter(-49) }, + { "Kvinnedagen", { NOTABLE }, fixed(3, 8) }, + { "Sommertid", { NOTABLE }, sunday(3, -1), note = "clocks-forward" }, + { "Palmesøndag", { NOTABLE }, from_easter(-7) }, + { "Skjærtorsdag", { HOLIDAY }, from_easter(-3) }, + { "Langfredag", { HOLIDAY }, from_easter(-2) }, + { "1. påskedag", { HOLIDAY, FLAG }, from_easter(0) }, + { "2. påskedag", { HOLIDAY }, from_easter(1) }, + { "Siste dag med piggdekk", { NOTABLE }, from_easter(8), note = "studded-tyres-end" }, + { "Båndtvang for hunder starter", { NOTABLE }, fixed(4, 1), note = "national-rule" }, + { "Bålforbud i skog og mark starter", { NOTABLE }, fixed(4, 15), note = "national-rule" }, + { "Arbeidernes dag", { HOLIDAY, FLAG }, fixed(5, 1) }, + { "Frigjøringsdagen", { FLAG }, fixed(5, 8) }, + { "Grunnlovsdagen", { HOLIDAY, FLAG }, fixed(5, 17) }, + { "Kristi himmelfartsdag", { HOLIDAY }, from_easter(39) }, + { "1. pinsedag", { HOLIDAY, FLAG }, from_easter(49) }, + { "2. pinsedag", { HOLIDAY }, from_easter(50) }, + { "Unionsoppløsningen", { FLAG }, fixed(6, 7) }, + { "Sankthansaften", { NOTABLE }, fixed(6, 23) }, + { "Dronning Sonja", { FLAG }, fixed(7, 4), born = 1937 }, + { "Kong Haakon", { FLAG }, fixed(7, 20), born = 1973 }, + { "Olsokdagen", { FLAG }, fixed(7, 29) }, + { "Dronning Mette-Marit", { FLAG }, fixed(8, 19), born = 1973 }, + { "Båndtvang for hunder opphører", { NOTABLE }, fixed(8, 21), note = "national-rule" }, + { "Bålforbud i skog og mark opphører", { NOTABLE }, fixed(9, 16), note = "national-rule" }, + { "FN-dagen", { NOTABLE }, fixed(10, 24) }, + { "Vintertid", { NOTABLE }, sunday(10, -1), note = "clocks-back" }, + { "Halloween", { NOTABLE }, fixed(10, 31) }, + { "Piggdekk tillatt", { NOTABLE }, fixed(11, 1), note = "southern-norway" }, + { "Allehelgensdag", { NOTABLE }, sunday(11, 1) }, + { "Farsdag", { NOTABLE }, sunday(11, 2) }, + { "1. søndag i advent", { NOTABLE }, advent(1) }, + { "2. søndag i advent", { NOTABLE }, advent(2) }, + { "3. søndag i advent", { NOTABLE }, advent(3) }, + { "Luciadagen", { NOTABLE }, fixed(12, 13) }, + { "4. søndag i advent", { NOTABLE }, advent(4) }, + { "Julaften", { NOTABLE }, fixed(12, 24) }, + { "1. juledag", { HOLIDAY, FLAG }, fixed(12, 25) }, + { "2. juledag", { HOLIDAY }, fixed(12, 26) }, + { "Nyttårsaften", { NOTABLE }, fixed(12, 31) }, +} + +local tags = { + { kind = HOLIDAY, tint = "red", icon = "calendar" }, + { kind = FLAG, tint = "blue", icon = "flag" }, + { kind = NOTABLE, tint = "gray" }, +} + +local function is(day, kinds) + for _, k in ipairs(day[2]) do + if kinds[k] then return true end + end + return false +end + +-- read_year takes a year out of what was typed; the other words look among the names. +local function read_year(rest) + local year, words = nil, {} + for w in rest:gmatch("%S+") do + local n = tonumber(w) + if not year and n and #w == 4 and n >= 1583 then year = n else table.insert(words, w) end + end + return year, table.concat(words, " ") +end + +local function when(today, n) + local diff = n - today + if diff == 0 then return toolshed.t("today") end + if diff == 1 then return toolshed.t("tomorrow") end + if diff == -1 then return toolshed.t("yesterday") end + if diff < 0 then return toolshed.t("days-ago", { count = -diff }) end + return toolshed.t("in-days", { count = diff }) +end + +local function date(n) + local y, m, d = civil(n) + return toolshed.t("date", { weekday = toolshed.t("weekday." .. weekday(n)), day = d, month = toolshed.t("month." .. m), year = y }) +end + +local function iso(n) + return string.format("%04d-%02d-%02d", civil(n)) +end + +local function jig(day, n, today) + local y = civil(n) + local about = { date(n), when(today, n) } + if day.born then table.insert(about, toolshed.t("turns", { age = y - day.born })) end + if day.note then table.insert(about, toolshed.t("note." .. day.note)) end + local on = {} + for _, t in ipairs(tags) do + if is(day, { [t.kind] = true }) then + table.insert(on, { text = toolshed.t("tag." .. t.kind), tint = t.tint, icon = t.icon }) + end + end + return { + key = day[1], title = day[1], subtitle = table.concat(about, ", "), tags = on, + data = { date = iso(n) }, + } +end + +-- upcoming lists the days of some kinds in a year, or without one, in the year from today, so +-- the next is first. +local function upcoming(rest, kinds) + local now = os.date("*t") + local today = day_number(now.year, now.month, now.day) + local year, filter = read_year(rest) + local from, to = today, day_number(now.year + 1, now.month, now.day) + if year then from, to = day_number(year, 1, 1), day_number(year + 1, 1, 1) end + local found = {} + for y = civil(from), civil(to) do + for i, day in ipairs(days) do + local n = day[3](y) + if is(day, kinds) and (not day.through or y <= day.through) and n >= from and n < to + and toolshed.match(filter, day[1]) > 0 then + table.insert(found, { day = day, n = n, order = i }) + end + end + end + table.sort(found, function(a, b) + if a.n ~= b.n then return a.n < b.n end + return a.order < b.order + end) + local jigs = {} + for _, f in ipairs(found) do table.insert(jigs, jig(f.day, f.n, today)) end + return jigs +end + +local name_days = require("name_days") + +local function today() + local now = os.date("*t") + return day_number(now.year, now.month, now.day) +end + +-- next_name_day is the day a month * 100 + day comes next, today or later. +local function next_name_day(md, from) + local y, m, d = civil(from), math.floor(md / 100), md % 100 + local n = day_number(y, m, d) + return n >= from and n or day_number(y + 1, m, d) +end + +-- named lists the name days of the next two weeks, or with a name typed, the names like it, the +-- closest first, each with the day it's next. +local function named(rest) + local from, query = today(), rest:match("^%s*(.-)%s*$") + local jigs = {} + if query == "" then + for n = from, from + 13 do + local _, m, d = civil(n) + local names = name_days[m * 100 + d] + if names then + local title = table.concat(names, ", ") + table.insert(jigs, { key = title, title = title, subtitle = date(n) .. ", " .. when(from, n), data = { date = iso(n) } }) + end + end + return jigs + end + local found = {} + for md, names in pairs(name_days) do + for _, name in ipairs(names) do + local score = toolshed.match(query, name) + if score > 0 then table.insert(found, { name = name, n = next_name_day(md, from), score = score }) end + end + end + table.sort(found, function(a, b) + if a.score ~= b.score then return a.score > b.score end + return a.n < b.n + end) + for _, f in ipairs(found) do + table.insert(jigs, { key = f.name, title = f.name, subtitle = date(f.n) .. ", " .. when(from, f.n), data = { date = iso(f.n) } }) + end + return jigs +end + +local copy_date = { key = "copy", title = "i18n:action.copy", icon = "copy", run = function(ctx) + toolshed.clipboard.copy(ctx.data.date) + return toolshed.t("copied", { date = ctx.data.date }) +end } + +local function days_tool(key, icon, kinds, words, keywords) + return { + key = key, + title = "i18n:tool." .. key .. ".title", + description = "i18n:tool." .. key .. ".description", + icon = icon, + words = words, + keywords = keywords, + examples = { words[1], words[1] .. " 2027" }, + items = true, + search = function(rest) return upcoming(rest, kinds) end, + actions = { copy_date }, + } +end + +return toolshed.toolbox { + key = "norway", + title = "i18n:toolbox.title", + description = "i18n:toolbox.description", + icon = "assets/flag.svg", + tint = "red", + tools = { + days_tool("holidays", "calendar", { [HOLIDAY] = true }, { "helligdager", "holidays" }, + { "røde dager", "public holidays", "påske", "easter", "pinse" }), + days_tool("flag-days", "flag", { [FLAG] = true }, { "flaggdager", "flagdays" }, + { "flag days", "flagging", "flagg" }), + days_tool("notable-days", "star", { [HOLIDAY] = true, [FLAG] = true, [NOTABLE] = true }, { "merkedager" }, + { "notable days", "morsdag", "farsdag", "advent", "sommertid", "vintertid", "båndtvang", "bålforbud", "piggdekk" }), + { + key = "name-days", + title = "i18n:tool.name-days.title", + description = "i18n:tool.name-days.description", + icon = "users", + words = { "navnedag", "nameday" }, + keywords = { "navnedager", "name day", "name days" }, + examples = { "navnedag", "navnedag karl" }, + items = true, + search = named, + actions = { copy_date }, + }, + }, +} diff --git a/norway/locales/en.toml b/norway/locales/en.toml new file mode 100644 index 0000000..b2cc7fe --- /dev/null +++ b/norway/locales/en.toml @@ -0,0 +1,137 @@ +[toolbox.title] +other = "Norway" + +[toolbox.description] +other = "Norway's public holidays, flag days, name days and other days people mark, like Morsdag, Advent and when the clocks change, for any year, with no network needed" + +[tool.holidays.title] +other = "Public Holidays in Norway" + +[tool.holidays.description] +other = "The red days in the year ahead, or in a year: helligdager 2027" + +[tool.flag-days.title] +other = "Flag Days in Norway" + +[tool.flag-days.description] +other = "The official flag days in the year ahead, or in a year: flaggdager 2027" + +[tool.notable-days.title] +other = "Notable Days in Norway" + +[tool.notable-days.description] +other = "Holidays, flag days and the days people mark, like Morsdag, Advent, summer time and båndtvang: merkedager 2027" + +[action.copy] +other = "Copy Date" + +[copied] +other = "{{.date}} copied" + +[tag.holiday] +other = "Public holiday" + +[tag.flag] +other = "Flag day" + +[tag.notable] +other = "Notable" + +[today] +other = "today" + +[tomorrow] +other = "tomorrow" + +[yesterday] +other = "yesterday" + +[in-days] +other = "in {{.count}} days" + +[days-ago] +other = "{{.count}} days ago" + +[turns] +other = "turns {{.age}}" + +[date] +other = "{{.weekday}} {{.day}} {{.month}} {{.year}}" + +[note.clocks-forward] +other = "clocks go from 2 to 3" + +[note.clocks-back] +other = "clocks go from 3 to 2" + +[note.national-rule] +other = "the national rule, a kommune may set its own" + +[note.southern-norway] +other = "in southern Norway" + +[note.studded-tyres-end] +other = "in southern Norway, the first Monday after 2. påskedag" + +[weekday.0] +other = "Sunday" + +[weekday.1] +other = "Monday" + +[weekday.2] +other = "Tuesday" + +[weekday.3] +other = "Wednesday" + +[weekday.4] +other = "Thursday" + +[weekday.5] +other = "Friday" + +[weekday.6] +other = "Saturday" + +[month.1] +other = "January" + +[month.2] +other = "February" + +[month.3] +other = "March" + +[month.4] +other = "April" + +[month.5] +other = "May" + +[month.6] +other = "June" + +[month.7] +other = "July" + +[month.8] +other = "August" + +[month.9] +other = "September" + +[month.10] +other = "October" + +[month.11] +other = "November" + +[month.12] +other = "December" + +[tool.name-days.title] +other = "Name Days in Norway" + +[tool.name-days.description] +other = "Who has their name day in the next two weeks, or when a name has it: navnedag karl" diff --git a/norway/locales/nb.toml b/norway/locales/nb.toml new file mode 100644 index 0000000..793102d --- /dev/null +++ b/norway/locales/nb.toml @@ -0,0 +1,137 @@ +[toolbox.title] +other = "Norge" + +[toolbox.description] +other = "Norges helligdager, flaggdager, navnedager og andre merkedager, som morsdag, advent og når klokka stilles, for hvilket som helst år, uten nett" + +[tool.holidays.title] +other = "Helligdager" + +[tool.holidays.description] +other = "De røde dagene i året som kommer, eller i et år: helligdager 2027" + +[tool.flag-days.title] +other = "Flaggdager" + +[tool.flag-days.description] +other = "De offisielle flaggdagene i året som kommer, eller i et år: flaggdager 2027" + +[tool.notable-days.title] +other = "Merkedager" + +[tool.notable-days.description] +other = "Helligdager, flaggdager og andre merkedager, som morsdag, advent, sommertid og båndtvang: merkedager 2027" + +[action.copy] +other = "Kopier dato" + +[copied] +other = "{{.date}} kopiert" + +[tag.holiday] +other = "Helligdag" + +[tag.flag] +other = "Flaggdag" + +[tag.notable] +other = "Merkedag" + +[today] +other = "i dag" + +[tomorrow] +other = "i morgen" + +[yesterday] +other = "i går" + +[in-days] +other = "om {{.count}} dager" + +[days-ago] +other = "for {{.count}} dager siden" + +[turns] +other = "fyller {{.age}}" + +[date] +other = "{{.weekday}} {{.day}}. {{.month}} {{.year}}" + +[note.clocks-forward] +other = "klokka stilles fra 2 til 3" + +[note.clocks-back] +other = "klokka stilles fra 3 til 2" + +[note.national-rule] +other = "nasjonal regel, kommunen kan bestemme annet" + +[note.southern-norway] +other = "i Sør-Norge" + +[note.studded-tyres-end] +other = "i Sør-Norge, første mandag etter 2. påskedag" + +[weekday.0] +other = "søndag" + +[weekday.1] +other = "mandag" + +[weekday.2] +other = "tirsdag" + +[weekday.3] +other = "onsdag" + +[weekday.4] +other = "torsdag" + +[weekday.5] +other = "fredag" + +[weekday.6] +other = "lørdag" + +[month.1] +other = "januar" + +[month.2] +other = "februar" + +[month.3] +other = "mars" + +[month.4] +other = "april" + +[month.5] +other = "mai" + +[month.6] +other = "juni" + +[month.7] +other = "juli" + +[month.8] +other = "august" + +[month.9] +other = "september" + +[month.10] +other = "oktober" + +[month.11] +other = "november" + +[month.12] +other = "desember" + +[tool.name-days.title] +other = "Navnedager" + +[tool.name-days.description] +other = "Hvem som har navnedag de neste to ukene, eller når et navn har det: navnedag karl" diff --git a/norway/name_days.lua b/norway/name_days.lua new file mode 100644 index 0000000..a41ad71 --- /dev/null +++ b/norway/name_days.lua @@ -0,0 +1,368 @@ +-- The Norwegian name days, from Almanakkforlaget's calendar (last revised December 2025) as +-- https://no.wikipedia.org/wiki/Liste_over_norske_navnedager lists it, by month * 100 + day. +-- 1 January, 29 February and 25 December have none. +return { + [102] = { "Dagfinn", "Dagfrid" }, + [103] = { "Alfred", "Alf", "Alva" }, + [104] = { "Roar", "Roger" }, + [105] = { "Hanna", "Hanne" }, + [106] = { "Aslaug", "Aisha", "Alex" }, + [107] = { "Eldbjørg", "Knut" }, + [108] = { "Turid", "Torfinn" }, + [109] = { "Gunnar", "Gunn" }, + [110] = { "Sigmund", "Sigrun", "Sina" }, + [111] = { "Børge", "Børre" }, + [112] = { "Nelly", "Nataniel" }, + [113] = { "Gisle", "Gislaug" }, + [114] = { "Herbjørn", "Herbjørg", "Hermine" }, + [115] = { "Laurits", "Laura", "Lykke" }, + [116] = { "Hjalmar", "Hilmar", "Hassan" }, + [117] = { "Anton", "Tønnes", "Tony" }, + [118] = { "Hildur", "Hild" }, + [119] = { "Marius", "Margunn", "Matheo" }, + [120] = { "Fabian", "Sebastian", "Bastian" }, + [121] = { "Agnes", "Agnete", "Abdul" }, + [122] = { "Ivan", "Vanja", "Vanessa" }, + [123] = { "Emil", "Emilie", "Emma" }, + [124] = { "Joar", "Jarle", "Jarl" }, + [125] = { "Paul", "Pål" }, + [126] = { "Øystein", "Esten" }, + [127] = { "Gaute", "Gry" }, + [128] = { "Karl", "Karoline", "Carlos" }, + [129] = { "Herdis", "Hermod", "Hermann" }, + [130] = { "Gunnhild", "Gunda" }, + [131] = { "Idun", "Ivar" }, + [201] = { "Birte", "Bjarte" }, + [202] = { "Jomar", "Jostein", "Omar", "Bianca" }, + [203] = { "Ansgar", "Asgeir", "Angelika" }, + [204] = { "Veronika", "Vera" }, + [205] = { "Agate", "Ågot" }, + [206] = { "Dortea", "Dorte", "Dominik" }, + [207] = { "Rikard", "Rigmor" }, + [208] = { "Åshild", "Åsne", "Ådne" }, + [209] = { "Lone", "Leikny", "Levi" }, + [210] = { "Ingfrid", "Ingrid" }, + [211] = { "Ingve", "Yngve" }, + [212] = { "Randi", "Ronja" }, + [213] = { "Svanhild", "Scott" }, + [214] = { "Valentin", "Valentina" }, + [215] = { "Sigbjørn", "Silas", "Sienna" }, + [216] = { "Julian", "Juliane", "Jill" }, + [217] = { "Aleksandra", "Sandra", "Sondre" }, + [218] = { "Frøydis", "Frode", "Fatima" }, + [219] = { "Ella", "Elna", "Ebba" }, + [220] = { "Halldis", "Halldor" }, + [221] = { "Samuel", "Selma", "Celine" }, + [222] = { "Tina", "Tim", "Tilde" }, + [223] = { "Torstein", "Torunn" }, + [224] = { "Mattias", "Mattis", "Mats" }, + [225] = { "Viktor", "Viktoria", "Vincent" }, + [226] = { "Inger", "Ingjerd" }, + [227] = { "Leander", "Laila", "Lill" }, + [228] = { "Marina", "Maren", "Mira" }, + [301] = { "Audny", "Audun" }, + [302] = { "Erna", "Ernst" }, + [303] = { "Gunnbjørg", "Gunnveig", "Gunnlaug" }, + [304] = { "Ada", "Adrian", "Adele" }, + [305] = { "Patrick", "Patricia" }, + [306] = { "Annfrid", "Aida", "Alida" }, + [307] = { "Arild", "Are", "Ali" }, + [308] = { "Beate", "Betty", "Bettina" }, + [309] = { "Sverre", "Sindre" }, + [310] = { "Edel", "Edle" }, + [311] = { "Edvin", "Tale" }, + [312] = { "Gregor", "Gro" }, + [313] = { "Greta", "Grete" }, + [314] = { "Mathilde", "Mette", "Mille" }, + [315] = { "Christel", "Christer", "Chris" }, + [316] = { "Gudmund", "Gudny" }, + [317] = { "Gjertrud", "Trude" }, + [318] = { "Aleksander", "Sander", "Edvard" }, + [319] = { "Josef", "Josefine", "Joel" }, + [320] = { "Joakim", "Kim" }, + [321] = { "Bendik", "Bengt", "Bent" }, + [322] = { "Paula", "Pauline" }, + [323] = { "Gerda", "Gerd" }, + [324] = { "Ulrikke", "Rikke" }, + [325] = { "Maria", "Marie", "Mari" }, + [326] = { "Gabriel", "Glenn" }, + [327] = { "Rudolf", "Rudi" }, + [328] = { "Åsta", "Åste" }, + [329] = { "Jonas", "Jonatan" }, + [330] = { "Holger", "Olga", "Olai" }, + [331] = { "Vebjørn", "Vegard" }, + [401] = { "Aron", "Arve", "Arvid" }, + [402] = { "Sigvard", "Sivert" }, + [403] = { "Gunnvald", "Gunvor" }, + [404] = { "Nanna", "Nancy", "Nina" }, + [405] = { "Irene", "Eirin", "Eiril" }, + [406] = { "Åsmund", "Asmund" }, + [407] = { "Oddveig", "Oddvin" }, + [408] = { "Asle", "Atle", "Ava" }, + [409] = { "Rannveig", "Rønnaug" }, + [410] = { "Ingvald", "Ingveig" }, + [411] = { "Ylva", "Ulf" }, + [412] = { "Julius", "Julie" }, + [413] = { "Asta", "Astrid" }, + [414] = { "Ellinor", "Nora", "Noah" }, + [415] = { "Oda", "Odin", "Odd" }, + [416] = { "Magnus", "Mons", "Mohammad" }, + [417] = { "Elise", "Else", "Elsa" }, + [418] = { "Eilen", "Eilert" }, + [419] = { "Arnfinn", "Arnstein", "Alvin" }, + [420] = { "Kjellaug", "Kjellrun" }, + [421] = { "Jeanette", "Jannike", "Jessica" }, + [422] = { "Oddgeir", "Oddny" }, + [423] = { "Georg", "Jørgen", "Jørn" }, + [424] = { "Albert", "Olaug", "Olivia" }, + [425] = { "Markus", "Mark", "Marco" }, + [426] = { "Terese", "Tea", "Telma" }, + [427] = { "Charles", "Charlotte", "Lotte" }, + [428] = { "Vivi", "Vivian", "Viljar" }, + [429] = { "Toralf", "Torolf" }, + [430] = { "Gina", "Gitte" }, + [501] = { "Filip", "Valborg", "Filippa" }, + [502] = { "Åsa", "Åse" }, + [503] = { "Gjermund", "Gøril" }, + [504] = { "Monika", "Mona", "Milla" }, + [505] = { "Nicole", "Noel", "Noor" }, + [506] = { "Guri", "Gyri", "Gudbrand" }, + [507] = { "Maia", "Mai", "Maiken" }, + [508] = { "Åge", "Åke", "Åslaug" }, + [509] = { "Kasper", "Jesper", "Kaspian" }, + [510] = { "Asbjørg", "Asbjørn", "Espen" }, + [511] = { "Magda", "Malvin", "Madelen" }, + [512] = { "Normann", "Norvald" }, + [513] = { "Linda", "Line", "Linn" }, + [514] = { "Kristian", "Kristen", "Karsten" }, + [515] = { "Hallvard", "Halvor" }, + [516] = { "Sara", "Siren", "Samira" }, + [517] = { "Harald", "Ragnhild" }, + [518] = { "Eirik", "Erik", "Erika" }, + [519] = { "Torjus", "Torje", "Truls" }, + [520] = { "Bjørnar", "Bror" }, + [521] = { "Helene", "Ellen", "Eli" }, + [522] = { "Henning", "Henny" }, + [523] = { "Oddleif", "Oddlaug" }, + [524] = { "Ester", "Iris" }, + [525] = { "Ragna", "Ragnar" }, + [526] = { "Annbjørg", "Annlaug", "Anneli" }, + [527] = { "Katinka", "Cato", "Carmen" }, + [528] = { "Vilhelm", "William", "Willy" }, + [529] = { "Magnar", "Magnhild", "Mario" }, + [530] = { "Gard", "Geir" }, + [531] = { "Pernille", "Preben" }, + [601] = { "June", "Juni" }, + [602] = { "Runa", "Runar", "Rune" }, + [603] = { "Rasmus", "Rakel", "Rafael" }, + [604] = { "Heidi", "Heid", "Helmer" }, + [605] = { "Torbjørg", "Torbjørn", "Torben" }, + [606] = { "Gustav", "Gyda" }, + [607] = { "Robert", "Robin" }, + [608] = { "Renate", "René" }, + [609] = { "Kolbjørn", "Kassandra" }, + [610] = { "Ingolf", "Ingunn" }, + [611] = { "Borgar", "Bjørge", "Bjørg" }, + [612] = { "Sigfrid", "Sigrid", "Siri" }, + [613] = { "Tone", "Tonje", "Tanja" }, + [614] = { "Erlend", "Erland", "Erle" }, + [615] = { "Vigdis", "Viggo", "Vilja" }, + [616] = { "Torhild", "Toril", "Tiril" }, + [617] = { "Botolv", "Bodil" }, + [618] = { "Bjarne", "Bjørn" }, + [619] = { "Erling", "Elling", "Ellie" }, + [620] = { "Sølve", "Sølvi" }, + [621] = { "Agnar", "Annar", "Ahmed" }, + [622] = { "Håkon", "Maud" }, + [623] = { "Elfrid", "Eldrid", "Elliot" }, + [624] = { "Johannes", "Jon", "Hans" }, + [625] = { "Jørund", "Jorunn" }, + [626] = { "Jenny", "Jonny", "Jennifer" }, + [627] = { "Aina", "Ina", "Ine" }, + [628] = { "Lea", "Leo", "Leon" }, + [629] = { "Peter", "Petter", "Per" }, + [630] = { "Solbjørg", "Solgunn", "Sol" }, + [701] = { "Ask", "Embla" }, + [702] = { "Kjartan", "Kjellfrid" }, + [703] = { "Andrea", "Andrine", "André" }, + [704] = { "Ulrik", "Ulla" }, + [705] = { "Mirjam", "Mina", "Michelle" }, + [706] = { "Torgrim", "Torgunn" }, + [707] = { "Håvard", "Hulda", "Hussein" }, + [708] = { "Sunniva", "Synnøve", "Synne" }, + [709] = { "Gøran", "Jøran", "Ørjan" }, + [710] = { "Anita", "Anja", "Amina" }, + [711] = { "Kjetil", "Kjell" }, + [712] = { "Elias", "Eldar", "Elida" }, + [713] = { "Mildrid", "Melissa", "Mia" }, + [714] = { "Solfrid", "Solrun", "Frøya" }, + [715] = { "Oddmund", "Oddrun" }, + [716] = { "Susanne", "Sanna", "Saga" }, + [717] = { "Guttorm", "Gorm" }, + [718] = { "Arnulf", "Ørnulf" }, + [719] = { "Gerhard", "Gjert" }, + [720] = { "Margareta", "Margit", "Marit" }, + [721] = { "Johanne", "Janne", "Jane" }, + [722] = { "Malene", "Malin", "Mali" }, + [723] = { "Brita", "Brit", "Britt" }, + [724] = { "Kristine", "Kristin", "Kristi" }, + [725] = { "Jakob", "Jack", "Jim" }, + [726] = { "Anna", "Anne", "Ane" }, + [727] = { "Marita", "Rita" }, + [728] = { "Reidar", "Reidun" }, + [729] = { "Olav", "Ola", "Ole" }, + [730] = { "Aurora", "Audhild", "Aud" }, + [731] = { "Elin", "Eline", "Elina" }, + [801] = { "Peder", "Petra" }, + [802] = { "Karen", "Karin", "Karina" }, + [803] = { "Oline", "Oliver", "Olve" }, + [804] = { "Arnhild", "Arna", "Arne" }, + [805] = { "Osvald", "Oskar" }, + [806] = { "Loke", "Lilja", "Luis" }, + [807] = { "Didrik", "Doris" }, + [808] = { "Evy", "Yvonne", "Yasmin" }, + [809] = { "Ronald", "Ronny" }, + [810] = { "Lorents", "Lars", "Lasse" }, + [811] = { "Torvald", "Tarald", "Tara" }, + [812] = { "Klara", "Camilla", "Lara" }, + [813] = { "Anny", "Anine", "Ann" }, + [814] = { "Stella", "Storm" }, + [815] = { "Margot", "Mary", "Marielle" }, + [816] = { "Brage", "Brynjulf", "Brynhild" }, + [817] = { "Verner", "Wenche" }, + [818] = { "Tormod", "Torodd", "Valdemar" }, + [819] = { "Sigvald", "Sigve" }, + [820] = { "Bernhard", "Bernt" }, + [821] = { "Ragnvald", "Ragni" }, + [822] = { "Harriet", "Harry" }, + [823] = { "Signe", "Signy" }, + [824] = { "Belinda", "Bertil" }, + [825] = { "Ludvig", "Lovise", "Louise" }, + [826] = { "Øyvind", "Eivind", "Even" }, + [827] = { "Roald", "Rolf" }, + [828] = { "Artur", "August", "Angela" }, + [829] = { "Johan", "Jone", "Jo" }, + [830] = { "Benjamin", "Ben" }, + [831] = { "Aria", "Ariana", "Ariel" }, + [901] = { "Solveig", "Solvor" }, + [902] = { "Lisa", "Lise", "Liss" }, + [903] = { "Alise", "Alvhild", "Vilde" }, + [904] = { "Ida", "Idar", "Iben" }, + [905] = { "Brede", "Brian", "Njål" }, + [906] = { "Siril", "Siv" }, + [907] = { "Regine", "Rose" }, + [908] = { "Amalie", "Alma", "Allan" }, + [909] = { "Trygve", "Tyra", "Trym" }, + [910] = { "Tord", "Tor" }, + [911] = { "Dagny", "Dag", "Damian" }, + [912] = { "Jofrid", "Jorid" }, + [913] = { "Stian", "Stig" }, + [914] = { "Ingebjørg", "Ingeborg" }, + [915] = { "Aslak", "Eskil", "Ailo" }, + [916] = { "Lillian", "Lilly", "Linnea" }, + [917] = { "Hildegunn", "Hjørdis" }, + [918] = { "Henriette", "Henry" }, + [919] = { "Konstanse", "Connie", "Kornelia" }, + [920] = { "Tobias", "Tage" }, + [921] = { "Trine", "Trond", "Tamara" }, + [922] = { "Kyrre", "Kåre" }, + [923] = { "Snorre", "Snefrid" }, + [924] = { "Jan", "Jens" }, + [925] = { "Ingvar", "Yngvar" }, + [926] = { "Einar", "Endre", "Elvira" }, + [927] = { "Dagmar", "Dagrun" }, + [928] = { "Lena", "Lene", "Elena" }, + [929] = { "Mikael", "Mikal", "Mikkel" }, + [930] = { "Helga", "Helge", "Hege" }, + [1001] = { "Rebekka", "Remi" }, + [1002] = { "Live", "Liv", "Linus" }, + [1003] = { "Evald", "Evelyn", "Emine" }, + [1004] = { "Frans", "Frank", "Fanny" }, + [1005] = { "Brynjar", "Boye", "Bo" }, + [1006] = { "Målfrid", "Møyfrid", "Mio" }, + [1007] = { "Birgitte", "Birgit", "Berit" }, + [1008] = { "Benedikte", "Bente" }, + [1009] = { "Leif", "Liam", "Dennis" }, + [1010] = { "Fridtjof", "Frida", "Frits" }, + [1011] = { "Kevin", "Kennet", "Kent" }, + [1012] = { "Valter", "Vibeke", "Vilma" }, + [1013] = { "Terje", "Tarjei", "Torgeir" }, + [1014] = { "Kaia", "Kai", "Kaisa" }, + [1015] = { "Hedvig", "Hedda" }, + [1016] = { "Finn", "Felix", "Ferdinand" }, + [1017] = { "Marta", "Marte", "Mathea" }, + [1018] = { "Kjersti", "Kjerstin", "Lukas" }, + [1019] = { "Tora", "Tore" }, + [1020] = { "Henrik", "Heine", "Henrikke" }, + [1021] = { "Bergljot", "Birger", "Birk" }, + [1022] = { "Karianne", "Karine", "Kine" }, + [1023] = { "Severin", "Søren", "Sean" }, + [1024] = { "Eilif", "Eivor", "Emrik" }, + [1025] = { "Margrete", "Merete", "Märta" }, + [1026] = { "Amandus", "Amanda" }, + [1027] = { "Sturla", "Sture" }, + [1028] = { "Simon", "Simen", "Simone" }, + [1029] = { "Norunn", "Naomi", "Nikoline" }, + [1030] = { "Aksel", "Ove" }, + [1031] = { "Edit", "Edna" }, + [1101] = { "Veslemøy", "Vetle" }, + [1102] = { "Tove", "Tuva" }, + [1103] = { "Raymond", "Roy" }, + [1104] = { "Otto", "Ottar", "Otilie" }, + [1105] = { "Egil", "Egon", "Eira" }, + [1106] = { "Leonard", "Lennart", "Leonora" }, + [1107] = { "Ingebrigt", "Ingelin" }, + [1108] = { "Ingvild", "Yngvild" }, + [1109] = { "Tordis", "Teodor", "Theo" }, + [1110] = { "Gudbjørg", "Gudveig" }, + [1111] = { "Martin", "Morten", "Martine" }, + [1112] = { "Torkjell", "Torkil", "Tomine" }, + [1113] = { "Kirsten", "Kirsti" }, + [1114] = { "Fredrik", "Fred", "Freddy" }, + [1115] = { "Oddfrid", "Oddvar" }, + [1116] = { "Edmund", "Edgar", "Emilian" }, + [1117] = { "Hugo", "Hogne", "Hauk" }, + [1118] = { "Magne", "Magny" }, + [1119] = { "Elisabet", "Lisbet" }, + [1120] = { "Halvdan", "Helle" }, + [1121] = { "Mariann", "Marianne", "Max" }, + [1122] = { "Cecilie", "Silje", "Sissel" }, + [1123] = { "Klement", "Klaus", "Klaudia" }, + [1124] = { "Gudrun", "Guro" }, + [1125] = { "Katarina", "Katrine", "Kari" }, + [1126] = { "Konrad", "Kurt" }, + [1127] = { "Torlaug", "Torleif", "Colin" }, + [1128] = { "Ruben", "Rut" }, + [1129] = { "Sofie", "Sonja", "Sofia" }, + [1130] = { "Andreas", "Anders", "Ana" }, + [1201] = { "Arnold", "Arnljot", "Arnt" }, + [1202] = { "Borghild", "Borgny", "Bård" }, + [1203] = { "Sveinung", "Svein" }, + [1204] = { "Barbara", "Barbro" }, + [1205] = { "Stine", "Ståle" }, + [1206] = { "Nikolai", "Nils", "Niklas" }, + [1207] = { "Hallfrid", "Hallstein", "Hallgeir" }, + [1208] = { "Marlene", "Marion", "Morgan" }, + [1209] = { "Anniken", "Annette" }, + [1210] = { "Judit", "James", "Jardar" }, + [1211] = { "Daniel", "Dan", "Daniela" }, + [1212] = { "Pia", "Peggy" }, + [1213] = { "Lucia", "Lydia", "Luna" }, + [1214] = { "Steinar", "Stein" }, + [1215] = { "Hilda", "Hilde" }, + [1216] = { "Oddbjørg", "Oddbjørn" }, + [1217] = { "Inga", "Inge", "Iman" }, + [1218] = { "Kristoffer", "Kate", "Kristiane" }, + [1219] = { "Iselin", "Isak", "Isa" }, + [1220] = { "Abraham", "Amund", "Abel" }, + [1221] = { "Tomas", "Tom", "Tommy" }, + [1222] = { "Ingemar", "Ingar" }, + [1223] = { "Sigurd", "Sjur" }, + [1224] = { "Adam", "Eva" }, + [1226] = { "Stefan", "Steffen", "Steven" }, + [1227] = { "Narve", "Natalie", "Nadia" }, + [1228] = { "Unni", "Une", "Unn" }, + [1229] = { "Vidar", "Vemund", "Vårin" }, + [1230] = { "David", "Diana", "Dina" }, + [1231] = { "Sylfest", "Sylvia", "Sylvi" }, +} diff --git a/projects/init.lua b/projects/init.lua new file mode 100644 index 0000000..fecfffc --- /dev/null +++ b/projects/init.lua @@ -0,0 +1,178 @@ +-- Open projects with the `dev` command: "p toolshed" does what `dev ~/git/toolshed` does, +-- a Kitty tab backed by a tmux session. Lists the repos under the folders below plus every +-- project dev remembers; remembered ones rank first and running sessions are marked live. + +local home = os.getenv("HOME") +local roots = { home .. "/git" } +local registry = (os.getenv("XDG_STATE_HOME") or (home .. "/.local/state")) .. "/dev/projects" + +-- Scanning folders and asking tmux on every keystroke would be wasteful. +local cache_seconds = 10 +local cached, cached_at = nil, 0 + +local function lines(text) + local out = {} + for line in text:gmatch("[^\n]+") do table.insert(out, line) end + return out +end + +local function read_registry() + local f = io.open(registry, "r") + if not f then return {} end + local text = f:read("*a") + f:close() + return lines(text) +end + +-- Same rule as dev's name_of: tmux session names can't hold '.' or ':'. +local function session_name(path) + return (path:match("([^/]+)/*$") or path):gsub("[.:]", "_") +end + +local function live_sessions() + local ok, out = pcall(toolshed.exec, { "tmux", "list-sessions", "-F", "#{session_name}" }) + local live = {} + if ok then + for _, name in ipairs(lines(out)) do live[name] = true end + end + return live +end + +local function projects() + if cached and os.time() - cached_at < cache_seconds then return cached end + + local list, seen = {}, {} + local function add(path, remembered) + if seen[path] then + if remembered then seen[path].remembered = true end + return + end + local p = { path = path, name = path:match("([^/]+)$"), remembered = remembered } + seen[path] = p + table.insert(list, p) + end + + for _, path in ipairs(read_registry()) do add(path, true) end + for _, root in ipairs(roots) do + local ok, out = pcall(toolshed.exec, { "find", root, "-mindepth", "2", "-maxdepth", "2", "-name", ".git" }) + if ok then + for _, git in ipairs(lines(out)) do add((git:gsub("/%.git$", "")), false) end + end + end + + local live = live_sessions() + for _, p in ipairs(list) do p.live = live[session_name(p.path)] == true end + + cached, cached_at = list, os.time() + return list +end + +-- git@host:owner/repo.git and https://host/owner/repo.git both become https://host/owner/repo. +local function web_url(remote) + remote = remote:gsub("%s+$", ""):gsub("%.git$", "") + local host, path = remote:match("^[%w._-]+@([^:]+):(.+)$") + if host then return "https://" .. host .. "/" .. path end + host, path = remote:match("^ssh://[^@]+@([^/:]+)[:%d]*/(.+)$") + if host then return "https://" .. host .. "/" .. path end + if remote:match("^https?://") then return remote end + return nil +end + +-- A tab already showing the project is focused wherever it is; place only decides where a +-- new one opens. Without a place, the open_in setting decides. +local function open_action(key, title, place) + return { + key = key, + title = title, + run = function(ctx) + toolshed.exec({ "dev", "--in", place or ctx.settings.open_in, ctx.data.path }) + cached = nil -- a session now runs, and dev remembers the project + end, + } +end + +return toolshed.toolbox { + key = "projects", + title = "i18n:toolbox.title", + description = "i18n:toolbox.description", + icon = "folder-git-2", + tint = "orange", + requires = { { command = "dev" }, { command = "tmux" } }, + + settings = { + { + key = "open_in", + title = "i18n:setting.open_in.title", + description = "i18n:setting.open_in.description", + type = "choice", + default = "dropdown", + options = { + { value = "desktop", title = "i18n:setting.open_in.desktop" }, + { value = "dropdown", title = "i18n:setting.open_in.dropdown" }, + }, + }, + }, + + tools = { { + key = "search", + title = "i18n:tool.search.title", + words = { "p" }, + keywords = { "prosjekter", "repo" }, + items = true, + + search = function(rest) + local matches = {} + for _, p in ipairs(projects()) do + local score = toolshed.match(rest, p.name) + if score > 0 then + if p.live then score = score + 0.1 elseif p.remembered then score = score + 0.05 end + table.insert(matches, { score = score, project = p }) + end + end + table.sort(matches, function(a, b) + if a.score ~= b.score then return a.score > b.score end + return a.project.name:lower() < b.project.name:lower() + end) + + local items = {} + for i = 1, math.min(#matches, 30) do + local p = matches[i].project + table.insert(items, { + title = p.name, + subtitle = (p.live and (toolshed.t("live") .. " · ") or "") .. p.path:gsub("^" .. home:gsub("%p", "%%%0"), "~"), + data = { path = p.path }, + }) + end + return items + end, + + actions = { + open_action("open", "i18n:action.search.open"), + open_action("open-desktop", "i18n:action.search.open-desktop", "desktop"), + open_action("open-dropdown", "i18n:action.search.open-dropdown", "dropdown"), + { + key = "finder", + title = "i18n:action.search.finder", + run = function(ctx) toolshed.open(ctx.data.path) end, + }, + { + key = "copy-path", + title = "i18n:action.search.copy-path", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.path) + return toolshed.t("path-copied") + end, + }, + { + key = "web", + title = "i18n:action.search.web", + run = function(ctx) + local ok, remote = pcall(toolshed.exec, { "git", "-C", ctx.data.path, "remote", "get-url", "origin" }) + local url = ok and web_url(remote) + if not url then error(toolshed.t("no-web-address")) end + toolshed.open(url) + end, + }, + }, + } }, +} diff --git a/projects/locales/en.toml b/projects/locales/en.toml new file mode 100644 index 0000000..3445396 --- /dev/null +++ b/projects/locales/en.toml @@ -0,0 +1,47 @@ +[toolbox.title] +other = "Projects" + +[toolbox.description] +other = "Open a project in a Kitty tab with its tmux session, the same as the dev command." + +[setting.open_in.title] +other = "Open new projects in" + +[setting.open_in.description] +other = "Projects already open in Kitty stay where they are" + +[setting.open_in.desktop] +other = "Desktop tab" + +[setting.open_in.dropdown] +other = "Dropdown" + +[tool.search.title] +other = "Projects" + +[action.search.open] +other = "Open" + +[action.search.open-desktop] +other = "Open in Desktop Tab" + +[action.search.open-dropdown] +other = "Open in Dropdown" + +[action.search.finder] +other = "Show in Finder" + +[action.search.copy-path] +other = "Copy Path" + +[action.search.web] +other = "Open Repository in Browser" + +[live] +other = "● live" + +[path-copied] +other = "Path copied" + +[no-web-address] +other = "No web address for this repository's origin remote" diff --git a/projects/locales/nb.toml b/projects/locales/nb.toml new file mode 100644 index 0000000..f0b992c --- /dev/null +++ b/projects/locales/nb.toml @@ -0,0 +1,47 @@ +[toolbox.title] +other = "Prosjekter" + +[toolbox.description] +other = "Åpne et prosjekt i en Kitty-fane med tmux-økten sin, slik dev-kommandoen gjør." + +[setting.open_in.title] +other = "Åpne nye prosjekter i" + +[setting.open_in.description] +other = "Prosjekter som allerede er åpne i Kitty, blir der de er" + +[setting.open_in.desktop] +other = "Fane på skrivebordet" + +[setting.open_in.dropdown] +other = "Nedtrekksvindu" + +[tool.search.title] +other = "Prosjekter" + +[action.search.open] +other = "Åpne" + +[action.search.open-desktop] +other = "Åpne i fane på skrivebordet" + +[action.search.open-dropdown] +other = "Åpne i nedtrekksvinduet" + +[action.search.finder] +other = "Vis i Finder" + +[action.search.copy-path] +other = "Kopier sti" + +[action.search.web] +other = "Åpne repoet i nettleseren" + +[live] +other = "● kjører" + +[path-copied] +other = "Sti kopiert" + +[no-web-address] +other = "Ingen nettadresse for origin-remoten til dette repoet" diff --git a/scripts/init.lua b/scripts/init.lua new file mode 100644 index 0000000..1303161 --- /dev/null +++ b/scripts/init.lua @@ -0,0 +1,41 @@ +-- Scripts: your own small commands (fixes, cleanups, other jobs), each a tool of its own, so it +-- can be found by name ("bluetooth") and given a hotkey. Add one as another tool below; when a +-- theme grows, it can move to an extension of its own. + +-- The Magic Keyboard and Trackpad sometimes only work with the cable in, and forgetting and +-- re-pairing them doesn't help. Restarting bluetoothd does, and macOS starts it again within +-- seconds. That takes root, so macOS asks for an administrator password. +local function restart_bluetooth() + local ok, err = pcall(toolshed.exec, { + "/usr/bin/osascript", "-e", + 'do shell script "/usr/bin/pkill bluetoothd" with administrator privileges', + }) + if ok then return toolshed.t("restarted") end + -- -128 is the password dialog being cancelled, which needs no message. + if tostring(err):find("-128", 1, true) then return nil end + error(toolshed.t("failed", { error = tostring(err) })) +end + +return toolshed.toolbox { + key = "scripts", + title = "i18n:toolbox.title", + description = "i18n:toolbox.description", + icon = "wrench", + tint = "orange", + tools = { + { + key = "restart-bluetooth", + title = "i18n:tool.restart-bluetooth.title", + icon = "bluetooth", + keywords = { "bluetooth", "keyboard", "trackpad", "mouse", "fix", "reconnect", "tastatur", "mus", "fiks", "koble til" }, + actions = { + { + key = "restart", + title = "i18n:action.restart-bluetooth.restart", + confirm = "i18n:confirm.restart-bluetooth", + run = restart_bluetooth, + }, + }, + }, + }, +} diff --git a/scripts/locales/en.toml b/scripts/locales/en.toml new file mode 100644 index 0000000..d5884a7 --- /dev/null +++ b/scripts/locales/en.toml @@ -0,0 +1,20 @@ +[toolbox.title] +other = "Scripts" + +[toolbox.description] +other = "Your own commands: fixes, cleanups and other small jobs." + +[tool.restart-bluetooth.title] +other = "Restart Bluetooth" + +[action.restart-bluetooth.restart] +other = "Restart Bluetooth" + +[confirm.restart-bluetooth] +other = "Restart Bluetooth? Wireless keyboards, mice and headphones disconnect for a few seconds." + +[restarted] +other = "Bluetooth restarted" + +[failed] +other = "Bluetooth restart failed: {{.error}}" diff --git a/scripts/locales/nb.toml b/scripts/locales/nb.toml new file mode 100644 index 0000000..ffda221 --- /dev/null +++ b/scripts/locales/nb.toml @@ -0,0 +1,20 @@ +[toolbox.title] +other = "Skript" + +[toolbox.description] +other = "Dine egne kommandoer: fikser, opprydding og andre små jobber." + +[tool.restart-bluetooth.title] +other = "Start Bluetooth på nytt" + +[action.restart-bluetooth.restart] +other = "Start Bluetooth på nytt" + +[confirm.restart-bluetooth] +other = "Starte Bluetooth på nytt? Trådløse tastaturer, mus og hodetelefoner kobles fra i noen sekunder." + +[restarted] +other = "Bluetooth startet på nytt" + +[failed] +other = "Klarte ikke å starte Bluetooth på nytt: {{.error}}" diff --git a/secrets/init.lua b/secrets/init.lua new file mode 100644 index 0000000..87959df --- /dev/null +++ b/secrets/init.lua @@ -0,0 +1,93 @@ +-- Search secrets with lazysecrets (https://github.com/karleinarb/lazysecrets): "s db-password". +-- Lists only what lazysecrets has cached, so typing never waits on Azure or Databricks; +-- open lazysecrets now and then to refresh it. + +-- Running lazysecrets on every keystroke would be wasteful, so the list is kept briefly. +local cache_seconds = 30 +local cached, cached_at = nil, 0 + +local function secrets() + if cached and os.time() - cached_at < cache_seconds then + return cached + end + local list = {} + local output = toolshed.exec({ "lazysecrets", "list", "--kind", "secret", "--cached", "--format", "json" }) + for line in output:gmatch("[^\n]+") do + local s = toolshed.json.decode(line) + if s.link and not s.error then + table.insert(list, { + name = table.concat(s.path, " / "), + account = s.account or "", + starred = s.starred == true, + link = s.link, + }) + end + end + cached, cached_at = list, os.time() + return list +end + +return toolshed.toolbox { + key = "secrets", + title = "i18n:toolbox.title", + description = "i18n:toolbox.description", + icon = "key-round", + tint = "purple", + requires = { { command = "lazysecrets" } }, + + tools = { { + key = "search", + title = "i18n:tool.search.title", + words = { "s" }, + keywords = { "hemmeligheter", "passord" }, + items = true, + + search = function(rest) + local matches = {} + for _, s in ipairs(secrets()) do + local score = toolshed.match(rest, s.name) + if score > 0 then + table.insert(matches, { score = score + (s.starred and 0.05 or 0), secret = s }) + end + end + table.sort(matches, function(a, b) return a.score > b.score end) + + local items = {} + for i = 1, math.min(#matches, 30) do + local s = matches[i].secret + table.insert(items, { + title = (s.starred and "★ " or "") .. s.name, + subtitle = s.account, + data = { link = s.link }, + }) + end + return items + end, + + actions = { + { + key = "open", + title = "i18n:action.search.open", + run = function(ctx) + toolshed.exec({ "lazysecrets", "launch", ctx.data.link }) + end, + }, + { + key = "copy-value", + title = "i18n:action.search.copy-value", + run = function(ctx) + toolshed.clipboard.copy_secret(toolshed.exec({ "lazysecrets", "get", ctx.data.link })) + return toolshed.t("value-copied") + end, + }, + { + key = "copy-link", + title = "i18n:action.search.copy-link", + run = function(ctx) + toolshed.clipboard.copy(ctx.data.link) + return toolshed.t("link-copied") + end, + }, + }, + } }, +} diff --git a/secrets/locales/en.toml b/secrets/locales/en.toml new file mode 100644 index 0000000..95e42a8 --- /dev/null +++ b/secrets/locales/en.toml @@ -0,0 +1,23 @@ +[toolbox.title] +other = "Secrets" + +[toolbox.description] +other = "Find secrets from Azure Key Vault, Databricks and your repos through lazysecrets." + +[tool.search.title] +other = "Secrets" + +[action.search.open] +other = "Open in lazysecrets" + +[action.search.copy-value] +other = "Copy Value" + +[action.search.copy-link] +other = "Copy Link" + +[value-copied] +other = "Copied — clears in 30 seconds" + +[link-copied] +other = "Link copied" diff --git a/secrets/locales/nb.toml b/secrets/locales/nb.toml new file mode 100644 index 0000000..ea361c4 --- /dev/null +++ b/secrets/locales/nb.toml @@ -0,0 +1,23 @@ +[toolbox.title] +other = "Hemmeligheter" + +[toolbox.description] +other = "Finn hemmeligheter fra Azure Key Vault, Databricks og repoene dine med lazysecrets." + +[tool.search.title] +other = "Hemmeligheter" + +[action.search.open] +other = "Åpne i lazysecrets" + +[action.search.copy-value] +other = "Kopier verdi" + +[action.search.copy-link] +other = "Kopier lenke" + +[value-copied] +other = "Kopiert – tømmes om 30 sekunder" + +[link-copied] +other = "Lenke kopiert" diff --git a/wikipedia/init.lua b/wikipedia/init.lua new file mode 100644 index 0000000..5b33fc1 --- /dev/null +++ b/wikipedia/init.lua @@ -0,0 +1,133 @@ +-- Wikipedia: "wiki rust" lists matching articles; Enter shows an article's summary, and Enter +-- there opens it. ⌘K opens it or copies its link from either. The last jig opens Wikipedia's +-- own search for what was typed. + +-- Wikimedia asks automated clients to say what they are. +local agent = "Toolshed-Wikipedia-extension/1.0" + +local encode = toolshed.url_encode + +local escape = toolshed.escape + +local function get(url, max_seconds) + return toolshed.json.decode(toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), "-A", agent, url })) +end + +local function site(settings) + return "https://" .. settings.language .. ".wikipedia.org" +end + +local function article_address(data) + return "https://" .. data.language .. ".wikipedia.org/wiki/" .. encode(data.key) +end + +return toolshed.toolbox { + key = "wikipedia", + title = "Wikipedia", + description = "i18n:toolbox.description", + icon = "book-open", + tint = "gray", + + settings = { + { key = "language", title = "i18n:setting.language.title", description = "i18n:setting.language.description", type = "choice", default = "en", + options = { + { value = "en", title = "English" }, + { value = "no", title = "Norsk (bokmål)" }, + { value = "nn", title = "Norsk (nynorsk)" }, + { value = "sv", title = "Svenska" }, + { value = "da", title = "Dansk" }, + { value = "de", title = "Deutsch" }, + { value = "fr", title = "Français" }, + { value = "es", title = "Español" }, + } }, + }, + + tools = { + { + key = "search", + title = "i18n:tool.search.title", + words = { "wiki" }, + examples = { "wiki rust", "wiki oslo" }, + keywords = { "wikipedia", "encyclopedia", "leksikon" }, + -- Wikipedia is asked once typing pauses, not for every letter on the way. + debounce = true, + + search = function(rest, settings) + if rest == "" then return {} end + local jigs = {} + -- Offline or slow, the search page is still offered. + local ok, found = pcall(get, site(settings) .. "/w/rest.php/v1/search/title?limit=8&q=" .. encode(rest), 1.5) + for _, page in ipairs(ok and found.pages or {}) do + local thumb = page.thumbnail and page.thumbnail.url + table.insert(jigs, { + title = page.title, + subtitle = page.description, + image = thumb and ("https:" .. thumb) or nil, + tool = "article", + data = { key = page.key, title = page.title, language = settings.language }, + }) + end + table.insert(jigs, { + title = toolshed.t("search-for", { query = rest }), + action = "open-search", + data = { query = rest, language = settings.language }, + }) + return jigs + end, + + actions = { + { + key = "open-search", title = "i18n:action.search.open-search", + run = function(ctx) + toolshed.open("https://" .. ctx.data.language .. ".wikipedia.org/w/index.php?fulltext=1&search=" .. encode(ctx.data.query)) + end, + }, + }, + }, + { + key = "article", + title = "i18n:tool.article.title", + hidden = true, + items = true, + + actions = { + { + -- The summary is a page with jigs for what to do next: Enter opens the article. + key = "summary", title = "i18n:action.article.summary", + run = function(ctx) + local s = get("https://" .. ctx.data.language .. ".wikipedia.org/api/rest_v1/page/summary/" .. encode(ctx.data.key), 10) + local picture = "" + if s.thumbnail and s.thumbnail.source then + picture = '' + end + local paragraphs = {} + for line in (s.extract or ""):gmatch("[^\n]+") do + table.insert(paragraphs, "

" .. escape(line) .. "

") + end + local page = '
' + .. picture + .. '

' .. escape(s.title) .. '

' + .. '
' .. escape(s.description) .. '
' + .. table.concat(paragraphs) + .. '
' + return { html = page, jigs = { + { title = toolshed.t("action.article.open"), icon = "external-link", action = "open", data = ctx.data }, + { title = toolshed.t("action.article.copy-link"), icon = "link", action = "copy-link", data = ctx.data }, + } } + end, + }, + { + key = "open", title = "i18n:action.article.open", shortcut = "cmd+enter", + run = function(ctx) toolshed.open(article_address(ctx.data)) end, + }, + { + key = "copy-link", title = "i18n:action.article.copy-link", shortcut = "cmd+shift+c", + run = function(ctx) + toolshed.clipboard.copy(article_address(ctx.data)) + return toolshed.t("link-copied") + end, + }, + }, + }, + }, +} diff --git a/wikipedia/locales/en.toml b/wikipedia/locales/en.toml new file mode 100644 index 0000000..0249d84 --- /dev/null +++ b/wikipedia/locales/en.toml @@ -0,0 +1,32 @@ +[toolbox.description] +other = "Finds Wikipedia articles and shows their summaries" + +[setting.language.title] +other = "Language" + +[setting.language.description] +other = "Which Wikipedia to search" + +[tool.search.title] +other = "Search Wikipedia" + +[search-for] +other = "Search Wikipedia for “{{.query}}”" + +[action.search.open-search] +other = "Open Search Page" + +[tool.article.title] +other = "Wikipedia Article" + +[action.article.summary] +other = "Show Summary" + +[action.article.open] +other = "Open in Browser" + +[action.article.copy-link] +other = "Copy Link" + +[link-copied] +other = "Link copied" diff --git a/wikipedia/locales/nb.toml b/wikipedia/locales/nb.toml new file mode 100644 index 0000000..215125d --- /dev/null +++ b/wikipedia/locales/nb.toml @@ -0,0 +1,32 @@ +[toolbox.description] +other = "Finner Wikipedia-artikler og viser sammendragene deres" + +[setting.language.title] +other = "Språk" + +[setting.language.description] +other = "Hvilken Wikipedia det søkes i" + +[tool.search.title] +other = "Søk i Wikipedia" + +[search-for] +other = "Søk i Wikipedia etter «{{.query}}»" + +[action.search.open-search] +other = "Åpne søkesiden" + +[tool.article.title] +other = "Wikipedia-artikkel" + +[action.article.summary] +other = "Vis sammendrag" + +[action.article.open] +other = "Åpne i nettleseren" + +[action.article.copy-link] +other = "Kopier lenke" + +[link-copied] +other = "Lenke kopiert" diff --git a/yr/init.lua b/yr/init.lua new file mode 100644 index 0000000..98a8a55 --- /dev/null +++ b/yr/init.lua @@ -0,0 +1,250 @@ +-- Yr: "yr bergen" finds places as yr.no does; Enter shows the weather there now, hour by hour +-- and for the week, from MET Norway, with yr.no's own weather symbols. ⌘K opens the place on yr.no. +-- Its text is in locales/, and places are named in the language Toolshed speaks. + +-- MET Norway asks automated clients to say what they are, and turns away those that don't. +local agent = "Toolshed-Yr-extension/1.0" + +-- MET Norway's weather symbols, the ones yr.no shows (https://github.com/metno/weathericons). +local symbols = "https://cdn.jsdelivr.net/gh/metno/weathericons@main/weather/svg/" + +local encode = toolshed.url_encode + +local escape = toolshed.escape + +local function get(url, max_seconds) + return toolshed.json.decode(toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), "-A", agent, url })) +end + +local function symbol(code, size) + if not code then return "" end + return '' +end + +-- "lightrainshowers_day" says "Light rain showers"; by day or night reads the same. +local function describe(code) + return toolshed.t("symbol." .. (code or ""):gsub("_.*", "")) +end + +-- yr.no speaks English, Bokmål and Nynorsk. +local function language() + local locale = toolshed.locale() + return (locale == "nb" or locale == "nn") and locale or "en" +end + +-- Forecasts are given in UTC; they're shown in the place's own time, offset as it is now. +local function utc_offset(zone) + local ok, out = pcall(toolshed.exec, { "env", "TZ=" .. zone, "date", "+%z" }) + local sign, hours, minutes = (ok and out or ""):match("([+-])(%d%d)(%d%d)") + if not sign then return 0 end + return (sign == "-" and -1 or 1) * (tonumber(hours) * 3600 + tonumber(minutes) * 60) +end + +-- local_time turns "2026-11-18T06:00:00Z" into a time to format with os.date as the place's. +local function local_time(iso, offset) + local y, mo, d, h, mi = iso:match("^(%d+)-(%d+)-(%d+)T(%d+):(%d+)") + return os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), min = tonumber(mi) + math.floor(offset / 60) }) +end + +local compass = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" } + +local function direction(degrees) + return toolshed.t("compass." .. compass[math.floor(((degrees or 0) + 22.5) / 45) % 8 + 1]) +end + +-- "Wednesday 25 Nov", as the language says it; os.date only knows English. +local function date(time) + local d = os.date("*t", time) + return toolshed.t("date", { weekday = toolshed.t("weekday." .. d.wday), day = d.day, month = toolshed.t("month." .. d.month) }) +end + +-- 2.5 in English, 2,5 in Norwegian. +local function number(n) + local text = string.format("%.1f", n):gsub("%.0$", ""):gsub("^%-0$", "0") + return (text:gsub("%.", toolshed.t("decimal"))) +end + +local function temperature(t) + return string.format("%d°", math.floor(t + 0.5)) +end + +local function tile(icon) + return '' +end + +local function sparkline(values, from_zero) + local text = {} + for _, v in ipairs(values) do table.insert(text, string.format("%.4g", v)) end + return '" +end + +local function figure(label, value, icon, tint, values, from_zero) + return '
' .. tile(icon) .. '
' .. value .. + '
' .. escape(label) .. "
" .. sparkline(values, from_zero) .. "
" +end + +local function precipitation(entry, hours) + local next = entry.data["next_" .. hours .. "_hours"] + return next and next.details and next.details.precipitation_amount or 0 +end + +local function next_symbol(entry) + local d = entry.data + local next = d.next_1_hours or d.next_6_hours or d.next_12_hours + return next and next.summary.symbol_code +end + +local function line(cells) + return '
' .. table.concat(cells) .. "
" +end + +local function forecast(place) + local f = get("https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=" .. + string.format("%.4f", place.lat) .. "&lon=" .. string.format("%.4f", place.lon), 10) + local series = f.properties.timeseries + local offset = utc_offset(place.zone) + local now = series[1] + local details = now.data.instant.details + + -- The next 24 hours, for the figures' lines and the hourly forecast. + local temps, rain, wind, hours = {}, {}, {}, {} + local total_rain = 0 + for i = 1, math.min(24, #series) do + local e = series[i] + local d = e.data.instant.details + local amount = precipitation(e, 1) + table.insert(temps, d.air_temperature) + table.insert(rain, amount) + table.insert(wind, d.wind_speed) + total_rain = total_rain + amount + if i <= 12 then + local none = '
—
' + table.insert(hours, line({ + '
' .. symbol(next_symbol(e), 24) .. '' .. os.date("%H:%M", local_time(e.time, offset)) .. "
", + '
' .. temperature(d.air_temperature) .. "
", + amount > 0 and ('
' .. number(amount) .. " mm
") or none, + '
' .. number(d.wind_speed) .. " m/s " .. escape(direction(d.wind_from_direction)) .. "
", + })) + end + end + + -- The coming days, each from midnight to midnight in the place's time, with the symbol yr.no + -- shows for the day: the six hours from noon. + local days, order = {}, {} + for _, e in ipairs(series) do + local t = local_time(e.time, offset) + local key = os.date("%Y-%m-%d", t) + local day = days[key] + if not day then + day = { time = t, low = math.huge, high = -math.huge, rain = 0 } + days[key] = day + table.insert(order, key) + end + local temp = e.data.instant.details.air_temperature + day.low, day.high = math.min(day.low, temp), math.max(day.high, temp) + if e.data.next_1_hours then + day.rain = day.rain + precipitation(e, 1) + elseif e.data.next_6_hours and tonumber(e.time:sub(12, 13)) % 6 == 0 then + day.rain = day.rain + precipitation(e, 6) + end + local hour = tonumber(os.date("%H", t)) + if e.data.next_6_hours and (not day.symbol or (hour >= 12 and not day.noon)) then + day.symbol, day.noon = e.data.next_6_hours.summary.symbol_code, hour >= 12 + end + end + local week = {} + for i, key in ipairs(order) do + if i > 8 then break end + local day = days[key] + table.insert(week, line({ + '
' .. symbol(day.symbol, 24) .. '' .. + escape(i == 1 and toolshed.t("today") or date(day.time)) .. "
", + '
' .. temperature(day.high) .. ' ' .. temperature(day.low) .. "
", + day.rain > 0 and ('
' .. number(day.rain) .. " mm
") or '
—
', + '
', + })) + end + + local code = next_symbol(now) + local heading = '
' .. symbol(code, 40) .. '' .. + escape(toolshed.t("now", { weather = describe(code), place = place.name })) .. ' · ' .. + escape(toolshed.t("updated", { time = os.date("%H:%M", local_time(f.properties.meta.updated_at, offset)) })) .. "
" + local top = '
' .. + figure(toolshed.t("temperature"), temperature(details.air_temperature), "thermometer", details.air_temperature < 0 and "blue" or "orange", temps) .. + figure(toolshed.t("rain-24h"), number(total_rain) .. " mm", "umbrella", "blue", rain, true) .. + figure(toolshed.t("wind-from", { direction = direction(details.wind_from_direction) }), number(details.wind_speed) .. " m/s", "wind", "teal", wind, true) .. + "
" + local columns = "minmax(0, 1fr) 80px 72px 110px" + local function table_of(title, last, lines) + return '
' .. escape(toolshed.t(title)) .. + '
' .. escape(toolshed.t("temp")) .. '
' .. escape(toolshed.t("rain")) .. + '
' .. escape(last) .. "
" .. table.concat(lines) .. "
" + end + return '
' .. heading .. top .. table_of("hour", toolshed.t("wind"), hours) .. table_of("day", "", week) .. "
" +end + +-- yr.no finds the rest of a place's address, in the language of the link, from its ID. +local function yr_address(place) + return toolshed.t("link") .. place.id +end + +return toolshed.toolbox { + key = "yr", + title = "Yr", + description = "i18n:toolbox.description", + icon = "cloud-sun", + tint = "blue", + + tools = { + { + key = "search", + title = "i18n:tool.search.title", + words = { "yr" }, + examples = { "yr oslo", "yr bergen", "yr tromsø" }, + keywords = { "weather", "forecast", "vær", "temperature" }, + items = true, + -- yr.no is asked once typing pauses, not for every letter on the way. + debounce = true, + + search = function(rest, settings) + if rest == "" then return {} end + local ok, found = pcall(get, "https://www.yr.no/api/v0/locations/search?language=" .. language() .. "&q=" .. encode(rest), 1.5) + local jigs = {} + for i, l in ipairs(ok and found._embedded and found._embedded.location or {}) do + if i > 10 then break end + local where = {} + for _, key in ipairs({ "subregion", "region", "country" }) do + local part = l[key] + if part and part.name and part.name ~= l.name and part.name ~= where[#where] then table.insert(where, part.name) end + end + table.insert(jigs, { + title = l.name, + subtitle = table.concat(where, ", ") .. (l.category and (" · " .. l.category.name) or ""), + icon = "map-pin", + data = { id = l.id, name = l.name, lat = l.position.lat, lon = l.position.lon, zone = l.timeZone }, + }) + end + return jigs + end, + + actions = { + { + key = "forecast", title = "i18n:action.search.forecast", icon = "cloud-sun", + run = function(ctx) return { html = forecast(ctx.data), refresh = 600 } end, + }, + { + key = "open", title = "i18n:action.search.open", icon = "external-link", shortcut = "cmd+enter", + run = function(ctx) toolshed.open(yr_address(ctx.data)) end, + }, + { + key = "copy-link", title = "i18n:action.search.copy-link", icon = "link", shortcut = "cmd+shift+c", + run = function(ctx) + toolshed.clipboard.copy(yr_address(ctx.data)) + return toolshed.t("link-copied") + end, + }, + }, + }, + }, +} diff --git a/yr/locales/en.toml b/yr/locales/en.toml new file mode 100644 index 0000000..6ccb31f --- /dev/null +++ b/yr/locales/en.toml @@ -0,0 +1,263 @@ +[toolbox.description] +other = "The weather anywhere, from yr.no and MET Norway" + +[tool.search.title] +other = "Weather" + +[action.search.forecast] +other = "Show Weather" + +[action.search.open] +other = "Open on yr.no" + +[action.search.copy-link] +other = "Copy Link" + +[link-copied] +other = "Link copied" + +[link] +other = "https://www.yr.no/en/forecast/daily-table/" + +[now] +other = "{{.weather}} in {{.place}}" + +[updated] +other = "updated {{.time}}" + +[temperature] +other = "Temperature" + +[rain-24h] +other = "Rain, next 24 h" + +[wind-from] +other = "Wind from {{.direction}}" + +[hour] +other = "Hour" + +[day] +other = "Day" + +[temp] +other = "Temp." + +[rain] +other = "Rain" + +[wind] +other = "Wind" + +[today] +other = "Today" + +[date] +other = "{{.weekday}} {{.day}} {{.month}}" + +[symbol.clearsky] +other = "Clear sky" + +[symbol.fair] +other = "Fair" + +[symbol.partlycloudy] +other = "Partly cloudy" + +[symbol.cloudy] +other = "Cloudy" + +[symbol.fog] +other = "Fog" + +[symbol.lightrain] +other = "Light rain" + +[symbol.lightrainshowers] +other = "Light rain showers" + +[symbol.lightrainandthunder] +other = "Light rain and thunder" + +[symbol.lightrainshowersandthunder] +other = "Light rain showers and thunder" + +[symbol.rain] +other = "Rain" + +[symbol.rainshowers] +other = "Rain showers" + +[symbol.rainandthunder] +other = "Rain and thunder" + +[symbol.rainshowersandthunder] +other = "Rain showers and thunder" + +[symbol.heavyrain] +other = "Heavy rain" + +[symbol.heavyrainshowers] +other = "Heavy rain showers" + +[symbol.heavyrainandthunder] +other = "Heavy rain and thunder" + +[symbol.heavyrainshowersandthunder] +other = "Heavy rain showers and thunder" + +[symbol.lightsleet] +other = "Light sleet" + +[symbol.lightsleetshowers] +other = "Light sleet showers" + +[symbol.lightsleetandthunder] +other = "Light sleet and thunder" + +[symbol.lightssleetshowersandthunder] +other = "Light sleet showers and thunder" + +[symbol.sleet] +other = "Sleet" + +[symbol.sleetshowers] +other = "Sleet showers" + +[symbol.sleetandthunder] +other = "Sleet and thunder" + +[symbol.sleetshowersandthunder] +other = "Sleet showers and thunder" + +[symbol.heavysleet] +other = "Heavy sleet" + +[symbol.heavysleetshowers] +other = "Heavy sleet showers" + +[symbol.heavysleetandthunder] +other = "Heavy sleet and thunder" + +[symbol.heavysleetshowersandthunder] +other = "Heavy sleet showers and thunder" + +[symbol.lightsnow] +other = "Light snow" + +[symbol.lightsnowshowers] +other = "Light snow showers" + +[symbol.lightsnowandthunder] +other = "Light snow and thunder" + +[symbol.lightssnowshowersandthunder] +other = "Light snow showers and thunder" + +[symbol.snow] +other = "Snow" + +[symbol.snowshowers] +other = "Snow showers" + +[symbol.snowandthunder] +other = "Snow and thunder" + +[symbol.snowshowersandthunder] +other = "Snow showers and thunder" + +[symbol.heavysnow] +other = "Heavy snow" + +[symbol.heavysnowshowers] +other = "Heavy snow showers" + +[symbol.heavysnowandthunder] +other = "Heavy snow and thunder" + +[symbol.heavysnowshowersandthunder] +other = "Heavy snow showers and thunder" + +[compass.N] +other = "N" + +[compass.NE] +other = "NE" + +[compass.E] +other = "E" + +[compass.SE] +other = "SE" + +[compass.S] +other = "S" + +[compass.SW] +other = "SW" + +[compass.W] +other = "W" + +[compass.NW] +other = "NW" + +[weekday.1] +other = "Sunday" + +[weekday.2] +other = "Monday" + +[weekday.3] +other = "Tuesday" + +[weekday.4] +other = "Wednesday" + +[weekday.5] +other = "Thursday" + +[weekday.6] +other = "Friday" + +[weekday.7] +other = "Saturday" + +[month.1] +other = "Jan" + +[month.2] +other = "Feb" + +[month.3] +other = "Mar" + +[month.4] +other = "Apr" + +[month.5] +other = "May" + +[month.6] +other = "Jun" + +[month.7] +other = "Jul" + +[month.8] +other = "Aug" + +[month.9] +other = "Sep" + +[month.10] +other = "Oct" + +[month.11] +other = "Nov" + +[month.12] +other = "Dec" + +[decimal] +other = "." diff --git a/yr/locales/nb.toml b/yr/locales/nb.toml new file mode 100644 index 0000000..fb59e1a --- /dev/null +++ b/yr/locales/nb.toml @@ -0,0 +1,263 @@ +[toolbox.description] +other = "Været hvor som helst, fra yr.no og Meteorologisk institutt" + +[tool.search.title] +other = "Vær" + +[action.search.forecast] +other = "Vis været" + +[action.search.open] +other = "Åpne på yr.no" + +[action.search.copy-link] +other = "Kopier lenke" + +[link-copied] +other = "Lenke kopiert" + +[link] +other = "https://www.yr.no/nb/v%C3%A6rvarsel/daglig-tabell/" + +[now] +other = "{{.weather}} i {{.place}}" + +[updated] +other = "oppdatert {{.time}}" + +[temperature] +other = "Temperatur" + +[rain-24h] +other = "Nedbør, neste 24 t" + +[wind-from] +other = "Vind fra {{.direction}}" + +[hour] +other = "Time" + +[day] +other = "Dag" + +[temp] +other = "Temp." + +[rain] +other = "Nedbør" + +[wind] +other = "Vind" + +[today] +other = "I dag" + +[date] +other = "{{.weekday}} {{.day}}. {{.month}}" + +[symbol.clearsky] +other = "Klarvær" + +[symbol.fair] +other = "Lettskyet" + +[symbol.partlycloudy] +other = "Delvis skyet" + +[symbol.cloudy] +other = "Skyet" + +[symbol.fog] +other = "Tåke" + +[symbol.lightrain] +other = "Lett regn" + +[symbol.lightrainshowers] +other = "Lette regnbyger" + +[symbol.lightrainandthunder] +other = "Lett regn og torden" + +[symbol.lightrainshowersandthunder] +other = "Lette regnbyger og torden" + +[symbol.rain] +other = "Regn" + +[symbol.rainshowers] +other = "Regnbyger" + +[symbol.rainandthunder] +other = "Regn og torden" + +[symbol.rainshowersandthunder] +other = "Regnbyger og torden" + +[symbol.heavyrain] +other = "Kraftig regn" + +[symbol.heavyrainshowers] +other = "Kraftige regnbyger" + +[symbol.heavyrainandthunder] +other = "Kraftig regn og torden" + +[symbol.heavyrainshowersandthunder] +other = "Kraftige regnbyger og torden" + +[symbol.lightsleet] +other = "Lett sludd" + +[symbol.lightsleetshowers] +other = "Lette sluddbyger" + +[symbol.lightsleetandthunder] +other = "Lett sludd og torden" + +[symbol.lightssleetshowersandthunder] +other = "Lette sluddbyger og torden" + +[symbol.sleet] +other = "Sludd" + +[symbol.sleetshowers] +other = "Sluddbyger" + +[symbol.sleetandthunder] +other = "Sludd og torden" + +[symbol.sleetshowersandthunder] +other = "Sluddbyger og torden" + +[symbol.heavysleet] +other = "Kraftig sludd" + +[symbol.heavysleetshowers] +other = "Kraftige sluddbyger" + +[symbol.heavysleetandthunder] +other = "Kraftig sludd og torden" + +[symbol.heavysleetshowersandthunder] +other = "Kraftige sluddbyger og torden" + +[symbol.lightsnow] +other = "Lett snø" + +[symbol.lightsnowshowers] +other = "Lette snøbyger" + +[symbol.lightsnowandthunder] +other = "Lett snø og torden" + +[symbol.lightssnowshowersandthunder] +other = "Lette snøbyger og torden" + +[symbol.snow] +other = "Snø" + +[symbol.snowshowers] +other = "Snøbyger" + +[symbol.snowandthunder] +other = "Snø og torden" + +[symbol.snowshowersandthunder] +other = "Snøbyger og torden" + +[symbol.heavysnow] +other = "Kraftig snø" + +[symbol.heavysnowshowers] +other = "Kraftige snøbyger" + +[symbol.heavysnowandthunder] +other = "Kraftig snø og torden" + +[symbol.heavysnowshowersandthunder] +other = "Kraftige snøbyger og torden" + +[compass.N] +other = "N" + +[compass.NE] +other = "NØ" + +[compass.E] +other = "Ø" + +[compass.SE] +other = "SØ" + +[compass.S] +other = "S" + +[compass.SW] +other = "SV" + +[compass.W] +other = "V" + +[compass.NW] +other = "NV" + +[weekday.1] +other = "søndag" + +[weekday.2] +other = "mandag" + +[weekday.3] +other = "tirsdag" + +[weekday.4] +other = "onsdag" + +[weekday.5] +other = "torsdag" + +[weekday.6] +other = "fredag" + +[weekday.7] +other = "lørdag" + +[month.1] +other = "jan." + +[month.2] +other = "feb." + +[month.3] +other = "mars" + +[month.4] +other = "apr." + +[month.5] +other = "mai" + +[month.6] +other = "juni" + +[month.7] +other = "juli" + +[month.8] +other = "aug." + +[month.9] +other = "sep." + +[month.10] +other = "okt." + +[month.11] +other = "nov." + +[month.12] +other = "des." + +[decimal] +other = ","