From 814450fd17f7f7cf7a3c2e7c6ceaf8f134ba8cd1 Mon Sep 17 00:00:00 2001 From: huangqian Date: Sun, 27 Feb 2022 13:22:26 +0800 Subject: [PATCH] gcmd example --- os/gcmd/gcmd_z_example_test.go | 111 +++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/os/gcmd/gcmd_z_example_test.go b/os/gcmd/gcmd_z_example_test.go index 491d5487f..6b6447067 100644 --- a/os/gcmd/gcmd_z_example_test.go +++ b/os/gcmd/gcmd_z_example_test.go @@ -7,7 +7,9 @@ package gcmd_test import ( + "context" "fmt" + "github.com/gogf/gf/v2/os/gctx" "os" "github.com/gogf/gf/v2/frame/g" @@ -93,3 +95,112 @@ func ExampleParse() { // true // false } + +func ExampleCommandFromCtx() { + var ( + command = gcmd.Command{ + Name: "start", + } + ) + + ctx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &command) + unAddCtx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &gcmd.Command{}) + nonKeyCtx := context.WithValue(gctx.New(), "Testkey", &gcmd.Command{}) + + fmt.Println(gcmd.CommandFromCtx(ctx).Name) + fmt.Println(gcmd.CommandFromCtx(unAddCtx).Name) + fmt.Println(gcmd.CommandFromCtx(nonKeyCtx) == nil) + + // Output: + // start + // + // true +} + +func ExampleCommand_AddCommand() { + commandRoot := &gcmd.Command{ + Name: "gf", + } + commandRoot.AddCommand(&gcmd.Command{ + Name: "start", + }, &gcmd.Command{}) + + commandRoot.Print() + + // Output: + //USAGE + // gf COMMAND [OPTION] + // + //COMMAND + // start +} + +func ExampleCommand_AddCommand_Repeat() { + commandRoot := &gcmd.Command{ + Name: "gf", + } + err := commandRoot.AddCommand(&gcmd.Command{ + Name: "start", + }, &gcmd.Command{ + Name: "stop", + }, &gcmd.Command{ + Name: "start", + }) + + fmt.Println(err) + + // Output: + // command "start" is already added to command "gf" +} + +func ExampleCommand_AddObject() { + var ( + command = gcmd.Command{ + Name: "start", + } + ) + + command.AddObject(&TestCmdObject{}) + + command.Print() + + // Output: + //USAGE + // start COMMAND [OPTION] + // + //COMMAND + // root root env command +} + +func ExampleCommand_AddObject_Error() { + var ( + command = gcmd.Command{ + Name: "start", + } + ) + + err := command.AddObject(&[]string{"Test"}) + + fmt.Println(err) + + // Output: + // input object should be type of struct, but got "*[]string" +} + +func ExampleCommand_Print() { + commandRoot := &gcmd.Command{ + Name: "gf", + } + commandRoot.AddCommand(&gcmd.Command{ + Name: "start", + }, &gcmd.Command{}) + + commandRoot.Print() + + // Output: + //USAGE + // gf COMMAND [OPTION] + // + //COMMAND + // start +}