chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
 
namespace OpenTap.Package
{
    static class PackageActionHelpers
    {
        readonly static TraceSource log = Log.CreateSource("PackageAction");
 
        static List<PackageDef> TriviallyResolvePackage(IEnumerable<PackageSpecifier> packages,
            ICollection<IPackageRepository> repositories, ICollection<PackageDef> directlyReferencedPackages)
        {
            directlyReferencedPackages = directlyReferencedPackages ?? new List<PackageDef>();
            List<PackageDef> forcePackages = new List<PackageDef>();
            foreach (var pkgSpec in packages)
            {
                PackageDef pkgDef = null;
                foreach (var repo in repositories)
                {
                    pkgDef = repo.GetPackages(pkgSpec).FirstOrDefault();
                    if (pkgDef != null) break;
                }
 
                if (pkgDef == null)
                {
                    pkgDef = directlyReferencedPackages.FirstOrDefault(x => x.Name == pkgSpec.Name && pkgSpec.Version.IsCompatible(x.Version));
                }
                
 
                if (pkgDef == null)
                {
                    throw new Exception($"Could not find package exactly matching {pkgSpec} (--force specified).");
                }
 
                forcePackages.Add(pkgDef);
 
            }
            return forcePackages;
            
        }
        
        
        internal static List<PackageDef> GatherPackagesAndDependencyDefs(Installation installation, PackageSpecifier[] pkgRefs, string[] packageNames, 
            string Version, CpuArchitecture arch, string OS, List<IPackageRepository> repositories, bool force, bool noDowngrade)
        {
            List<PackageDef> directlyReferencesPackages = new List<PackageDef>();
            
 
            List<PackageSpecifier> packages = new List<PackageSpecifier>();
            if (pkgRefs != null)
                packages = pkgRefs.ToList();
            else
            {
                if (packageNames == null)
                    throw new Exception("No packages specified.");
                foreach (string packageName in packageNames)
                {
                    var version = Version;
                    if (Path.GetExtension(packageName).ToLower().EndsWith("tappackages"))
                    {
                        if(!File.Exists(packageName))
                            throw new FileNotFoundException($"Unable to find the file {packageName}.");
                        var tempDir = Path.GetTempPath();
                        var bundleFiles = PluginInstaller.UnpackPackage(packageName, tempDir);
                        var packagesInBundle = bundleFiles.Select(PackageDef.FromPackage);
 
                        // A packages file may contain the several variants of the same package, try to select one based on OS and Architecture
                        foreach (IGrouping<string, PackageDef> grp in packagesInBundle.GroupBy(p => p.Name))
                        {
                            var selected = grp.ToList();
                            if (selected.Count == 1)
                            {
                                var pkg = selected.First();
                                directlyReferencesPackages.Add(pkg);
                                packages.Add(pkg.GetSpecifier());
                                continue;
                            }
                            if (!string.IsNullOrEmpty(OS))
                            {
                                selected = selected.Where(p => p.OS.ToLower().Split(',').Any(OS.ToLower().Contains)).ToList();
                                if (selected.Count == 1)
                                {
                                    var pkg = selected.First();
                                    directlyReferencesPackages.Add(pkg);
                                    packages.Add(pkg.GetSpecifier());
                                    log.Debug("TapPackages file contains packages for several operating systems. Picking only the one for {0}.", OS);
                                    continue;
                                }
                            }
                            if (arch != CpuArchitecture.Unspecified)
                            {
                                selected = selected.Where(p => ArchitectureHelper.CompatibleWith(arch, p.Architecture)).ToList();
                                if (selected.Count == 1)
                                {
                                    var pkg = selected.First();
                                    directlyReferencesPackages.Add(pkg);
                                    packages.Add(pkg.GetSpecifier());
                                    log.Debug("TapPackages file contains packages for several CPU architectures. Picking only the one for {0}.", arch);
                                    continue;
                                }
                            }
                            throw new Exception("TapPackages file contains multiple variants of the same package. Unable to auto-select a suitable one.");
                        }
                    }
                    else if (Path.GetExtension(packageName)
                             .Equals(".Tappackage", StringComparison.OrdinalIgnoreCase) 
                             // if the file exists try installing it, but only if it has an extension.
                             // otherwise there is a great risk that the name conflicts with a remote package name.
                             // For example, the Editor package has a file called Editor inside it (on Linux).
                             || (File.Exists(packageName) && Path.HasExtension(packageName)))
                    {
                        
                        var pkg = PackageDef.FromPackage(packageName);
                        directlyReferencesPackages.Add(pkg);
                        packages.Add(pkg.GetSpecifier());
                    }
                    else if (string.IsNullOrWhiteSpace(packageName) == false)
                    {
                        packages.Add(new PackageSpecifier(packageName, VersionSpecifier.Parse(version ?? ""), arch, OS));
                    }
                }
            }
 
            if (force)
            {
                // when --force is specified, exact package specifiers has to be used.
                // there is no need to resolve the image in this case.
                var packagesToInstall = TriviallyResolvePackage(packages, repositories, directlyReferencesPackages);
                
                if (noDowngrade)
                {
                    packagesToInstall = packagesToInstall.Where(x =>
                    {
                        var installed = installation.FindPackage(x.Name);
                        if (installed != null && installed.Version.CompareTo(x.Version) > 0)
                            return false;
                        return true;
                    }).Select(x => directlyReferencesPackages.FirstOrDefault(y => y.Name == x.Name && y.Version == x.Version) ?? x)
                        .ToList();
                }
                // make sure to use the TapPackage if one was directly referenced
                packagesToInstall = packagesToInstall.Select(x => directlyReferencesPackages.FirstOrDefault(y => y.Name == x.Name && y.Version == x.Version) ?? x)
                    .ToList();
 
                return packagesToInstall;
 
            }
 
            if (noDowngrade)
            {
                // if --no-downgrade is specified, none of the already installed packages are allowed to get downgraded
                // hence they can be added as extra constraints for the dependency resolver.
                var existingSpec = installation.GetPackages().Select(pkg =>
                    new PackageSpecifier(pkg.Name, pkg.Version.AsCompatibleSpecifier(), pkg.Architecture, pkg.OS));
                packages = packages.Concat(existingSpec).ToList();
            }
 
            var img = ImageSpecifier.FromAddedPackages(installation, packages);
            if (!string.IsNullOrWhiteSpace(OS))
                img.OS = OS;
            if (arch != CpuArchitecture.Unspecified)
                img.Architecture = arch;
            
            if (noDowngrade)
            {
                img.InstalledPackages = installation.GetPackages().ToImmutableArray();
            }
            img.Repositories = repositories.Select(x => x.Url).ToList();
            img.AdditionalPackages.AddRange(directlyReferencesPackages);
            var result = img.Resolve(TapThread.Current.AbortToken);
 
            // missing dependencies are those which are not installed
 
            List<PackageDef> installedAsDependencies = new List<PackageDef>();
            List<PackageDef> gatheredPackages = new List<PackageDef>();
            foreach (var pkg in result.Packages)
            {
                var installed = img.InstalledPackages.FirstOrDefault(x => x.Name == pkg.Name && x.Version == pkg.Version);
                if (installed != null) continue; // this package is already provided by the installation.
                var gathered = packages.FirstOrDefault(x => x.Name == pkg.Name);
                gatheredPackages.Add(pkg);
                if (gathered == null)
                    installedAsDependencies.Add(pkg);
            }
 
            foreach (var additional in installedAsDependencies)
            {
                if (img.InstalledPackages.Any(x => x.Name == additional.Name))
                {  
                    // This implies that the version is newer.
                    log.Info("Updating dependency {0} {1}", additional.Name, additional.Version);    
                }
                else
                {
                    log.Info("Adding dependency {0} {1}", additional.Name, additional.Version);
                }
            }
            
            // make sure to use the TapPackage if one was directly referenced
            gatheredPackages = gatheredPackages
                .Select(x => directlyReferencesPackages.FirstOrDefault(y => y.Name == x.Name && y.Version == x.Version) ?? x)
                .ToList();
 
            var unavailablePackages =
                gatheredPackages.Where(x => x.PackageSource is InstalledPackageDefSource).ToArray();
            if (unavailablePackages.Any())
            {
                var str = string.Join("', '", unavailablePackages.Select(x => x.Name));
                throw new Exception($"The following packages are not available: '{str}'");
            }
 
            return gatheredPackages;
        }
 
