Create and index gogs repos from da CLI.

This commit is contained in:
Mr. Is
2016-07-27 13:38:10 -04:00
commit 02b08974de
6 changed files with 511 additions and 0 deletions

52
cmd/config.go Normal file
View File

@ -0,0 +1,52 @@
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// configCmd represents the config command
var configCmd = &cobra.Command{
Use: "config",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
// TODO: Work your own magic here
fmt.Println("config called")
},
}
func init() {
RootCmd.AddCommand(configCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// configCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// configCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

134
cmd/repo.go Normal file
View File

@ -0,0 +1,134 @@
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var newRepo bool
var newOrgRepo bool
var repoName string
var orgName string
var path string
type repository struct {
Name string `json:"name"`
}
// repoCmd represents the repo command
var repoCmd = &cobra.Command{
Use: "repo",
Short: "Manage gogs repositories",
Long: `Supported operations are .`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Args: ", args)
if newRepo {
// create new repo
if len(args) == 0 { // testes || RotBlauer testes
// a name for the repo is required
fmt.Println("Please provide a name for your new repository.")
return
}
if !newOrgRepo {
// create repo for user
path = "/user/repos"
repoName = args[0]
} else {
// create repo for organization
if len(args) < 2 {
fmt.Println("Usage: [orgname] [reponame]")
return
}
path = "/org/" + args[0] + "/repos"
repoName = args[1]
}
repo := repository{
Name: repoName,
}
client := &http.Client{}
jsonString, _ := json.Marshal(repo)
req, _ := http.NewRequest("POST", viper.GetString("api_url")+path, bytes.NewBuffer(jsonString))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", ("token " + viper.GetString("token")))
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(body))
}
} else {
// get all repos owned by authenticated user
path = "/user/repos"
client := &http.Client{}
req, err := http.NewRequest("GET", viper.GetString("api_url")+path, nil)
req.Header.Set("Authorization", "token "+viper.GetString("token"))
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(body))
}
}
},
}
func init() {
RootCmd.AddCommand(repoCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// repoCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// repoCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
repoCmd.Flags().BoolVarP(&newRepo, "new", "n", false, "Create a new repository. A name is required.")
repoCmd.Flags().BoolVarP(&newOrgRepo, "org", "o", false, "Specify an organization you own.")
}

102
cmd/root.go Normal file
View File

@ -0,0 +1,102 @@
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var apiURL string
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "gogs",
Short: "Connect to the Gogs API.",
Long: `Welcome to the Gogs CLI.
You'll probably want a token for interacting with private data.
Visit your profile settings on Gogs and create a token, then stick it into
$HOME/.gogs-cli.yaml. While you're there you can adjust the default to your liking, too.`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
token := viper.GetString("token")
if token != "" {
fmt.Println("Token authentication enabled.")
} else {
fmt.Println("No token found.")
}
url := viper.GetString("api_url")
if url != "" {
fmt.Println("Using API url @ ", url)
} else {
fmt.Println("No API url coming through... uh oh.")
}
},
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gogs-cli.yaml)")
RootCmd.PersistentFlags().StringVar(&apiURL, "url", "", "api url should include /api/v1 path (default is try.gogs.io/api/v1)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
}
viper.SetConfigName(".gogs-cli") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
viper.SetDefault("api_url", "try.gogs.io/api/v1")
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
} else {
fmt.Println("No configuration file found.")
}
// if api_url was flagged, set it to that (override cfg)
if apiURL != "" {
viper.Set("api_url", apiURL)
}
}