Bring the before func to command level (#245)

This commit is contained in:
magodo 2022-09-30 11:02:02 +08:00 коммит произвёл GitHub
Родитель 0e6af8baff
Коммит b2cdc608a6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
8 изменённых файлов: 78 добавлений и 119 удалений

Просмотреть файл

@ -1,12 +1,14 @@
package config
type CommonConfig struct {
LogPath string
SubscriptionId string
OutputDir string
Overwrite bool
Append bool
DevProvider bool
Batch bool
ContinueOnError bool
BackendType string
BackendConfig []string
FullConfig bool

Просмотреть файл

@ -12,7 +12,7 @@ import (
"github.com/magodo/spinner"
)
func BatchImport(cfg config.Config, continueOnError bool) error {
func BatchImport(cfg config.Config) error {
c, err := meta.NewMeta(cfg)
if err != nil {
return err
@ -56,7 +56,7 @@ func BatchImport(cfg config.Config, continueOnError bool) error {
c.Import(&list[i])
if err := list[i].ImportError; err != nil {
msg := fmt.Sprintf("Failed to import %s as %s: %v", list[i].TFResourceId, list[i].TFAddr, err)
if !continueOnError {
if !cfg.ContinueOnError {
return fmt.Errorf(msg)
}
errors = append(errors, msg)

Просмотреть файл

@ -96,7 +96,7 @@ resource "azurerm_subnet" "test" {
ARGPredicate: fmt.Sprintf(`resourceGroup =~ "%s" and type =~ "microsoft.network/virtualnetworks"`, d.RandomRgName()),
}
t.Log("Importing in non-recursive mode")
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run batch import non-recursively: %v", err)
}
test.Verify(t, ctx, aztfyDir, tfexecPath, 1)
@ -106,7 +106,7 @@ resource "azurerm_subnet" "test" {
// aztfyDir = t.TempDir()
// cfg.CommonConfig.OutputDir = aztfyDir
cfg.RecursiveQuery = true
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run batch import recursively: %v", err)
}
test.Verify(t, ctx, aztfyDir, tfexecPath, 2)

Просмотреть файл

@ -77,7 +77,7 @@ func runCase(t *testing.T, d test.Data, c cases.Case) {
MappingFile: mapFile,
}
t.Logf("Batch importing the resource group %s\n", d.RandomRgName())
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run batch import: %v", err)
}
test.Verify(t, ctx, aztfyDir, tfexecPath, len(resMapping))

Просмотреть файл

@ -74,7 +74,7 @@ func runCase(t *testing.T, d test.Data, c cases.Case) {
TFResourceName: fmt.Sprintf("res-%d", idx),
}
t.Logf("Resource importing %s\n", rctx.AzureId)
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run resource import: %v", err)
}
test.Verify(t, ctx, aztfyDir, tfexecPath, rctx.ExpectResourceCount)

Просмотреть файл

@ -88,7 +88,7 @@ resource "azurerm_resource_group" "test3" {
cfg.ResourceGroupName = d.RandomRgName() + "1"
cfg.ResourceNamePattern = "round1_"
t.Log("Batch importing the 1st rg")
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run first batch import: %v", err)
}
// Import the second resource group mutably
@ -96,7 +96,7 @@ resource "azurerm_resource_group" "test3" {
cfg.ResourceGroupName = d.RandomRgName() + "2"
cfg.ResourceNamePattern = "round2_"
t.Log("Batch importing the 2nd rg")
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run second batch import: %v", err)
}
// Import the third resource group mutably
@ -104,7 +104,7 @@ resource "azurerm_resource_group" "test3" {
cfg.ResourceGroupName = d.RandomRgName() + "3"
cfg.ResourceNamePattern = "round3_"
t.Log("Batch importing the 3rd rg")
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run second batch import: %v", err)
}

Просмотреть файл

@ -67,7 +67,7 @@ func runCase(t *testing.T, d test.Data, c cases.Case) {
ResourceNamePattern: "res-",
}
t.Logf("Batch importing the resource group %s\n", d.RandomRgName())
if err := internal.BatchImport(cfg, false); err != nil {
if err := internal.BatchImport(cfg); err != nil {
t.Fatalf("failed to run batch import: %v", err)
}
test.Verify(t, ctx, aztfyDir, tfexecPath, c.Total())

175
main.go
Просмотреть файл

@ -21,46 +21,47 @@ import (
"github.com/urfave/cli/v2"
)
var (
// common flags
flagSubscriptionId string
flagOutputDir string
flagOverwrite bool
flagAppend bool
flagDevProvider bool
flagBackendType string
flagBackendConfig cli.StringSlice
flagFullConfig bool
flagParallelism int
flagContinue bool
flagNonInteractive bool
flagGenerateMappingFile bool
// common flags (hidden)
hflagMockClient bool
hflagLogPath string
hflagPlainUI bool
// Subcommand specific flags
//
// res:
// flagResName
// flagResType
//
// rg:
// flagPattern
//
// query:
// flagPattern
// flagRecursive
flagPattern string
flagRecursive bool
flagResName string
flagResType string
)
func main() {
commonFlagsCheck := func() error {
var (
// common flags
flagSubscriptionId string
flagOutputDir string
flagOverwrite bool
flagAppend bool
flagDevProvider bool
flagBackendType string
flagBackendConfig cli.StringSlice
flagFullConfig bool
flagParallelism int
flagContinue bool
flagNonInteractive bool
flagGenerateMappingFile bool
// common flags (hidden)
hflagMockClient bool
hflagLogPath string
hflagPlainUI bool
// Subcommand specific flags
//
// res:
// flagResName
// flagResType
//
// rg:
// flagPattern
//
// query:
// flagPattern
// flagRecursive
flagPattern string
flagRecursive bool
flagResName string
flagResType string
)
beforeFunc := func(ctx *cli.Context) error {
// Common flags check
if flagAppend {
if flagBackendType != "local" {
return fmt.Errorf("`--append` only works for local backend")
@ -78,6 +79,19 @@ func main() {
}
}
// Identify the subscription id, which comes from one of following (starts from the highest priority):
// - Command line option
// - Env variable: AZTFY_SUBSCRIPTION_ID
// - Env variable: ARM_SUBSCRIPTION_ID
// - Output of azure cli, the current active subscription
if flagSubscriptionId == "" {
var err error
flagSubscriptionId, err = subscriptionIdFromCLI()
if err != nil {
return fmt.Errorf("retrieving subscription id from CLI: %v", err)
}
}
return nil
}
@ -245,11 +259,8 @@ func main() {
Usage: "Terrafying a single resource",
UsageText: "aztfy resource [option] <resource id>",
Flags: resourceFlags,
Before: beforeFunc,
Action: func(c *cli.Context) error {
if err := commonFlagsCheck(); err != nil {
return err
}
if c.NArg() == 0 {
return fmt.Errorf("No resource id specified")
}
@ -257,19 +268,6 @@ func main() {
return fmt.Errorf("More than one resource ids specified")
}
// Identify the subscription id, which comes from one of following (starts from the highest priority):
// - Command line option
// - Env variable: AZTFY_SUBSCRIPTION_ID
// - Env variable: ARM_SUBSCRIPTION_ID
// - Output of azure cli, the current active subscription
if flagSubscriptionId == "" {
var err error
flagSubscriptionId, err = subscriptionIdFromCLI()
if err != nil {
return fmt.Errorf("retrieving subscription id from CLI: %v", err)
}
}
resId := c.Args().First()
if _, err := armid.ParseResourceId(resId); err != nil {
@ -280,12 +278,14 @@ func main() {
cfg := config.Config{
MockClient: hflagMockClient,
CommonConfig: config.CommonConfig{
LogPath: hflagLogPath,
SubscriptionId: flagSubscriptionId,
OutputDir: flagOutputDir,
Overwrite: flagOverwrite,
Append: flagAppend,
DevProvider: flagDevProvider,
Batch: flagNonInteractive,
ContinueOnError: flagContinue,
BackendType: flagBackendType,
BackendConfig: flagBackendConfig.Value(),
FullConfig: flagFullConfig,
@ -307,11 +307,8 @@ func main() {
Usage: "Terrafying a resource group and the nested resources resides within it",
UsageText: "aztfy resource-group [option] <resource group name>",
Flags: resourceGroupFlags,
Before: beforeFunc,
Action: func(c *cli.Context) error {
if err := commonFlagsCheck(); err != nil {
return err
}
if c.NArg() == 0 {
return fmt.Errorf("No resource group specified")
}
@ -319,31 +316,20 @@ func main() {
return fmt.Errorf("More than one resource groups specified")
}
// Identify the subscription id, which comes from one of following (starts from the highest priority):
// - Command line option
// - Env variable: AZTFY_SUBSCRIPTION_ID
// - Env variable: ARM_SUBSCRIPTION_ID
// - Output of azure cli, the current active subscription
if flagSubscriptionId == "" {
var err error
flagSubscriptionId, err = subscriptionIdFromCLI()
if err != nil {
return fmt.Errorf("retrieving subscription id from CLI: %v", err)
}
}
rg := c.Args().First()
// Initialize the config
cfg := config.Config{
MockClient: hflagMockClient,
CommonConfig: config.CommonConfig{
LogPath: hflagLogPath,
SubscriptionId: flagSubscriptionId,
OutputDir: flagOutputDir,
Overwrite: flagOverwrite,
Append: flagAppend,
DevProvider: flagDevProvider,
Batch: flagNonInteractive,
ContinueOnError: flagContinue,
BackendType: flagBackendType,
BackendConfig: flagBackendConfig.Value(),
FullConfig: flagFullConfig,
@ -364,11 +350,8 @@ func main() {
Usage: "Terrafying a customized scope of resources determined by an Azure Resource Graph where predicate",
UsageText: "aztfy query [option] <ARG where predicate>",
Flags: queryFlags,
Before: beforeFunc,
Action: func(c *cli.Context) error {
if err := commonFlagsCheck(); err != nil {
return err
}
if c.NArg() == 0 {
return fmt.Errorf("No query specified")
}
@ -376,31 +359,20 @@ func main() {
return fmt.Errorf("More than one queries specified")
}
// Identify the subscription id, which comes from one of following (starts from the highest priority):
// - Command line option
// - Env variable: AZTFY_SUBSCRIPTION_ID
// - Env variable: ARM_SUBSCRIPTION_ID
// - Output of azure cli, the current active subscription
if flagSubscriptionId == "" {
var err error
flagSubscriptionId, err = subscriptionIdFromCLI()
if err != nil {
return fmt.Errorf("retrieving subscription id from CLI: %v", err)
}
}
predicate := c.Args().First()
// Initialize the config
cfg := config.Config{
MockClient: hflagMockClient,
CommonConfig: config.CommonConfig{
LogPath: hflagLogPath,
SubscriptionId: flagSubscriptionId,
OutputDir: flagOutputDir,
Overwrite: flagOverwrite,
Append: flagAppend,
DevProvider: flagDevProvider,
Batch: flagNonInteractive,
ContinueOnError: flagContinue,
BackendType: flagBackendType,
BackendConfig: flagBackendConfig.Value(),
FullConfig: flagFullConfig,
@ -422,11 +394,8 @@ func main() {
Usage: "Terrafying a customized scope of resources determined by the resource mapping file",
UsageText: "aztfy mapping-file [option] <resource mapping file>",
Flags: mappingFileFlags,
Before: beforeFunc,
Action: func(c *cli.Context) error {
if err := commonFlagsCheck(); err != nil {
return err
}
if c.NArg() == 0 {
return fmt.Errorf("No resource mapping file specified")
}
@ -436,19 +405,6 @@ func main() {
mapFile := c.Args().First()
// Identify the subscription id, which comes from one of following (starts from the highest priority):
// - Command line option
// - Env variable: AZTFY_SUBSCRIPTION_ID
// - Env variable: ARM_SUBSCRIPTION_ID
// - Output of azure cli, the current active subscription
if flagSubscriptionId == "" {
var err error
flagSubscriptionId, err = subscriptionIdFromCLI()
if err != nil {
return fmt.Errorf("retrieving subscription id from CLI: %v", err)
}
}
// Initialize the config
cfg := config.Config{
MockClient: hflagMockClient,
@ -459,6 +415,7 @@ func main() {
Append: flagAppend,
DevProvider: flagDevProvider,
Batch: flagNonInteractive,
ContinueOnError: flagContinue,
BackendType: flagBackendType,
BackendConfig: flagBackendConfig.Value(),
FullConfig: flagFullConfig,
@ -523,13 +480,13 @@ func subscriptionIdFromCLI() (string, error) {
func realMain(cfg config.Config) error {
// Initialize log
if err := initLog(hflagLogPath); err != nil {
if err := initLog(cfg.LogPath); err != nil {
return err
}
// Run in non-interactive mode
if cfg.Batch {
if err := internal.BatchImport(cfg, flagContinue); err != nil {
if err := internal.BatchImport(cfg); err != nil {
return err
}
return nil