Skip to content

Commit

Permalink
Inital import project
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen committed Dec 3, 2020
0 parents commit ad9ecd3
Show file tree
Hide file tree
Showing 16 changed files with 1,482 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Zhao Xiaojie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build:
go build ./pkg
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[![](https://goreportcard.com/badge/linuxsuren/go-cli-plugin)](https://goreportcard.com/report/linuxsuren/go-cli-plugin)
[![](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=flat-square)](https://godoc.org/github.com/linuxsuren/go-cli-plugin)
[![Contributors](https://img.shields.io/github/contributors/linuxsuren/go-cli-plugin.svg)](https://github.com/linuxsuren/go-cli-plugin/graphs/contributors)
[![GitHub release](https://img.shields.io/github/release/linuxsuren/go-cli-plugin.svg?label=release)](https://github.com/linuxsuren/go-cli-plugin/releases/latest)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/linuxsuren/go-cli-plugin)
[![HitCount](http://hits.dwyl.com/linuxsuren/go-cli-plugin.svg)](http://hits.dwyl.com/linuxsuren/go-cli-plugin)

This project aims to provide an easy way to let you writing a plugin for your CLI project.

# Original

This project originally comes from [jcli](https://github.com/linuxsuren/go-cli-plugin).
15 changes: 15 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module github.com/linuxsuren/go-cli-plugin

go 1.15

require (
github.com/gosuri/uiprogress v0.0.1
github.com/jenkins-zh/jenkins-cli v0.0.32
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.9.1
github.com/spf13/cobra v1.1.1
go.uber.org/zap v1.16.0
golang.org/x/crypto v0.0.0-20201124201722-c8d3bf9c5392
gopkg.in/src-d/go-git.v4 v4.13.1
gopkg.in/yaml.v2 v2.4.0
)
483 changes: 483 additions & 0 deletions go.sum

Large diffs are not rendered by default.

48 changes: 48 additions & 0 deletions pkg/cmd/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package config

import (
"github.com/linuxsuren/go-cli-plugin/pkg"
"github.com/spf13/cobra"
"strings"
)

// ValidPluginNames returns the valid plugin name list
func ValidPluginNames(cmd *cobra.Command, args []string, prefix string) (pluginNames []string, directive cobra.ShellCompDirective) {
directive = cobra.ShellCompDirectiveNoFileComp
if plugins, err := pkg.FindPlugins(); err == nil {
pluginNames = make([]string, 0)
for i := range plugins {
plugin := plugins[i]
name := plugin.Use

switch cmd.Use {
case "install":
if plugin.Installed {
continue
}
case "uninstall":
if !plugin.Installed {
continue
}
}

duplicated := false
for j := range args {
if name == args[j] {
duplicated = true
break
}
}

if !duplicated && strings.HasPrefix(name, prefix) {
pluginNames = append(pluginNames, name)
}
}
}
return
}

// NoFileCompletion avoid completion with files
func NoFileCompletion(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
}
121 changes: 121 additions & 0 deletions pkg/cmd/fetch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package config

import (
"fmt"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
gitssh "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
"io/ioutil"
"os"
"strings"
)

// NewConfigPluginFetchCmd create a command for fetching plugin metadata
func NewConfigPluginFetchCmd(pluginOrg, pluginRepo string) (cmd *cobra.Command) {
pluginFetchCmd := jcliPluginFetchCmd{
PluginOrg: pluginOrg,
PluginRepo: pluginRepo,
}

cmd = &cobra.Command{
Use: "fetch",
Short: "fetch metadata of plugins",
Long: fmt.Sprintf(`fetch metadata of plugins
The official metadata git repository is https://github.com/%s/%s,
but you can change it by giving a command parameter.`, pluginFetchCmd.PluginOrg, pluginFetchCmd.PluginRepo),
ValidArgsFunction: NoFileCompletion,
RunE: pluginFetchCmd.Run,
}

// add flags
flags := cmd.Flags()
flags.StringVarP(&pluginFetchCmd.PluginRepo, "plugin-repo", "",
fmt.Sprintf("https://github.com/%s/%s", pluginFetchCmd.PluginOrg, pluginFetchCmd.PluginRepo),
"The plugin git repository URL")
flags.BoolVarP(&pluginFetchCmd.Reset, "reset", "", true,
"If you want to reset the git local repo when pulling it")
flags.StringVarP(&pluginFetchCmd.Username, "username", "u", "",
"The username of git repository")
flags.StringVarP(&pluginFetchCmd.Password, "password", "p", "",
"The password of git repository")

sshKeyFile := fmt.Sprintf("%s/.ssh/id_rsa", os.Getenv("HOME"))
flags.StringVarP(&pluginFetchCmd.SSHKeyFile, "ssh-key-file", "", sshKeyFile,
"SSH key file")
return
}

// Run is the main entry point of plugin fetch command
func (c *jcliPluginFetchCmd) Run(cmd *cobra.Command, args []string) (err error) {
var userHome string
if userHome, err = homedir.Dir(); err != nil {
return
}

pluginRepo := fmt.Sprintf("%s/.jenkins-cli/plugins-repo", userHome)
c.output = cmd.OutOrStdout()

var r *git.Repository
if r, err = git.PlainOpen(pluginRepo); err == nil {
var w *git.Worktree
if w, err = r.Worktree(); err != nil {
return
}

if c.Reset {
if err = w.Reset(&git.ResetOptions{
Mode: git.HardReset,
}); err != nil {
return
}
}

err = w.Pull(c.getPullOptions())
if err == git.NoErrAlreadyUpToDate {
err = nil // consider it's ok
}
} else {
cloneOptions := c.getCloneOptions()
_, err = git.PlainClone(pluginRepo, false, cloneOptions)
}
return
}

func (c *jcliPluginFetchCmd) getCloneOptions() (cloneOptions *git.CloneOptions) {
cloneOptions = &git.CloneOptions{
URL: c.PluginRepo,
Progress: c.output,
Auth: c.getAuth(),
}
return
}

func (c *jcliPluginFetchCmd) getPullOptions() (pullOptions *git.PullOptions) {
pullOptions = &git.PullOptions{
RemoteName: "origin",
Progress: c.output,
Auth: c.getAuth(),
}
return
}

func (c *jcliPluginFetchCmd) getAuth() (auth transport.AuthMethod) {
if c.Username != "" {
auth = &githttp.BasicAuth{
Username: c.Username,
Password: c.Password,
}
}

if strings.HasPrefix(c.PluginRepo, "git@") {
if sshKey, err := ioutil.ReadFile(c.SSHKeyFile); err == nil {
signer, _ := ssh.ParsePrivateKey(sshKey)
auth = &gitssh.PublicKeys{User: "git", Signer: signer}
}
}
return
}
137 changes: 137 additions & 0 deletions pkg/cmd/install.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package config

import (
"archive/tar"
"compress/gzip"
"fmt"
"github.com/linuxsuren/go-cli-plugin/pkg"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
)

// NewConfigPluginInstallCmd create a command for fetching plugin metadata
func NewConfigPluginInstallCmd(pluginOrg, pluginRepo string) (cmd *cobra.Command) {
pluginInstallCmd := jcliPluginInstallCmd{
PluginOrg: pluginOrg,
PluginRepo: pluginRepo,
}

cmd = &cobra.Command{
Use: "install",
Short: "install a jcli plugin",
Long: "install a jcli plugin",
Args: cobra.MinimumNArgs(1),
ValidArgsFunction: ValidPluginNames,
RunE: pluginInstallCmd.Run,
}

// add flags
flags := cmd.Flags()
flags.BoolVarP(&pluginInstallCmd.ShowProgress, "show-progress", "", true,
"If you want to show the progress of download")
return
}

// Run main entry point for plugin install command
func (c *jcliPluginInstallCmd) Run(cmd *cobra.Command, args []string) (err error) {
name := args[0]
var userHome string
if userHome, err = homedir.Dir(); err != nil {
return
}

var data []byte
pluginsMetadataFile := fmt.Sprintf("%s/.jenkins-cli/plugins-repo/%s.yaml", userHome, name)
if data, err = ioutil.ReadFile(pluginsMetadataFile); err == nil {
plugin := pkg.Plugin{}
if err = yaml.Unmarshal(data, &plugin); err == nil {
err = c.download(plugin)
}
}

if err == nil {
cachedMetadataFile := pkg.GetJCLIPluginPath(userHome, name, true)
err = ioutil.WriteFile(cachedMetadataFile, data, 0664)
}
return
}

func (c *jcliPluginInstallCmd) download(plu pkg.Plugin) (err error) {
var userHome string
if userHome, err = homedir.Dir(); err != nil {
return
}

link := c.getDownloadLink(plu)
output := fmt.Sprintf("%s/.jenkins-cli/plugins/%s.tar.gz", userHome, plu.Main)

downloader := pkg.HTTPDownloader{
RoundTripper: c.RoundTripper,
TargetFilePath: output,
URL: link,
ShowProgress: c.ShowProgress,
}
if err = downloader.DownloadFile(); err == nil {
err = c.extractFiles(plu, output)
}
return
}

func (c *jcliPluginInstallCmd) getDownloadLink(plu pkg.Plugin) (link string) {
link = plu.DownloadLink
if link == "" {
operationSystem := runtime.GOOS
arch := runtime.GOARCH
link = fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/%s-%s-%s.tar.gz",
c.PluginOrg, plu.Main, plu.Version, plu.Main, operationSystem, arch)
}
return
}

func (c *jcliPluginInstallCmd) extractFiles(plugin pkg.Plugin, tarFile string) (err error) {
var f *os.File
var gzf *gzip.Reader
if f, err = os.Open(tarFile); err != nil {
return
}
defer f.Close()

if gzf, err = gzip.NewReader(f); err != nil {
return
}

tarReader := tar.NewReader(gzf)
var header *tar.Header
for {
if header, err = tarReader.Next(); err == io.EOF {
err = nil
break
} else if err != nil {
break
}
name := header.Name

switch header.Typeflag {
case tar.TypeReg:
if name != plugin.Main {
continue
}
var targetFile *os.File
if targetFile, err = os.OpenFile(fmt.Sprintf("%s/%s", filepath.Dir(tarFile), name),
os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)); err != nil {
break
}
if _, err = io.Copy(targetFile, tarReader); err != nil {
break
}
targetFile.Close()
}
}
return
}
32 changes: 32 additions & 0 deletions pkg/cmd/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package config

import (
"github.com/linuxsuren/go-cli-plugin/pkg"
"github.com/spf13/cobra"
)

// NewConfigPluginListCmd create a command for list all jcli plugins
func NewConfigPluginListCmd() (cmd *cobra.Command) {
configPluginListCmd := configPluginListCmd{}

cmd = &cobra.Command{
Use: "list",
Short: "List all installed plugins",
Long: "List all installed plugins",
RunE: configPluginListCmd.RunE,
ValidArgsFunction: NoFileCompletion,
}

configPluginListCmd.SetFlagWithHeaders(cmd, "Use,Version,Installed,DownloadLink")
return
}

// RunE is the main entry point of config plugin list command
func (c *configPluginListCmd) RunE(cmd *cobra.Command, args []string) (err error) {
c.Writer = cmd.OutOrStdout()
var plugins []pkg.Plugin
if plugins, err = pkg.FindPlugins(); err == nil {
err = c.OutputV2(plugins)
}
return
}
Loading

0 comments on commit ad9ecd3

Please sign in to comment.