Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
85d659a
initial structure of command
vinit-chauhan Oct 9, 2025
17e4b39
fix: error skipped in edit dashboard command
vinit-chauhan Oct 9, 2025
01a681c
fix: error skipped in edit dashboard command
vinit-chauhan Oct 9, 2025
010f1a4
code refactors
vinit-chauhan Oct 10, 2025
358f9d6
Merge branch 'elastic:main' into cmd-filter
vinit-chauhan Oct 10, 2025
c3fef19
update response format.
vinit-chauhan Oct 14, 2025
3d84151
move filter code to internal
vinit-chauhan Oct 14, 2025
9a1c2aa
ignore .vscode dir
vinit-chauhan Oct 14, 2025
1336ff2
no args will return list of all packages
vinit-chauhan Oct 14, 2025
b588164
Merge branch 'main' of github.com:elastic/elastic-package into cmd-fi…
vinit-chauhan Oct 14, 2025
53bd4f8
initial implementation for foreach.
vinit-chauhan Oct 15, 2025
2d827cc
run multiple commands
vinit-chauhan Oct 15, 2025
bc7a167
add option to run commands in parallel
vinit-chauhan Oct 15, 2025
ada16f7
stash: filter-registry
vinit-chauhan Oct 16, 2025
9123dae
working with subcommand flags
vinit-chauhan Oct 16, 2025
423f035
Merge branch 'cmd-filter' into implement-filter-registry
vinit-chauhan Oct 16, 2025
2e3721c
created structure with working input filter
vinit-chauhan Oct 16, 2025
8180ff4
minor refactor; add code owner flag
vinit-chauhan Oct 16, 2025
f2abc11
minor refactor
vinit-chauhan Oct 16, 2025
f72ea26
add category flag
vinit-chauhan Oct 16, 2025
5c4d63e
refactor code
vinit-chauhan Oct 16, 2025
d94e9b2
added spec version flag
vinit-chauhan Oct 20, 2025
3cc0824
fix issue with unused filters applied
vinit-chauhan Oct 21, 2025
78cce2b
Merge branch 'main' into implement-filter-registry
vinit-chauhan Oct 21, 2025
2656a22
Merge branch 'elastic:main' into implement-filter-registry
vinit-chauhan Oct 21, 2025
c36efd7
run command in parallel
vinit-chauhan Oct 21, 2025
0649c73
remove --exec to leverage -- to pass sub commands without string
vinit-chauhan Oct 22, 2025
5e3b8b0
add subcommand allowlist
vinit-chauhan Oct 22, 2025
df2c85b
create map of dir_name and manifest to allow different package_name i…
vinit-chauhan Oct 22, 2025
b495ced
add flag suffix to go files
vinit-chauhan Oct 22, 2025
812530c
add integration type flag
vinit-chauhan Oct 22, 2025
e3e3c9a
add package name flag
vinit-chauhan Oct 22, 2025
54fce2b
minor refactors
vinit-chauhan Oct 23, 2025
13f348f
use glob instead of regex.
vinit-chauhan Oct 24, 2025
b10bb7f
removing duplicate code because I overlooked it while merging branches.
vinit-chauhan Oct 24, 2025
ab72763
move allowlist out of the validateSubCommand func
vinit-chauhan Oct 24, 2025
005c2c3
uniform command flag name.
vinit-chauhan Oct 24, 2025
8189930
create a type to hold dirname and manifest
vinit-chauhan Oct 27, 2025
caaff9a
lint and build docs
vinit-chauhan Oct 27, 2025
f997640
solve some review comments
vinit-chauhan Nov 5, 2025
a9699e4
- add way to filter packages in arbitrary directory.
vinit-chauhan Nov 6, 2025
90a93ad
add a output type flag
vinit-chauhan Nov 7, 2025
689eb72
remove parallel execution code from PR.
vinit-chauhan Nov 12, 2025
6196985
- add changelog to allowlist
vinit-chauhan Nov 13, 2025
12a7bea
fix: check
vinit-chauhan Nov 13, 2025
d93ee4f
add example in filter command.
vinit-chauhan Nov 14, 2025
89ef933
Merge branch 'main' of github.com:elastic/elastic-package into implem…
vinit-chauhan Nov 14, 2025
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ elastic-package
# IDEA
.idea

