Skip to content

Commit

Permalink
Meta: Extract and extend getRepositoryInfo (#3695)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Nov 3, 2020
1 parent 86ed023 commit 059a3cd
Show file tree
Hide file tree
Showing 35 changed files with 104 additions and 121 deletions.
6 changes: 3 additions & 3 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"element-ready": "^4.1.1",
"fit-textarea": "^2.0.0",
"flat-zip": "^1.0.1",
"github-url-detection": "^4.1.1",
"github-url-detection": "^4.3.0-1",
"image-promise": "^7.0.1",
"indent-textarea": "^2.0.2",
"linkify-issues": "2.0.0-nolookbehind",
Expand Down
6 changes: 3 additions & 3 deletions source/features/bugs-tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import SearchQuery from '../github-helpers/search-query';
import {getRepoURL} from '../github-helpers';
import {getRepo} from '../github-helpers';

const numberFormatter = new Intl.NumberFormat();
const countBugs = cache.function(async (): Promise<number> => {
const {search} = await api.v4(`
search(type: ISSUE, query: "label:bug is:open is:issue repo:${getRepoURL()}") {
search(type: ISSUE, query: "label:bug is:open is:issue repo:${getRepo()!.nameWithOwner}") {
issueCount
}
`);
Expand All @@ -22,7 +22,7 @@ const countBugs = cache.function(async (): Promise<number> => {
}, {
maxAge: {minutes: 30},
staleWhileRevalidate: {days: 4},
cacheKey: (): string => __filebasename + ':' + getRepoURL()
cacheKey: (): string => __filebasename + ':' + getRepo()!.nameWithOwner
});

async function init(): Promise<void | false> {
Expand Down
4 changes: 2 additions & 2 deletions source/features/ci-link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import * as pageDetect from 'github-url-detection';

import features from '.';
import fetchDom from '../helpers/fetch-dom';
import {getRepoURL} from '../github-helpers';
import {buildRepoURL} from '../github-helpers';

// Look for the CI icon in the latest 2 days of commits #2990
const getIcon = onetime(fetchDom.bind(null,
`/${getRepoURL()}/commits`, [
buildRepoURL('commits'), [
'.commit-group:nth-of-type(-n+2) .commit-build-statuses', // Pre "Repository refresh" layout
'.TimelineItem--condensed:nth-of-type(-n+2) .commit-build-statuses'
].join()
Expand Down
6 changes: 3 additions & 3 deletions source/features/clean-conversation-filters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import * as pageDetect from 'github-url-detection';

import features from '.';
import * as api from '../github-helpers/api';
import {getRepositoryInfo, getRepoURL, getRepoGQL} from '../github-helpers';
import {getRepo, getRepoGQL} from '../github-helpers';

const hasAnyProjects = cache.function(async (): Promise<boolean> => {
const {repository, organization} = await api.v4(`
repository(${getRepoGQL()}) {
projects { totalCount }
}
organization(login: "${getRepositoryInfo().owner!}") {
organization(login: "${getRepo()!.owner}") {
projects { totalCount }
}
`, {
Expand All @@ -23,7 +23,7 @@ const hasAnyProjects = cache.function(async (): Promise<boolean> => {
}, {
maxAge: {days: 1},
staleWhileRevalidate: {days: 20},
cacheKey: () => `has-projects:${getRepoURL()}`
cacheKey: () => `has-projects:${getRepo()!.nameWithOwner}`
});

function getCount(element: HTMLElement): number {
Expand Down
4 changes: 2 additions & 2 deletions source/features/enable-file-links-in-compare-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import * as pageDetect from 'github-url-detection';

import features from '.';
import GitHubURL from '../github-helpers/github-url';
import {getCurrentBranch, getPRRepositoryInfo} from '../github-helpers';
import {getCurrentBranch, getPRHeadRepo} from '../github-helpers';

/** Rebuilds the "View file" link because it points to the base repo and to the commit, instead of the head repo and its branch */
function handlePRMenuOpening({delegateTarget: dropdown}: delegate.Event): void {
dropdown.classList.add('rgh-actionable-link'); // Mark this as processed
const filePath = dropdown.closest('[data-path]')!.getAttribute('data-path')!;

const viewFile = select<HTMLAnchorElement>('[data-ga-click^="View file"]', dropdown)!;
viewFile.pathname = [getPRRepositoryInfo().url!, 'blob', getCurrentBranch()!, filePath].join('/'); // Do not replace with `GitHubURL` #3152 #3111 #2595
viewFile.pathname = [getPRHeadRepo()!.nameWithOwner, 'blob', getCurrentBranch()!, filePath].join('/'); // Do not replace with `GitHubURL` #3152 #3111 #2595
}

function handleCompareMenuOpening({delegateTarget: dropdown}: delegate.Event): void {
Expand Down
8 changes: 4 additions & 4 deletions source/features/first-published-tag-for-merged-pr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@ import * as pageDetect from 'github-url-detection';
import features from '.';
import fetchDom from '../helpers/fetch-dom';
import observeElement from '../helpers/simplified-element-observer';
import {getRepoURL, buildRepoURL} from '../github-helpers';
import {buildRepoURL, getRepo} from '../github-helpers';

const getFirstTag = cache.function(async (commit: string): Promise<string | undefined> => {
const firstTag = await fetchDom<HTMLAnchorElement>(
`/${getRepoURL()}/branch_commits/${commit}`,
buildRepoURL('branch_commits', commit),
'ul.branches-tag-list li:last-child a'
);

return firstTag?.textContent!;
}, {
cacheKey: ([commit]) => `first-tag:${getRepoURL()}:${commit}`
cacheKey: ([commit]) => `first-tag:${getRepo()!.nameWithOwner}:${commit}`
});

async function init(): Promise<void> {
const mergeCommit = select(`.TimelineItem.js-details-container.Details a[href^="/${getRepoURL()}/commit/" i] > code.link-gray-dark`)!.textContent!;
const mergeCommit = select(`.TimelineItem.js-details-container.Details a[href^="/${getRepo()!.nameWithOwner}/commit/" i] > code.link-gray-dark`)!.textContent!;
const tagName = await getFirstTag(mergeCommit);

if (!tagName) {
Expand Down
4 changes: 2 additions & 2 deletions source/features/fork-source-link-same-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import features from '.';
import GitHubURL from '../github-helpers/github-url';
import doesFileExist from '../github-helpers/does-file-exist';
import getDefaultBranch from '../github-helpers/get-default-branch';
import {getRepositoryInfo, getForkedRepo} from '../github-helpers';
import {getRepo, getForkedRepo} from '../github-helpers';

async function init(): Promise<void> {
const forkedRepository = getRepositoryInfo(getForkedRepo());
const forkedRepository = getRepo(getForkedRepo())!;
const sameViewUrl = new GitHubURL(location.href).assign({
user: forkedRepository.owner,
repository: forkedRepository.name,
Expand Down
14 changes: 7 additions & 7 deletions source/features/forked-to.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ import LinkExternalIcon from 'octicon/link-external.svg';
import features from '.';
import fetchDom from '../helpers/fetch-dom';
import GitHubURL from '../github-helpers/github-url';
import {getRepoURL, getUsername, getForkedRepo} from '../github-helpers';
import {getUsername, getForkedRepo, getRepo} from '../github-helpers';

const getForkSourceRepo = (): string => getForkedRepo() ?? getRepoURL();
const getCacheKey = (): string => `forked-to:${getUsername()}@${getForkSourceRepo().toLowerCase()}`;
const getForkSourceRepo = (): string => getForkedRepo() ?? getRepo()!.nameWithOwner;
const getCacheKey = (): string => `forked-to:${getForkSourceRepo()}@${getUsername()}`;

const updateCache = cache.function(async (): Promise<string[] | undefined> => {
const document = await fetchDom(`/${getForkSourceRepo()}/fork?fragment=1`);
const forks = select
.all('.octicon-repo-forked', document)
.map(({nextSibling}) => nextSibling!.textContent!.trim().toLowerCase());
.map(({nextSibling}) => nextSibling!.textContent!.trim());

return forks.length > 0 ? forks : undefined;
}, {
Expand All @@ -45,7 +45,7 @@ function createLink(baseRepo: string): string {

async function updateUI(forks: string[]): Promise<void> {
// Don't add button if you're visiting the only fork available
if (forks.length === 1 && forks[0] === getRepoURL()) {
if (forks.length === 1 && forks[0] === getRepo()!.nameWithOwner) {
return;
}

Expand Down Expand Up @@ -78,11 +78,11 @@ async function updateUI(forks: string[]): Promise<void> {
{forks.map(fork => (
<a
href={createLink(fork)}
className={`select-menu-item ${fork === getRepoURL() ? 'selected' : ''}`}
className={`select-menu-item ${fork === getRepo()!.nameWithOwner ? 'selected' : ''}`}
title={`Open your fork at ${fork}`}
>
<span className="select-menu-item-icon rgh-forked-to-icon">
{fork === getRepoURL() ? <CheckIcon/> : <ForkIcon/>}
{fork === getRepo()!.nameWithOwner ? <CheckIcon/> : <ForkIcon/>}
</span>
{fork}
</a>
Expand Down
10 changes: 5 additions & 5 deletions source/features/git-checkout-pr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import ClippyIcon from 'octicon/clippy.svg';
import * as pageDetect from 'github-url-detection';

import features from '.';
import {getCurrentBranch, getPRRepositoryInfo, getRepositoryInfo, getUsername} from '../github-helpers';
import {getCurrentBranch, getPRHeadRepo, getRepo, getUsername} from '../github-helpers';

// Logic explained in https://github.com/sindresorhus/refined-github/pull/3596#issuecomment-720910840
function getRemoteName(): string | undefined {
const author = getPRRepositoryInfo().owner;
const author = getPRHeadRepo()!.owner;
if (author === getUsername()) {
return; // `origin`, don't add remote
}

if (author !== getRepositoryInfo().owner) {
if (author !== getRepo()!.owner) {
return author;
}

Expand Down Expand Up @@ -51,9 +51,9 @@ function checkoutOption(remote?: string, remoteType?: 'HTTPS' | 'SSH'): JSX.Elem
className="copyable-terminal-content"
>
<span className="user-select-contain">
{remote && `git remote add ${remote} ${connectionType[remoteType!]}${getPRRepositoryInfo().url!}.git\n`}
{remote && `git remote add ${remote} ${connectionType[remoteType!]}${getPRHeadRepo()!.nameWithOwner}.git\n`}
git fetch {remote ?? 'origin'} {getCurrentBranch()}{'\n'}
git switch {remote && `--track ${getPRRepositoryInfo().owner!}/`}{getCurrentBranch()}
git switch {remote && `--track ${getPRHeadRepo()!.owner}/`}{getCurrentBranch()}
</span>
</pre>
</div>
Expand Down
4 changes: 2 additions & 2 deletions source/features/go-to-action-from-file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import select from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '.';
import {buildRepoURL, getRepoPath} from '../github-helpers';
import {buildRepoURL, getRepo} from '../github-helpers';

const isWorkflowFile = (): boolean => pageDetect.isSingleFile() && /\/\.github\/workflows\/.+\.ya?ml$/.test(getRepoPath()!);
const isWorkflowFile = (): boolean => pageDetect.isSingleFile() && /\/\.github\/workflows\/.+\.ya?ml$/.test(getRepo()!.path);

function init(): void {
const actionName = select.all('.blob-code-inner')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import * as pageDetect from 'github-url-detection';

import features from '.';
import fetchDom from '../helpers/fetch-dom';
import {getRepoURL, getUsername} from '../github-helpers';
import {buildRepoURL, getRepo, getUsername} from '../github-helpers';

const getCollaborators = cache.function(async (): Promise<string[]> => {
const dom = await fetchDom(getRepoURL() + '/issues/show_menu_content?partial=issues/filters/authors_content');
const dom = await fetchDom(buildRepoURL('issues/show_menu_content?partial=issues/filters/authors_content'));
return select
.all<HTMLImageElement>('.SelectMenu-item [alt]', dom)
.map(avatar => avatar.alt.slice(1));
}, {
maxAge: {days: 1},
staleWhileRevalidate: {days: 20},
cacheKey: () => 'repo-collaborators:' + getRepoURL()
cacheKey: () => 'repo-collaborators:' + getRepo()!.nameWithOwner
});

async function highlightCollaborators(): Promise<void> {
Expand Down
5 changes: 2 additions & 3 deletions source/features/highlight-non-default-base-branch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import PullRequestIcon from 'octicon/git-pull-request.svg';
import features from '.';
import * as api from '../github-helpers/api';
import getDefaultBranch from '../github-helpers/get-default-branch';
import {getRepositoryInfo, getRepoGQL} from '../github-helpers';
import {getRepoGQL, buildRepoURL} from '../github-helpers';

interface BranchInfo {
baseRef: string;
Expand All @@ -32,7 +32,6 @@ async function init(): Promise<false | void> {
return false;
}

const currentRepository = getRepositoryInfo();
const query = buildQuery(prLinks.map(pr => pr.id));
const [data, defaultBranch] = await Promise.all([
api.v4(query),
Expand All @@ -45,7 +44,7 @@ async function init(): Promise<false | void> {
continue;
}

const branch = pr.baseRef && `/${currentRepository.owner!}/${currentRepository.name!}/tree/${pr.baseRefName}`;
const branch = pr.baseRef && buildRepoURL(`tree/${pr.baseRefName}`);

prLink.parentElement!.querySelector('.text-small.text-gray')!.append(
<span className="issue-meta-section d-inline-block">
Expand Down
4 changes: 2 additions & 2 deletions source/features/latest-tag-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import pluralize from '../helpers/pluralize';
import GitHubURL from '../github-helpers/github-url';
import {groupButtons} from '../github-helpers/group-buttons';
import getDefaultBranch from '../github-helpers/get-default-branch';
import {buildRepoURL, getCurrentBranch, getRepoURL, getRepoGQL, getLatestVersionTag} from '../github-helpers';
import {buildRepoURL, getCurrentBranch, getRepoGQL, getLatestVersionTag, getRepo} from '../github-helpers';

interface RepoPublishState {
latestTag: string | false;
Expand Down Expand Up @@ -75,7 +75,7 @@ const getRepoPublishState = cache.function(async (): Promise<RepoPublishState> =
}, {
maxAge: {hours: 1},
staleWhileRevalidate: {days: 2},
cacheKey: () => `tag-ahead-by:${getRepoURL()}`
cacheKey: () => `tag-ahead-by:${getRepo()!.nameWithOwner}`
});

async function init(): Promise<false | void> {
Expand Down
11 changes: 4 additions & 7 deletions source/features/link-to-github-io.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as pageDetect from 'github-url-detection';
import LinkExternalIcon from 'octicon/link-external.svg';

import features from '.';
import {getRepositoryInfo} from '../github-helpers';
import {getRepo} from '../github-helpers';

function initRepoList(): void {
observe('a[href$=".github.io"][itemprop="name codeRepository"]:not(.rgh-github-io)', {
Expand All @@ -28,11 +28,11 @@ function initRepoList(): void {
}

async function initRepo(): Promise<void> {
const repoTitle = await elementReady('[itemprop="name"]')!;
const repoTitle = await elementReady('[itemprop="name"]');
repoTitle!.after(
<a
className="mr-2"
href={`https://${getRepositoryInfo().name!}`}
href={`https://${repoTitle!.textContent!.trim()}`}
target="_blank"
rel="noopener noreferrer"
>
Expand All @@ -42,11 +42,8 @@ async function initRepo(): Promise<void> {
}

void features.add(__filebasename, {
include: [
pageDetect.isRepo
],
exclude: [
() => !getRepositoryInfo()!.name!.endsWith('.github.io')
() => !getRepo()?.name.endsWith('.github.io')
],
init: initRepo
}, {
Expand Down
4 changes: 2 additions & 2 deletions source/features/list-prs-for-file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import PullRequestIcon from 'octicon/git-pull-request.svg';
import features from '.';
import * as api from '../github-helpers/api';
import getDefaultBranch from '../github-helpers/get-default-branch';
import {buildRepoURL, getRepoURL, getRepoGQL} from '../github-helpers';
import {buildRepoURL, getRepoGQL, getRepo} from '../github-helpers';

function getPRUrl(prNumber: number): string {
return buildRepoURL('pull', prNumber, 'files');
Expand Down Expand Up @@ -90,7 +90,7 @@ const getPrsByFile = cache.function(async (): Promise<Record<string, number[]>>
}, {
maxAge: {hours: 2},
staleWhileRevalidate: {days: 9},
cacheKey: () => __filebasename + ':' + getRepoURL()
cacheKey: () => __filebasename + ':' + getRepo()!.nameWithOwner
});

async function init(): Promise<void> {
Expand Down
4 changes: 2 additions & 2 deletions source/features/next-scheduled-github-action.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as pageDetect from 'github-url-detection';

import features from '.';
import * as api from '../github-helpers/api';
import {getRepoURL, getRepoGQL} from '../github-helpers';
import {getRepoGQL, getRepo} from '../github-helpers';

const getScheduledWorkflows = cache.function(async (): Promise<Record<string, string> | false> => {
const {repository: {object: {entries: workflows}}} = await api.v4(`
Expand Down Expand Up @@ -44,7 +44,7 @@ const getScheduledWorkflows = cache.function(async (): Promise<Record<string, st
}, {
maxAge: {days: 1},
staleWhileRevalidate: {days: 10},
cacheKey: () => __filebasename + ':' + getRepoURL()
cacheKey: () => __filebasename + ':' + getRepo()!.nameWithOwner
});

async function init(): Promise<false | void> {
Expand Down
4 changes: 2 additions & 2 deletions source/features/pinned-issues-update-time.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import looseParseInt from '../helpers/loose-parse-int';
import {getRepoGQL, getRepoURL} from '../github-helpers';
import {getRepoGQL, getRepo} from '../github-helpers';

interface IssueInfo {
updatedAt: string;
Expand All @@ -26,7 +26,7 @@ const getLastUpdated = cache.function(async (issueNumbers: number[]): Promise<Re
return repository;
}, {
maxAge: {minutes: 30},
cacheKey: ([issues]) => __filebasename + ':' + getRepoURL() + ':' + String(issues)
cacheKey: ([issues]) => __filebasename + ':' + getRepo()!.nameWithOwner + ':' + String(issues)
});

function getPinnedIssueNumber(pinnedIssue: HTMLElement): number {
Expand Down

0 comments on commit 059a3cd

Please sign in to comment.