Skip to content

Commit

Permalink
shared: rename unwrap to nullthrows
Browse files Browse the repository at this point in the history
Summary:
The `unwrap` is treated as a jotai library function so `jotai/babel/plugin-debug-label` rewrites code like:

  const parentRev = unwrap(this.singleParentRev(rev));

to:

  const parentRev = unwrap(this.singleParentRev(rev));
  parentRev.debugLabel = "parentRev";

which causes issues (since `parentRev` is a number). It does not seem there is
a way to customize the babel plugin to blocklist function names. For now let's
just rename our `unwrap` to avoid the conflict.

See https://github.com/pmndrs/jotai/blob/234dff9c89642c6a1a724d2a73398119e4ea00fc/src/babel/utils.ts#L39

Reviewed By: evangrayk

Differential Revision: D54821276

fbshipit-source-id: f2dbb2035271114c2a5aeb202bfefe4c81df25a0
  • Loading branch information
quark-zju authored and facebook-github-bot committed Mar 12, 2024
1 parent d18f33b commit 216632d
Show file tree
Hide file tree
Showing 33 changed files with 123 additions and 109 deletions.
4 changes: 2 additions & 2 deletions addons/isl-server/proxy/existingServerStateFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import rmtree from './rmtree';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

export type ExistingServerInfo = {
sensitiveToken: string;
Expand All @@ -28,7 +28,7 @@ export type ExistingServerInfo = {

const cacheDir =
process.platform == 'win32'
? path.join(unwrap(process.env.LOCALAPPDATA), 'cache')
? path.join(nullthrows(process.env.LOCALAPPDATA), 'cache')
: process.platform == 'darwin'
? path.join(os.homedir(), 'Library/Caches')
: process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
Expand Down
4 changes: 2 additions & 2 deletions addons/isl-server/src/Repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import {RateLimiter} from 'shared/RateLimiter';
import {TypedEventEmitter} from 'shared/TypedEventEmitter';
import {exists} from 'shared/fs';
import {removeLeadingPathSep} from 'shared/pathUtils';
import {notEmpty, randomId, unwrap} from 'shared/utils';
import {notEmpty, randomId, nullthrows} from 'shared/utils';

/**
* This class is responsible for providing information about the working copy
Expand Down Expand Up @@ -497,7 +497,7 @@ export class Repository {
}

private normalizeOperationArgs(cwd: string, args: Array<CommandArg>): Array<string> {
const repoRoot = unwrap(this.info.repoRoot);
const repoRoot = nullthrows(this.info.repoRoot);
return args.flatMap(arg => {
if (typeof arg === 'object') {
switch (arg.type) {
Expand Down
4 changes: 2 additions & 2 deletions addons/isl-server/src/ServerToClientAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {repositoryCache} from './RepositoryCache';
import {findPublicAncestor, parseExecJson} from './utils';
import {serializeToString, deserializeFromString} from 'isl/src/serialize';
import {revsetForComparison} from 'shared/Comparison';
import {randomId, unwrap} from 'shared/utils';
import {randomId, nullthrows} from 'shared/utils';
import {Readable} from 'stream';

export type IncomingMessage = ClientToServerMessage;
Expand Down Expand Up @@ -254,7 +254,7 @@ export default class ServerToClientAPI {
}
this.tracker
.operation('UploadImage', 'UploadImageError', {}, () =>
uploadFile(unwrap(this.connection.logger), {filename, data: payload}),
uploadFile(nullthrows(this.connection.logger), {filename, data: payload}),
)
.then((result: string) => {
this.connection.logger?.info('sucessfully uploaded file', filename, result);
Expand Down
4 changes: 2 additions & 2 deletions addons/isl-server/src/analytics/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
import type {ApplicationInfo} from './types';

import os from 'os';
import {randomId, unwrap} from 'shared/utils';
import {randomId, nullthrows} from 'shared/utils';

export function getUsername(): string {
try {
return os.userInfo().username;
} catch (osInfoError) {
try {
const {env} = process;
return unwrap(env.LOGNAME || env.USER || env.LNAME || env.USERNAME);
return nullthrows(env.LOGNAME || env.USER || env.LNAME || env.USERNAME);
} catch (processEnvError) {
throw new Error(String(processEnvError) + String(osInfoError));
}
Expand Down
7 changes: 5 additions & 2 deletions addons/isl-server/src/serverPlatform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type {

import {spawn} from 'child_process';
import pathModule from 'path';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

/**
* Platform-specific server-side API for each target: vscode extension host, electron standalone, browser, ...
Expand Down Expand Up @@ -43,7 +43,10 @@ export const browserServerPlatform: ServerPlatform = {
) => {
switch (message.type) {
case 'platform/openContainingFolder': {
const absPath: AbsolutePath = pathModule.join(unwrap(repo?.info.repoRoot), message.path);
const absPath: AbsolutePath = pathModule.join(
nullthrows(repo?.info.repoRoot),
message.path,
);
let args: Array<string> = [];
// use OS-builtin open command to open parent directory
// (which may open different file extensions with different programs)
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/Cleanup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {type Dag, dagWithPreviews} from './previews';
import {VSCodeButton} from '@vscode/webview-ui-toolkit/react';
import {useAtomValue} from 'jotai';
import {Icon} from 'shared/Icon';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

export function isStackEligibleForCleanup(
hash: Hash,
Expand Down Expand Up @@ -99,7 +99,7 @@ export function CleanupAllButton() {
contextKey="cleanup-all"
runOperation={() => {
return cleanableStacks.map(hash => {
const info = unwrap(dag.get(hash));
const info = nullthrows(dag.get(hash));
return new HideOperation(latestSuccessorUnlessExplicitlyObsolete(info));
});
}}
Expand Down
6 changes: 3 additions & 3 deletions addons/isl/src/CommitInfoView/CommitInfoView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ import {useCallback, useEffect} from 'react';
import {ComparisonType} from 'shared/Comparison';
import {useContextMenu} from 'shared/ContextMenu';
import {Icon} from 'shared/Icon';
import {firstLine, notEmpty, unwrap} from 'shared/utils';
import {firstLine, notEmpty, nullthrows} from 'shared/utils';

import './CommitInfoView.css';

Expand Down Expand Up @@ -779,7 +779,7 @@ function ActionsBar({
answer,
);
setRepoInfo(info => ({
...unwrap(info),
...nullthrows(info),
preferredSubmitCommand: answer,
}));
// setRepoInfo updates `provider`, but we still have a stale reference in this callback.
Expand All @@ -802,7 +802,7 @@ function ActionsBar({
// during another amend or amend message.
const shouldUpdateMessage = !isCommitMode && messageSyncEnabled && anythingToCommit;

const submitOp = unwrap(provider).submitOperation(
const submitOp = nullthrows(provider).submitOperation(
commit.isHead ? [] : [commit], // [] means to submit the head commit
{
draft: shouldSubmitAsDraft,
Expand Down
6 changes: 3 additions & 3 deletions addons/isl/src/CommitInfoView/GenerateWithAI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {useCallback} from 'react';
import {ComparisonType} from 'shared/Comparison';
import {Icon} from 'shared/Icon';
import {useThrottledEffect} from 'shared/hooks';
import {randomId, unwrap} from 'shared/utils';
import {randomId, nullthrows} from 'shared/utils';

import './GenerateWithAI.css';

Expand Down Expand Up @@ -145,7 +145,7 @@ const generatedCommitMessages = atomFamilyWeak((hashKey: string | undefined) =>
const comparison: Comparison = hashKey.startsWith('commit/')
? {type: ComparisonType.UncommittedChanges}
: {type: ComparisonType.Committed, hash: hashKey};
const response = await unwrap(Internal.generateAICommitMessage)({
const response = await nullthrows(Internal.generateAICommitMessage)({
comparison,
title: latestWrittenTitle,
});
Expand Down Expand Up @@ -296,7 +296,7 @@ class FunnelTracker {
/** Get or create the funnel tracker for this hashKey */
static get(hashKey: HashKey): FunnelTracker {
if (this.trackersByHashKey.has(hashKey)) {
return unwrap(this.trackersByHashKey.get(hashKey));
return nullthrows(this.trackersByHashKey.get(hashKey));
}
const tracker = new FunnelTracker();
this.trackersByHashKey.set(hashKey, tracker);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import FilepathClassifier from 'shared/textmate-lib/FilepathClassifier';
import createTextMateRegistry from 'shared/textmate-lib/createTextMateRegistry';
import {updateTextMateGrammarCSS} from 'shared/textmate-lib/textmateStyles';
import {tokenizeLines} from 'shared/textmate-lib/tokenize';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';
import {loadWASM} from 'vscode-oniguruma';

const URL_TO_ONIG_WASM = 'generated/textmate/onig.wasm';
Expand Down Expand Up @@ -208,7 +208,7 @@ async function tokenizeContent(
const grammarCache: Map<string, Promise<IGrammar | null>> = new Map();
function getGrammar(store: Registry, scopeName: string): Promise<IGrammar | null> {
if (grammarCache.has(scopeName)) {
return unwrap(grammarCache.get(scopeName));
return nullthrows(grammarCache.get(scopeName));
}
const grammarPromise = store.loadGrammar(scopeName);
grammarCache.set(scopeName, grammarPromise);
Expand Down
7 changes: 5 additions & 2 deletions addons/isl/src/ConfirmSubmitStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {VSCodeDivider, VSCodeButton, VSCodeTextField} from '@vscode/webview-ui-t
import {useAtom, useAtomValue} from 'jotai';
import {useState} from 'react';
import {useAutofocusRef} from 'shared/hooks';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

import './ConfirmSubmitStack.css';

Expand Down Expand Up @@ -66,7 +66,10 @@ export function useShowConfirmSubmitStack() {

const provider = readAtom(codeReviewProvider);

const replace = {$numCommits: String(stack.length), $cmd: unwrap(provider).submitCommandName()};
const replace = {
$numCommits: String(stack.length),
$cmd: nullthrows(provider).submitCommandName(),
};
const title =
mode === 'submit'
? t('Submitting $numCommits commits for review with $cmd', {replace})
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/DownloadCommitsMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {useAtom} from 'jotai';
import {useEffect, useRef, useState} from 'react';
import {Icon} from 'shared/Icon';
import {KeyCode, Modifier} from 'shared/KeyboardShortcuts';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

import './DownloadCommitsMenu.css';

Expand Down Expand Up @@ -128,7 +128,7 @@ function DownloadCommitsTooltip({dismiss}: {dismiss: () => unknown}) {
const dest =
rebaseType === 'rebase_ontop'
? '.'
: unwrap(findCurrentPublicBase(readAtom(dagWithPreviews))?.hash);
: nullthrows(findCurrentPublicBase(readAtom(dagWithPreviews))?.hash);
// Use exact revsets for sources, so that you can type a specific hash to download and not be surprised by succession.
// Only use succession for destination, which may be in flux at the moment you start the download.
runOperation(new Op(exactRevset(enteredDiffNum), succeedableRevset(dest)));
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/SettingsTooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
import {useAtom, useAtomValue} from 'jotai';
import {Icon} from 'shared/Icon';
import {KeyCode, Modifier} from 'shared/KeyboardShortcuts';
import {tryJsonParse, unwrap} from 'shared/utils';
import {tryJsonParse, nullthrows} from 'shared/utils';

import './VSCodeDropdown.css';
import './SettingsTooltip.css';
Expand Down Expand Up @@ -159,7 +159,7 @@ function SettingsDropdown({
runOperation(
new SetConfigOperation('local', 'github.preferred_submit_command', value),
);
setRepoInfo(info => ({...unwrap(info), preferredSubmitCommand: value}));
setRepoInfo(info => ({...nullthrows(info), preferredSubmitCommand: value}));
}}>
{repoInfo.preferredSubmitCommand == null ? (
<VSCodeOption value={'not set'}>(not set)</VSCodeOption>
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/__tests__/ComparisonView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import fs from 'fs';
import path from 'path';
import {ComparisonType} from 'shared/Comparison';
import {nextTick} from 'shared/testUtils';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

afterEach(cleanup);

Expand Down Expand Up @@ -594,7 +594,7 @@ function mockFetchToSupportSyntaxHighlighting(): jest.SpyInstance {
jest.fn(async url => {
if (url.includes('generated/textmate')) {
const match = /.*generated\/textmate\/(.*)$/.exec(url);
const filename = unwrap(match)[1];
const filename = nullthrows(match)[1];
const toPublicDir = (filename: string) =>
path.normalize(path.join(__dirname, '../../public/generated/textmate', filename));
if (filename === 'onig.wasm') {
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/__tests__/FillCommitMessage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
import {fireEvent, render, screen, waitFor, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {act} from 'react-dom/test-utils';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

/* eslint-disable @typescript-eslint/no-non-null-assertion */

Expand Down Expand Up @@ -110,7 +110,7 @@ describe('FillCommitMessage', () => {
expect(loadFromLastCommit).toBeInTheDocument();
fireEvent.click(loadFromLastCommit);
await waitFor(() => expect(getTitleEditor().value).toMatch('Head Commit'));
expect(getFieldEditor(unwrap(Internal.diffFieldTag))).toHaveValue('');
expect(getFieldEditor(nullthrows(Internal.diffFieldTag))).toHaveValue('');
});

it('Load from commit template', async () => {
Expand Down
4 changes: 2 additions & 2 deletions addons/isl/src/__tests__/Shelve.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {fireEvent, render, screen, waitFor, within} from '@testing-library/react
import userEvent from '@testing-library/user-event';
import {act} from 'react-dom/test-utils';
import {ComparisonType} from 'shared/Comparison';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

describe('Shelve', () => {
beforeEach(() => {
Expand Down Expand Up @@ -99,7 +99,7 @@ describe('Shelve', () => {

// uncheck one file
fireEvent.click(
unwrap(
nullthrows(
screen.getByTestId('changed-file-src/file2.js').querySelector('input[type=checkbox]'),
),
);
Expand Down
7 changes: 5 additions & 2 deletions addons/isl/src/codeReview/CodeReviewInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {GithubUICodeReviewProvider} from './github/github';
import {atom} from 'jotai';
import {clearTrackedCache} from 'shared/LRU';
import {debounce} from 'shared/debounce';
import {firstLine, unwrap} from 'shared/utils';
import {firstLine, nullthrows} from 'shared/utils';

export const codeReviewProvider = atom<UICodeReviewProvider | null>(get => {
const repoInfo = get(repositoryInfo);
Expand Down Expand Up @@ -88,7 +88,10 @@ registerDisposable(

// merge old values with newly fetched ones
return {
value: new Map([...unwrap(existing.value).entries(), ...event.summaries.value.entries()]),
value: new Map([
...nullthrows(existing.value).entries(),
...event.summaries.value.entries(),
]),
};
});
}),
Expand Down
5 changes: 3 additions & 2 deletions addons/isl/src/dag/base_dag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {HashSet} from './set';
import {Map as ImMap, Record, List} from 'immutable';
import {LRU, cachedMethod} from 'shared/LRU';
import {SelfUpdate} from 'shared/immutableExt';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

/**
* Hash-map like container with graph related queries.
Expand Down Expand Up @@ -263,7 +263,8 @@ export class BaseDag<C extends HashWithParents> extends SelfUpdate<BaseDagRecord
const filledSet = gap ? this.range(hashSet, hashSet) : hashSet;
const alreadyVisited = new Set<Hash>();
// We use concat and pop (not unshift) so the order is reversed.
const compareHash = (a: Hash, b: Hash) => -compare(unwrap(this.get(a)), unwrap(this.get(b)));
const compareHash = (a: Hash, b: Hash) =>
-compare(nullthrows(this.get(a)), nullthrows(this.get(b)));
// The number of parents remaining to be visited. This ensures merges are not
// outputted until all parents are outputted.
const remaining = new Map<Hash, number>(
Expand Down
6 changes: 3 additions & 3 deletions addons/isl/src/dag/dag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {arrayFromHashes, HashSet} from './set';
import {List, Record, Map as ImMap, Set as ImSet} from 'immutable';
import {LRU, cachedMethod} from 'shared/LRU';
import {SelfUpdate} from 'shared/immutableExt';
import {group, notEmpty, splitOnce, unwrap} from 'shared/utils';
import {group, notEmpty, splitOnce, nullthrows} from 'shared/utils';

/**
* Main commit graph type used for preview calculation and queries.
Expand Down Expand Up @@ -369,7 +369,7 @@ export class Dag extends SelfUpdate<CommitDagRecord> {
const pureHash = isSucc ? h.substring(REBASE_SUCC_PREFIX.length) : h;
const isPred = !isSucc && duplicated.contains(h);
const isRoot = srcRoots.contains(pureHash);
const info = unwrap(isSucc ? this.get(pureHash) : c);
const info = nullthrows(isSucc ? this.get(pureHash) : c);
return info.withMutations(mut => {
// Reset the seqNumber so the rebase preview tends to show as right-most branches.
let newInfo = mut.set('seqNumber', undefined);
Expand Down Expand Up @@ -565,7 +565,7 @@ export class Dag extends SelfUpdate<CommitDagRecord> {
// Render row by row. The main complexity is to figure out the "ancestors",
// especially when the provided `set` is a subset of the dag.
for (const hash of sorted) {
const info = unwrap(this.get(hash));
const info = nullthrows(this.get(hash));
const parents: ReadonlyArray<Hash> = info?.parents ?? [];
// directParents: solid edges
// indirectParents: dashed edges
Expand Down
8 changes: 4 additions & 4 deletions addons/isl/src/linelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {hash, List, Record, Set as ImSet} from 'immutable';
import {cached, cachedMethod, LRU} from 'shared/LRU';
import {diffLines, splitLines} from 'shared/diff';
import {SelfUpdate} from 'shared/immutableExt';
import {unwrap} from 'shared/utils';
import {nullthrows} from 'shared/utils';

/** Operation code. */
enum Op {
Expand Down Expand Up @@ -378,7 +378,7 @@ class Code implements ValueObject {
if (aLinesMutable) {
aLines[a1] = {...aLines[a1], pc: jlInst == null ? code.size : code.size + 1};
}
const a1Inst = unwrap(code.get(a1Pc));
const a1Inst = nullthrows(code.get(a1Pc));
if (jlInst === undefined) {
// [3]
code = code.push(a1Inst);
Expand Down Expand Up @@ -551,7 +551,7 @@ class Code implements ValueObject {
delStack.pop();
onStackPop?.(delStack);
}
const code = unwrap(this.get(pc));
const code = nullthrows(this.get(pc));
switch (code.op) {
case Op.LINE:
onLine?.(code);
Expand Down Expand Up @@ -898,7 +898,7 @@ class LineLog extends SelfUpdate<LineLogRecord> {
let patience = this.code.getSize() * 2;
const deleted = present == null ? () => false : (pc: Pc) => !present[pc];
while (patience > 0) {
const code = unwrap(this.code.get(pc));
const code = nullthrows(this.code.get(pc));
switch (code.op) {
case Op.END:
lines.push({data: '', rev: 0, pc, deleted: deleted(pc)});
Expand Down
Loading

0 comments on commit 216632d

Please sign in to comment.