# VSCode
.vscode

# Build directory
/build

Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,29 @@ Use this command to export ingest pipelines with referenced pipelines from the E

Use this command to download selected ingest pipelines and its referenced processor pipelines from Elasticsearch. Select data stream or the package root directories to download the pipelines. Pipelines are downloaded as is and will need adjustment to meet your package needs.

### `elastic-package filter [flags]`

_Context: package_

This command gives you a list of all packages based on the given query.

The command will search for packages in the working directory for default depth of 2 and
return the list of packages that match the given criteria.

Use --change-directory to change the working directory and --depth to change the depth of the search.

### `elastic-package foreach [flags] -- <SUBCOMMAND>`

_Context: package_

Execute a command for each package matching the given filter criteria.

This command combines filtering capabilities with command execution, allowing you to run
any elastic-package subcommand across multiple packages in a single operation.

The command uses the same filter flags as the 'filter' command to select packages,
then executes the specified subcommand for each matched package.

### `elastic-package format`

_Context: package_
Expand Down
116 changes: 116 additions & 0 deletions cmd/filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.

package cmd

import (
"fmt"
"io"
"os"

"github.com/spf13/cobra"

"github.com/elastic/elastic-package/internal/cobraext"
"github.com/elastic/elastic-package/internal/filter"
"github.com/elastic/elastic-package/internal/packages"
)

const filterLongDescription = `This command gives you a list of all packages based on the given query.

The command will search for packages in the working directory for default depth of 2 and
return the list of packages that match the given criteria.

Use --change-directory to change the working directory and --depth to change the depth of the search.`

const filterExample = `elastic-package filter --inputs tcp,udp --categories security --depth 3 --output json
elastic-package filter --packages 'cisco_*,fortinet_*' --output yaml
`

func setupFilterCommand() *cobraext.Command {
cmd := &cobra.Command{
Use: "filter [flags]",
Short: "filter integrations based on given flags",
Long: filterLongDescription,
Args: cobra.NoArgs,
RunE: filterCommandAction,
Example: filterExample,
}

// add filter flags to the command (input, code owner, kibana version, categories)
filter.SetFilterFlags(cmd)

// add the output package name and absolute path flags to the command
cmd.Flags().StringP(cobraext.FilterOutputFlagName, cobraext.FilterOutputFlagShorthand, "", cobraext.FilterOutputFlagDescription)
cmd.Flags().StringP(cobraext.FilterOutputInfoFlagName, "", cobraext.FilterOutputInfoFlagDefault, cobraext.FilterOutputInfoFlagDescription)

return cobraext.NewCommand(cmd, cobraext.ContextPackage)
}

func filterCommandAction(cmd *cobra.Command, args []string) error {
filtered, err := filterPackage(cmd)
if err != nil {
return fmt.Errorf("filtering packages failed: %w", err)
}

outputFormatStr, err := cmd.Flags().GetString(cobraext.FilterOutputFlagName)
if err != nil {
return fmt.Errorf("getting output format flag failed: %w", err)
}

outputInfoStr, err := cmd.Flags().GetString(cobraext.FilterOutputInfoFlagName)
if err != nil {
return fmt.Errorf("getting output info flag failed: %w", err)
}

outputOptions, err := filter.NewOutputOptions(outputInfoStr, outputFormatStr)
if err != nil {
return fmt.Errorf("creating output options failed: %w", err)
}

if err = printPkgList(filtered, outputOptions, os.Stdout); err != nil {
return fmt.Errorf("printing JSON failed: %w", err)
}

return nil
}

func filterPackage(cmd *cobra.Command) ([]packages.PackageDirNameAndManifest, error) {
depth, err := cmd.Flags().GetInt(cobraext.FilterDepthFlagName)
if err != nil {
return nil, fmt.Errorf("getting depth flag failed: %w", err)
}

excludeDirs, err := cmd.Flags().GetString(cobraext.FilterExcludeDirFlagName)
if err != nil {
return nil, fmt.Errorf("getting exclude-dir flag failed: %w", err)
}

filters := filter.NewFilterRegistry(depth, excludeDirs)

if err := filters.Parse(cmd); err != nil {
return nil, fmt.Errorf("parsing filter options failed: %w", err)
}

if err := filters.Validate(); err != nil {
return nil, fmt.Errorf("validating filter options failed: %w", err)
}

filtered, errors := filters.Execute()
if errors != nil {
return nil, fmt.Errorf("filtering packages failed: %s", errors.Error())
}

return filtered, nil
}

func printPkgList(pkgs []packages.PackageDirNameAndManifest, outputOptions *filter.OutputOptions, w io.Writer) error {
formatted, err := outputOptions.ApplyTo(pkgs)
if err != nil {
return fmt.Errorf("applying output format failed: %w", err)
}

// write the formatted packages to the writer
_, err = io.WriteString(w, formatted+"\n")
return err
}
97 changes: 97 additions & 0 deletions cmd/foreach.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.

package cmd

import (
"fmt"
"slices"
"strings"

"github.com/spf13/cobra"

"github.com/elastic/elastic-package/internal/cobraext"
"github.com/elastic/elastic-package/internal/filter"
"github.com/elastic/elastic-package/internal/logger"
"github.com/elastic/elastic-package/internal/multierror"
)

const foreachLongDescription = `Execute a command for each package matching the given filter criteria.

This command combines filtering capabilities with command execution, allowing you to run
any elastic-package subcommand across multiple packages in a single operation.

The command uses the same filter flags as the 'filter' command to select packages,
then executes the specified subcommand for each matched package.`

// getAllowedSubCommands returns the list of allowed subcommands for the foreach command.
func getAllowedSubCommands() []string {
return []string{
"build",
"check",
"changelog",
"clean",
"format",
"install",
"lint",
"test",
"uninstall",
}
}

func setupForeachCommand() *cobraext.Command {
cmd := &cobra.Command{
Use: "foreach [flags] -- <SUBCOMMAND>",
Short: "Execute a command for filtered packages",
Long: foreachLongDescription,
Example: ` # Run system tests for packages with specific inputs
elastic-package foreach --input tcp,udp -- test system -g`,
RunE: foreachCommandAction,
Args: cobra.MinimumNArgs(1),
}

// Add filter flags
filter.SetFilterFlags(cmd)

return cobraext.NewCommand(cmd, cobraext.ContextPackage)
}

