Skip to content

Commit 8404d1c

Browse files
authored
Fix Bun manager detection, search, and global package listing (#4880)
1 parent c4da61c commit 8404d1c

3 files changed

Lines changed: 85 additions & 56 deletions

File tree

‎src/UniGetUI.PackageEngine.Managers.Bun/Bun.cs‎

Lines changed: 53 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -54,32 +54,29 @@ public Bun()
5454

5555
protected override IReadOnlyList<Package> FindPackages_UnSafe(string query)
5656
{
57-
using Process p = new()
58-
{
59-
StartInfo = new ProcessStartInfo
60-
{
61-
FileName = Status.ExecutablePath,
62-
Arguments = Status.ExecutableCallArgs + " search \"" + query + "\" --json",
63-
RedirectStandardOutput = true,
64-
RedirectStandardError = true,
65-
RedirectStandardInput = true,
66-
UseShellExecute = false,
67-
CreateNoWindow = true,
68-
WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
69-
StandardOutputEncoding = System.Text.Encoding.UTF8
70-
}
71-
};
72-
73-
IProcessTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages, p);
74-
p.Start();
75-
76-
string strContents = p.StandardOutput.ReadToEnd();
77-
logger.AddToStdOut(strContents);
78-
logger.AddToStdErr(p.StandardError.ReadToEnd());
79-
p.WaitForExit();
80-
logger.Close(p.ExitCode);
57+
// Bun has no `search` subcommand; it resolves packages from the npm registry.
58+
// Query the registry's search endpoint directly (the same data npm search uses).
59+
INativeTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages);
60+
string url = "https://registry.npmjs.org/-/v1/search?size=100&text=" + Uri.EscapeDataString(query);
61+
logger.Log($"Querying the npm registry: {url}");
8162

82-
return ParseSearchOutput(strContents, DefaultSource, this);
63+
try
64+
{
65+
using HttpClient client = new(CoreTools.GenericHttpClientParameters);
66+
client.DefaultRequestHeaders.UserAgent.ParseAdd(CoreData.UserAgentString);
67+
string strContents = client.GetStringAsync(url).GetAwaiter().GetResult();
68+
logger.Log(strContents);
69+
70+
var packages = ParseSearchOutput(strContents, DefaultSource, this);
71+
logger.Close(0);
72+
return packages;
73+
}
74+
catch (Exception e)
75+
{
76+
logger.Error(e);
77+
logger.Close(1);
78+
return [];
79+
}
8380
}
8481

8582
protected override IReadOnlyList<Package> GetAvailableUpdates_UnSafe()
@@ -146,20 +143,32 @@ protected override IReadOnlyList<Package> GetAvailableUpdates_UnSafe()
146143

