utils

package module
v0.0.0-...-d6ccb58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2022 License: LGPL-3.0-or-later Imports: 5 Imported by: 1

README

package: github.com/mikelue/go-misc/utils GoDoc

This package contains language libraries over GoLang.

./reflect - Some convenient libraries to manipulate reflect in GoLang.

RollbackContainer

RollbackContainer is an interface with "Setup()"/"TearDown" life-cycle to wrap certain function with fabricated environment.

The RollbackExecutor can be used to run a function(func() {}) wrapped by "1:M" RollbackContainers.

tempDir := RollbackContainerBuilder.NewTmpDir("my-temp-*")

RollbackExecutor.RunP(
    func(params Params) {
        /* The directory of created is params[PKEY_TEMP_DIR] */
    },
    tempDir,
)

RollbackContainerBuilder provides some methods to constructs useful containers:

  • NewTmpDir() - Builds temporary directory and remove it afterward, see RollbackContainerP.
  • NewEnv() - Sets up environment variable and reset them afterward.
  • NewChdir() - Changes current directory and change-back afterward.

See GoDoc go-misc/utils

Documentation

Overview

This package contains various utilities to ease development of GoLang.

Rollback

While we are testing, there are something we like to set-up. For example:

  1. make a temporary directory
  2. copy some test files to that directory
  3. sets some environment variable

After we finish our test, the environment should be as same as nothing happened.

The "RollbackExecutor" can be used to execute your routine with "RollbackContainer"s.

This package provides some built-in containers for temp directory, environment variables, etc.

RollbackExecutor

Using this space to perform execution surrounding by some containers.

See examples of this documentation.

RollbackContainerBuilder

See examples of this documentation.

Index

Examples

Constants

View Source
const EmptyRollbackContainer emptyRollbackContainer = 0

Empty rollback container, do nothing.

View Source
const EmptyRollbackContainerP emptyRollbackContainerP = 0

Empty rollback container with parameters, do nothing.

