func()

in cmd/harp/internal/cmd/plugin_list.go [82:168]


func (o *pluginListOptions) Run(cmd *cobra.Command) error {
	_, cancel := cmdutil.Context(cmd.Context(), "harp-plugin-list", conf.Debug.Enable, conf.Instrumentation.Logs.Level)
	defer cancel()

	var (
		pluginsFound   = false
		isFirstFile    = true
		pluginErrors   = []error{}
		pluginWarnings = 0
	)

	// Deduplicate plugin paths
	filteredPaths := uniquePathsList(o.PluginPaths)

	// For each path
	for _, dir := range filteredPaths {
		// Ignore empty dir
		if strings.TrimSpace(dir) == "" {
			continue
		}

		// Crawl each directory to identify readable ones
		files, err := os.ReadDir(dir)
		if err != nil {
			var pathErr *os.PathError
			if errors.As(err, &pathErr) {
				fmt.Fprintf(os.Stderr, "Unable read directory %q from your PATH: %v. Skipping...\n", dir, pathErr)
				continue
			}

			pluginErrors = append(pluginErrors, fmt.Errorf("error: unable to read directory %q in your PATH: %w", dir, err))
			continue
		}

		// Crawl each files
		for _, f := range files {
			if f.IsDir() {
				continue
			}
			if !hasValidPrefix(f.Name(), validPluginFilenamePrefixes) {
				continue
			}

			// First file identified
			if isFirstFile {
				fmt.Fprintf(os.Stdout, "The following compatible plugins are available:\n\n")
				pluginsFound = true
				isFirstFile = false
			}

			// Display name according to flag
			pluginPath := f.Name()
			if !o.NameOnly {
				pluginPath = filepath.Join(dir, pluginPath)
			}

			fmt.Fprintf(os.Stdout, "%s\n", pluginPath)
			if errs := o.Verifier.Verify(filepath.Join(dir, f.Name())); len(errs) != 0 {
				for _, err := range errs {
					fmt.Fprintf(os.Stderr, "  - %s\n", err)
					pluginWarnings++
				}
			}
		}
	}

	if !pluginsFound {
		pluginErrors = append(pluginErrors, fmt.Errorf("error: unable to find any harp plugins in your PATH"))
	}

	if pluginWarnings > 0 {
		if pluginWarnings == 1 {
			pluginErrors = append(pluginErrors, fmt.Errorf("error: one plugin warning was found"))
		} else {
			pluginErrors = append(pluginErrors, fmt.Errorf("error: %v plugin warnings were found", pluginWarnings))
		}
	}
	if len(pluginErrors) > 0 {
		errs := bytes.NewBuffer(nil)
		for _, e := range pluginErrors {
			fmt.Fprintln(errs, e)
		}
		return fmt.Errorf("%s", errs.String())
	}

	return nil
}