func()

in packages/packages.go [360:453]


func (f *Filter) Apply(ctx context.Context, packages Packages) (Packages, error) {
	if f == nil {
		return packages, nil
	}

	span, ctx := apm.StartSpan(ctx, "FilterPackages", "app")
	defer span.End()

	if f.Experimental {
		return f.legacyApply(ctx, packages), nil
	}

	// Checks that only the most recent version of an integration is added to the list
	var packagesList Packages
	for _, p := range packages {
		// Skip experimental packages if flag is not specified.
		if p.Release == ReleaseExperimental && !f.Prerelease {
			continue
		}

		// Skip prerelease packages by default.
		if p.IsPrerelease() && !f.Prerelease {
			continue
		}

		if f.KibanaVersion != nil {
			if valid := p.HasKibanaVersion(f.KibanaVersion); !valid {
				continue
			}
		}

		if f.PackageName != "" && f.PackageName != p.Name {
			continue
		}

		if f.PackageVersion != "" && f.PackageVersion != p.Version {
			continue
		}

		if f.PackageType != "" && f.PackageType != p.Type {
			continue
		}

		if f.Capabilities != nil {
			if valid := p.WorksWithCapabilities(f.Capabilities); !valid {
				continue
			}
		}

		if f.Discovery != nil && !f.Discovery.Matches(p) {
			continue
		}

		if f.SpecMin != nil || f.SpecMax != nil {
			valid, err := p.HasCompatibleSpec(f.SpecMin, f.SpecMax, f.KibanaVersion)
			if err != nil {
				return nil, fmt.Errorf("can't compare spec version for %s (%s-%s): %w", p.Name, f.SpecMin, f.SpecMax, err)
			}

			if !valid {
				continue
			}
		}

		addPackage := true
		if !f.AllVersions {
			// Check if the version exists and if it should be added or not.
			for i, current := range packagesList {
				if current.Name != p.Name {
					continue
				}

				addPackage = false

				// If the package in the list is newer or equal, do nothing.
				if current.IsNewerOrEqual(p) {
					continue
				}

				// Otherwise replace it.
				packagesList[i] = p
			}
		}

		if addPackage {
			packagesList = append(packagesList, p)
		}
	}

	// Filter by category after selecting the newer packages.
	packagesList = filterCategories(packagesList, f.Category)

	return packagesList, nil
}