How to use onetime - 10 common examples

To help you get started, we’ve selected a few onetime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sindresorhus / refined-github / source / libs / utils.ts View on Github external
import select from 'select-dom';
import onetime from 'onetime';
import {isRepo, isPR, isIssue} from './page-detect';

export const getUsername = onetime(() => select('meta[name="user-login"]')!.getAttribute('content')!);

export const getDiscussionNumber = (): string | undefined => {
	if (isPR() || isIssue()) {
		return getCleanPathname().split('/')[3];
	}

	return undefined;
};

// Drops leading and trailing slash to avoid /\/?/ everywhere
export const getCleanPathname = (): string => location.pathname.replace(/^[/]|[/]$/g, '');

// Parses a repo's subpage, e.g.
// '/user/repo/issues/' -> 'issues'
// '/user/repo/' -> ''
// returns undefined if the path is not a repo
github refined-bitbucket / refined-bitbucket / src / page-detect.js View on Github external
// @flow

import onetime from 'onetime'

// Some of this functions are borrowed from https://github.com/sindresorhus/refined-github/blob/master/source/libs/page-detect.js

// Drops leading and trailing slash to avoid /\/?/ everywhere
const getCleanPathname = () => location.pathname.replace(/^[/]|[/]$/g, '')

// '/user/repo/.../...' -> 'user/repo'
// eslint-disable-next-line no-warning-comments
// FIXME TODO: I noticed much later that maybe this could simply be:
// `JSON.parse(document.body.dataset.currentRepo).fullslug`
// Confirm, compare perf and replace in better.
export const getRepoURL = onetime(() =>
    location.pathname
        .slice(1)
        .split('/', 2)
        .join('/')
)

// Parses a repo's subpage, e.g.
// '/user/repo/pull-requests/' -> 'pull-requests'
// '/user/repo/' -> ''
// returns false if the path is not a repo
const getRepoPath = () => {
    const match = /^[^/]+[/][^/]+[/]?(.*)$/.exec(getCleanPathname())
    return (match && match[1]) || ''
}

export const isPullRequestList = () => getRepoPath() === 'pull-requests'
github andreypopp / sitegen / src / bin / OutputRenderer.js View on Github external
/**
 * @copyright 2016-present, Sitegen team
 */

import fs from 'fs';
import logUpdate from 'log-update';
import onetime from 'onetime';
import exitHook from 'exit-hook';

const NEWLINE = '\n';

let installExitHook = onetime(() =>
  exitHook(() => OutputRenderer.done()));

