Skip to content

Feature proposal: ignore lists for upgrade-interactive #2562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import {ItemOptions}
import {Pad} from '@yarnpkg/libui/sources/components/Pad';
import {ScrollableItems} from '@yarnpkg/libui/sources/components/ScrollableItems';
import {useMinistore} from '@yarnpkg/libui/sources/hooks/useMinistore';
import {useKeypress} from '@yarnpkg/libui/sources/hooks/useKeypress';
import {renderForm, SubmitInjectedComponent} from '@yarnpkg/libui/sources/misc/renderForm';
import {suggestUtils} from '@yarnpkg/plugin-essentials';
import {Command, Usage} from 'clipanion';
import {diffWords} from 'diff';
import {Box, Text} from 'ink';
import React, {useEffect, useRef, useState} from 'react';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import semver from 'semver';

const SIMPLE_SEMVER = /^((?:[\^~]|>=?)?)([0-9]+)(\.[0-9]+)(\.[0-9]+)((?:-\S+)?)$/;
Expand Down Expand Up @@ -143,6 +144,46 @@ export default class UpgradeInteractiveCommand extends BaseCommand {
return suggestions;
};

const formatAction = ({isIgnore, version}: {isIgnore: boolean; version: string}) => {
return `${isIgnore ? `ignore` : `update`}__${version}`;
};

const parseAction = (action: string) => {
const [command, version] = action.split(`__`);

return {
isIgnore: command === `ignore`,
version,
};
};

const readIgnoreList = () => {
return configuration.get(`upgradeInteractiveIgnoredVersions`).reduce((allVersions, versionString) => {
const [packageName, versionRange = `*`] = versionString.split(`:`);

if (!packageName) return allVersions;

return {
...allVersions,
[packageName]: versionRange,
};
}, {} as Record<string, string>);
};

const writeIgnoreList = async (ignoredDependencyUpdates: Record<string, string>) => {
const currentList = readIgnoreList();

const newList = {
...currentList,
...ignoredDependencyUpdates,
};

await Configuration.updateConfiguration(configuration.startingCwd, {
upgradeInteractiveIgnoredVersions: Object.entries(newList)
.map(([packageName, versionRange]) => `${packageName}:${versionRange}`),
});
};

