is

package module
v0.5.7 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2023 License: Apache-2.0 Imports: 10 Imported by: 18

README

is

Go GitHub tag (latest SemVer) go.dev

is provides a set of detectors for the environment checking.

Features

  • Env() holds a global struct for CLI app basic states, such as: verbose/quiet/debug/trace....
  • InDebugging(), InTesting(), and InTracing(), ....
  • DebugBuild()
  • K8sBuild(), DockerBuild(), ....
  • ColoredTty() bool, ....
  • Terminal colorizers
  • stringtool: RandomStringPure
  • basics: closable, closer, signals

To using environ detecting utilities better and smoother, some terminal (and stringtool, basics) tools are bundled together.

Usages

package main

import (
	"fmt"

	"github.com/hedzr/is"
	"github.com/hedzr/is/basics"
	"github.com/hedzr/is/term/color"
)

func main() {
	defer basics.Close()

	println(is.InTesting())
	println(is.Env().GetDebugLevel())

	fmt.Printf("%v", color.GetCPT().Translate(`<code>code</code> | <kbd>CTRL</kbd>
	<b>bold / strong / em</b>
	<i>italic / cite</i>
	<u>underline</u>
	<mark>inverse mark</mark>
	<del>strike / del </del>
	<font color="green">green text</font>
	`, color.FgDefault))
}

Result got:

image-20231107101843524

Lists

The partials:

  • InDebugging / InDebugMode

  • DebuggerAttached (relyes on delve tag)

  • InTracing / InTestingT

  • InTesting / InTestingT

  • InDevelopingTime

  • InVscodeTerminal

  • InK8s

  • InIstio

  • InDocker / InDockerEnvSimple

  • Build

    • K8sBuild
    • IstioBuild
    • DockerBuild
    • VerboseBuild
    • DebugBuild
  • States / Env

    • VerboseModeEnabled
    • GetVerboseLevel / SetVerboseMode / SetVerboseLevel
    • QuietModeEnabled
    • GetQuietLevel / SetQuietMode / SetQuietLevel
    • NoColorMode
    • GetNoColorLevel / SetNoColorMode / SetNoColorLevel
    • DebugMode
    • GetDebugLevel / SetDebugMode / SetDebugLevel
    • Tracing
    • TraceMode
    • GetTraceLevel / SetTraceMode / SetTraceLevel
  • Terminal / Tty

    • IsTty(w)
    • IsColoredTty(w)
    • IsTtyEscaped(s)
    • StripEscapes(s)
    • ReadPassword
    • GetTtySize
  • [Special] Terminal / Color

    • escaping tools: GetCPT()/GetCPTC()/GetCPTNC()
    • Highlight, Dimf, Text, Dim, ToDim, ToHighlight, ToColor, ...
  • Basics

    • Peripheral, Closable, Closer
    • RegisterClosable
    • RegisterClosers
    • RegisterCloseFns
Buildtags

Some functions want special buildtags presented. These are including:

  • verbose: See VerboseBuild, ...
  • delve: See DebugBuild, ...
  • k8s: See K8sBuild
  • istio: See IstioBuild
  • docker: See DockerBuild
  • ...
Colorizes

The test codes:

import "github.com/hedzr/is/term/color"

func TestGetCPT(t *testing.T) {
t.Logf("%v", color.GetCPT().Translate(`<code>code</code> | <kbd>CTRL</kbd>
	<b>bold / strong / em</b>
	<i>italic / cite</i>
	<u>underline</u>
	<mark>inverse mark</mark>
	<del>strike / del </del>
	<font color="green">green text</font>
    `, color.FgDefault))
}

Result:

image-20231107100150520

And more:

func TestStripLeftTabs(t *testing.T) {
t.Logf("%v", color.StripLeftTabs(`
	
		<code>code</code>
	NC Cool
	 But it's tight.
	  Hold On!
	Hurry Up.
    `))
}

func TestStripHTMLTags(t *testing.T) {
t.Logf("%v", color.StripHTMLTags(`
	
		<code>code</code>
	NC Cool
	 But it's tight.
	  Hold On!
	Hurry Up.
    `))
}
Basics (Closers)

The Closers() collects all closable objects and allow shutting down them at once.

package main

import (
	"os"

	"github.com/hedzr/is/basics"
)

type redisHub struct{}

func (s *redisHub) Close() {
    // close the connections to redis servers
    println("redis connections closed")
}

func main() {
    defer basics.Close()

    tmpFile, _ := os.CreateTemp(os.TempDir(), "1*.log")
    basics.RegisterClosers(tmpFile)

    basics.RegisterCloseFn(func() {
        // do some shutdown operations here
        println("close single functor")
    })

    basics.RegisterPeripheral(&redisHub{})
}
Basics (Signals)

