Skip to content

Commit

Permalink
feat: automatically resolve github token from gh cli
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 3, 2023
1 parent c8afa86 commit 231a3ec
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"pathe": "^1.1.0",
"pkg-types": "^1.0.2",
"scule": "^1.0.0",
"semver": "^7.3.8"
"semver": "^7.3.8",
"yaml": "^2.2.1"
},
"devDependencies": {
"@types/node": "^18.14.2",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion src/commands/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { resolve } from "pathe";
import consola from "consola";
import { underline, cyan } from "colorette";
import open from "open";
import { getGithubChangelog, syncGithubRelease } from "../github";
import {
getGithubChangelog,
resolveGithubToken,
syncGithubRelease,
} from "../github";
import {
ChangelogConfig,
loadChangelogConfig,
Expand Down Expand Up @@ -83,6 +87,11 @@ export async function githubRelease(
config: ChangelogConfig,
release: { version: string; body: string }
) {
if (!config.tokens.github) {
config.tokens.github = await resolveGithubToken(config).catch(
() => undefined
);
}
const result = await syncGithubRelease(config, release);
if (result.status === "manual") {
if (result.error) {
Expand Down
24 changes: 24 additions & 0 deletions src/github.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { existsSync, promises as fsp } from "node:fs";
import { homedir } from "node:os";
import { $fetch, FetchOptions } from "ofetch";
import { join } from "pathe";
import { ChangelogConfig } from "./config";

export interface GithubOptions {
Expand Down Expand Up @@ -114,6 +117,27 @@ export function githubNewReleaseURL(
}&title=v${release.version}&body=${encodeURIComponent(release.body)}`;
}

export async function resolveGithubToken(config: ChangelogConfig) {
const env =
process.env.CHANGELOGEN_TOKENS_GITHUB ||
process.env.GITHUB_TOKEN ||
process.env.GH_TOKEN;
if (env) {
return env;
}

const configHome = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
const ghCLIPath = join(configHome, "gh", "hosts.yml");
if (existsSync(ghCLIPath)) {
const yamlContents = await fsp.readFile(ghCLIPath, "utf8");
const parseYAML = await import("yaml").then((r) => r.parse);
const ghCLIConfig = parseYAML(yamlContents);
if (ghCLIConfig && ghCLIConfig[config.repo.domain]) {
return ghCLIConfig["github.com"].oauth_token;
}
}
}

// --- Internal utils ---
async function githubFetch(
config: ChangelogConfig,
Expand Down

0 comments on commit 231a3ec

Please sign in to comment.