go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers-sdk/v1/plugin/gen/gen.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package gen
     5  
     6  import (
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"os"
    11  	"path/filepath"
    12  
    13  	"github.com/Masterminds/semver"
    14  	"github.com/spf13/afero"
    15  	"go.mondoo.com/cnquery/providers-sdk/v1/plugin"
    16  )
    17  
    18  // This package contains shared components for plugin generation.
    19  // You use this library in your own plugins under:
    20  // <PLUGIN>/gen/main.go
    21  // See our builtin plugins for examples.
    22  
    23  // CLI starts and manages the CLI of the plugin generation code.
    24  func CLI(conf *plugin.Provider) {
    25  	if len(os.Args) < 2 {
    26  		fmt.Fprintln(os.Stderr, "You have to provide the path of the plugin")
    27  		os.Exit(1)
    28  	}
    29  
    30  	if conf.Version == "" {
    31  		fmt.Fprintln(os.Stderr, "You must specify a version for the '"+conf.Name+"' provider (semver required)")
    32  		os.Exit(1)
    33  	}
    34  
    35  	_, err := semver.NewVersion(conf.Version)
    36  	if err != nil {
    37  		fmt.Fprintln(os.Stderr, "Version must be a semver for '"+conf.Name+"' provider (was: '"+conf.Version+"')")
    38  		os.Exit(1)
    39  	}
    40  
    41  	pluginPath := os.Args[1]
    42  	fmt.Println("--> looking for plugin in " + pluginPath)
    43  
    44  	if ok, err := afero.IsDir(fs, pluginPath); err != nil || !ok {
    45  		fmt.Fprintln(os.Stderr, "Looks like the plugin path you provided isn't correct: "+pluginPath)
    46  		os.Exit(1)
    47  	}
    48  
    49  	distPath := filepath.Join(pluginPath, "dist")
    50  	ensureDir(distPath)
    51  
    52  	data, err := json.Marshal(conf)
    53  	if err != nil {
    54  		fmt.Fprintln(os.Stderr, "Failed to generate JSON: "+string(data))
    55  		os.Exit(1)
    56  	}
    57  
    58  	dst := filepath.Join(distPath, conf.Name+".json")
    59  	fmt.Println("--> writing plugin json to " + dst)
    60  	if err = afero.WriteFile(fs, dst, data, 0o644); err != nil {
    61  		fmt.Fprintln(os.Stderr, "Failed to write JSON to file "+dst+": "+string(data))
    62  		os.Exit(1)
    63  	}
    64  }
    65  
    66  var fs afero.Fs
    67  
    68  func init() {
    69  	fs = afero.NewOsFs()
    70  }
    71  
    72  func ensureDir(path string) error {
    73  	exist, err := afero.DirExists(fs, path)
    74  	if err != nil {
    75  		return errors.New("failed to check if " + path + " exists: " + err.Error())
    76  	}
    77  	if exist {
    78  		return nil
    79  	}
    80  
    81  	fmt.Println("--> creating " + path)
    82  	if err := fs.MkdirAll(path, 0o755); err != nil {
    83  		return errors.New("failed to create " + path + ": " + err.Error())
    84  	}
    85  	return nil
    86  }