Refactored repository integration and added GitLab support

This commit is contained in:
squidfunk
2020-02-18 10:10:40 +01:00
parent af50d5b177
commit ac7c8e20a8
14 changed files with 578 additions and 114 deletions

View File

@@ -36,7 +36,6 @@ import {
} from "rxjs"
import {
delay,
map,
switchMap,
tap,
filter,
@@ -61,7 +60,6 @@ import {
} from "./observables"
import { setupSearchWorker } from "./workers"
import { renderSource } from "templates"
import { fetchGitHubStats } from "integrations/source/github"
import { setToggle, setScrollLock, resetScrollLock } from "actions"
import {
mountHeader,
@@ -78,6 +76,7 @@ import {
import { mountClipboard } from "./integrations/clipboard"
import { patchTables, patchDetails, patchScrollfix } from "patches"
import { takeIf, not, isConfig } from "utilities"
import { fetchSourceFacts } from "integrations/source"
/* ------------------------------------------------------------------------- */
@@ -105,48 +104,14 @@ function repository() {
return of(x)
}
// TODO: do correct rounding, see GitHub - done
function format(value: number) {
if (value > 999) {
const digits = +((value - 950) % 1000 > 99)
return `${(++value / 1000).toFixed(digits)}k`
} else {
return value.toString()
}
}
// github repository...
const [, user, repo] = el.href.match(/^.+github\.com\/([^\/]+)\/?([^\/]+)?.*$/i)
// storage memoization!?
// get, if not available, exec and persist
// getOrRetrieve... storage$.
// Show repo stats
if (user && repo) {
return fetchGitHubStats(user, repo)
.pipe(
map(({ stargazers_count, forks_count }) => ([
`${format(stargazers_count || 0)} Stars`,
`${format(forks_count || 0)} Forks`
])),
tap(data => sessionStorage.setItem("repository", JSON.stringify(data)))
)
// Show user or organization stats
} else if (user) {
return fetchGitHubStats(user)
.pipe(
map(({ public_repos }) => ([
`${format(public_repos || 0)} Repositories`
])),
tap(data => sessionStorage.setItem("repository", JSON.stringify(data)))
)
}
return of([])
return fetchSourceFacts(el.href)
.pipe(
tap(data => sessionStorage.setItem("repository", JSON.stringify(data)))
)
}
// memoize
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */

View File

@@ -0,0 +1,89 @@
/*
* Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { Observable, of } from "rxjs"
import { fetchSourceFactsFromGitHub } from "../github"
import { fetchSourceFactsFromGitLab } from "../gitlab"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Source facts
*/
export type SourceFacts = string[]
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Fetch source facts
*
* @param url - Source repository URL
*
* @return Source facts observable
*/
export function fetchSourceFacts(
url: string
): Observable<SourceFacts> {
const [type] = url.match(/(git(?:hub|lab))/i) || []
switch (type.toLowerCase()) {
/* GitHub repository */
case "github":
const [, user, repo] = url.match(/^.+github\.com\/([^\/]+)\/?([^\/]+)/i)
return fetchSourceFactsFromGitHub(user, repo)
/* GitLab repository */
case "gitlab":
const [, base, project] = url.match(/^.+?([^\/]*gitlab[^\/]+)\/(.+)/i)
return fetchSourceFactsFromGitLab(base, project)
/* Everything else */
default:
return of([])
}
}
/* ------------------------------------------------------------------------- */
/**
* Round a number for display with source facts
*
* This is a reverse engineered implementation of GitHub's weird rounding
* algorithm for stars, forks and all other numbers. Probably incorrect.
*
* @param value - Original value
*
* @return Rounded value
*/
export function roundSourceFactValue(value: number) {
if (value > 999) {
const digits = +((value - 950) % 1000 > 99)
return `${((value + 1) / 1000).toFixed(digits)}k`
} else {
return value.toString()
}
}

View File

@@ -21,82 +21,54 @@
*/
import { Repo, User } from "github-types"
import { NEVER, Observable } from "rxjs"
import { Observable, of } from "rxjs"
import { ajax } from "rxjs/ajax"
import { filter, map, pluck, shareReplay } from "rxjs/operators"
import { filter, pluck, shareReplay, switchMap } from "rxjs/operators"
import { SourceFacts, roundSourceFactValue } from "../_"
/* ----------------------------------------------------------------------------
* Helper functions
* Functions
* ------------------------------------------------------------------------- */
/**
* Round a number
* Fetch GitHub source facts
*
* TODO: document
* @param user - GitHub user
* @param repo - GitHub repository
*
* @return Source facts observable
*/
function round(value: number) {
return value > 999
? `${(value / 1000).toFixed(1)}k`
: `${(value)}`
}
/**
* TODO: document
*/
export function fetchGitHubStats(
user: string
): Observable<User>
export function fetchGitHubStats(
user: string, repo: string
): Observable<Repo>
export function fetchGitHubStats(
export function fetchSourceFactsFromGitHub(
user: string, repo?: string
): Observable<User | Repo> {
const endpoint = typeof repo !== "undefined"
? `repos/${user}/${repo}`
: `users/${user}`
): Observable<SourceFacts> {
return ajax({
url: `https://api.github.com/${endpoint}`,
url: typeof repo !== "undefined"
? `https://api.github.com/repos/${user}/${repo}`
: `https://api.github.com/users/${user}`,
responseType: "json"
})
.pipe(
filter(({ status }) => status === 200),
pluck("response"),
switchMap(data => {
/* GitHub repository */
if (typeof repo !== "undefined") {
const { stargazers_count, forks_count }: Repo = data
return of([
`${roundSourceFactValue(stargazers_count || 0)} Stars`,
`${roundSourceFactValue(forks_count || 0)} Forks`
])
/* GitHub user/organization */
} else {
const { public_repos }: User = data
return of([
`${roundSourceFactValue(public_repos || 0)} Repositories`
])
}
}),
shareReplay(1)
)
}
// TODO: GitLab API:
// https://docs.gitlab.com/ee/api/projects.html#get-single-project
// curl "https://gitlab.com/api/v4/projects/johannes-z%2Fmkdocs-material"
/* ------------------------------------------------------------------------- */
/**
* Get repository information
*
* TODO: document
*/
export function getRepository(user: string, repo: string): Observable<string[]> {
return fetchGitHubStats(user, repo)
.pipe(
map(({ stargazers_count, forks_count }) => ([
`${round(stargazers_count || 0)} Stars`,
`${round(forks_count || 0)} Forks`
]))
)
}
/**
* Get user/organization information
*
* TODO: document
*/
export function getUser(user: string): Observable<string[]> {
return fetchGitHubStats(user)
.pipe(
map(({ public_repos }) => ([
`${round(public_repos || 0)} Repositories`
]))
)
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { ProjectSchema } from "gitlab"
import { Observable } from "rxjs"
import { ajax } from "rxjs/ajax"
import { filter, map, pluck, shareReplay } from "rxjs/operators"
import { SourceFacts, roundSourceFactValue } from "../_"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Fetch GitLab source facts
*
* @param base - GitLab base
* @param project - GitLab project
*
* @return Source facts observable
*/
export function fetchSourceFactsFromGitLab(
base: string, project: string
): Observable<SourceFacts> {
return ajax({
url: `https://${base}/api/v4/projects/${encodeURIComponent(project)}`,
responseType: "json"
})
.pipe(
filter(({ status }) => status === 200),
pluck("response"),
map(({ star_count, forks_count }: ProjectSchema) => ([
`${roundSourceFactValue(star_count || 0)} Stars`,
`${roundSourceFactValue(forks_count || 0)} Forks`
])),
shareReplay(1)
)
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
export * from "./_"
export * from "./github"

View File

@@ -69,7 +69,7 @@ export function renderSearchResult(
})
return (
<li class={css.item}>
{...children}
{children}
</li>
)
}

View File

@@ -20,6 +20,7 @@
* IN THE SOFTWARE.
*/
import { SourceFacts } from "integrations/source"
import { h } from "utilities"
/* ----------------------------------------------------------------------------
@@ -46,11 +47,12 @@ const css = {
* @return Element
*/
export function renderSource(
facts: any // TODO: add typings
facts: SourceFacts
): HTMLElement {
const children = facts.map(fact => <li class={css.fact}>{fact}</li>)
return (
<ul class={css.facts}>
{facts.map((fact: any) => <li class={css.fact}>{fact}</li>)}
{children}
</ul>
)
}