        internal static List<string> DownloadPackages(string destinationDir, List<PackageDef> PackagesToDownload, List<string> filenames = null, Action<int, string> progressUpdate = null, bool ignoreCache = false)
        {
            progressUpdate = progressUpdate ?? ((i, s) => { });
 
            List<string> downloadedPackages = new List<string>();
 
            for (int i = 0; i < PackagesToDownload.Count; i++)
            {
                Stopwatch timer = Stopwatch.StartNew();
 
                var pkg = PackagesToDownload[i];
                // Package names can contain slashes and backslashes -- avoid creating subdirectories when downloading packages
                var packageName = GetQualifiedFileName(pkg).Replace('/', '.');
                string filename = filenames?.ElementAtOrDefault(i) ??
                                  Path.Combine(destinationDir, packageName);
 
                TapThread.ThrowIfAborted();
 
                var i1 = i;
 
                void innerProgress(string header, long pos, long len)
                {
                    var downloadProgress = 100.0 * pos / len;
 
                    var thisProgress = downloadProgress / PackagesToDownload.Count;
                    var otherProgress = (100.0 * i1) / PackagesToDownload.Count;
 
                    var progress = thisProgress + otherProgress;
 
                    var progressString = $"({downloadProgress:0.00}% | {Utils.BytesToReadable(pos)} of {Utils.BytesToReadable(len)})";
                    progressUpdate((int)progress, $"Downloading '{pkg}' {progressString}");
                }
 
 
                try
                {
                    PackageDef existingPkg = null;
                    try
                    {
                        // If the package we are installing is from a file, we should always use that file instead of a cached package.
                        // During development a package might not change version but still have different content.
                        if (pkg.PackageSource is FilePackageDefSource == false && File.Exists(filename) &&
                            !ignoreCache && Path.HasExtension(filename))
                        {
                            log.Info($"Treating {filename} as a package");
                            existingPkg = PackageDef.FromPackage(filename);
                        }
                    }
                    catch (Exception e)
                    {
                        log.Warning("Could not open OpenTAP Package. Redownloading package.", e);
                        File.Delete(filename);
                    }
 
                    if (existingPkg != null)
                    {
                        if (existingPkg.Version == pkg.Version && existingPkg.OS == pkg.OS && existingPkg.Architecture == pkg.Architecture)
                        {
                            if (!PackageCacheHelper.PackageIsFromCache(existingPkg))
                                log.Info("Package '{0}' already exists in '{1}'.", pkg.Name, destinationDir);
                            else
                                log.Info("Package '{0}' already exists in cache '{1}'.", pkg.Name, destinationDir);
                        }
                        else
                        {
                            throw new Exception($"A package already exists but it is not the same as the package that is being downloaded.");
                        }
                    }
                    else
                    {
                        IPackageRepository rm = null;
                        switch (pkg.PackageSource)
                        {
                            case HttpRepositoryPackageDefSource repoSource:
                                rm = new HttpPackageRepository(repoSource.RepositoryUrl);
                                break;
                            case FileRepositoryPackageDefSource repoSource:
                                rm = new FilePackageRepository(repoSource.RepositoryUrl);
                                break;
                            case IFilePackageDefSource fileSource:
                                rm = new FilePackageRepository(System.IO.Path.GetDirectoryName(fileSource.PackageFilePath));
                                break;
                            default:
                                throw new Exception($"Unable to determine repository type for package source {pkg.PackageSource.GetType()}.");
                        }
                        if (rm is IPackageDownloadProgress r)
                        {
                            r.OnProgressUpdate = innerProgress;
                        }
                        if (PackageCacheHelper.PackageIsFromCache(pkg) && !ignoreCache)
                        {
                            rm.DownloadPackage(pkg, filename);
                            log.Info(timer, "Found package '{0}' in cache. Copied to '{1}'.", pkg.Name, Path.GetFullPath(filename));
                        }
                        else
                        {
                            log.Debug("Downloading '{0}' version '{1}' from '{2}'", pkg.Name, pkg.Version, rm.Url);
                            rm.DownloadPackage(pkg, filename);
                            log.Info(timer, "Downloaded '{0}' to '{1}'.", pkg.Name, Path.GetFullPath(filename));
                            PackageCacheHelper.CachePackage(filename);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex is OperationCanceledException)
                        throw;
                    log.Error($"Failed to download '{pkg.Name}' package.");
                    log.Debug(ex);
                    throw;
                }
 
                downloadedPackages.Add(filename);
                float progress_f = (float)(i + 1) / PackagesToDownload.Count;
                progressUpdate((int)(progress_f * 100), $"Acquired '{pkg}'.");
            }
 
            progressUpdate(100, "Finished downloading packages.");
 
            return downloadedPackages;
        }
 
        internal static string GetQualifiedFileName(PackageDef pkg)
        {
            List<string> filenameParts = new List<string> { pkg.Name };
            if (pkg.Version != null)
                filenameParts.Add(pkg.Version.ToString());
            if (pkg.Architecture != CpuArchitecture.AnyCPU)
                filenameParts.Add(pkg.Architecture.ToString());
            if (!String.IsNullOrEmpty(pkg.OS) && pkg.OS != "Windows")
                filenameParts.Add(pkg.OS);
            filenameParts.Add("TapPackage");
            return String.Join(".", filenameParts);
        }
    }
}