Signals() could catch os signals and entering a infinite loop.

For example, a tcp server could be:

package main

import (
	"context"
	"fmt"
	"os"
	"sync"

	"github.com/hedzr/go-socketlib/net"
	"github.com/hedzr/is"
	logz "github.com/hedzr/logg/slog"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	logger := logz.New("new-dns")
	server := net.NewServer(":7099",
		net.WithServerLogger(logger.WithSkip(1)),
		net.WithServerHandlerFunc(func(ctx context.Context, w net.Response, r net.Request) (processed bool, err error) {
			// write your own reading incoming data loop, handle ctx.Done to stop loop.
			// w.WrChannel() <- []byte{}
			return
		}),
		net.WithServerOnProcessData(func(data []byte, w net.Response, r net.Request) (nn int, err error) {
			logz.Debug("[server] RECEIVED:", "data", string(data), "client.addr", w.RemoteAddr())
			nn = len(data)
			return
		}),
	)
	defer server.Close()

	catcher := is.Signals().Catch()
	catcher.
		WithVerboseFn(func(msg string, args ...any) {
			logger.WithSkip(2).Verbose(fmt.Sprintf("[verbose] %s", fmt.Sprintf(msg, args...)))
		}).
		WithOnSignalCaught(func(sig os.Signal, wg *sync.WaitGroup) {
			println()
			logger.Debug("signal caught", "sig", sig)
			if err := server.Shutdown(); err != nil {
				logger.Error("server shutdown error", "err", err)
			}
			cancel()
		}).
		Wait(func(stopChan chan<- os.Signal, wgShutdown *sync.WaitGroup) {
			// logger.Debug("entering looper's loop...")

			go func() {
				server.WithOnShutdown(func(err error, ss net.Server) { wgShutdown.Done() })
				err := server.ListenAndServe(ctx, nil)
				if err != nil {
					logger.Fatal("server serve failed", "err", err)
				}
			}()
		})
}

// ...

some packages has stayed in progress so the above codes is just a skeleton.

Contributions

Kindly welcome, please issue me first for keeping this repo smaller.

License

Apache 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Closers added in v0.5.7

func Closers() closerS

func ColoredTty added in v0.5.1

func ColoredTty(w io.Writer) bool

ColoredTty detects a writer if it is a colorful tty device.

A colorful tty device can receive ANSI escaped sequences and draw its.

func DebugBuild

func DebugBuild() bool

func DebugMode

func DebugMode() bool

func DebuggerAttached

func DebuggerAttached() bool

DebuggerAttached returns status if debugger attached or is a debug build.

See also InDebugging.

To check wildly like cli app debug mode (via --debug), call InDebugMode

To find parent process is dlv (that is, detecting a real debugger present), another library needed.

func DockerBuild

func DockerBuild() bool

func Env

func Env() states.CmdrMinimal

func FileExists added in v0.5.7

func FileExists(filepath string) bool

FileExists detects if a file or a directory is existed.

func GetDebugLevel

func GetDebugLevel() int

func GetNoColorLevel

func GetNoColorLevel() int

func GetQuietLevel

func GetQuietLevel() int

func GetTraceLevel

func GetTraceLevel() int

func GetTtySize

func GetTtySize() (cols, rows int)

GetTtySize returns the window size in columns and rows in the active console window. The return value of this function is in the order of cols, rows.

func GetVerboseLevel

func GetVerboseLevel() int

func InDebugMode

func InDebugMode() bool

InDebugMode returns if:

  • debugger attached
  • a debug build
  • SetDebugMode(true) called.

To find parent process is dlv (that is, detecting a real debugger present), another library needed.

func InDebugging

func InDebugging() bool

InDebugging returns status if debugger attached or is a debug build.

To enable the debugger attached mode for cmdr, run `go build` with `-tags=delve` options. eg:

go run -tags=delve ./cli
go build -tags=delve -o my-app ./cli

For Goland, you can enable this under 'Run/Debug Configurations', by adding the following into 'Go tool arguments:'

-tags=delve

InDebugging() is a synonym to DebuggerAttached().

NOTE that `isdelve` algor is from https://stackoverflow.com/questions/47879070/how-can-i-see-if-the-goland-debugger-is-running-in-the-program

To check wildly like cli app debug mode (via --debug), call InDebugMode.

To find parent process is dlv (that is, detecting a real debugger present), another library needed.

func InDevelopingTime

func InDevelopingTime() (status bool)

InDevelopingTime detects whether is in developing time (debugging or testing).

If the main program has been built as an executable binary, we would assume which is not in developing time.

If GetDebugMode() is true, that's in developing time too.

func InDocker