func foreachCommandAction(cmd *cobra.Command, args []string) error {
if err := validateSubCommand(args[0]); err != nil {
return fmt.Errorf("validating sub command failed: %w", err)
}

// reuse filterPackage from cmd/filter.go
filtered, err := filterPackage(cmd)
if err != nil {
return fmt.Errorf("filtering packages failed: %w", err)
}

errors := multierror.Error{}

for _, pkg := range filtered {
rootCmd := cmd.Root()
Copy link
Member

Choose a reason for hiding this comment

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

We could define another root command with the specific commands that are supported and use it here, then we could have different sets of subcommands, and maybe we could even plug it directly as subcommands of foreach.

This could be left for a future refactor too.

Something like this:

import (
        "github.com/spf13/cobra"

        "github.com/elastic/elastic-package/internal/cobraext"
)

var forEachCommands = []*cobraext.Command{
        setupBuildCommand(),
        setupCheckCommand(),
        setupCleanCommand(),
        setupFormatCommand(),
        setupInstallCommand(),
        setupLintCommand(),
        setupTestCommand(),
        setupUninstallCommand(),
}

// ForEachRootCmd creates and returns root cmd for elastic-package
func ForEachRootCmd() *cobra.Command {
        forEachCmd := &cobra.Command{
                SilenceUsage: true,
                PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
                        return cobraext.ComposeCommandActions(cmd, args,
                                processPersistentFlags,
                                checkVersionUpdate,
                        )
                },
        }
        forEachCmd.PersistentFlags().CountP(cobraext.VerboseFlagName, cobraext.VerboseFlagShorthand, cobraext.VerboseFlagDescription)
        forEachCmd.PersistentFlags().StringP(cobraext.ChangeDirectoryFlagName, cobraext.ChangeDirectoryFlagShorthand, "", cobraext.ChangeDirectoryFlagDescription)

        for _, cmd := range forEachCommands {
                forEachCmd.AddCommand(cmd.Command)
        }
        return forEachCmd
}

That could be used here like this:

Suggested change
rootCmd := cmd.Root()
rootCmd := ForEachRootCmd()
rootCmd.SetContext(cmd.Context())

Copy link
Author

Choose a reason for hiding this comment

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

This is something that we need to do to add parallel execution. That's why I left it out of this PR, and would like to revisit it while I work on the other PR.

With that said, we do have a list of allowed sub-commands. Here

Let me know if I missed any command. - I'll also add changelog command in allow list.

Copy link
Member

Choose a reason for hiding this comment

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

Yes, we can leave this for a future refactor.

I'll also add changelog command in allow list.

Yes please.

rootCmd.SetArgs(append(args, "--change-directory", pkg.Path))
if err := rootCmd.Execute(); err != nil {
errors = append(errors, err)
}
}

logger.Infof("Successfully executed command for %d packages", len(filtered)-len(errors))

if errors.Error() != "" {
logger.Errorf("Errors occurred for %d packages", len(errors))
return fmt.Errorf("errors occurred while executing command for packages: \n%s", errors.Error())
}

return nil
}

