summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Fregante <opensource@bfred.it> 2020-06-16 19:56:43 +0200
committerGravatar GitHub <noreply@github.com> 2020-06-16 19:56:43 +0200
commita918f9a3eb6827dd67efdd1bcf362df2e7152406 (patch)
tree4aeb0966e89ed9a641f519f8934a959a868a8823
parent1d003c988da53f575b0285f8366ada9b80b76510 (diff)
downloadrefined-github-a918f9a3eb6827dd67efdd1bcf362df2e7152406.tar.gz
refined-github-a918f9a3eb6827dd67efdd1bcf362df2e7152406.tar.zst
refined-github-a918f9a3eb6827dd67efdd1bcf362df2e7152406.zip
Meta: Minor improvements and lint (#3231)
-rw-r--r--.github/workflows/deployment.yml1
-rw-r--r--.github/workflows/test.yml1
-rw-r--r--contributing.md1
-rw-r--r--source/features/clean-issue-filters.tsx4
-rw-r--r--source/features/latest-tag-button.tsx7
-rw-r--r--source/features/pr-branches.tsx12
-rw-r--r--source/github-helpers/dom-formatters.ts8
-rw-r--r--source/github-helpers/get-default-branch.ts36
-rw-r--r--source/github-helpers/github-url.ts7
-rw-r--r--source/github-helpers/index.ts21
-rw-r--r--test/helpers.ts14
11 files changed, 58 insertions, 54 deletions
diff --git a/.github/workflows/deployment.yml b/.github/workflows/deployment.yml
index 0d0287f4..af129c2e 100644
--- a/.github/workflows/deployment.yml
+++ b/.github/workflows/deployment.yml
@@ -1,3 +1,4 @@
+# Copied from https://github.com/notlmn/browser-extension-template/blob/master/.github/workflows/deployment.yml
name: Deployment
on:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index e68739e7..4230bc22 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -7,6 +7,7 @@ on:
push:
branches:
- master
+ - 'test/*'
jobs:
diff --git a/contributing.md b/contributing.md
index a8541012..85440780 100644
--- a/contributing.md
+++ b/contributing.md
@@ -9,7 +9,6 @@ Suggestions and pull requests are highly encouraged! Have a look at the [open is
- [JSX](https://reactjs.org/docs/introducing-jsx.html) is used to create DOM elements.
- All the [latest DOM APIs](https://github.com/WebReflection/dom4#features) and JavaScript features are available because the extension only has to work in the latest Chrome and Firefox. 🎉
- Each JavaScript feature lives in its own file under [`source/features`](https://github.com/sindresorhus/refined-github/tree/master/source/features) and it's imported in [`source/refined-github.ts`](https://github.com/sindresorhus/refined-github/blob/master/source/refined-github.ts).
-- Some GitHub pages are loaded via AJAX/PJAX, so some features use the special `onAjaxedPages` loader (see it as a custom "on DOM ready").
- See what a _feature_ [looks like](https://github.com/sindresorhus/refined-github/blob/master/source/features/user-profile-follower-badge.tsx).
- Follow [the styleguide](https://github.com/sindresorhus/refined-github/blob/master/readme.md#L100) that appears in the Readme's source to write readable descriptions.
- Refined GitHub tries to integrate as best as possible, so [GitHub's own styleguide](https://primer.style/css) might come in useful.
diff --git a/source/features/clean-issue-filters.tsx b/source/features/clean-issue-filters.tsx
index ea4ad320..a6e6dcb2 100644
--- a/source/features/clean-issue-filters.tsx
+++ b/source/features/clean-issue-filters.tsx
@@ -5,14 +5,14 @@ import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
-import {getOwnerAndRepo, getRepoURL, getRepoGQL} from '../github-helpers';
+import {getCurrentRepository, getRepoURL, getRepoGQL} from '../github-helpers';
const hasAnyProjects = cache.function(async (): Promise<boolean> => {
const {repository, organization} = await api.v4(`
repository(${getRepoGQL()}) {
projects { totalCount }
}
- organization(login: "${getOwnerAndRepo().ownerName!}") {
+ organization(login: "${getCurrentRepository().owner!}") {
projects { totalCount }
}
`, {
diff --git a/source/features/latest-tag-button.tsx b/source/features/latest-tag-button.tsx
index 89001830..55ed1833 100644
--- a/source/features/latest-tag-button.tsx
+++ b/source/features/latest-tag-button.tsx
@@ -114,7 +114,12 @@ async function init(): Promise<false | void> {
const defaultBranch = await getDefaultBranch();
if (currentBranch === defaultBranch) {
link.append(<sup> +{aheadBy}</sup>);
- link.setAttribute('aria-label', aheadBy ? `${defaultBranch} is ${pluralize(aheadBy, '1 commit', '$$ commits')} ahead of the latest release` : `The HEAD of ${defaultBranch} isn’t tagged`);
+ link.setAttribute(
+ 'aria-label',
+ aheadBy ?
+ `${defaultBranch} is ${pluralize(aheadBy, '1 commit', '$$ commits')} ahead of the latest release` :
+ `The HEAD of ${defaultBranch} isn’t tagged`
+ );
} else {
link.setAttribute('aria-label', 'Visit the latest release');
}
diff --git a/source/features/pr-branches.tsx b/source/features/pr-branches.tsx
index 1d4cf0b3..2182b7e9 100644
--- a/source/features/pr-branches.tsx
+++ b/source/features/pr-branches.tsx
@@ -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 {getOwnerAndRepo, getRepoGQL} from '../github-helpers';
+import {getCurrentRepository, getRepoGQL} from '../github-helpers';
type RepositoryReference = {
owner: string;
@@ -32,19 +32,19 @@ function normalizeBranchInfo(data: BranchInfo): {
base?: RepositoryReference;
head?: RepositoryReference;
} {
- const {ownerName, repoName} = getOwnerAndRepo();
+ const currentRepository = getCurrentRepository();
const base = {} as RepositoryReference; // eslint-disable-line @typescript-eslint/consistent-type-assertions
base.branchExists = Boolean(data.baseRef);
base.label = data.baseRefName;
if (base.branchExists) {
- base.url = `/${ownerName!}/${repoName!}/tree/${data.baseRefName}`;
+ base.url = `/${currentRepository.owner!}/${currentRepository.name!}/tree/${data.baseRefName}`;
}
const head = {} as RepositoryReference; // eslint-disable-line @typescript-eslint/consistent-type-assertions
head.branchExists = Boolean(data.headRef);
head.owner = data.headOwner.login;
- if (data.headOwner.login === ownerName) {
+ if (data.headOwner.login === currentRepository.owner) {
head.label = data.headRefName;
} else {
head.label = `${data.headOwner.login}:${data.headRefName}`;
@@ -99,7 +99,7 @@ async function init(): Promise<false | void> {
return false;
}
- const {ownerName} = getOwnerAndRepo();
+ const currentRepository = getCurrentRepository();
const query = buildQuery(prLinks.map(pr => pr.id));
const [data, defaultBranch] = await Promise.all([
api.v4(query),
@@ -118,7 +118,7 @@ async function init(): Promise<false | void> {
base = undefined;
}
- if (head!.owner !== ownerName) {
+ if (head!.owner !== currentRepository.owner) {
head = undefined;
}
diff --git a/source/github-helpers/dom-formatters.ts b/source/github-helpers/dom-formatters.ts
index 99783f81..9340ec07 100644
--- a/source/github-helpers/dom-formatters.ts
+++ b/source/github-helpers/dom-formatters.ts
@@ -3,7 +3,7 @@ import linkifyURLsCore from 'linkify-urls';
import linkifyIssuesCore from 'linkify-issues';
import getTextNodes from '../helpers/get-text-nodes';
-import {getOwnerAndRepo} from '.';
+import {getCurrentRepository} from '.';
import parseBackticksCore from './parse-backticks';
// Shared class necessary to avoid also shortening the links
@@ -12,12 +12,12 @@ export const linkifiedURLClass = 'rgh-linkified-code';
// If we are not in a repo, relative issue references won't make sense
// but `user`/`repo` need to be set to avoid breaking errors in `linkify-issues`
// https://github.com/sindresorhus/refined-github/issues/1305
-const currentRepo = getOwnerAndRepo();
+const currentRepo = getCurrentRepository();
export function linkifyIssues(element: Element, options: Partial<linkifyIssuesCore.TypeDomOptions> = {}): void {
const linkified = linkifyIssuesCore(element.textContent!, {
- user: currentRepo.ownerName ?? '/',
- repository: currentRepo.repoName ?? '/',
+ user: currentRepo.owner ?? '/',
+ repository: currentRepo.name ?? '/',
type: 'dom',
baseUrl: '',
...options,
diff --git a/source/github-helpers/get-default-branch.ts b/source/github-helpers/get-default-branch.ts
index f9ab632c..33ad4d22 100644
--- a/source/github-helpers/get-default-branch.ts
+++ b/source/github-helpers/get-default-branch.ts
@@ -1,8 +1,9 @@
-import select from 'select-dom';
import cache from 'webext-storage-cache';
+import select from 'select-dom';
+import {isForkedRepo} from 'github-url-detection/esm';
import * as api from './api';
-import {getRepoURL, getRepoGQL} from '.';
+import {RepositoryInfo, getCurrentRepository, getRepoURL} from '.';
// This regex should match all of these combinations:
// "This branch is even with master."
@@ -11,30 +12,29 @@ import {getRepoURL, getRepoGQL} from '.';
// "This branch is 1 commit ahead, 27 commits behind master."
const branchInfoRegex = /([^ ]+)\.$/;
-function parseBranchFromDom(): string | undefined {
- if (select.exists('.repohead h1 .octicon-repo-forked')) {
- return; // It's a fork, no "default branch" info available #1132
+export default cache.function(async (repository: Partial<RepositoryInfo> = getCurrentRepository()): Promise<string> => {
+ if (JSON.stringify(repository) === JSON.stringify(getCurrentRepository())) {
+ if (!isForkedRepo()) {
+ // We can find the name in the infobar, available in folder views
+ const branchInfo = select('.branch-infobar')?.textContent!.trim();
+ const defaultBranch = branchInfoRegex.exec(branchInfo!)?.[1];
+ if (defaultBranch) {
+ return defaultBranch;
+ }
+ }
}
- // We can find the name in the infobar, available in folder views
- const branchInfo = select('.branch-infobar')?.textContent!.trim();
- return branchInfoRegex.exec(branchInfo!)?.[1];
-}
-
-async function fetchFromApi(): Promise<string> {
- const {repository} = await api.v4(`
- repository(${getRepoGQL()}) {
+ const response = await api.v4(`
+ repository(owner: "${repository.owner!}", name: "${repository.name!}") {
defaultBranchRef {
name
}
}
`);
- return repository.defaultBranchRef.name;
-}
-
-export default cache.function(async () => parseBranchFromDom() ?? fetchFromApi(), {
+ return response.repository.defaultBranchRef.name;
+}, {
maxAge: 10,
staleWhileRevalidate: 20,
- cacheKey: () => 'default-branch:' + getRepoURL()
+ cacheKey: ([repository]) => repository ? `default-branch:${repository.owner!}/${repository.name!}` : `default-branch:${getRepoURL()}`
});
diff --git a/source/github-helpers/github-url.ts b/source/github-helpers/github-url.ts
index 1966ee2a..97c347a0 100644
--- a/source/github-helpers/github-url.ts
+++ b/source/github-helpers/github-url.ts
@@ -12,8 +12,6 @@ export default class GitHubURL {
// @ts-expect-error
filePath: string;
- assign = Object.assign.bind(null, this);
-
private internalUrl: URL;
constructor(url: string) {
@@ -30,6 +28,11 @@ export default class GitHubURL {
return this.href;
}
+ assign(...replacements: Array<Partial<GitHubURL>>): this {
+ Object.assign(this, ...replacements);
+ return this;
+ }
+
private disambiguateReference(ambiguousReference: string[]): {branch: string; filePath: string} {
const branch = ambiguousReference[0];
const filePathFromSearch = this.searchParams.getAll('path[]').join('/');
diff --git a/source/github-helpers/index.ts b/source/github-helpers/index.ts
index 8f9432f3..fc02b7a8 100644
--- a/source/github-helpers/index.ts
+++ b/source/github-helpers/index.ts
@@ -34,20 +34,21 @@ export const isFirefox = navigator.userAgent.includes('Firefox/');
export const getRepoURL = (): string => location.pathname.slice(1).split('/', 2).join('/').toLowerCase();
export const getRepoGQL = (): string => {
- const {ownerName, repoName} = getOwnerAndRepo();
- return `owner: "${ownerName!}", name: "${repoName!}"`;
+ const {owner, name} = getCurrentRepository();
+ return `owner: "${owner!}", name: "${name!}"`;
};
-export const getOwnerAndRepo = (): {
- ownerName?: string;
- repoName?: string;
-} => {
- const [, ownerName, repoName] = location.pathname.split('/', 3);
- return {ownerName, repoName};
-};
+export interface RepositoryInfo {
+ owner: string;
+ name: string;
+}
+export const getCurrentRepository = oneTime((): Partial<RepositoryInfo> => {
+ const [, owner, name] = location.pathname.split('/', 3);
+ return {owner, name};
+});
export function getForkedRepo(): string | undefined {
- return select<HTMLAnchorElement>('.fork-flag a')?.pathname.slice(1);
+ return select<HTMLMetaElement>('[name="octolytics-dimension-repository_parent_nwo"]')?.content;
}
export const parseTag = (tag: string): {version: string; namespace: string} => {
diff --git a/test/helpers.ts b/test/helpers.ts
index 60b1dff6..45751407 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -4,7 +4,7 @@ import './fixtures/globals';
import pluralize from '../source/helpers/pluralize';
import {
getDiscussionNumber,
- getOwnerAndRepo,
+ getCurrentRepository,
parseTag,
compareNames,
getScopedSelector,
@@ -85,15 +85,9 @@ test('getDiscussionNumber', t => {
test('getOwnerAndRepo', t => {
location.href = 'https://github.com/sindresorhus/refined-github/pull/148';
- t.deepEqual(getOwnerAndRepo(), {
- ownerName: 'sindresorhus',
- repoName: 'refined-github'
- });
-
- location.href = 'https://github.com/DrewML/GifHub/blob/master/.gitignore';
- t.deepEqual(getOwnerAndRepo(), {
- ownerName: 'DrewML',
- repoName: 'GifHub'
+ t.deepEqual(getCurrentRepository(), {
+ owner: 'sindresorhus',
+ name: 'refined-github'
});
});