let OutputRenderer = {

  stdout: [],
  stderr: [],

  _stdoutWrite: process.stdout.write,
  _stderrWrite: process.stderr.write,
  _consoleLog: console.log, // eslint-disable-line no-console
  _consoleWarning: console.warning, // eslint-disable-line no-console
  _consoleError: console.error, // eslint-disable-line no-console
  _consoleDebug: console.debug, // eslint-disable-line no-console

  get hasBuffer() {
    return this.stdout.length || this.stderr.length;
github sindresorhus / refined-github / source / features / ci-link.tsx View on Github external
async function init(): Promise {
	const icon = await fetchCIStatus();
	if (!icon) {
		return false;
	}

	if (onetime.callCount(fetchCIStatus) > 1) {
		icon.style.animation = 'none';
	}

	// Append to title (aware of forks and private repos)
	appendBefore('.pagehead h1', '.fork-flag', icon);
}
github sindresorhus / refined-github / source / features / ci-link.tsx View on Github external
async function init() {
	const icon = await fetchStatus();
	if (!icon) {
		return false;
	}

	if (callCount(fetchStatus) > 1) {
		icon.style.animation = 'none';
	}

	// Append to title (aware of forks and private repos)
	appendBefore('.pagehead h1', '.fork-flag', icon);
}
github sindresorhus / refined-github / source / features / remove-projects-tab.tsx View on Github external
import React from 'dom-chef';
import select from 'select-dom';
import onetime from 'onetime';
import elementReady from 'element-ready';
import features from '../libs/features';
import {isUserProfile, isOwnOrganizationProfile, isOrganizationProfile} from '../libs/page-detect';

const addNewProjectLink = onetime(() => {
	if (isUserProfile()) {
		// The link already exists on our profile,
		// and we can't create projects on others' profiles
		return;
	}

	if (isOrganizationProfile() && !isOwnOrganizationProfile()) {
		// We can only add projects to our organizations
		return;
	}

	// We can't detect whether we can create projects on a repo,
	// so we're just gonna show a potentially-404 link. 🤷

	// URLs patterns:
	// https://github.com/orgs/USER/projects/new
github sindresorhus / refined-github / source / features / revert-file.tsx View on Github external
import features from '../libs/features';
import fetchDom from '../libs/fetch-dom';
import postForm from '../libs/post-form';
import {getDiscussionNumber, getRepoGQL, getRepoURL, getCurrentBranch} from '../libs/utils';

function showError(menuItem: HTMLButtonElement, error: string): void {
	menuItem.disabled = true;
	menuItem.style.background = 'none'; // Disables hover background color
	menuItem.textContent = error;
}

/**
Get the current base commit of this PR. It should change after rebases and merges in this PR.
This value is not consistently available on the page (appears in `/files` but not when only 1 commit is selected)
*/
const getBaseReference = onetime(async (): Promise => {
	const {repository} = await api.v4(`
		repository(${getRepoGQL()}) {
			pullRequest(number: ${getDiscussionNumber()!}) {
				baseRefOid
			}
		}
	`);
	return repository.pullRequest.baseRefOid;
});

async function getFile(menuItem: Element): Promise<{isTruncated: boolean; text: string} | null> {
	const filePath = menuItem.closest('[data-path]')!.dataset.path!;
	const {repository} = await api.v4(`
		repository(${getRepoGQL()}) {
			file: object(expression: "${await getBaseReference()}:${filePath}") {
				... on Blob {
github sindresorhus / refined-github / source / features / wait-for-build.tsx View on Github external
import './wait-for-build.css';
import React from 'dom-chef';
import select from 'select-dom';
import onetime from 'onetime';
import infoIcon from 'octicon/info.svg';
import delegate, {DelegateEvent} from 'delegate-it';
import features from '../libs/features';
import * as prCiStatus from '../libs/pr-ci-status';
import onPrMergePanelOpen from '../libs/on-pr-merge-panel-open';

let waiting: symbol | undefined;

// Reuse the same checkbox to preserve its status
const generateCheckbox = onetime(() => (
	<label>
		<input checked="" name="rgh-pr-check-waiter" type="checkbox">
		{' Wait for successful checks '}
		<a aria-label="This only works if you keep this tab open while waiting." href="https://github.com/sindresorhus/refined-github/pull/975">
			{infoIcon()}
		</a>
	</label>
));

function canMerge(): boolean {
	return select.exists('[data-details-container=".js-merge-pr"]:not(:disabled)');
}

function getCheckbox(): HTMLInputElement | null {
	return select('[name="rgh-pr-check-waiter"]');
}
github refined-bitbucket / refined-bitbucket / src / utils.js View on Github external
// @flow

import onetime from 'onetime'

export const getApiToken: () =&gt; string = onetime(
    (): string =&gt; {
        const meta: HTMLMetaElement = (document.querySelector(
            'meta[name="apitoken"]'
        ): any)
        const apiTokenContent = meta.content
        const parsedApiTokenContent = JSON.parse(apiTokenContent)
        return parsedApiTokenContent.token
    }
)

export const getMainBranch: () =&gt; string = onetime(
    (): string =&gt;
        JSON.parse((document.body || {}).dataset.currentRepo).mainbranch.name
)

export function getFirstFileContents(
    localUrls: string[],
    externalUrl: string
): Promise {
    const requests = localUrls.map(url =&gt;
        fetch(url, { credentials: 'include' })
    )

    if (externalUrl) {
        requests.push(fetch(externalUrl))
    }
github refined-bitbucket / refined-bitbucket / test / test-utils.js View on Github external
import { h } from 'dom-chef'
import onetime from 'onetime'

export const cleanDocumentBody = () =&gt; {
    while (document.body.hasChildNodes()) {
        document.body.removeChild(document.body.lastChild)
    }
}

export const addApiTokenMetadata = onetime(() =&gt; {
    const meta = (
        
    )
    document.head.appendChild(meta)
})

export const setUrlLocation = () =&gt; {
    global.location = new URL('https://www.bitbucket.org/user/repo')
}

onetime

Ensure a function is only called once

MIT
Latest version published 11 months ago

Package Health Score

74 / 100
Full package analysis

Popular onetime functions