func validateSubCommand(subCommand string) error {
if !slices.Contains(getAllowedSubCommands(), subCommand) {
return fmt.Errorf("invalid subcommand: %s. Allowed subcommands are: [%s]", subCommand, strings.Join(getAllowedSubCommands(), ", "))
}

return nil
}
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ var commands = []*cobraext.Command{
setupDumpCommand(),
setupEditCommand(),
setupExportCommand(),
setupFilterCommand(),
setupFormatCommand(),
setupForeachCommand(),
setupInstallCommand(),
setupLinksCommand(),
setupLintCommand(),
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require (
github.com/elastic/package-spec/v3 v3.5.2
github.com/fatih/color v1.18.0
github.com/go-viper/mapstructure/v2 v2.4.0
github.com/gobwas/glob v0.2.3
github.com/google/go-cmp v0.7.0
github.com/google/go-github/v32 v32.1.0
github.com/google/go-querystring v1.1.0
Expand All @@ -34,6 +35,7 @@ require (
github.com/shirou/gopsutil/v3 v3.24.5
github.com/spf13/cobra v1.10.1
github.com/stretchr/testify v1.11.1
go.yaml.in/yaml/v2 v2.4.2
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
golang.org/x/tools v0.39.0
gopkg.in/dnaeon/go-vcr.v3 v3.2.0
Expand Down Expand Up @@ -157,7 +159,6 @@ require (
github.com/yuin/goldmark v1.7.13 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.mongodb.org/mongo-driver v1.11.1 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.44.0 // indirect
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
Expand Down
45 changes: 43 additions & 2 deletions internal/cobraext/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,49 @@ const (
FailOnMissingFlagName = "fail-on-missing"
FailOnMissingFlagDescription = "fail if tests are missing"

FailFastFlagName = "fail-fast"
FailFastFlagDescription = "fail immediately if any file requires updates (do not overwrite)"
FailFastFlagName = "fail-fast"
FailFastFlagDescription = "fail immediately if any file requires updates (do not overwrite)"

FilterCategoriesFlagName = "categories"
FilterCategoriesFlagDescription = "integration categories to filter by (comma-separated values)"

FilterCodeOwnerFlagName = "code-owners"
FilterCodeOwnerFlagDescription = "code owners to filter by (comma-separated values)"

FilterDepthFlagName = "depth"
FilterDepthFlagDescription = "maximum depth to search for packages"
FilterDepthFlagDefault = 2
FilterDepthFlagShorthand = "d"
Copy link
Member

Choose a reason for hiding this comment

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

Maybe we need to filter out built packages by default, otherwise they are discovered, and it is confusing to see them listed as their versions:

$ elastic-package filter -d 10 --packages apache
2025/11/12 21:31:32  INFO Found 3 matching package(s)
["999.999.999","apache","apache_basic_license"]

999.999.999 there is a built package under ./build/packages/apache/999.999.999/.

Copy link
Author

Choose a reason for hiding this comment

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

I came across the same issue, so I've added a --exclude-dirs flag that can be use to explicitly exclude directories.
Also, .git is excluded by default.

❯ go run main.go filter -d 10 --packages apache --exclude-dirs build
2025/11/13 09:24:18  INFO Found 2 matching package(s)
["apache","apache_basic_license"]

Copy link
Member

Choose a reason for hiding this comment

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

Maybe build could be also excluded by default as I don't think it is ever intended to search into it.


FilterExcludeDirFlagName = "exclude-dirs"
FilterExcludeDirFlagDescription = "comma-separated list of directories to exclude from search"

FilterInputFlagName = "inputs"
FilterInputFlagDescription = "name of the inputs to filter by (comma-separated values)"

FilterKibanaVersionFlagName = "kibana-version"
FilterKibanaVersionFlagDescription = "kibana version to filter by (semver)"

FilterOutputFlagName = "output"
FilterOutputFlagDescription = "format of the output. Available options: json, yaml (leave empty for newline-separated list)"
FilterOutputFlagShorthand = "o"

FilterOutputInfoFlagName = "output-info"
FilterOutputInfoFlagDescription = "output information about the packages. Available options: pkgname, dirname, absolute"
FilterOutputInfoFlagDefault = "dirname"

FilterPackageDirNameFlagName = "package-dirs"
FilterPackageDirNameFlagDescription = "package directories to filter by (comma-separated values)"
Copy link
Member

Choose a reason for hiding this comment

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

How is this flag expected to work? If I use --package-dirs ./test/packages/parallel in the elastic-package repository it doesn't find any package.

$ elastic-package filter --package-dirs ./test/packages/parallel
2025/11/12 21:20:31  INFO Found 0 matching package(s)
null

Copy link
Author

@vinit-chauhan vinit-chauhan Nov 13, 2025

Choose a reason for hiding this comment

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

package-dirs would filter packages based on the name of the package's directory. This is used to search without needing to know the package name in the manifest file.

example:

 go run main.go -C ../integrations filter --package-dirs sql_input -o pkgname
2025/11/13 09:29:56  INFO Found 1 matching package(s)
["sql"]

if you want to filter all packages in one directory you can use the following command.

❯ go run main.go -C test/packages/parallel filter
2025/11/13 09:11:51  INFO Found 19 matching package(s)
["apache","apache_basic_license","auditd_manager","auth0_logsdb","aws","awsfirehose","custom_entrypoint","httpcheck","mongodb","nginx","nginx_multiple_services","oracle","otel_http_server","sql_input","system","terraform_local","ti_anomali","ti_anomali_logsdb","ti_anomali_template"]

Copy link
Member

Choose a reason for hiding this comment

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

Oh ok. So it is not possible to search in multiple directories. I guess this is fine.

Copy link
Contributor

Choose a reason for hiding this comment

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

does it make sense to add the example to the description so it goes to the docs?


FilterPackagesFlagName = "packages"
FilterPackagesFlagDescription = "package names to filter by (comma-separated values)"

FilterPackageTypeFlagName = "package-types"
FilterPackageTypeFlagDescription = "package types to filter by (comma-separated values)"

FilterSpecVersionFlagName = "spec-version"
FilterSpecVersionFlagDescription = "Package spec version to filter by (semver)"

GenerateTestResultFlagName = "generate"
GenerateTestResultFlagDescription = "generate test result file"

Expand Down
Loading