const Prompt = () => {
return (
<Box flexDirection="row">
Expand All @@ -157,6 +198,11 @@ export default class UpgradeInteractiveCommand extends BaseCommand {
Press <Text bold color="cyanBright">{`<left>`}</Text>/<Text bold color="cyanBright">{`<right>`}</Text> to select versions.
</Text>
</Box>
<Box marginLeft={1}>
<Text>
Press <Text bold color="cyanBright">{`<i>`}</Text> to toggle ignore mode.
</Text>
</Box>
</Box>
<Box flexDirection="column">
<Box marginLeft={1}>
Expand Down Expand Up @@ -191,9 +237,37 @@ export default class UpgradeInteractiveCommand extends BaseCommand {

const UpgradeEntry = ({active, descriptor, suggestions}: {active: boolean, descriptor: Descriptor, suggestions: Array<UpgradeSuggestion>}) => {
const [action, setAction] = useMinistore<string | null>(descriptor.descriptorHash, null);
const [isIgnoreMode, setIgnoreMode] = useState(false);

const packageIdentifier = structUtils.stringifyIdent(descriptor);
const padLength = Math.max(0, 45 - packageIdentifier.length);

useKeypress({active}, (ch, key) => {
switch (key.name) {
case `i`:
setIgnoreMode(prevIsIgnore => {
const nextIsIgnore = !prevIsIgnore;

if (action !== null) {
const {version} = parseAction(action);
setAction(formatAction({isIgnore: nextIsIgnore, version}));
}

return nextIsIgnore;
});
}
}, [action, setAction, setIgnoreMode]);

const onItemChange = useCallback((newAction: string | null) => {
if (newAction === null) {
setAction(null);
} else {
setAction(formatAction({isIgnore: isIgnoreMode, version: newAction}));
}
}, [isIgnoreMode, setAction]);

const {version: value} = action ? parseAction(action) : {version: null};

return <>
<Box>
<Box width={45}>
Expand All @@ -203,7 +277,15 @@ export default class UpgradeInteractiveCommand extends BaseCommand {
<Pad active={active} length={padLength}/>
</Box>
{suggestions !== null
? <ItemOptions active={active} options={suggestions} value={action} skewer={true} onChange={setAction} sizes={[17, 17, 17]} />
? <ItemOptions
active={active}
gemColor={isIgnoreMode ? `red` : undefined /* use default */}
options={suggestions}
value={value}
skewer={true}
onChange={onItemChange}
sizes={[17, 17, 17]}
/>
: <Box marginLeft={2}><Text color="gray">Fetching suggestions...</Text></Box>
}
</Box>
Expand All @@ -221,12 +303,28 @@ export default class UpgradeInteractiveCommand extends BaseCommand {
});

useEffect(() => {
const ignoreList = readIgnoreList();

Promise.all(dependencies.map(descriptor => fetchSuggestions(descriptor)))
.then(allSuggestions => {
const mappedToSuggestions = dependencies.map((descriptor, i) => {
const suggestionsForDescriptor = allSuggestions[i];
return [descriptor, suggestionsForDescriptor] as const;
}).filter(([_, suggestions]) => suggestions.length > 1);
}).filter(([_, suggestions]) => suggestions.length > 1)
.filter(([{scope, name}, suggestions]) => {
const ignoredVersionRange = ignoreList[scope ? `@${scope}/${name}` : name];

if (!ignoredVersionRange)
return true;

// The latest version is always the last one in the array
const latestVersion = suggestions[suggestions.length - 1]?.value?.replace(`^`, ``);
if (!latestVersion)
return true;

// If the latest version satisfies the ignore range, we filter out the dependency
return !semver.satisfies(latestVersion, ignoredVersionRange);
});

if (mountedRef.current) {
setSuggestions(mappedToSuggestions);
Expand Down Expand Up @@ -272,24 +370,38 @@ export default class UpgradeInteractiveCommand extends BaseCommand {
if (typeof updateRequests === `undefined`)
return 1;

let hasChanged = false;
let shouldInstall = false;
let shouldUpdateIgnoreList = false;

const ignoredDependencyUpdates: Record<string, string> = {};

for (const workspace of project.workspaces) {
for (const dependencyType of [`dependencies`, `devDependencies`] as Array<HardDependencies>) {
const dependencies = workspace.manifest[dependencyType];

for (const descriptor of dependencies.values()) {
const newRange = updateRequests.get(descriptor.descriptorHash);

if (typeof newRange !== `undefined` && newRange !== null) {
dependencies.set(descriptor.identHash, structUtils.makeDescriptor(descriptor, newRange));
hasChanged = true;
const action = updateRequests.get(descriptor.descriptorHash);

if (typeof action !== `undefined` && action !== null) {
const {isIgnore, version: newRange} = parseAction(action);

if (isIgnore) {
const key = descriptor.scope ? `@${descriptor.scope}/${descriptor.name}` : descriptor.name;
ignoredDependencyUpdates[key] = newRange;
shouldUpdateIgnoreList = true;
} else {
dependencies.set(descriptor.identHash, structUtils.makeDescriptor(descriptor, newRange));
shouldInstall = true;
}
}
}
}
}

if (!hasChanged)
if (shouldUpdateIgnoreList)
await writeIgnoreList(ignoredDependencyUpdates);

if (!shouldInstall)
return 0;

const installReport = await StreamReport.start({
Expand Down
11 changes: 11 additions & 0 deletions packages/yarnpkg-core/sources/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,14 @@ export const coreDefinitions: {[coreSettingName: string]: SettingsDefinition} =
},
},
},

// Settings related to plugins
upgradeInteractiveIgnoredVersions: {
description: `List of versions ignored by the upgrade-interactive command`,
type: SettingsType.STRING,
default: [],
isArray: true,
},
};

/**
Expand Down Expand Up @@ -546,6 +554,9 @@ export interface ConfigurationValueMap {
peerDependencies?: Map<string, string>,
peerDependenciesMeta?: Map<string, miscUtils.ToMapValue<{optional?: boolean}>>,
}>>;

// Settings related to plugins
upgradeInteractiveIgnoredVersions: Array<string>;
}

export type PackageExtensionData = miscUtils.MapValueToObjectValue<miscUtils.MapValue<ConfigurationValueMap['packageExtensions']>>;
Expand Down
7 changes: 4 additions & 3 deletions packages/yarnpkg-libui/sources/components/Gem.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {Text} from 'ink';
import {Text, TextProps} from 'ink';
import React, {memo, useMemo} from 'react';

export interface GemProps {
active: boolean
activeColor?: TextProps['color']
}
export const Gem: React.FC<GemProps> = memo(({active}) => {
export const Gem: React.FC<GemProps> = memo(({active, activeColor = `green`}) => {
const text = useMemo(() => active ? `◉` : `◯`, [active]);
const color = useMemo(() => active ? `green` : `yellow`, [active]);
const color = useMemo(() => active ? activeColor : `yellow`, [active, activeColor]);
return <Text color={color}>{text}</Text>;
});
4 changes: 3 additions & 1 deletion packages/yarnpkg-libui/sources/components/ItemOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import {Pad} from './Pad';

export const ItemOptions = function <T>({
active,
gemColor,
skewer,
options,
value,
onChange,
sizes = [],
}: {
active: boolean,
gemColor: string | undefined;
skewer?: boolean,
options: Array<{value: T, label: string}>,
value: T,
Expand Down Expand Up @@ -56,7 +58,7 @@ export const ItemOptions = function <T>({
return (
<Box key={label} width={boxWidth} marginLeft={1}>
<Text wrap={`truncate`}>
<Gem active={isGemActive} />{` `}{label}
<Gem active={isGemActive} activeColor={gemColor} />{` `}{label}
</Text>
{skewer ? <Pad active={active} length={padWidth}/> : null}
</Box>
Expand Down