func InDocker() bool

InDocker detects if the service is running under docker environment.

We tests these two conditions:

  1. find if `/.dockerenv` exists or not.
  2. `docker` in buildtags

func InDockerEnvSimple

func InDockerEnvSimple() (status bool)

InDockerEnvSimple detects whether is running within docker container environment.

InDockerEnvSimple finds if `/.dockerenv` exists or not.

func InIstio

func InIstio() bool

InIstio detects if the service is running under istio injected.

### IMPORTANT

To make this detector work properly, you must mount a DownwordAPI volume to your container/pod. See also:

https://kubernetes.io/en/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/

func InK8s

func InK8s() bool

InK8s detects if the service is running under k8s environment.

func InK8sYN

func InK8sYN() bool

InK8sYN is yet another DetectInK8s impl

func InTesting

func InTesting() bool

InTesting detects whether is running under go test mode

func InTestingT

func InTestingT(args []string) bool

InTestingT detects whether is running under 'go test' mode

func InTracing

func InTracing() bool

InTracing tests if trace.IsEnabled() or env.traceMode (cli app trace mode via --trace).

See the github.com/is/states/trace package.

func InVscodeTerminal

func InVscodeTerminal() bool

InVscodeTerminal tests if running under visual studio code integrated terminal

func IstioBuild

func IstioBuild() bool

func K8sBuild

func K8sBuild() bool

func NoColorMode

func NoColorMode() bool

func QuietModeEnabled

func QuietModeEnabled() bool

func ReadFile added in v0.5.7

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents.

func ReadPassword

func ReadPassword() (text string, err error)

ReadPassword reads the password from stdin with safe protection

func SetDebugLevel

func SetDebugLevel(hits int)

func SetDebugMode

func SetDebugMode(b bool)

func SetNoColorLevel

func SetNoColorLevel(hits int)

func SetNoColorMode

func SetNoColorMode(b bool)

func SetQuietLevel

func SetQuietLevel(hits int)

func SetQuietMode

func SetQuietMode(b bool)

func SetTraceLevel

func SetTraceLevel(hits int)

func SetTraceMode

func SetTraceMode(b bool)

func SetVerboseLevel

func SetVerboseLevel(hits int)

func SetVerboseMode

func SetVerboseMode(b bool)

func Signals added in v0.5.7

func Signals() signalS

Signals return a signals helper so that you can catch them, raise them.

For example:

package main

import (
  "context"
  "fmt"
  "os"
  "sync"

  "github.com/hedzr/env"
  "github.com/hedzr/go-socketlib/net"
  logz "github.com/hedzr/logg/slog"
)

func main() {
  logz.SetLevel(logz.DebugLevel)

  server := net.NewServer(":7099")
  defer server.Close()

  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()

  catcher := env.Signals().Catch()
  catcher.WithVerboseFn(func(msg string, args ...any) {
    logz.Debug(fmt.Sprintf("[verbose] %s", fmt.Sprintf(msg, args...)))
  }).WithSignalCaught(func(sig os.Signal, wg *sync.WaitGroup) {
    println()
    logz.Debug("signal caught", "sig", sig)
    if err := server.Shutdown(); err != nil {
    	logz.Error("server shutdown error", "err", err)
    }
    cancel()
  }).Wait(func(stopChan chan<- os.Signal, wgShutdown *sync.WaitGroup) {
    logz.Debug("entering looper's loop...")

    server.WithOnShutdown(func(err error) { wgShutdown.Done() })
    err := server.StartAndServe(ctx)
    if err != nil {
      logz.Fatal("server serve failed", "err", err)
    }
  })
}

func States

func States() states.CmdrMinimal

States or Env returns a minimal environment settings for a typical CLI app.

See also states.CmdrMinimal.

func StripEscapes

func StripEscapes(str string) (strCleaned string)

StripEscapes removes any ansi color escaped sequences from a string

func TraceMode

func TraceMode() bool

func Tracing

func Tracing() bool

func Tty added in v0.5.1

func Tty(w io.Writer) bool

Tty detects a writer if it is abstracting from a tty (console, terminal) device.

func TtyEscaped added in v0.5.1

func TtyEscaped(s string) bool

TtyEscaped detects a string if it contains ansi color escaped sequences

func UpdateEnvWith

func UpdateEnvWith(env states.CmdrMinimal)

func VerboseBuild

func VerboseBuild() bool

func VerboseModeEnabled

func VerboseModeEnabled() bool

Types

This section is empty.

Directories

Path Synopsis
_examples
small command
color
Package color provides a wrapped standard output device like printf but with colored enhancements.
Package color provides a wrapped standard output device like printf but with colored enhancements.

Jump to

Keyboard shortcuts

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