147144
protected override IReadOnlyList<Package> GetInstalledPackages_UnSafe()
148145
{
146+
// `bun pm ls --global` is a no-op for the --global flag: Bun ignores it and walks
147+
// up from the working directory to the nearest lockfile. List the dedicated global
148+
// package.json by running from that directory instead, mirroring GetAvailableUpdates_UnSafe.
149+
string globalDir = GetGlobalPackagesDirectory(
150+
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
151+
152+
if (!HasGlobalPackageManifest(globalDir))
153+
{
154+
Logger.Info($"Bun: Skipping installed package detection because {globalDir} is missing package.json");
155+
return [];
156+
}
157+
149158
List<Package> Packages = [];
150159

151160
using Process p = new()
152161
{
153162
StartInfo = new ProcessStartInfo
154163
{
155164
FileName = Status.ExecutablePath,
156-
Arguments = Status.ExecutableCallArgs + " pm ls --global",
165+
Arguments = Status.ExecutableCallArgs + " pm ls",
157166
RedirectStandardOutput = true,
158167
RedirectStandardError = true,
159168
RedirectStandardInput = true,
160169
UseShellExecute = false,
161170
CreateNoWindow = true,
162-
WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
171+
WorkingDirectory = globalDir,
163172
StandardOutputEncoding = System.Text.Encoding.UTF8
164173
}
165174
};
@@ -186,7 +195,16 @@ protected override IReadOnlyList<Package> GetInstalledPackages_UnSafe()
186195
}
187196

188197
public override IReadOnlyList<string> FindCandidateExecutableFiles()
189-
=> CoreTools.WhichMultiple(OperatingSystem.IsWindows() ? "bun.exe" : "bun");
198+
{
199+
if (!OperatingSystem.IsWindows())
200+
return CoreTools.WhichMultiple("bun");
201+
202+
// The official installer ships bun.exe, but `npm i -g bun` only puts a bun.cmd
203+
// wrapper on the PATH (the real bun.exe stays inside node_modules). Search both.
204+
List<string> candidates = [.. CoreTools.WhichMultiple("bun.exe")];
205+
candidates.AddRange(CoreTools.WhichMultiple("bun.cmd"));
206+
return candidates;
207+
}
190208

191209
internal static string GetGlobalPackagesDirectory(string userProfile)
192210
=> Path.Combine(userProfile, ".bun", "install", "global");
@@ -209,7 +227,7 @@ protected override void _loadManagerVersion(out string version)
209227
StartInfo = new ProcessStartInfo
210228
{
211229
FileName = Status.ExecutablePath,
212-
Arguments = Status.ExecutableCallArgs + "--version",
230+
Arguments = Status.ExecutableCallArgs + " --version",
213231
UseShellExecute = false,
214232
RedirectStandardOutput = true,
215233
RedirectStandardError = true,
@@ -225,8 +243,8 @@ protected override void _loadManagerVersion(out string version)
225243
}
226244

227245
/// <summary>
228-
/// Parses JSON search results from 'bun search &lt;query&gt; --json'.
229-
/// Each result object contains 'name' and 'version' fields.
246+
/// Parses the npm registry search response (https://registry.npmjs.org/-/v1/search).
247+
/// The payload is { "objects": [ { "package": { "name", "version" } } ] }.
230248
/// </summary>
231249
internal static IReadOnlyList<Package> ParseSearchOutput(
232250
string output,
@@ -239,11 +257,12 @@ internal static IReadOnlyList<Package> ParseSearchOutput(
239257

240258
try
241259
{
242-
JsonArray? results = JsonNode.Parse(output) as JsonArray;
260+
JsonArray? results = (JsonNode.Parse(output) as JsonObject)?["objects"] as JsonArray;
243261
foreach (JsonNode? entry in results ?? [])
244262
{
245-
string? id = entry?["name"]?.ToString();
246-
string? version = entry?["version"]?.ToString();
263+
JsonNode? pkg = entry?["package"];
264+
string? id = pkg?["name"]?.ToString();
265+
string? version = pkg?["version"]?.ToString();
247266
if (id is not null && version is not null)
248267
{
249268
packages.Add(new Package(CoreTools.FormatAsName(id), id, version, source, manager));

‎src/UniGetUI.PackageEngine.Tests/BunManagerTests.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@ private sealed class TestableBun : Bun
2323
}
2424

2525
/// <summary>
26-
/// Tests parsing of JSON search results from 'bun search &lt;query&gt; --json'.
26+
/// Tests parsing of the npm registry search response (registry.npmjs.org/-/v1/search).
2727
/// Verifies that multiple packages with different names and versions are correctly parsed.
2828
/// </summary>
2929
[Fact]
30-
public void ParseSearchOutputParsesJsonArray()
30+
public void ParseSearchOutputParsesRegistryResponse()
3131
{
3232
var manager = new Bun();
3333

@@ -297,13 +297,13 @@ Invalid line without marker
297297
}
298298

299299
/// <summary>
300-
/// Tests that search returns empty list for empty JSON array input.
300+
/// Tests that search returns empty list for an empty registry response.
301301
/// </summary>
302302
[Fact]
303-
public void ParseSearchOutputReturnsEmptyForEmptyArray()
303+
public void ParseSearchOutputReturnsEmptyForEmptyResults()
304304
{
305305
var manager = new Bun();
306-
var packages = Bun.ParseSearchOutput("[]", manager.DefaultSource, manager);
306+
var packages = Bun.ParseSearchOutput("""{"objects":[],"total":0}""", manager.DefaultSource, manager);
307307

308308
Assert.Empty(packages);
309309
}
Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
1-
[
2-
{
3-
"name": "typescript",
4-
"version": "5.3.3",
5-
"description": "TypeScript is a language for application scale JavaScript development"
6-
},
7-
{
8-
"name": "lodash",
9-
"version": "4.17.21",
10-
"description": "Lodash modular utilities."
11-
},
12-
{
13-
"name": "@types/node",
14-
"version": "20.10.6",
15-
"description": "TypeScript definitions for Node.js"
16-
}
17-
]
1+
{
2+
"objects": [
3+
{
4+
"package": {
5+
"name": "typescript",
6+
"version": "5.3.3",
7+
"description": "TypeScript is a language for application scale JavaScript development"
8+
}
9+
},
10+
{
11+
"package": {
12+
"name": "lodash",
13+
"version": "4.17.21",
14+
"description": "Lodash modular utilities."
15+
}
16+
},
17+
{
18+
"package": {
19+
"name": "@types/node",
20+
"version": "20.10.6",
21+
"description": "TypeScript definitions for Node.js"
22+
}
23+
}
24+
],
25+
"total": 3,
26+
"time": "Mon Jun 04 2026 00:00:00 GMT+0000"
27+
}

0 commit comments

Comments
 (0)