View Source
const (
	PKEY_TEMP_DIR = "_u_temp_dir_"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type IRollbackContainerBuilder

type IRollbackContainerBuilder int
Example (NewChdir)
tempDirName := fmt.Sprintf("%s/chdir-temp", os.TempDir())
chDir := RollbackContainerBuilder.NewChdir(tempDirName)

RollbackExecutor.Run(
	func() {
		workingDir, _ := os.Getwd()
		fmt.Printf("Working directory is same as created: %v\n",
			workingDir == tempDirName,
		)
	},
	// Creates the sample directory first
	RollbackContainerBuilder.NewDir(tempDirName),
	chDir,
)

workingDir, _ := os.Getwd()
fmt.Printf("Working directory is changed back: %v\n",
	workingDir != tempDirName,
)
Output:

Working directory is same as created: true
Working directory is changed back: true
Example (NewCopyfiles)
tempDirName := fmt.Sprintf("%s/copy-files-temp", os.TempDir())

destFileName1 := fmt.Sprintf("%s/sample-1.txt", tempDirName)
destFileName2 := fmt.Sprintf("%s/sample-2.txt", tempDirName)

copyFiles := RollbackContainerBuilder.NewCopyFiles(
	tempDirName,
	fmt.Sprintf("%s/sample-1.txt", testSourceDir),
	fmt.Sprintf("%s/sample-2.txt", testSourceDir),
)

RollbackExecutor.Run(
	func() {
		_, err1 := os.Stat(destFileName1)
		_, err2 := os.Stat(destFileName1)

		fmt.Printf("[Existing] File 1: %v. File 2: %v\n",
			err1 == nil, err2 == nil,
		)
	},
	// Creates the sample directory first
	RollbackContainerBuilder.NewDir(tempDirName),
	copyFiles,
)

_, err1 := os.Stat(destFileName1)
_, err2 := os.Stat(destFileName2)
fmt.Printf("[Removed] File 1: %v. File 2: %v\n",
	os.IsNotExist(err1), os.IsNotExist(err2),
)
Output:

[Existing] File 1: true. File 2: true
[Removed] File 1: true. File 2: true
Example (NewDir)
tempDirName := fmt.Sprintf("%s/example-newdir", os.TempDir())
newDir := RollbackContainerBuilder.NewDir(tempDirName)

RollbackExecutor.Run(
	func() {
		stat, err := os.Stat(tempDirName)
		fmt.Printf("Name of new directory: %v %v\n", stat.IsDir(), err == nil)
	},
	newDir,
)

_, err := os.Stat(tempDirName)
fmt.Printf("Directory is removed: %v\n", os.IsNotExist(err))
Output:

Name of new directory: true true
Directory is removed: true
Example (NewEnv)
changeEnv := RollbackContainerBuilder.NewEnv(
	map[string]string{
		"MYENV_1": "hello",
		"MYENV_2": "world",
	},
)

RollbackExecutor.Run(
	func() {
		v1, _ := os.LookupEnv("MYENV_1")
		v2, _ := os.LookupEnv("MYENV_2")
		fmt.Printf("Environment: %s %s\n", v1, v2)
	},
	changeEnv,
)

_, ok1 := os.LookupEnv("MYENV_1")
_, ok2 := os.LookupEnv("MYENV_2")
fmt.Printf("Reset: %v %v", ok1, ok2)
Output:

Environment: hello world
Reset: false false
Example (NewTempDir)
tempDir := RollbackContainerBuilder.NewTmpDir("proj1-*")

var createdDir string
RollbackExecutor.RunP(
	func(params Params) {
		// Access name of create directory of temporary by "params[PKEY_TEMP_DIR]"
		createdDir = params[PKEY_TEMP_DIR].(string)
		stat, err := os.Stat(createdDir)
		fmt.Printf("Name of temporary directory: %v %v\n", stat.IsDir(), err == nil)
	},
	tempDir,
)

_, err := os.Stat(createdDir)
fmt.Printf("Temporary directory is removed: %v", os.IsNotExist(err))
Output:

Name of temporary directory: true true
Temporary directory is removed: true
var RollbackContainerBuilder IRollbackContainerBuilder

Method space to build new instances of executors

func (*IRollbackContainerBuilder) Concate

func (self *IRollbackContainerBuilder) Concate(containers ...RollbackContainer) RollbackContainer

Concatenate multiple "RollbackContainer"s as a single one.

The following containers would not be Setup() if the setup of prior container hsa failed

Only the containers of successful setting-up would be tear-down in reversed order.

func (*IRollbackContainerBuilder) ConcateP

The following containers would not be Setup() if the setup of prior container hsa failed

Only the containers of successful setting-up would be tear-down in reversed order.

The parameters would be merged as arguments.

func (*IRollbackContainerBuilder) NewChdir

func (*IRollbackContainerBuilder) NewChdir(targetDir string) RollbackContainer

Constructs an new container with modified working directory.

The "os.Chdir()" would be used to revert the working dictionary.

func (*IRollbackContainerBuilder) NewCopyFiles

func (*IRollbackContainerBuilder) NewCopyFiles(dir string, files ...string) RollbackContainer

Constructs an new container with copy/removal of files.

The copied files would be remove by the rollback.

func (*IRollbackContainerBuilder) NewDir

Constructs an new container with creation/removal a directory.

The directory would be removed after the execution.

func (*IRollbackContainerBuilder) NewEnv

func (*IRollbackContainerBuilder) NewEnv(changedEnvVars map[string]string) RollbackContainer

Constructs an new container with modified environment.

The "os.Environ()" would be reverted to original status after the execution.

func (*IRollbackContainerBuilder) NewTmpDir

Constructs an new container with creation/removal temp directory.

The key of parameters for the temp directory is "PKEY_TEMP_DIR".

The temp directory would be removed after the execution.

func (*IRollbackContainerBuilder) ToContainer

Converts a "RollbackExecutorP" to a "RollbackExecutor"

func (*IRollbackContainerBuilder) ToContainerP

Converts a "RollbackExecutor" to a "RollbackExecutorP"

type IRollbackExecutor

type IRollbackExecutor int
var RollbackExecutor IRollbackExecutor

Method space to run callback with 1:M containers

func (*IRollbackExecutor) Run

func (*IRollbackExecutor) Run(callback func(), containers ...RollbackContainer) error

Run callback with simple containers

func (*IRollbackExecutor) RunP

func (*IRollbackExecutor) RunP(callback func(Params), containers ...RollbackContainerP) error

Run callback with containers having parameters

type Params

type Params map[string]interface{}

type RollbackContainer

type RollbackContainer interface {
	// This method sets-up your fabricated container
	Setup() error
	// This method gets called as defer way after the callback gets finised
	TearDown() error
}

The container is used to perform setup/teardown logic

Example
package main

import (
	"fmt"
)

type weightContainer int

func (weightContainer) Setup() error {
	fmt.Println("[1] Setup container")
	return nil
}
func (weightContainer) TearDown() error {
	fmt.Println("[3] Teardown container")
	return nil
}

func main() {
	RollbackExecutor.Run(
		func() {
			fmt.Println("[2] Perform job")
		},
		weightContainer(0),
	)

}
Output:

[1] Setup container
[2] Perform job
[3] Teardown container

type RollbackContainerP

type RollbackContainerP interface {
	// This method sets-up your fabricated container
	Setup() (Params, error)
	// This method gets called as defer way after the callback gets finised
	TearDown(Params) error
}

The container is used to perform setup/teardown logic with parameters

Example
package main

import (
	"fmt"
)

type weightContainerP int

func (weightContainerP) Setup() (Params, error) {
	fmt.Println("[1] Setup container")
	return Params{"v1": 871}, nil
}
func (weightContainerP) TearDown(params Params) error {
	fmt.Printf("[3] Teardown container: %v\n", params["v2"])
	return nil
}

func main() {
	RollbackExecutor.RunP(
		func(params Params) {
			fmt.Printf("[2] Perform job: %v\n", params["v1"])
			params["v2"] = 145
		},
		weightContainerP(0),
	)

}
Output:

[1] Setup container
[2] Perform job: 871
[3] Teardown container: 145

Directories

Path Synopsis
This package provides utilities to ease manipulation over objects in "reflect".
This package provides utilities to ease manipulation over objects in "reflect".
types
This package contains instances of "reflect.Type".
This package contains instances of "reflect.Type".
This package contains utilities of manipulating objects on package of "runtime".
This package contains utilities of manipulating objects on package of "runtime".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL