未验证 提交 a28c5707 编写于 作者: LinuxSuRen's avatar LinuxSuRen 提交者: GitHub

Add support to download a plugin from mirror site (#222)

* Add logger for jcli

* Add more test cases for plugin download command

* Remove unused function

* Add test cases for init logger
上级 8bdb4571
......@@ -35,8 +35,7 @@ var centerDownloadCmd = &cobra.Command{
Short: "Download Jenkins",
Long: `Download Jenkins from a mirror site. You can get more mirror sites from https://jenkins-zh.cn/tutorial/management/mirror/`,
Run: func(cmd *cobra.Command, _ []string) {
config := getConfig()
mirrorSite := centerDownloadOption.getMirrorSite(config)
mirrorSite := getMirror(centerDownloadOption.Mirror)
if mirrorSite == "" {
cmd.PrintErrln("cannot found Jenkins mirror by:", centerDownloadOption.Mirror)
return
......@@ -54,14 +53,3 @@ var centerDownloadCmd = &cobra.Command{
helper.CheckErr(cmd, err)
},
}
func (c *CenterDownloadOption) getMirrorSite(config *Config) (site string) {
mirrors := getMirrors()
for _, mirror := range mirrors {
if mirror.Name == c.Mirror {
site = mirror.URL
return
}
}
return
}
......@@ -2,6 +2,7 @@ package cmd
import (
"fmt"
"go.uber.org/zap"
"io/ioutil"
"log"
"os"
......@@ -177,6 +178,22 @@ func getMirrors() (mirrors []JenkinsMirror) {
return
}
func getMirror(name string) string {
mirrors := getMirrors()
for _, mirror := range mirrors {
if mirror.Name == name {
logger.Debug("find mirror", zap.String("name", name), zap.String("url", mirror.URL))
return mirror.URL
}
}
return ""
}
func getDefaultMirror() string {
return getMirror("default")
}
func saveConfig() (err error) {
var data []byte
config := getConfig()
......
......@@ -3,19 +3,47 @@ package cmd
import (
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/spf13/cobra"
"net/http"
)
// PluginDownloadOption is the option for plugin download command
type PluginDownloadOption struct {
SkipDependency bool
SkipOptional bool
UseMirror bool
ShowProgress bool
RoundTripper http.RoundTripper
}
var pluginDownloadOption PluginDownloadOption
func init() {
pluginCmd.AddCommand(pluginDownloadCmd)
pluginDownloadCmd.Flags().BoolVarP(&pluginDownloadOption.SkipDependency, "skip-dependency", "", false,
"If you want to skip download dependency of plugin")
pluginDownloadCmd.Flags().BoolVarP(&pluginDownloadOption.SkipOptional, "skip-optional", "", true,
"If you want to skip download optional dependency of plugin")
pluginDownloadCmd.Flags().BoolVarP(&pluginDownloadOption.UseMirror, "use-mirror", "", true,
"If you want to download plugin from a mirror site")
pluginDownloadCmd.Flags().BoolVarP(&pluginDownloadOption.ShowProgress, "show-progress", "", true,
"If you want to show the progress of download a plugin")
}
var pluginDownloadCmd = &cobra.Command{
Use: "download <keyword>",
Short: "Download the plugins",
Long: `Download the plugins`,
Long: `Download the plugins which contain the target plugin and its dependencies`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
jclient := &client.PluginAPI{}
jclient.DownloadPlugins(args)
jClient := &client.PluginAPI{
SkipDependency: pluginDownloadOption.SkipDependency,
SkipOptional: pluginDownloadOption.SkipOptional,
UseMirror: pluginDownloadOption.UseMirror,
ShowProgress: pluginDownloadOption.ShowProgress,
MirrorURL: getDefaultMirror(),
RoundTripper: pluginDownloadOption.RoundTripper,
}
jClient.DownloadPlugins(args)
},
}
package cmd
import (
"bytes"
"github.com/jenkins-zh/jenkins-cli/client"
"io/ioutil"
"os"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/jenkins-zh/jenkins-cli/mock/mhttp"
)
var _ = Describe("plugin download command", func() {
var (
ctrl *gomock.Controller
roundTripper *mhttp.MockRoundTripper
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
roundTripper = mhttp.NewMockRoundTripper(ctrl)
pluginDownloadOption.RoundTripper = roundTripper
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
})
AfterEach(func() {
rootCmd.SetArgs([]string{})
os.Remove(rootOptions.ConfigFile)
rootOptions.ConfigFile = ""
ctrl.Finish()
})
Context("basic cases", func() {
It("should success", func() {
var err error
var data []byte
data, err = generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
client.PrepareOnePluginWithOptionalDep(roundTripper, "fake")
client.PrepareDownloadPlugin(roundTripper)
rootCmd.SetArgs([]string{"plugin", "download", "fake", "--show-progress=false", "--use-mirror=false"})
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(Equal(""))
_, err = os.Stat("fake.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
})
})
})
......@@ -2,6 +2,7 @@ package cmd
import (
"fmt"
"github.com/jenkins-zh/jenkins-cli/util"
"io"
"log"
"os"
......@@ -12,14 +13,19 @@ import (
"github.com/jenkins-zh/jenkins-cli/app"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
var logger *zap.Logger
// RootOptions is a global option for whole cli
type RootOptions struct {
ConfigFile string
Jenkins string
Version bool
Debug bool
LoggerLevel string
}
var rootCmd = &cobra.Command{
......@@ -28,6 +34,14 @@ var rootCmd = &cobra.Command{
Long: `jcli is Jenkins CLI which could help with your multiple Jenkins,
Manage your Jenkins and your pipelines
More information could found at https://jenkins-zh.cn`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
var err error
if logger, err = util.InitLogger(rootOptions.LoggerLevel); err != nil {
cmd.PrintErrln(err)
} else {
client.SetLogger(logger)
}
},
Run: func(cmd *cobra.Command, args []string) {
cmd.Println("Jenkins CLI (jcli) manage your Jenkins")
if rootOptions.Version {
......@@ -49,7 +63,6 @@ var rootCmd = &cobra.Command{
// Execute will exectue the command
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
......@@ -62,6 +75,8 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&rootOptions.Jenkins, "jenkins", "j", "", "Select a Jenkins server for this time")
rootCmd.PersistentFlags().BoolVarP(&rootOptions.Version, "version", "v", false, "Print the version of Jenkins CLI")
rootCmd.PersistentFlags().BoolVarP(&rootOptions.Debug, "debug", "", false, "Print the output into debug.html")
rootCmd.PersistentFlags().StringVarP(&rootOptions.LoggerLevel, "logger-level", "", "warn",
"Logger level which could be: debug, info, warn, error")
}
func initConfig() {
......@@ -128,7 +143,7 @@ func getCmdPath(cmd *cobra.Command) string {
func executePreCmd(cmd *cobra.Command, _ []string, writer io.Writer) (err error) {
config := getConfig()
if config == nil {
err = fmt.Errorf("Cannot find config file")
err = fmt.Errorf("cannot find config file")
return
}
......
package client
import (
"github.com/jenkins-zh/jenkins-cli/util"
"go.uber.org/zap"
)
var logger *zap.Logger
// SetLogger set a global logger
func SetLogger(zapLogger *zap.Logger) {
logger = zapLogger
}
func init() {
if logger == nil {
var err error
if logger, err = util.InitLogger("warn"); err != nil {
panic(err)
}
}
}
// CoreClient hold the client of Jenkins core
type CoreClient struct {
JenkinsCore
......
......@@ -5,16 +5,23 @@ import (
"encoding/json"
"fmt"
"github.com/jenkins-zh/jenkins-cli/util"
"go.uber.org/zap"
"io/ioutil"
"log"
"net/http"
"strings"
)
// PluginAPI represetns a plugin API
// PluginAPI represents a plugin API
type PluginAPI struct {
dependencyMap map[string]string
SkipDependency bool
SkipOptional bool
UseMirror bool
ShowProgress bool
MirrorURL string
RoundTripper http.RoundTripper
}
......@@ -87,34 +94,49 @@ func (d *PluginAPI) ShowTrend(name string) (trend string, err error) {
// DownloadPlugins will download those plugins from update center
func (d *PluginAPI) DownloadPlugins(names []string) {
d.dependencyMap = make(map[string]string)
fmt.Println("Start to collect plugin dependencies...")
logger.Info("start to collect plugin dependencies...")
plugins := make([]PluginInfo, 0)
for _, name := range names {
logger.Debug("start to collect dependency", zap.String("plugin", name))
plugins = append(plugins, d.collectDependencies(strings.ToLower(name))...)
}
fmt.Printf("Ready to download plugins, total: %d.\n", len(plugins))
logger.Info("ready to download plugins", zap.Int("total", len(plugins)))
var err error
for i, plugin := range plugins {
fmt.Printf("Start to download plugin %s, version: %s, number: %d\n",
plugin.Name, plugin.Version, i)
logger.Info("start to download plugin",
zap.String("name", plugin.Name),
zap.String("version", plugin.Version),
zap.String("url", plugin.URL),
zap.Int("number", i))
if err = d.download(plugin.URL, plugin.Name); err != nil {
logger.Error("download plugin error", zap.String("name", plugin.Name), zap.Error(err))
}
}
}
d.download(plugin.URL, plugin.Name)
func (d *PluginAPI) getMirrorURL(url string) (mirror string) {
mirror = url
if d.UseMirror && d.MirrorURL != "" {
logger.Debug("replace with mirror", zap.String("original", url))
mirror = strings.Replace(url, "http://updates.jenkins-ci.org/download/", d.MirrorURL, -1)
}
return
}
func (d *PluginAPI) download(url string, name string) {
if resp, err := http.Get(url); err != nil {
fmt.Println(err)
} else {
defer resp.Body.Close()
if body, err := ioutil.ReadAll(resp.Body); err != nil {
fmt.Println(err)
} else {
if err = ioutil.WriteFile(fmt.Sprintf("%s.hpi", name), body, 0644); err != nil {
fmt.Println(err)
}
}
func (d *PluginAPI) download(url string, name string) (err error) {
url = d.getMirrorURL(url)
logger.Info("prepare to download", zap.String("name", name), zap.String("url", url))
downloader := util.HTTPDownloader{
RoundTripper: d.RoundTripper,
TargetFilePath: fmt.Sprintf("%s.hpi", name),
URL: url,
ShowProgress: d.ShowProgress,
}
err = downloader.DownloadFile()
return
}
func (d *PluginAPI) getPlugin(name string) (plugin *PluginInfo, err error) {
......@@ -129,7 +151,10 @@ func (d *PluginAPI) getPlugin(name string) (plugin *PluginInfo, err error) {
cli.Transport = d.RoundTripper
}
resp, err := cli.Get("https://plugins.jenkins.io/api/plugin/" + name)
pluginAPI := fmt.Sprintf("https://plugins.jenkins.io/api/plugin/%s", name)
logger.Debug("fetch data from plugin API", zap.String("url", pluginAPI))
resp, err := cli.Get(pluginAPI)
if err != nil {
return plugin, err
}
......@@ -154,9 +179,12 @@ func (d *PluginAPI) collectDependencies(pluginName string) (plugins []PluginInfo
plugins = make([]PluginInfo, 0)
plugins = append(plugins, *plugin)
if d.SkipDependency {
return
}
for _, dependency := range plugin.Dependencies {
if dependency.Optional {
if d.SkipOptional && dependency.Optional {
continue
}
if _, ok := d.dependencyMap[dependency.Name]; !ok {
......
......@@ -5,6 +5,7 @@ import (
"github.com/jenkins-zh/jenkins-cli/mock/mhttp"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"os"
)
var _ = Describe("plugin api test", func() {
......@@ -19,6 +20,9 @@ var _ = Describe("plugin api test", func() {
roundTripper = mhttp.NewMockRoundTripper(ctrl)
pluginAPI = PluginAPI{
RoundTripper: roundTripper,
ShowProgress: false,
UseMirror: false,
SkipOptional: true,
}
})
......@@ -37,4 +41,97 @@ var _ = Describe("plugin api test", func() {
Expect(trend).NotTo(Equal(""))
})
})
Context("DownloadPlugins", func() {
var (
names []string
)
BeforeEach(func() {
names = []string{}
})
It("empty name list", func() {
pluginAPI.DownloadPlugins(names)
})
It("one plugin name", func() {
names = []string{"fake"}
PrepareOnePluginInfo(roundTripper, "fake")
PrepareDownloadPlugin(roundTripper)
pluginAPI.DownloadPlugins(names)
_, err := os.Stat("fake.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
})
It("use mirror", func() {
pluginAPI.UseMirror = true
pluginAPI.MirrorURL = "http://updates.jenkins-ci.org/download/"
names = []string{"fake"}
PrepareOnePluginInfo(roundTripper, "fake")
PrepareDownloadPlugin(roundTripper)
pluginAPI.DownloadPlugins(names)
_, err := os.Stat("fake.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
})
It("with dependency which is not optional", func() {
names = []string{"fake"}
PrepareOnePluginWithDep(roundTripper, "fake")
PrepareDownloadPlugin(roundTripper)
PrepareDownloadPlugin(roundTripper)
pluginAPI.SkipDependency = false
pluginAPI.DownloadPlugins(names)
var err error
_, err = os.Stat("fake.hpi")
Expect(err).To(BeNil())
_, err = os.Stat("fake-1.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
defer os.Remove("fake-1.hpi")
})
It("with dependency which is optional", func() {
names = []string{"fake"}
PrepareOnePluginWithOptionalDep(roundTripper, "fake")
PrepareDownloadPlugin(roundTripper)
pluginAPI.SkipDependency = false
pluginAPI.SkipOptional = true
pluginAPI.DownloadPlugins(names)
var err error
_, err = os.Stat("fake.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
})
It("skip dependency", func() {
names = []string{"fake"}
PrepareOnePluginWithOptionalDep(roundTripper, "fake")
PrepareDownloadPlugin(roundTripper)
pluginAPI.SkipDependency = true
pluginAPI.SkipOptional = true
pluginAPI.DownloadPlugins(names)
var err error
_, err = os.Stat("fake.hpi")
Expect(err).To(BeNil())
defer os.Remove("fake.hpi")
})
})
})
......@@ -10,16 +10,61 @@ import (
)
// PrepareShowTrend only for test
func PrepareShowTrend(roundTripper *mhttp.MockRoundTripper, keyword string) {
func PrepareShowTrend(roundTripper *mhttp.MockRoundTripper, keyword string) (
response *http.Response) {
request, _ := http.NewRequest("GET", fmt.Sprintf("https://plugins.jenkins.io/api/plugin/%s", keyword), nil)
response := &http.Response{
response = &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString(`
{"stats": {"installations":[{"total":1512},{"total":3472},{"total":4385},{"total":3981}]}}
{"name":"fake","version": "0.1.8","url": "http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi",
"stats": {"installations":[{"total":1512},{"total":3472},{"total":4385},{"total":3981}]}}
`)),
}
roundTripper.EXPECT().
RoundTrip(request).Return(response, nil)
return
}
// PrepareOnePluginInfo only for test
func PrepareOnePluginInfo(roundTripper *mhttp.MockRoundTripper, pluginName string) {
PrepareShowTrend(roundTripper, pluginName)
}
// PrepareOnePluginWithDep only for test
func PrepareOnePluginWithDep(roundTripper *mhttp.MockRoundTripper, pluginName string) {
response := PrepareShowTrend(roundTripper, pluginName)
response.Body = ioutil.NopCloser(bytes.NewBufferString(`
{"name":"fake","version": "0.1.8","url": "http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi",
"dependencies":[{"name":"fake-1","optional":false,"version":"2.4"}]}
`))
fake1 := PrepareShowTrend(roundTripper, "fake-1")
fake1.Body = ioutil.NopCloser(bytes.NewBufferString(`
{"name":"fake-1","version": "0.1.8","url": "http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi"}
`))
}
// PrepareOnePluginWithOptionalDep only for test
func PrepareOnePluginWithOptionalDep(roundTripper *mhttp.MockRoundTripper, pluginName string) {
response := PrepareShowTrend(roundTripper, pluginName)
response.Body = ioutil.NopCloser(bytes.NewBufferString(`
{"name":"fake","version": "0.1.8","url": "http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi",
"dependencies":[{"name":"fake-1","optional":true,"version":"2.4"}]}
`))
}
// PrepareDownloadPlugin only for test
func PrepareDownloadPlugin(roundTripper *mhttp.MockRoundTripper) {
request, _ := http.NewRequest("GET",
"http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi", nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString("")),
}
roundTripper.EXPECT().
RoundTrip(request).Return(response, nil)
}
......@@ -15,7 +15,6 @@ require (
github.com/onsi/ginkgo v1.10.3
github.com/onsi/gomega v1.7.1
github.com/spf13/cobra v0.0.5
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac // indirect
golang.org/x/tools v0.0.0-20190911230505-6bfd74cf029c // indirect
go.uber.org/zap v1.12.0
gopkg.in/yaml.v2 v2.2.4
)
......@@ -15,6 +15,7 @@ github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8Nz
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
......@@ -23,6 +24,7 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfU
github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/gosuri/uilive v0.0.3 h1:kvo6aB3pez9Wbudij8srWo4iY6SFTTxTKOkb+uRCE8I=
github.com/gosuri/uilive v0.0.3/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8=
github.com/gosuri/uiprogress v0.0.1 h1:0kpv/XY/qTmFWl/SkaJykZXrBBzwwadmW8fRb7RJSxw=
......@@ -36,8 +38,12 @@ github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NH
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.4 h1:5Myjjh3JY/NaAi4IsUbHADytDyl1VE1Y9PXDlL+P/VQ=
github.com/kr/pty v1.1.4/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
......@@ -65,8 +71,10 @@ github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa
github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
......@@ -77,17 +85,30 @@ github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb6
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
go.uber.org/atomic v1.5.0 h1:OI5t8sDa1Or+q8AeE+yKeB/SDYioSHAgcVljj9JIETY=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/multierr v1.3.0 h1:sFPn2GLc3poCkfrpIXGhBD2X0CMIo4Q/zSULXrj/+uc=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.12.0 h1:dySoUQPFBGj6xwjmBzageVL8jGi8uxc6bEmJQjA06bw=
go.uber.org/zap v1.12.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5 h1:8dUaAV7K4uHsF56JQWkprecIQKdPHtR9jCHF5nB8uzc=
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac h1:8R1esu+8QioDxo4E4mX6bFztO+dMTM49DNAaWfO5OeY=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
......@@ -114,11 +135,16 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262 h1:qsl9y/CJx34tuA7QCPNp86JNJe4spst6Ff8MjvPUdPg=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190911230505-6bfd74cf029c h1:ZgedNh8bIOBjyY5XEG0kR/41dSN9H+5jFZWuR/TgA1g=
golang.org/x/tools v0.0.0-20190911230505-6bfd74cf029c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
......@@ -128,3 +154,4 @@ gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
package util
import (
"encoding/json"
"fmt"
"go.uber.org/zap"
)
// InitLogger returns a logger
func InitLogger(level string) (logger *zap.Logger, err error) {
rawJSON := []byte(fmt.Sprintf(`{
"level": "%s",
"encoding": "json",
"outputPaths": ["stdout", "/tmp/logs"],
"errorOutputPaths": ["stderr"],
"encoderConfig": {
"messageKey": "message",
"levelKey": "level",
"levelEncoder": "lowercase"
}
}`, level))
var cfg zap.Config
if err = json.Unmarshal(rawJSON, &cfg); err == nil {
logger, err = cfg.Build()
}
return
}
package util
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("logger test", func() {
Context("InitLogger", func() {
It("basic test", func() {
logger, err := InitLogger("warn")
Expect(err).To(BeNil())
Expect(logger).NotTo(BeNil())
})
})
})
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册