-
Notifications
You must be signed in to change notification settings - Fork 4
/
root.go
182 lines (161 loc) · 5.52 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Copyright © 2017 Brian Ketelsen
//
// 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.
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/atotto/clipboard"
homedir "github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile, Alias, Channel, Event string
var baseURL string
var (
CommitHash string
BuildTime string
Tag string
)
type Submission struct {
URL string `json:"url"`
ShortCode string `json:"short_code"`
}
type Response struct {
URL string `json:"url"`
ShortCode string `json:"short_code"`
Error string `json:"error"`
}
const track = "?WT.mc_id"
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "cda URL SHORTCODE",
Short: "a URL Shortening service and corresponding command line tool",
Long: `cda is a URL shortening service that automatically appends
the appropriate tracking tags to a URL. The command line tool can be
used to submit a new link using personalized values.`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
err := submit(args[0], args[1])
if err != nil {
fmt.Println("Error: ", err)
}
},
}
func submit(url, shortCode string) error {
Alias = viper.GetString("alias")
Channel = viper.GetString("channel")
Event = viper.GetString("event")
if Alias == "" {
fmt.Println("Alias is required. Set with -a or in config file.")
return errors.New("Alias not provided.")
}
if Event == "" {
fmt.Println("Event is required. Set with -e or in config file.")
return errors.New("Event not provided.")
}
if Channel == "" {
fmt.Println("Channel is required. Set with -c or in config file.")
return errors.New("Channel not provided.")
}
reqURL := build(url)
// submit to server
fmt.Println("Submitting", url, "to", baseURL, "with shortcode", shortCode)
jsonValue, err := json.Marshal(Submission{ShortCode: shortCode, URL: reqURL})
if err != nil {
return errors.Wrap(err, "creating JSON")
}
resp, err := http.Post(baseURL+"/save", "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
return errors.Wrap(err, "posting to server")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var result Response
err = json.Unmarshal(body, &result)
if err != nil {
return errors.Wrap(err, "Unmarshaling result")
}
if resp.StatusCode != 200 {
return errors.New(result.Error)
}
fmt.Println(result.URL)
err = clipboard.WriteAll(result.URL)
if err != nil {
fmt.Println("Unable to insert into clipboard: ", err)
}
return nil
}
func build(url string) string {
return fmt.Sprintf("%s%s=%s-%s-%s", url, track, Event, Channel, Alias)
}
// Execute adds all child commands to the root command and 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)
if os.Getenv("BASE_URL") == "" {
baseURL = "cda.ms"
} else {
baseURL = os.Getenv("BASE_URL")
}
// 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/.cda.yaml)")
RootCmd.PersistentFlags().StringVar(&baseURL, "server", "http://cda.ms", "URL Shortening server")
RootCmd.PersistentFlags().StringVarP(&Alias, "alias", "a", "", "CDA Alias")
viper.BindPFlag("alias", RootCmd.PersistentFlags().Lookup("alias"))
RootCmd.PersistentFlags().StringVarP(&Event, "event", "e", "", "event")
viper.BindPFlag("event", RootCmd.PersistentFlags().Lookup("event"))
RootCmd.PersistentFlags().StringVarP(&Channel, "channel", "c", "", "channel")
viper.BindPFlag("channel", RootCmd.PersistentFlags().Lookup("channel"))
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".cda" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".cda")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}