Skip to content
Open
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
39 changes: 30 additions & 9 deletions src/runtime/suggestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,18 +137,33 @@ const getMatchRelevance = (name: string, partialCmd: string): number => {
return 0;
};

// Sorts by priority, then ranks file and folder suggestions within a priority band by match quality,
// shorter names and alphabetically. Paths only swap places with other paths, so subcommands, options
// and spec-authored suggestions keep their source order.
const sortSuggestions = (suggestions: Suggestion[], partialCmd: string | undefined): Suggestion[] => {
const sorted = suggestions.sort((a, b) => b.priority - a.priority);
if (!partialCmd) return sorted;
// Whether any of a suggestion's names is exactly the text typed so far. Case-sensitive, since options
// (-l vs -L) and git refs differ by case. Tokens containing a path separator are treated as paths and
// reduced to their basename (partialCmd). File and folder suggestions are named by their basename, so
// they compare against it; every other suggestion (e.g. the git branch feat/foo) is named in full and
// compares against the full token, so typing feat/foo does not match an unrelated branch named foo.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: trying to keep comments to a minimum in the repo, this function looks pretty self explanatory, no need to add it

const isExactMatch = (suggestion: Suggestion, partialCmd: string, token: string | undefined): boolean => {
const typed = getPathy(suggestion.type) ? partialCmd : token ?? partialCmd;
return suggestion.allNames.some((name) => name === typed);
};

// Sorts exact matches first, then by priority. Typing a suggestion's full name is the clearest signal of
// intent, so it beats spec priorities, which only hint at what to show while input is still partial
// (e.g. git ranks the current branch at 100 over other branches at 75, which otherwise kept the current
// branch above a fully typed branch name). Within a priority band file and folder suggestions are further
// ranked by match quality, shorter names and alphabetically. Paths only swap places with other paths, so
// subcommands, options and spec-authored suggestions keep their source order.
const sortSuggestions = (suggestions: Suggestion[], partialCmd: string | undefined, token: string | undefined): Suggestion[] => {
if (!partialCmd) return suggestions.sort((a, b) => b.priority - a.priority);
const byExactMatchThenPriority = (a: Suggestion, b: Suggestion) =>
Number(isExactMatch(b, partialCmd, token)) - Number(isExactMatch(a, partialCmd, token)) || b.priority - a.priority;
const sorted = suggestions.sort(byExactMatchThenPriority);
const pathIndexes = sorted.flatMap((s, i) => (getPathy(s.type) ? [i] : []));
const rankedPaths = pathIndexes
.map((i) => sorted[i])
.sort(
(a, b) =>
b.priority - a.priority ||
byExactMatchThenPriority(a, b) ||
getMatchRelevance(b.name, partialCmd) - getMatchRelevance(a.name, partialCmd) ||
a.name.length - b.name.length ||
a.name.localeCompare(b.name),
Expand Down Expand Up @@ -398,7 +413,10 @@ export const getSubcommandDrivenRecommendation = async (
removeEmptySuggestion(
removeHiddenSuggestions(
removeHomeDirectorySuggestion(
removeAcceptedSuggestions(adjustPathSuggestions(sortSuggestions(suggestions, partialCmd), partialToken, lastToken, shell), acceptedTokens),
removeAcceptedSuggestions(
adjustPathSuggestions(sortSuggestions(suggestions, partialCmd, partialToken?.token), partialToken, lastToken, shell),
acceptedTokens,
),
allTokens,
),
partialToken,
Expand Down Expand Up @@ -445,7 +463,10 @@ export const getArgDrivenRecommendation = async (
removeEmptySuggestion(
removeHiddenSuggestions(
removeHomeDirectorySuggestion(
removeAcceptedSuggestions(adjustPathSuggestions(sortSuggestions(suggestions, partialCmd), partialToken, lastToken, shell), acceptedTokens),
removeAcceptedSuggestions(
adjustPathSuggestions(sortSuggestions(suggestions, partialCmd, partialToken?.token), partialToken, lastToken, shell),
acceptedTokens,
),
allTokens,
),
partialToken,
Expand Down
24 changes: 12 additions & 12 deletions src/tests/runtime/__snapshots__/runtime.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,18 @@ exports[`parseCommand optionsSuggestedAfterVariadicArg 1`] = `
},
"argumentDescription": undefined,
"suggestions": [
{
"allNames": [
"-l",
],
"description": "(The lowercase letter \`\`ell''.) List in long format. (See below.) A total sum for all the file sizes is output on a line before the long listing",
"hidden": undefined,
"icon": "🔗",
"insertValue": undefined,
"name": "-l",
"priority": 50,
"type": undefined,
},
{
"allNames": [
"package-lock.json",
Expand All @@ -609,18 +621,6 @@ exports[`parseCommand optionsSuggestedAfterVariadicArg 1`] = `
"priority": 50,
"type": undefined,
},
{
"allNames": [
"-l",
],
"description": "(The lowercase letter \`\`ell''.) List in long format. (See below.) A total sum for all the file sizes is output on a line before the long listing",
"hidden": undefined,
"icon": "🔗",
"insertValue": undefined,
"name": "-l",
"priority": 50,
"type": undefined,
},
],
}
`;
Expand Down
104 changes: 104 additions & 0 deletions src/tests/runtime/suggestion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { getArgDrivenRecommendation, getSubcommandDrivenRecommendation } from "../../runtime/suggestion.js";

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe instead of adding this suggestion.test.ts, we can just add some cases to testData in runtime.test.ts to cover it?

import { CommandToken } from "../../runtime/parser.js";
import { Shell } from "../../utils/shell.js";

// The runtime flags any token containing a path separator as a path (see resolveCwd), so branch names
// like feat/foo reach the suggestion ranking as path tokens.
const token = (value: string): CommandToken => ({
token: value,
tokenLength: value.length,
complete: false,
isOption: false,
...(value.includes("/") ? { isPath: true, isPathComplete: value.endsWith("/") } : {}),
});

type Rank = (suggestions: Fig.Suggestion[], typed: string, filterStrategy?: Fig.Arg["filterStrategy"]) => Promise<string[]>;

// Completing an argument right after a subcommand, e.g. `git checkout feat/foo`.
const rankFromSubcommand: Rank = async (suggestions, typed, filterStrategy) => {
const partialToken = token(typed);
const blob = await getSubcommandDrivenRecommendation(
{ name: "checkout", args: { name: "branch", suggestions, filterStrategy } },
[],
partialToken,
false,
false,
[],
[partialToken],
process.cwd(),
Shell.Bash,
);
return blob?.suggestions.map((s) => s.name) ?? [];
};

// Completing an argument slot reached after other tokens, e.g. an option's value or a variadic argument.
const rankFromArg: Rank = async (suggestions, typed, filterStrategy) => {
const partialToken = token(typed);
const blob = await getArgDrivenRecommendation(
[{ name: "branch", suggestions, filterStrategy }],
{ name: "checkout" },
[],
partialToken,
[],
[partialToken],
false,
process.cwd(),
Shell.Bash,
);
return blob?.suggestions.map((s) => s.name) ?? [];
};

// Mirrors the git spec, which gives the current branch priority 100 and other branches priority 75, and
// filters branch arguments fuzzily (path tokens are filtered by their basename, e.g. search-).
const branches: Fig.Suggestion[] = [
{ name: "feat/search-1234", description: "Current branch", priority: 100 },
{ name: "feat/search-", description: "Branch", priority: 75 },
{ name: "fix/search-5678", description: "Branch", priority: 75 },
];

describe.each([
["getSubcommandDrivenRecommendation", rankFromSubcommand],
["getArgDrivenRecommendation", rankFromArg],
])("%s ranking", (_, rank) => {
const rankBranches = (typed: string) => rank(branches, typed, "fuzzy");

test("ranks an exact branch name above the higher priority current branch", async () => {
expect(await rankBranches("feat/search-")).toEqual(["feat/search-", "feat/search-1234", "fix/search-5678"]);
});

test("matches exactly case-sensitively", async () => {
const options: Fig.Suggestion[] = [
{ name: "-L", priority: 100 },
{ name: "-l", priority: 50 },
];
expect(await rank(options, "-l")).toEqual(["-l", "-L"]);
});

test("matches exactly on any of a suggestion's names", async () => {
const suggestions: Fig.Suggestion[] = [
{ name: "statistics", priority: 100 },
{ name: ["stat", "status"], priority: 50 },
];
expect((await rank(suggestions, "stat"))[0]).toBe("stat");
});

test("keeps priority order when nothing matches exactly", async () => {
expect(await rankBranches("feat/s")).toEqual(["feat/search-1234", "feat/search-", "fix/search-5678"]);
});

test("does not match a branch that only shares the typed basename", async () => {
const withBasenameBranch: Fig.Suggestion[] = [{ name: "search-", priority: 75 }, ...branches];
expect(await rank(withBasenameBranch, "feat/search-", "fuzzy")).toEqual(["feat/search-", "feat/search-1234", "search-", "fix/search-5678"]);
});

test("matches files by basename and keeps an exact file above a higher priority file", async () => {
const files: Fig.Suggestion[] = [
{ name: "index.ts.bak", type: "file", priority: 80 },
{ name: "index.ts", type: "file", priority: 50 },
];
expect(await rank(files, "src/index.ts")).toEqual(["index.ts", "index.ts.bak"]);
});
});