diff --git a/README.md b/README.md index a345992..554a04c 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,7 @@ You can then configure the actions you want for each key: ```toml currency = "USD" defaultView = "" +api = "coingecko" [shortcuts] "$" = "last_page" @@ -502,12 +503,34 @@ Frequently asked questions: - Q: Where is the data from? - - A: Currently the data is from [CoinMarketCap](https://coinmarketcap.com/). + - A: By default, the data is from [CoinGecko](https://www.coingecko.com/). Data from [CoinMarketCap](https://coinmarketcap.com/) is another option. + +- Q: What APIs does it support? + + - A: APIs currently supported are [CoinMarketCap](https://coinmarketcap.com/) and [CoinGecko](https://www.coingecko.com/). - Q: What coins does this support? - A: This supports any coin supported by the API being used to fetch coin information. +- Q: How do I set the API to use? + + - A: You can use the `--api` flag, eg. `--api coingecko`. You can also set the API choice in the config file. + + ```toml + api = "coingecko" + ``` + + Options are: `coinmarketcap`, `coingecko` + +- Q: Where is the config file located? + + - A: The default configuration file is located under `~/.cointop/config` + +- Q: What format is the configuration file in? + + - A: The configuration file is in [TOML](https://en.wikipedia.org/wiki/TOML) format. + - Q: Will you be supporting more coin API's in the future? - A: Yes supporting more coin APIs is planned. @@ -558,14 +581,6 @@ Frequently asked questions: export PATH=$PATH:$GOPATH/bin ``` -- Q: Where is the config file located? - - - A: The default configuration file is located under `~/.cointop/config` - -- Q: What format is the configuration file in? - - - A: The configuration file is in [TOML](https://en.wikipedia.org/wiki/TOML) format. - - Q: How do I search? - A: The default key to open search is /. Type the search query after the `/` in the field and hit Enter. @@ -680,6 +695,8 @@ Frequently asked questions: The supported crypto currencies for conversion are `BTC` and `ETH`. + Please note that some APIs may have limited support for certain conversion formats. + - Q: How do I save the selected currency to convert to? - A: Press ctrl+s to save the selected currency to convert to. diff --git a/cmd/cointop.go b/cmd/cointop.go index ae1b668..62b40e7 100644 --- a/cmd/cointop.go +++ b/cmd/cointop.go @@ -10,7 +10,7 @@ import ( // Run ... func Run() { var v, ver, test, clean, reset bool - var config, cmcAPIKey string + var config, cmcAPIKey, apiChoice string flag.BoolVar(&v, "v", false, "Version") flag.BoolVar(&ver, "version", false, "Version") flag.BoolVar(&test, "test", false, "Run test") @@ -18,6 +18,7 @@ func Run() { flag.BoolVar(&reset, "reset", false, "Reset config") flag.StringVar(&config, "config", "", "Config filepath") flag.StringVar(&cmcAPIKey, "coinmarketcap-api-key", "", "CoinMarketCap API key") + flag.StringVar(&apiChoice, "api", cointop.CoinMarketCap, "API choice") flag.Parse() if v || ver { fmt.Printf("cointop v%s", cointop.Version()) @@ -31,6 +32,7 @@ func Run() { cointop.NewCointop(&cointop.Config{ ConfigFilepath: config, CoinMarketCapAPIKey: cmcAPIKey, + APIChoice: apiChoice, }).Run() } } diff --git a/cointop/api/coingecko/LICENSE.txt b/cointop/api/coingecko/LICENSE.txt new file mode 100644 index 0000000..0ce84ff --- /dev/null +++ b/cointop/api/coingecko/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright 2019 Lai Weng Han + +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. \ No newline at end of file diff --git a/cointop/api/coingecko/README.md b/cointop/api/coingecko/README.md new file mode 100644 index 0000000..3386ca8 --- /dev/null +++ b/cointop/api/coingecko/README.md @@ -0,0 +1 @@ +This is a fork diff --git a/cointop/api/coingecko/format/format.go b/cointop/api/coingecko/format/format.go new file mode 100644 index 0000000..cb2e500 --- /dev/null +++ b/cointop/api/coingecko/format/format.go @@ -0,0 +1,13 @@ +package format + +import "strconv" + +// Bool2String boolean to string +func Bool2String(b bool) string { + return strconv.FormatBool(b) +} + +// Int2String Integer to string +func Int2String(i int) string { + return strconv.Itoa(i) +} diff --git a/cointop/api/coingecko/v3/types/model.go b/cointop/api/coingecko/v3/types/model.go new file mode 100644 index 0000000..5e3daa6 --- /dev/null +++ b/cointop/api/coingecko/v3/types/model.go @@ -0,0 +1,259 @@ +package types + +// OrderType + +// OrderType in CoinGecko +type OrderType struct { + MarketCapDesc string + MarketCapAsc string + GeckoDesc string + GeckoAsc string + VolumeAsc string + VolumeDesc string +} + +// OrderTypeObject for certain order +var OrderTypeObject = &OrderType{ + MarketCapDesc: "market_cap_desc", + MarketCapAsc: "market_cap_asc", + GeckoDesc: "gecko_desc", + GeckoAsc: "gecko_asc", + VolumeAsc: "volume_asc", + VolumeDesc: "volume_desc", +} + +// PriceChangePercentage + +// PriceChangePercentage in different amount of time +type PriceChangePercentage struct { + PCP1h string + PCP24h string + PCP7d string + PCP14d string + PCP30d string + PCP200d string + PCP1y string +} + +// PriceChangePercentageObject for different amount of time +var PriceChangePercentageObject = &PriceChangePercentage{ + PCP1h: "1h", + PCP24h: "24h", + PCP7d: "7d", + PCP14d: "14d", + PCP30d: "30d", + PCP200d: "200d", + PCP1y: "1y", +} + +// SHARED +// coinBaseStruct [private] +type coinBaseStruct struct { + ID string `json:"id"` + Symbol string `json:"symbol"` + Name string `json:"name"` +} + +// AllCurrencies map all currencies (USD, BTC) to float64 +type AllCurrencies map[string]float64 + +// LocalizationItem map all locale (en, zh) into respective string +type LocalizationItem map[string]string + +// TYPES + +// DescriptionItem map all description (in locale) into respective string +type DescriptionItem map[string]string + +// LinksItem map all links +type LinksItem map[string]interface{} + +// ChartItem ... +type ChartItem [2]float32 + +// MarketDataItem map all market data item +type MarketDataItem struct { + CurrentPrice AllCurrencies `json:"current_price"` + ROI *ROIItem `json:"roi"` + ATH AllCurrencies `json:"ath"` + ATHChangePercentage AllCurrencies `json:"ath_change_percentage"` + ATHDate map[string]string `json:"ath_date"` + MarketCap AllCurrencies `json:"market_cap"` + MarketCapRank uint16 `json:"market_cap_rank"` + TotalVolume AllCurrencies `json:"total_volume"` + High24 AllCurrencies `json:"high_24h"` + Low24 AllCurrencies `json:"low_24h"` + PriceChange24h float64 `json:"price_change_24h"` + PriceChangePercentage24h float64 `json:"price_change_percentage_24h"` + PriceChangePercentage7d float64 `json:"price_change_percentage_7d"` + PriceChangePercentage14d float64 `json:"price_change_percentage_14d"` + PriceChangePercentage30d float64 `json:"price_change_percentage_30d"` + PriceChangePercentage60d float64 `json:"price_change_percentage_60d"` + PriceChangePercentage200d float64 `json:"price_change_percentage_200d"` + PriceChangePercentage1y float64 `json:"price_change_percentage_1y"` + MarketCapChange24h float64 `json:"market_cap_change_24h"` + MarketCapChangePercentage24h float64 `json:"market_cap_change_percentage_24h"` + PriceChange24hInCurrency AllCurrencies `json:"price_change_24h_in_currency"` + PriceChangePercentage1hInCurrency AllCurrencies `json:"price_change_percentage_1h_in_currency"` + PriceChangePercentage24hInCurrency AllCurrencies `json:"price_change_percentage_24h_in_currency"` + PriceChangePercentage7dInCurrency AllCurrencies `json:"price_change_percentage_7d_in_currency"` + PriceChangePercentage14dInCurrency AllCurrencies `json:"price_change_percentage_14d_in_currency"` + PriceChangePercentage30dInCurrency AllCurrencies `json:"price_change_percentage_30d_in_currency"` + PriceChangePercentage60dInCurrency AllCurrencies `json:"price_change_percentage_60d_in_currency"` + PriceChangePercentage200dInCurrency AllCurrencies `json:"price_change_percentage_200d_in_currency"` + PriceChangePercentage1yInCurrency AllCurrencies `json:"price_change_percentage_1y_in_currency"` + MarketCapChange24hInCurrency AllCurrencies `json:"market_cap_change_24h_in_currency"` + MarketCapChangePercentage24hInCurrency AllCurrencies `json:"market_cap_change_percentage_24h_in_currency"` + TotalSupply *float64 `json:"total_supply"` + CirculatingSupply float64 `json:"circulating_supply"` + Sparkline *SparklineItem `json:"sparkline_7d"` + LastUpdated string `json:"last_updated"` +} + +// CommunityDataItem map all community data item +type CommunityDataItem struct { + FacebookLikes *uint `json:"facebook_likes"` + TwitterFollowers *uint `json:"twitter_followers"` + RedditAveragePosts48h *float64 `json:"reddit_average_posts_48h"` + RedditAverageComments48h *float64 `json:"reddit_average_comments_48h"` + RedditSubscribers *uint `json:"reddit_subscribers"` + RedditAccountsActive48h *interface{} `json:"reddit_accounts_active_48h"` + TelegramChannelUserCount *uint `json:"telegram_channel_user_count"` +} + +// DeveloperDataItem map all developer data item +type DeveloperDataItem struct { + Forks *uint `json:"forks"` + Stars *uint `json:"stars"` + Subscribers *uint `json:"subscribers"` + TotalIssues *uint `json:"total_issues"` + ClosedIssues *uint `json:"closed_issues"` + PRMerged *uint `json:"pull_requests_merged"` + PRContributors *uint `json:"pull_request_contributors"` + CommitsCount4Weeks *uint `json:"commit_count_4_weeks"` +} + +// PublicInterestItem map all public interest item +type PublicInterestItem struct { + AlexaRank uint `json:"alexa_rank"` + BingMatches uint `json:"bing_matches"` +} + +// ImageItem struct for all sizes of image +type ImageItem struct { + Thumb string `json:"thumb"` + Small string `json:"small"` + Large string `json:"large"` +} + +// ROIItem ROI Item +type ROIItem struct { + Times float64 `json:"times"` + Currency string `json:"currency"` + Percentage float64 `json:"percentage"` +} + +// SparklineItem for sparkline +type SparklineItem struct { + Price []float64 `json:"price"` +} + +// TickerItem for ticker +type TickerItem struct { + Base string `json:"base"` + Target string `json:"target"` + Market struct { + Name string `json:"name"` + Identifier string `json:"identifier"` + TradingIncentive bool `json:"has_trading_incentive"` + } `json:"market"` + Last float64 `json:"last"` + ConvertedLast map[string]float64 `json:"converted_last"` + Volume float64 `json:"volume"` + ConvertedVolume map[string]float64 `json:"converted_volume"` + Timestamp string `json:"timestamp"` + IsAnomaly bool `json:"is_anomaly"` + IsStale bool `json:"is_stale"` + CoinID string `json:"coin_id"` +} + +// StatusUpdateItem for BEAM +type StatusUpdateItem struct { + Description string `json:"description"` + Category string `json:"category"` + CreatedAt string `json:"created_at"` + User string `json:"user"` + UserTitle string `json:"user_title"` + Pin bool `json:"pin"` + Project struct { + coinBaseStruct + Type string `json:"type"` + Image ImageItem `json:"image"` + } `json:"project"` +} + +// CoinsListItem item in CoinList +type CoinsListItem struct { + coinBaseStruct +} + +// CoinsMarketItem item in CoinMarket +type CoinsMarketItem struct { + coinBaseStruct + Image string `json:"image"` + CurrentPrice float64 `json:"current_price"` + MarketCap float64 `json:"market_cap"` + MarketCapRank int16 `json:"market_cap_rank"` + TotalVolume float64 `json:"total_volume"` + High24 float64 `json:"high_24h"` + Low24 float64 `json:"low_24h"` + PriceChange24h float64 `json:"price_change_24h"` + PriceChangePercentage24h float64 `json:"price_change_percentage_24h"` + MarketCapChange24h float64 `json:"market_cap_change_24h"` + MarketCapChangePercentage24h float64 `json:"market_cap_change_percentage_24h"` + CirculatingSupply float64 `json:"circulating_supply"` + TotalSupply float64 `json:"total_supply"` + ATH float64 `json:"ath"` + ATHChangePercentage float64 `json:"ath_change_percentage"` + ATHDate string `json:"ath_date"` + ROI *ROIItem `json:"roi"` + LastUpdated string `json:"last_updated"` + SparklineIn7d *SparklineItem `json:"sparkline_in_7d"` + PriceChangePercentage1hInCurrency *float64 `json:"price_change_percentage_1h_in_currency"` + PriceChangePercentage24hInCurrency *float64 `json:"price_change_percentage_24h_in_currency"` + PriceChangePercentage7dInCurrency *float64 `json:"price_change_percentage_7d_in_currency"` + PriceChangePercentage14dInCurrency *float64 `json:"price_change_percentage_14d_in_currency"` + PriceChangePercentage30dInCurrency *float64 `json:"price_change_percentage_30d_in_currency"` + PriceChangePercentage200dInCurrency *float64 `json:"price_change_percentage_200d_in_currency"` + PriceChangePercentage1yInCurrency *float64 `json:"price_change_percentage_1y_in_currency"` +} + +// EventCountryItem item in EventsCountries +type EventCountryItem struct { + Country string `json:"country"` + Code string `json:"code"` +} + +// ExchangeRatesItem item in ExchangeRate +type ExchangeRatesItem map[string]ExchangeRatesItemStruct + +// ExchangeRatesItemStruct struct in ExchangeRateItem +type ExchangeRatesItemStruct struct { + Name string `json:"name"` + Unit string `json:"unit"` + Value float64 `json:"value"` + Type string `json:"type"` +} + +// Global for data of /global +type Global struct { + ActiveCryptocurrencies uint16 `json:"active_cryptocurrencies"` + UpcomingICOs uint16 `json:"upcoming_icos"` + EndedICOs uint16 `json:"ended_icos"` + Markets uint16 `json:"markets"` + MarketCapChangePercentage24hUSD float32 `json:"market_cap_change_percentage_24h_usd"` + TotalMarketCap AllCurrencies `json:"total_market_cap"` + TotalVolume AllCurrencies `json:"total_volume"` + MarketCapPercentage AllCurrencies `json:"market_cap_percentage"` + UpdatedAt int64 `json:"updated_at"` +} diff --git a/cointop/api/coingecko/v3/types/types.go b/cointop/api/coingecko/v3/types/types.go new file mode 100644 index 0000000..eb8a97b --- /dev/null +++ b/cointop/api/coingecko/v3/types/types.go @@ -0,0 +1,127 @@ +package types + +// Ping https://api.coingecko.com/api/v3/ping +type Ping struct { + GeckoSays string `json:"gecko_says"` +} + +// SimpleSinglePrice https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd +type SimpleSinglePrice struct { + ID string + Currency string + MarketPrice float32 +} + +// SimpleSupportedVSCurrencies https://api.coingecko.com/api/v3/simple/supported_vs_currencies +type SimpleSupportedVSCurrencies []string + +// CoinList https://api.coingecko.com/api/v3/coins/list +type CoinList []CoinsListItem + +// CoinsMarket https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false +type CoinsMarket []CoinsMarketItem + +// CoinsID https://api.coingecko.com/api/v3/coins/bitcoin +type CoinsID struct { + coinBaseStruct + BlockTimeInMin int32 `json:"block_time_in_minutes"` + Categories []string `json:"categories"` + Localization LocalizationItem `json:"localization"` + Description DescriptionItem `json:"description"` + Links *LinksItem `json:"links"` + Image ImageItem `json:"image"` + CountryOrigin string `json:"country_origin"` + GenesisDate string `json:"genesis_date"` + MarketCapRank uint16 `json:"market_cap_rank"` + CoinGeckoRank uint16 `json:"coingecko_rank"` + CoinGeckoScore float32 `json:"coingecko_score"` + DeveloperScore float32 `json:"developer_score"` + CommunityScore float32 `json:"community_score"` + LiquidityScore float32 `json:"liquidity_score"` + PublicInterestScore float32 `json:"public_interest_score"` + MarketData *MarketDataItem `json:"market_data"` + CommunityData *CommunityDataItem `json:"community_data"` + DeveloperData *DeveloperDataItem `json:"developer_data"` + PublicInterestStats *PublicInterestItem `json:"public_interest_stats"` + StatusUpdates *[]StatusUpdateItem `json:"status_updates"` + LastUpdated string `json:"last_updated"` + Tickers *[]TickerItem `json:"tickers"` +} + +// CoinsIDTickers https://api.coingecko.com/api/v3/coins/steem/tickers?page=1 +type CoinsIDTickers struct { + Name string `json:"name"` + Tickers []TickerItem `json:"tickers"` +} + +// CoinsIDHistory https://api.coingecko.com/api/v3/coins/steem/history?date=30-12-2018 +type CoinsIDHistory struct { + coinBaseStruct + Localization LocalizationItem `json:"localization"` + Image ImageItem `json:"image"` + MarketData *MarketDataItem `json:"market_data"` + CommunityData *CommunityDataItem `json:"community_data"` + DeveloperData *DeveloperDataItem `json:"developer_data"` + PublicInterest *PublicInterestItem `json:"public_interest_stats"` +} + +// CoinsIDMarketChart https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1 +type CoinsIDMarketChart struct { + coinBaseStruct + Prices *[]ChartItem `json:"prices"` + MarketCaps *[]ChartItem `json:"market_caps"` + TotalVolumes *[]ChartItem `json:"total_volumes"` +} + +// CoinsIDStatusUpdates + +// CoinsIDContractAddress https://api.coingecko.com/api/v3/coins/{id}/contract/{contract_address} +// type CoinsIDContractAddress struct { +// ID string `json:"id"` +// Symbol string `json:"symbol"` +// Name string `json:"name"` +// BlockTimeInMin uint16 `json:"block_time_in_minutes"` +// Categories []string `json:"categories"` +// Localization LocalizationItem `json:"localization"` +// Description DescriptionItem `json:"description"` +// Links LinksItem `json:"links"` +// Image ImageItem `json:"image"` +// CountryOrigin string `json:"country_origin"` +// GenesisDate string `json:"genesis_date"` +// ContractAddress string `json:"contract_address"` +// MarketCapRank uint16 `json:"market_cap_rank"` +// CoinGeckoRank uint16 `json:"coingecko_rank"` +// CoinGeckoScore float32 `json:"coingecko_score"` +// DeveloperScore float32 `json:"developer_score"` +// CommunityScore float32 `json:"community_score"` +// LiquidityScore float32 `json:"liquidity_score"` +// PublicInterestScore float32 `json:"public_interest_score"` +// MarketData `json:"market_data"` +// } + +// EventsCountries https://api.coingecko.com/api/v3/events/countries +type EventsCountries struct { + Data []EventCountryItem `json:"data"` +} + +// EventsTypes https://api.coingecko.com/api/v3/events/types +type EventsTypes struct { + Data []string `json:"data"` + Count uint16 `json:"count"` +} + +// ExchangeRatesResponse https://api.coingecko.com/api/v3/exchange_rates +type ExchangeRatesResponse struct { + Rates ExchangeRatesItem `json:"rates"` +} + +// GlobalResponse https://api.coingecko.com/api/v3/global +type GlobalResponse struct { + Data Global `json:"data"` +} + +// GlobalCharts ... +type GlobalCharts struct { + Stats *[]ChartItem `json:"stats"` + TotalVolumes *[]ChartItem `json:"total_volumes"` +} diff --git a/cointop/api/coingecko/v3/v3.go b/cointop/api/coingecko/v3/v3.go new file mode 100644 index 0000000..1b67e80 --- /dev/null +++ b/cointop/api/coingecko/v3/v3.go @@ -0,0 +1,385 @@ +// Package coingecko is forked from https://github.com/superoo7/go-gecko +package coingecko + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "log" + "net/http" + "net/url" + "strings" + + "github.com/miguelmota/cointop/cointop/api/coingecko/format" + "github.com/miguelmota/cointop/cointop/api/coingecko/v3/types" +) + +var baseURL = "https://api.coingecko.com/api/v3" + +// Client struct +type Client struct { + httpClient *http.Client +} + +// NewClient create new client object +func NewClient(httpClient *http.Client) *Client { + if httpClient == nil { + httpClient = http.DefaultClient + } + return &Client{httpClient: httpClient} +} + +// helper +// doReq HTTP client +func doReq(req *http.Request, client *http.Client) ([]byte, error) { + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + if 200 != resp.StatusCode { + return nil, fmt.Errorf("%s", body) + } + return body, nil +} + +// MakeReq HTTP request helper +func (c *Client) MakeReq(url string) ([]byte, error) { + req, err := http.NewRequest("GET", url, nil) + + if err != nil { + return nil, err + } + resp, err := doReq(req, c.httpClient) + if err != nil { + return nil, err + } + return resp, err +} + +// API + +// Ping /ping endpoint +func (c *Client) Ping() (*types.Ping, error) { + url := fmt.Sprintf("%s/ping", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.Ping + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// SimpleSinglePrice /simple/price Single ID and Currency (ids, vsCurrency) +func (c *Client) SimpleSinglePrice(id string, vsCurrency string) (*types.SimpleSinglePrice, error) { + idParam := []string{strings.ToLower(id)} + vcParam := []string{strings.ToLower(vsCurrency)} + + t, err := c.SimplePrice(idParam, vcParam) + if err != nil { + return nil, err + } + curr := (*t)[id] + data := &types.SimpleSinglePrice{ID: id, Currency: vsCurrency, MarketPrice: curr[vsCurrency]} + return data, nil +} + +// SimplePrice /simple/price Multiple ID and Currency (ids, vs_currencies) +func (c *Client) SimplePrice(ids []string, vsCurrencies []string) (*map[string]map[string]float32, error) { + params := url.Values{} + idsParam := strings.Join(ids[:], ",") + vsCurrenciesParam := strings.Join(vsCurrencies[:], ",") + + params.Add("ids", idsParam) + params.Add("vs_currencies", vsCurrenciesParam) + + url := fmt.Sprintf("%s/simple/price?%s", baseURL, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + + t := make(map[string]map[string]float32) + err = json.Unmarshal(resp, &t) + if err != nil { + return nil, err + } + + return &t, nil +} + +// SimpleSupportedVSCurrencies /simple/supported_vs_currencies +func (c *Client) SimpleSupportedVSCurrencies() (*types.SimpleSupportedVSCurrencies, error) { + url := fmt.Sprintf("%s/simple/supported_vs_currencies", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.SimpleSupportedVSCurrencies + err = json.Unmarshal(resp, &data) + return data, nil +} + +// CoinsList /coins/list +func (c *Client) CoinsList() (*types.CoinList, error) { + url := fmt.Sprintf("%s/coins/list", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + + var data *types.CoinList + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// CoinsMarket /coins/market +func (c *Client) CoinsMarket(vsCurrency string, ids []string, order string, perPage int, page int, sparkline bool, priceChangePercentage []string) (*types.CoinsMarket, error) { + if len(vsCurrency) == 0 { + return nil, fmt.Errorf("vsCurrency is required") + } + params := url.Values{} + // vsCurrency + params.Add("vs_currency", vsCurrency) + // order + if len(order) == 0 { + order = types.OrderTypeObject.MarketCapDesc + } + params.Add("order", order) + // ids + if len(ids) != 0 { + idsParam := strings.Join(ids[:], ",") + params.Add("ids", idsParam) + } + // per_page + if perPage <= 0 || perPage > 250 { + perPage = 100 + } + params.Add("per_page", format.Int2String(perPage)) + params.Add("page", format.Int2String(page)) + // sparkline + params.Add("sparkline", format.Bool2String(sparkline)) + // price_change_percentage + if len(priceChangePercentage) != 0 { + priceChangePercentageParam := strings.Join(priceChangePercentage[:], ",") + params.Add("price_change_percentage", priceChangePercentageParam) + } + url := fmt.Sprintf("%s/coins/markets?%s", baseURL, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.CoinsMarket + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// CoinsID /coins/{id} +func (c *Client) CoinsID(id string, localization bool, tickers bool, marketData bool, communityData bool, developerData bool, sparkline bool) (*types.CoinsID, error) { + + if len(id) == 0 { + return nil, fmt.Errorf("id is required") + } + params := url.Values{} + params.Add("localization", format.Bool2String(sparkline)) + params.Add("tickers", format.Bool2String(tickers)) + params.Add("market_data", format.Bool2String(marketData)) + params.Add("community_data", format.Bool2String(communityData)) + params.Add("developer_data", format.Bool2String(developerData)) + params.Add("sparkline", format.Bool2String(sparkline)) + url := fmt.Sprintf("%s/coins/%s?%s", baseURL, id, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + + var data *types.CoinsID + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// CoinsIDTickers /coins/{id}/tickers +func (c *Client) CoinsIDTickers(id string, page int) (*types.CoinsIDTickers, error) { + if len(id) == 0 { + return nil, fmt.Errorf("id is required") + } + params := url.Values{} + if page > 0 { + params.Add("page", format.Int2String(page)) + } + url := fmt.Sprintf("%s/coins/%s/tickers?%s", baseURL, id, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.CoinsIDTickers + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// CoinsIDHistory /coins/{id}/history?date={date}&localization=false +func (c *Client) CoinsIDHistory(id string, date string, localization bool) (*types.CoinsIDHistory, error) { + if len(id) == 0 || len(date) == 0 { + return nil, fmt.Errorf("id and date is required") + } + params := url.Values{} + params.Add("date", date) + params.Add("localization", format.Bool2String(localization)) + + url := fmt.Sprintf("%s/coins/%s/history?%s", baseURL, id, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.CoinsIDHistory + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil +} + +// CoinsIDMarketChart /coins/{id}/market_chart?vsCurrency={usd, eur, jpy, etc.}&days={1,14,30,max} +func (c *Client) CoinsIDMarketChart(id string, vsCurrency string, days string) (*types.CoinsIDMarketChart, error) { + if len(id) == 0 || len(vsCurrency) == 0 || len(days) == 0 { + return nil, fmt.Errorf("id, vsCurrency, and days is required") + } + + params := url.Values{} + params.Add("vs_currency", vsCurrency) + params.Add("days", days) + + url := fmt.Sprintf("%s/coins/%s/market_chart?%s", baseURL, id, params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + + m := types.CoinsIDMarketChart{} + err = json.Unmarshal(resp, &m) + if err != nil { + return &m, err + } + + return &m, nil +} + +// CoinsIDStatusUpdates + +// CoinsIDContractAddress https://api.coingecko.com/api/v3/coins/{id}/contract/{contract_address} +// func CoinsIDContractAddress(id string, address string) (nil, error) { +// url := fmt.Sprintf("%s/coins/%s/contract/%s", baseURL, id, address) +// resp, err := request.MakeReq(url) +// if err != nil { +// return nil, err +// } +// } + +// EventsCountries https://api.coingecko.com/api/v3/events/countries +func (c *Client) EventsCountries() ([]types.EventCountryItem, error) { + url := fmt.Sprintf("%s/events/countries", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.EventsCountries + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data.Data, nil + +} + +// EventsTypes https://api.coingecko.com/api/v3/events/types +func (c *Client) EventsTypes() (*types.EventsTypes, error) { + url := fmt.Sprintf("%s/events/types", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.EventsTypes + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return data, nil + +} + +// ExchangeRates https://api.coingecko.com/api/v3/exchange_rates +func (c *Client) ExchangeRates() (*types.ExchangeRatesItem, error) { + url := fmt.Sprintf("%s/exchange_rates", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.ExchangeRatesResponse + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return &data.Rates, nil +} + +// Global https://api.coingecko.com/api/v3/global +func (c *Client) Global() (*types.Global, error) { + url := fmt.Sprintf("%s/global", baseURL) + resp, err := c.MakeReq(url) + if err != nil { + return nil, err + } + var data *types.GlobalResponse + err = json.Unmarshal(resp, &data) + if err != nil { + return nil, err + } + return &data.Data, nil +} + +// GlobalCharts https://www.coingecko.com/market_cap/total_charts_data?duration=7&locale=en&vs_currency=usd +func (c *Client) GlobalCharts(vsCurrency string, days string) (*types.GlobalCharts, error) { + if len(vsCurrency) == 0 || len(days) == 0 { + return nil, fmt.Errorf("vsCurrency, and days is required") + } + + params := url.Values{} + params.Add("locale", "en") + params.Add("vs_currency", vsCurrency) + params.Add("duration", days) + + url := fmt.Sprintf("https://www.coingecko.com/market_cap/total_charts_data?%s", params.Encode()) + resp, err := c.MakeReq(url) + if err != nil { + log.Fatal(err) + return nil, err + } + + m := types.GlobalCharts{} + err = json.Unmarshal(resp, &m) + if err != nil { + return &m, err + } + + return &m, nil +} diff --git a/cointop/cache.go b/cointop/cache.go new file mode 100644 index 0000000..d869a66 --- /dev/null +++ b/cointop/cache.go @@ -0,0 +1,10 @@ +package cointop + +import ( + "fmt" + "strings" +) + +func (ct *Cointop) cacheKey(key string) string { + return strings.ToLower(fmt.Sprintf("%s_%s", ct.apiChoice, key)) +} diff --git a/cointop/chart.go b/cointop/chart.go index 3f6b9c9..a75231d 100644 --- a/cointop/chart.go +++ b/cointop/chart.go @@ -24,8 +24,9 @@ func (ct *Cointop) updateChart() error { return err } } else { - coin := ct.selectedCoinSymbol() - ct.chartPoints(coin) + symbol := ct.selectedCoinSymbol() + name := ct.selectedCoinName() + ct.chartPoints(symbol, name) } if len(ct.chartpoints) != 0 { @@ -52,7 +53,7 @@ func (ct *Cointop) updateChart() error { return nil } -func (ct *Cointop) chartPoints(coin string) error { +func (ct *Cointop) chartPoints(symbol string, name string) error { maxX := ct.maxtablewidth - 3 chartpointslock.Lock() defer chartpointslock.Unlock() @@ -78,11 +79,11 @@ func (ct *Cointop) chartPoints(coin string) error { var data []float64 - keyname := coin + keyname := symbol if keyname == "" { keyname = "globaldata" } - cachekey := strings.ToLower(fmt.Sprintf("%s_%s", keyname, strings.Replace(ct.selectedchartrange, " ", "", -1))) + cachekey := ct.cacheKey(fmt.Sprintf("%s_%s", keyname, strings.Replace(ct.selectedchartrange, " ", "", -1))) cached, found := ct.cache.Get(cachekey) if found { @@ -92,7 +93,7 @@ func (ct *Cointop) chartPoints(coin string) error { } if len(data) == 0 { - if coin == "" { + if symbol == "" { graphData, err := ct.api.GetGlobalMarketGraphData(start, end) if err != nil { return nil @@ -102,7 +103,7 @@ func (ct *Cointop) chartPoints(coin string) error { data = append(data, price/1E9) } } else { - graphData, err := ct.api.GetCoinGraphData(coin, start, end) + graphData, err := ct.api.GetCoinGraphData(symbol, name, start, end) if err != nil { return nil } @@ -188,8 +189,7 @@ func (ct *Cointop) portfolioChart() error { } var graphData []float64 - coin := p.Symbol - cachekey := strings.ToLower(fmt.Sprintf("%s_%s", coin, strings.Replace(ct.selectedchartrange, " ", "", -1))) + cachekey := strings.ToLower(fmt.Sprintf("%s_%s", p.Symbol, strings.Replace(ct.selectedchartrange, " ", "", -1))) cached, found := ct.cache.Get(cachekey) if found { // cache hit @@ -200,7 +200,7 @@ func (ct *Cointop) portfolioChart() error { if len(graphData) == 0 { time.Sleep(2 * time.Second) - apiGraphData, err := ct.api.GetCoinGraphData(coin, start, end) + apiGraphData, err := ct.api.GetCoinGraphData(p.Symbol, p.Name, start, end) if err != nil { return err } diff --git a/cointop/cointop.go b/cointop/cointop.go index 8c6b45b..f6378e0 100644 --- a/cointop/cointop.go +++ b/cointop/cointop.go @@ -1,6 +1,7 @@ package cointop import ( + "errors" "fmt" "io/ioutil" "os" @@ -20,9 +21,13 @@ import ( // TODO: clean up and optimize codebase +// ErrInvalidAPIChoice is error for invalid API choice +var ErrInvalidAPIChoice = errors.New("Invalid API choice") + // Cointop cointop type Cointop struct { g *gocui.Gui + apiChoice string marketbarviewname string marketbarview *gocui.View chartview *gocui.View @@ -45,15 +50,15 @@ type Cointop struct { sortdesc bool sortby string api api.Interface - allcoins []*coin - coins []*coin - allcoinsslugmap map[string]*coin + allcoins []*Coin + coins []*Coin + allcoinsslugmap map[string]*Coin page int perpage int refreshmux sync.Mutex refreshticker *time.Ticker forcerefresh chan bool - selectedcoin *coin + selectedcoin *Coin actionsmap map[string]bool shortcutkeys map[string]string config config // toml config @@ -61,8 +66,10 @@ type Cointop struct { searchfield *gocui.View searchfieldviewname string searchfieldvisible bool + // DEPRECATED: favorites by 'symbol' is deprecated because of collisions. - favoritesbysymbol map[string]bool + favoritesbysymbol map[string]bool + favorites map[string]bool filterByFavorites bool savemux sync.Mutex @@ -86,6 +93,12 @@ type Cointop struct { limiter <-chan time.Time } +// CoinMarketCap is API choice +var CoinMarketCap = "coinmarketcap" + +// CoinGecko is API choice +var CoinGecko = "coingecko" + // PortfolioEntry is portfolio entry type portfolioEntry struct { Coin string @@ -99,6 +112,7 @@ type portfolio struct { // Config config options type Config struct { + APIChoice string ConfigFilepath string CoinMarketCapAPIKey string NoPrompts bool @@ -126,8 +140,9 @@ func NewCointop(config *Config) *Cointop { } ct := &Cointop{ - allcoinsslugmap: make(map[string]*coin), - allcoins: []*coin{}, + apiChoice: CoinGecko, + allcoinsslugmap: make(map[string]*Coin), + allcoins: []*Coin{}, refreshticker: time.NewTicker(1 * time.Minute), sortby: "rank", page: 0, @@ -216,7 +231,14 @@ func NewCointop(config *Config) *Cointop { } } - if ct.apiKeys.cmc == "" { + if config.APIChoice != "" { + ct.apiChoice = config.APIChoice + if err := ct.saveConfig(); err != nil { + log.Fatal(err) + } + } + + if ct.apiChoice == CoinMarketCap && ct.apiKeys.cmc == "" { apiKey := os.Getenv("CMC_PRO_API_KEY") if apiKey == "" { if !config.NoPrompts { @@ -230,9 +252,19 @@ func NewCointop(config *Config) *Cointop { } } - ct.api = api.NewCMC(ct.apiKeys.cmc) + if ct.apiChoice == CoinGecko { + ct.selectedchartrange = "1Y" + } + + if ct.apiChoice == CoinMarketCap { + ct.api = api.NewCMC(ct.apiKeys.cmc) + } else if ct.apiChoice == CoinGecko { + ct.api = api.NewCG() + } else { + log.Fatal(ErrInvalidAPIChoice) + } - coinscachekey := "allcoinsslugmap" + coinscachekey := ct.cacheKey("allcoinsslugmap") filecache.Get(coinscachekey, &ct.allcoinsslugmap) for k := range ct.allcoinsslugmap { @@ -260,18 +292,21 @@ func NewCointop(config *Config) *Cointop { } var globaldata []float64 - chartcachekey := strings.ToLower(fmt.Sprintf("%s_%s", "globaldata", strings.Replace(ct.selectedchartrange, " ", "", -1))) + chartcachekey := ct.cacheKey(fmt.Sprintf("%s_%s", "globaldata", strings.Replace(ct.selectedchartrange, " ", "", -1))) filecache.Get(chartcachekey, &globaldata) ct.cache.Set(chartcachekey, globaldata, 10*time.Second) var market types.GlobalMarketData - marketcachekey := "market" + marketcachekey := ct.cacheKey("market") filecache.Get(marketcachekey, &market) ct.cache.Set(marketcachekey, market, 10*time.Second) - err = ct.api.Ping() - if err != nil { - log.Fatal(err) - } + + // TODO: notify offline status in status bar + /* + if err := ct.api.Ping(); err != nil { + log.Fatal(err) + } + */ return ct } diff --git a/cointop/common/api/api.go b/cointop/common/api/api.go index 87e3b54..55bc781 100644 --- a/cointop/common/api/api.go +++ b/cointop/common/api/api.go @@ -1,12 +1,13 @@ package api import ( + cg "github.com/miguelmota/cointop/cointop/common/api/impl/coingecko" cmc "github.com/miguelmota/cointop/cointop/common/api/impl/coinmarketcap" ) // NewCMC new CoinMarketCap API func NewCMC(apiKey string) Interface { - return cmc.New(apiKey) + return cmc.NewCMC(apiKey) } // NewCC new CryptoCompare API @@ -15,6 +16,6 @@ func NewCC() { } // NewCG new CoinGecko API -func NewCG() { - // TODO +func NewCG() Interface { + return cg.NewCoinGecko() } diff --git a/cointop/common/api/impl/coingecko/coingecko.go b/cointop/common/api/impl/coingecko/coingecko.go index 4d1dfc3..a0f8cf0 100644 --- a/cointop/common/api/impl/coingecko/coingecko.go +++ b/cointop/common/api/impl/coingecko/coingecko.go @@ -1,3 +1,269 @@ package coingecko -// TODO +import ( + "errors" + "fmt" + "strconv" + "strings" + "time" + + gecko "github.com/miguelmota/cointop/cointop/api/coingecko/v3" + geckoTypes "github.com/miguelmota/cointop/cointop/api/coingecko/v3/types" + apitypes "github.com/miguelmota/cointop/cointop/common/api/types" + util "github.com/miguelmota/cointop/cointop/common/api/util" +) + +// ErrPingFailed is the error for when pinging the API fails +var ErrPingFailed = errors.New("Failed to ping") + +// Service service +type Service struct { + client *gecko.Client +} + +// NewCoinGecko new service +func NewCoinGecko() *Service { + client := gecko.NewClient(nil) + return &Service{ + client: client, + } +} + +// Ping ping API +func (s *Service) Ping() error { + if _, err := s.client.Ping(); err != nil { + return err + } + + return nil +} + +func (s *Service) getLimitedCoinData(convert string, offset int) ([]apitypes.Coin, error) { + var ret []apitypes.Coin + ids := []string{} + perPage := 250 + page := offset + sparkline := false + pcp := geckoTypes.PriceChangePercentageObject + priceChangePercentage := []string{pcp.PCP1h, pcp.PCP24h, pcp.PCP7d} + order := geckoTypes.OrderTypeObject.MarketCapDesc + convertTo := strings.ToLower(convert) + if convertTo == "" { + convertTo = "usd" + } + list, err := s.client.CoinsMarket(convertTo, ids, order, perPage, page, sparkline, priceChangePercentage) + if err != nil { + return nil, err + } + + if list != nil { + for _, item := range *list { + var percentChange1H float64 + var percentChange24H float64 + var percentChange7D float64 + + if item.PriceChangePercentage1hInCurrency != nil { + percentChange1H = *item.PriceChangePercentage1hInCurrency + } + + if item.PriceChangePercentage24hInCurrency != nil { + percentChange24H = *item.PriceChangePercentage24hInCurrency + } + + if item.PriceChangePercentage7dInCurrency != nil { + percentChange7D = *item.PriceChangePercentage7dInCurrency + } + + availableSupply := item.CirculatingSupply + totalSupply := item.TotalSupply + if totalSupply == 0 { + totalSupply = availableSupply + } + + ret = append(ret, apitypes.Coin{ + ID: util.FormatID(item.ID), + Name: util.FormatName(item.Name), + Symbol: util.FormatSymbol(item.Symbol), + Rank: util.FormatRank(item.MarketCapRank), + AvailableSupply: util.FormatSupply(availableSupply), + TotalSupply: util.FormatSupply(totalSupply), + MarketCap: util.FormatMarketCap(item.MarketCap), + Price: util.FormatPrice(item.CurrentPrice, convert), + PercentChange1H: util.FormatPercentChange(percentChange1H), + PercentChange24H: util.FormatPercentChange(percentChange24H), + PercentChange7D: util.FormatPercentChange(percentChange7D), + Volume24H: util.FormatVolume(item.TotalVolume), + LastUpdated: util.FormatLastUpdated(item.LastUpdated), + }) + } + } + + return ret, nil +} + +// GetAllCoinData gets all coin data. Need to paginate through all pages +func (s *Service) GetAllCoinData(convert string, ch chan []apitypes.Coin) error { + go func() { + maxPages := 5 + defer close(ch) + for i := 0; i < maxPages; i++ { + if i > 0 { + time.Sleep(1 * time.Second) + } + coins, err := s.getLimitedCoinData(convert, i) + if err != nil { + return + } + ch <- coins + } + }() + return nil +} + +// GetCoinGraphData gets coin graph data +func (s *Service) GetCoinGraphData(symbol, name string, start, end int64) (apitypes.CoinGraph, error) { + ret := apitypes.CoinGraph{} + days := strconv.Itoa(util.CalcDays(start, end)) + chart, err := s.client.CoinsIDMarketChart(strings.ToLower(name), "usd", days) + if err != nil { + return ret, err + } + + var marketCap [][]float64 + var priceUSD [][]float64 + var priceBTC [][]float64 + var volumeUSD [][]float64 + + if chart.Prices != nil { + for _, item := range *chart.Prices { + priceUSD = append(priceUSD, []float64{ + float64(item[0]), + float64(item[1]), + }) + } + } + + ret.MarketCapByAvailableSupply = marketCap + ret.PriceBTC = priceBTC + ret.PriceUSD = priceUSD + ret.VolumeUSD = volumeUSD + + return ret, nil +} + +// GetGlobalMarketGraphData gets global market graph data +func (s *Service) GetGlobalMarketGraphData(start int64, end int64) (apitypes.MarketGraph, error) { + days := strconv.Itoa(util.CalcDays(start, end)) + ret := apitypes.MarketGraph{} + graphData, err := s.client.GlobalCharts("usd", days) + if err != nil { + return ret, err + } + + var marketCapUSD [][]float64 + var marketVolumeUSD [][]float64 + if graphData.Stats != nil { + for _, item := range *graphData.Stats { + marketCapUSD = append(marketCapUSD, []float64{ + float64(item[0]), + float64(item[1]), + }) + } + } + + ret.MarketCapByAvailableSupply = marketCapUSD + ret.VolumeUSD = marketVolumeUSD + return ret, nil +} + +// GetGlobalMarketData gets global market data +func (s *Service) GetGlobalMarketData(convert string) (apitypes.GlobalMarketData, error) { + ret := apitypes.GlobalMarketData{} + market, err := s.client.Global() + if err != nil { + return ret, err + } + + var totalMarketCap float64 + for _, value := range market.TotalMarketCap { + totalMarketCap += value + } + + var totalVolume float64 + for _, value := range market.TotalVolume { + totalVolume += value + } + + btcDominance := market.MarketCapPercentage["btc"] + + ret = apitypes.GlobalMarketData{ + TotalMarketCapUSD: totalMarketCap, + Total24HVolumeUSD: totalVolume, + BitcoinPercentageOfMarketCap: btcDominance, + ActiveCurrencies: int(market.ActiveCryptocurrencies), + ActiveAssets: 0, + ActiveMarkets: int(market.Markets), + } + return ret, nil +} + +// CoinLink returns the URL link for the coin +func (s *Service) CoinLink(name string) string { + slug := util.NameToSlug(name) + return fmt.Sprintf("https://www.coingecko.com/en/coins/%s", slug) +} + +// SupportedCurrencies returns a list of supported currencies +func (s *Service) SupportedCurrencies() []string { + return []string{ + "BTC", + "ETH", + "BNB", + "EOS", + "USD", + "AED", + "ARS", + "AUD", + "BDT", + "BHD", + "BMD", + "BRL", + "CAD", + "CHF", + "CLP", + "CNY", + "CZK", + "DKK", + "EUR", + "GBP", + "HKD", + "HUF", + "IDR", + "ILS", + "INR", + "JPY", + "KRW", + "KWD", + "LKR", + "MMK", + "MXN", + "MYR", + "NOK", + "NZD", + "PHP", + "PKR", + "PLN", + "RUB", + "SAR", + "SEK", + "SGD", + "THB", + "TRY", + "TWD", + "VEF", + "VND", + "ZAR", + "XDR", + "XAG", + } +} diff --git a/cointop/common/api/impl/coinmarketcap/coinmarketcap.go b/cointop/common/api/impl/coinmarketcap/coinmarketcap.go index 7dca567..520b6cd 100644 --- a/cointop/common/api/impl/coinmarketcap/coinmarketcap.go +++ b/cointop/common/api/impl/coinmarketcap/coinmarketcap.go @@ -1,24 +1,30 @@ package coinmarketcap import ( + "errors" "fmt" "os" - "strconv" - "strings" "time" apitypes "github.com/miguelmota/cointop/cointop/common/api/types" + util "github.com/miguelmota/cointop/cointop/common/api/util" cmc "github.com/miguelmota/go-coinmarketcap/pro/v1" cmcv2 "github.com/miguelmota/go-coinmarketcap/v2" ) +// ErrQuoteNotFound is the error for when a quote is not found +var ErrQuoteNotFound = errors.New("Quote not found") + +// ErrPingFailed is the error for when pinging the API fails +var ErrPingFailed = errors.New("Failed to ping") + // Service service type Service struct { client *cmc.Client } -// New new service -func New(apiKey string) *Service { +// NewCMC new service +func NewCMC(apiKey string) *Service { if apiKey == "" { apiKey = os.Getenv("CMC_PRO_API_KEY") } @@ -32,23 +38,20 @@ func New(apiKey string) *Service { // Ping ping API func (s *Service) Ping() error { - // TODO: notify in statusbar of failed ping (instead of fatal to make it work offline) - /* - info, err := s.client.Cryptocurrency.Info(&cmc.InfoOptions{ - Symbol: "BTC", - }) - if err != nil { - return errors.New("failed to ping") - } - if info == nil { - return errors.New("failed to ping") - } - */ + info, err := s.client.Cryptocurrency.Info(&cmc.InfoOptions{ + Symbol: "BTC", + }) + if err != nil { + return ErrPingFailed + } + if info == nil { + return ErrPingFailed + } return nil } -func (s *Service) getLimitedCoinData(convert string, offset int) (map[string]apitypes.Coin, error) { - ret := make(map[string]apitypes.Coin) +func (s *Service) getLimitedCoinData(convert string, offset int) ([]apitypes.Coin, error) { + var ret []apitypes.Coin max := 100 listings, err := s.client.Cryptocurrency.LatestListings(&cmc.ListingOptions{ @@ -60,32 +63,32 @@ func (s *Service) getLimitedCoinData(convert string, offset int) (map[string]api return nil, err } for _, v := range listings { - price := formatPrice(v.Quote[convert].Price, convert) - lastUpdated, err := time.Parse(time.RFC3339, v.LastUpdated) - if err != nil { - return nil, err - } - ret[v.Name] = apitypes.Coin{ - ID: strings.ToLower(v.Name), - Name: v.Name, - Symbol: v.Symbol, - Rank: int(v.CMCRank), - AvailableSupply: v.CirculatingSupply, - TotalSupply: v.TotalSupply, - MarketCap: float64(int(v.Quote[convert].MarketCap)), - Price: price, - PercentChange1H: v.Quote[convert].PercentChange1H, - PercentChange24H: v.Quote[convert].PercentChange24H, - PercentChange7D: v.Quote[convert].PercentChange7D, - Volume24H: formatVolume(v.Quote[convert].Volume24H), - LastUpdated: strconv.Itoa(int(lastUpdated.Unix())), + quote, ok := v.Quote[convert] + if !ok { + return nil, ErrQuoteNotFound } + + ret = append(ret, apitypes.Coin{ + ID: util.FormatID(v.Name), + Name: util.FormatName(v.Name), + Symbol: util.FormatSymbol(v.Symbol), + Rank: util.FormatRank(v.CMCRank), + AvailableSupply: util.FormatSupply(v.CirculatingSupply), + TotalSupply: util.FormatSupply(v.TotalSupply), + MarketCap: util.FormatMarketCap(quote.MarketCap), + Price: util.FormatPrice(v.Quote[convert].Price, convert), + PercentChange1H: util.FormatPercentChange(quote.PercentChange1H), + PercentChange24H: util.FormatPercentChange(quote.PercentChange24H), + PercentChange7D: util.FormatPercentChange(quote.PercentChange7D), + Volume24H: util.FormatVolume(v.Quote[convert].Volume24H), + LastUpdated: util.FormatLastUpdated(v.LastUpdated), + }) } return ret, nil } // GetAllCoinData gets all coin data. Need to paginate through all pages -func (s *Service) GetAllCoinData(convert string, ch chan map[string]apitypes.Coin) error { +func (s *Service) GetAllCoinData(convert string, ch chan []apitypes.Coin) error { go func() { maxPages := 10 defer close(ch) @@ -93,25 +96,23 @@ func (s *Service) GetAllCoinData(convert string, ch chan map[string]apitypes.Coi if i > 0 { time.Sleep(1 * time.Second) } + coins, err := s.getLimitedCoinData(convert, i) if err != nil { return } - ret := make(map[string]apitypes.Coin) - for k, v := range coins { - ret[k] = v - } - ch <- ret + + ch <- coins } }() return nil } // GetCoinGraphData gets coin graph data -func (s *Service) GetCoinGraphData(coin string, start int64, end int64) (apitypes.CoinGraph, error) { +func (s *Service) GetCoinGraphData(symbol string, name string, start int64, end int64) (apitypes.CoinGraph, error) { ret := apitypes.CoinGraph{} graphData, err := cmcv2.TickerGraph(&cmcv2.TickerGraphOptions{ - Symbol: coin, + Symbol: symbol, Start: start, End: end, }) @@ -163,15 +164,48 @@ func (s *Service) GetGlobalMarketData(convert string) (apitypes.GlobalMarketData return ret, nil } -func formatPrice(price float64, convert string) float64 { - pricestr := fmt.Sprintf("%.2f", price) - if convert == "ETH" || convert == "BTC" || price < 1 { - pricestr = fmt.Sprintf("%.5f", price) - } - price, _ = strconv.ParseFloat(pricestr, 64) - return price +// CoinLink returns the URL link for the coin +func (s *Service) CoinLink(name string) string { + slug := util.NameToSlug(name) + return fmt.Sprintf("https://coinmarketcap.com/currencies/%s", slug) } -func formatVolume(volume float64) float64 { - return float64(int64(volume)) +// SupportedCurrencies returns a list of supported currencies +func (s *Service) SupportedCurrencies() []string { + return []string{ + "BTC", + "ETH", + "AUD", + "BRL", + "CAD", + "CFH", + "CLP", + "CNY", + "CZK", + "DKK", + "EUR", + "GBP", + "HKD", + "HUF", + "IDR", + "ILS", + "INR", + "JPY", + "KRW", + "MXN", + "MYR", + "NOK", + "NZD", + "PLN", + "PHP", + "PKR", + "RUB", + "SEK", + "SGD", + "THB", + "TRY", + "TWD", + "USD", + "ZAR", + } } diff --git a/cointop/common/api/interface.go b/cointop/common/api/interface.go index f526461..c993b14 100644 --- a/cointop/common/api/interface.go +++ b/cointop/common/api/interface.go @@ -7,12 +7,14 @@ import ( // Interface interface type Interface interface { Ping() error - GetAllCoinData(convert string, ch chan map[string]types.Coin) error - GetCoinGraphData(coin string, start int64, end int64) (types.CoinGraph, error) + GetAllCoinData(convert string, ch chan []types.Coin) error + GetCoinGraphData(symbol string, name string, start int64, end int64) (types.CoinGraph, error) GetGlobalMarketGraphData(start int64, end int64) (types.MarketGraph, error) GetGlobalMarketData(convert string) (types.GlobalMarketData, error) //GetCoinData(coin string) (types.Coin, error) //GetAltcoinMarketGraphData(start int64, end int64) (types.MarketGraph, error) //GetCoinPriceUSD(coin string) (float64, error) //GetCoinMarkets(coin string) ([]types.Market, error) + CoinLink(name string) string + SupportedCurrencies() []string } diff --git a/cointop/common/api/util/util.go b/cointop/common/api/util/util.go new file mode 100644 index 0000000..c6e7606 --- /dev/null +++ b/cointop/common/api/util/util.go @@ -0,0 +1,103 @@ +package util + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +// NameToSlug converts a coin name to slug for URLs +func NameToSlug(name string) string { + re := regexp.MustCompile(`[^a-zA-Z0-9]`) + return strings.ToLower(re.ReplaceAllString(name, "-")) +} + +// FormatID formats the ID value +func FormatID(id string) string { + return strings.ToLower(id) +} + +// FormatSymbol formats the symbol value +func FormatSymbol(id string) string { + return strings.ToUpper(id) +} + +// FormatName formats the name value +func FormatName(name string) string { + return name +} + +// FormatRank formats the rank value +func FormatRank(rank interface{}) int { + switch v := rank.(type) { + case int: + return v + case uint: + return int(v) + case int16: + return int(v) + case uint16: + return int(v) + case int32: + return int(v) + case uint32: + return int(v) + case int64: + return int(v) + case uint64: + return int(v) + case float32: + return int(v) + case float64: + return int(v) + } + + return 0 +} + +// FormatPrice formats the price value +func FormatPrice(price float64, convert string) float64 { + pricestr := fmt.Sprintf("%.2f", price) + if convert == "ETH" || convert == "BTC" || price < 1 { + pricestr = fmt.Sprintf("%.5f", price) + } + price, _ = strconv.ParseFloat(pricestr, 64) + return price +} + +// FormatVolume formats the volume value +func FormatVolume(volume float64) float64 { + return float64(int64(volume)) +} + +// FormatMarketCap formats the market cap value +func FormatMarketCap(marketCap float64) float64 { + return float64(int64(marketCap)) +} + +// FormatSupply formats the supply value +func FormatSupply(supply float64) float64 { + return float64(int64(supply)) +} + +// FormatPercentChange formats the percent change value +func FormatPercentChange(percentChange float64) float64 { + return percentChange +} + +// FormatLastUpdated formats the last updated value +func FormatLastUpdated(lastUpdated string) string { + lastUpdatedTime, err := time.Parse(time.RFC3339, lastUpdated) + if err != nil { + return "" + } + + return strconv.Itoa(int(lastUpdatedTime.Unix())) +} + +// CalcDays calculates the number of days between two timestamps +func CalcDays(start, end int64) int { + return int(time.Unix(end, 0).Sub(time.Unix(start, 0)).Hours() / 24) +} diff --git a/cointop/config.go b/cointop/config.go index e0047b5..b4c242d 100644 --- a/cointop/config.go +++ b/cointop/config.go @@ -18,41 +18,38 @@ type config struct { Currency interface{} `toml:"currency"` DefaultView interface{} `toml:"defaultView"` CoinMarketCap map[string]interface{} `toml:"coinmarketcap"` + API interface{} `toml:"api"` } func (ct *Cointop) setupConfig() error { - err := ct.createConfigIfNotExists() - if err != nil { + if err := ct.createConfigIfNotExists(); err != nil { return err } - err = ct.parseConfig() - if err != nil { + if err := ct.parseConfig(); err != nil { return err } - err = ct.loadShortcutsFromConfig() - if err != nil { + if err := ct.loadShortcutsFromConfig(); err != nil { return err } - err = ct.loadFavoritesFromConfig() - if err != nil { + if err := ct.loadFavoritesFromConfig(); err != nil { return err } - err = ct.loadPortfolioFromConfig() - if err != nil { + if err := ct.loadPortfolioFromConfig(); err != nil { return err } - err = ct.loadCurrencyFromConfig() - if err != nil { + if err := ct.loadCurrencyFromConfig(); err != nil { return err } - err = ct.loadDefaultViewFromConfig() - if err != nil { + if err := ct.loadDefaultViewFromConfig(); err != nil { return err } - err = ct.loadAPIKeysFromConfig() - if err != nil { + if err := ct.loadAPIKeysFromConfig(); err != nil { return err } + if err := ct.loadAPIChoiceFromConfig(); err != nil { + return err + } + return nil } @@ -170,6 +167,7 @@ func (ct *Cointop) configToToml() ([]byte, error) { cmcIfc := map[string]interface{}{ "pro_api_key": ct.apiKeys.cmc, } + var apiChoiceIfc interface{} = ct.apiChoice var inputs = &config{ Shortcuts: shortcutsIfcs, @@ -178,6 +176,7 @@ func (ct *Cointop) configToToml() ([]byte, error) { Currency: currencyIfc, DefaultView: defaultViewIfc, CoinMarketCap: cmcIfc, + API: apiChoiceIfc, } var b bytes.Buffer @@ -242,6 +241,15 @@ func (ct *Cointop) loadAPIKeysFromConfig() error { return nil } +func (ct *Cointop) loadAPIChoiceFromConfig() error { + apiChoice, ok := ct.config.API.(string) + if ok { + apiChoice = strings.TrimSpace(strings.ToLower(apiChoice)) + ct.apiChoice = apiChoice + } + return nil +} + func (ct *Cointop) loadFavoritesFromConfig() error { for k, arr := range ct.config.Favorites { // DEPRECATED: favorites by 'symbol' is deprecated because of collisions. Kept for backward compatibility. diff --git a/cointop/conversion.go b/cointop/conversion.go index 39b7f49..48db42d 100644 --- a/cointop/conversion.go +++ b/cointop/conversion.go @@ -8,7 +8,7 @@ import ( "github.com/miguelmota/cointop/cointop/common/pad" ) -var supportedfiatconversions = map[string]string{ +var fiatCurrencyNames = map[string]string{ "AUD": "Australian Dollar", "BRL": "Brazilian Real", "CAD": "Canadian Dollar", @@ -43,12 +43,12 @@ var supportedfiatconversions = map[string]string{ "ZAR": "South African Rand", } -var supportedcryptoconversion = map[string]string{ +var cryptocurrencyNames = map[string]string{ "BTC": "Bitcoin", "ETH": "Ethereum", } -var currencysymbols = map[string]string{ +var currencySymbol = map[string]string{ "AUD": "$", "BRL": "R$", "BTC": "Ƀ", @@ -89,21 +89,24 @@ var alphanumericcharacters = []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', func (ct *Cointop) supportedCurrencyConversions() map[string]string { all := map[string]string{} - for k, v := range supportedfiatconversions { - all[k] = v - } - for k, v := range supportedcryptoconversion { - all[k] = v + for _, symbol := range ct.api.SupportedCurrencies() { + if v, ok := fiatCurrencyNames[symbol]; ok { + all[symbol] = v + } + if v, ok := cryptocurrencyNames[symbol]; ok { + all[symbol] = v + } } + return all } func (ct *Cointop) supportedFiatCurrencyConversions() map[string]string { - return supportedfiatconversions + return fiatCurrencyNames } func (ct *Cointop) supportedCryptoCurrencyConversions() map[string]string { - return supportedfiatconversions + return cryptocurrencyNames } func (ct *Cointop) sortedSupportedCurrencyConversions() []string { @@ -203,5 +206,10 @@ func (ct *Cointop) setCurrencyConverstion(convert string) func() error { } func (ct *Cointop) currencySymbol() string { - return currencysymbols[ct.currencyconversion] + symbol, ok := currencySymbol[ct.currencyconversion] + if ok { + return symbol + } + + return "$" } diff --git a/cointop/list.go b/cointop/list.go index dec8edf..fd82706 100644 --- a/cointop/list.go +++ b/cointop/list.go @@ -14,11 +14,12 @@ var updatecoinsmux sync.Mutex func (ct *Cointop) updateCoins() error { coinslock.Lock() defer coinslock.Unlock() - cachekey := "allcoinsslugmap" + cachekey := ct.cacheKey("allcoinsslugmap") var err error var allcoinsslugmap map[string]types.Coin cached, found := ct.cache.Get(cachekey) + _ = cached if found { // cache hit allcoinsslugmap, _ = cached.(map[string]types.Coin) @@ -28,18 +29,14 @@ func (ct *Cointop) updateCoins() error { // cache miss if allcoinsslugmap == nil { ct.debuglog("cache miss") - ch := make(chan map[string]types.Coin) + ch := make(chan []types.Coin) err = ct.api.GetAllCoinData(ct.currencyconversion, ch) if err != nil { return err } for coins := range ch { - allcoinsslugmap := make(map[string]types.Coin) - for _, c := range coins { - allcoinsslugmap[c.Name] = c - } - go ct.processCoinsMap(allcoinsslugmap) + go ct.processCoins(coins) ct.cache.Set(cachekey, ct.allcoinsslugmap, 10*time.Second) filecache.Set(cachekey, ct.allcoinsslugmap, 24*time.Hour) } @@ -50,12 +47,22 @@ func (ct *Cointop) updateCoins() error { return nil } -func (ct *Cointop) processCoinsMap(allcoinsslugmap map[string]types.Coin) { +func (ct *Cointop) processCoinsMap(coinsMap map[string]types.Coin) { + var coins []types.Coin + for _, v := range coinsMap { + coins = append(coins, v) + } + + ct.processCoins(coins) +} + +func (ct *Cointop) processCoins(coins []types.Coin) { updatecoinsmux.Lock() defer updatecoinsmux.Unlock() - for k, v := range allcoinsslugmap { + for _, v := range coins { + k := v.Name last := ct.allcoinsslugmap[k] - ct.allcoinsslugmap[k] = &coin{ + ct.allcoinsslugmap[k] = &Coin{ ID: v.ID, Name: v.Name, Symbol: v.Symbol, @@ -75,8 +82,9 @@ func (ct *Cointop) processCoinsMap(allcoinsslugmap map[string]types.Coin) { } } if len(ct.allcoins) < len(ct.allcoinsslugmap) { - list := []*coin{} - for k := range allcoinsslugmap { + list := []*Coin{} + for _, v := range coins { + k := v.Name coin := ct.allcoinsslugmap[k] list = append(list, coin) } @@ -108,7 +116,10 @@ func (ct *Cointop) processCoinsMap(allcoinsslugmap map[string]types.Coin) { } } - ct.updateTable() + time.AfterFunc(10*time.Millisecond, func() { + ct.sort(ct.sortby, ct.sortdesc, ct.coins, true) + ct.updateTable() + }) } func (ct *Cointop) getListCount() int { diff --git a/cointop/marketbar.go b/cointop/marketbar.go index e09451c..9b5be81 100644 --- a/cointop/marketbar.go +++ b/cointop/marketbar.go @@ -65,7 +65,7 @@ func (ct *Cointop) updateMarketbar() error { } else { var market types.GlobalMarketData var err error - cachekey := "market" + cachekey := ct.cacheKey("market") cached, found := ct.cache.Get(cachekey) if found { diff --git a/cointop/portfolio.go b/cointop/portfolio.go index 64bf3f0..3811c77 100644 --- a/cointop/portfolio.go +++ b/cointop/portfolio.go @@ -126,7 +126,7 @@ func (ct *Cointop) setPortfolioHoldings() error { return nil } -func (ct *Cointop) portfolioEntry(c *coin) (*portfolioEntry, bool) { +func (ct *Cointop) portfolioEntry(c *Coin) (*portfolioEntry, bool) { if c == nil { return &portfolioEntry{}, true } @@ -168,7 +168,7 @@ func (ct *Cointop) removePortfolioEntry(coin string) { delete(ct.portfolio.Entries, strings.ToLower(coin)) } -func (ct *Cointop) portfolioEntryExists(c *coin) bool { +func (ct *Cointop) portfolioEntryExists(c *Coin) bool { _, isNew := ct.portfolioEntry(c) return !isNew } @@ -177,8 +177,8 @@ func (ct *Cointop) portfolioEntriesCount() int { return len(ct.portfolio.Entries) } -func (ct *Cointop) getPortfolioSlice() []*coin { - sliced := []*coin{} +func (ct *Cointop) getPortfolioSlice() []*Coin { + sliced := []*Coin{} for i := range ct.allcoins { if ct.portfolioEntriesCount() == 0 { break diff --git a/cointop/sort.go b/cointop/sort.go index d9adeb4..ceee7a3 100644 --- a/cointop/sort.go +++ b/cointop/sort.go @@ -9,7 +9,7 @@ import ( var sortlock sync.Mutex -func (ct *Cointop) sort(sortby string, desc bool, list []*coin, renderHeaders bool) { +func (ct *Cointop) sort(sortby string, desc bool, list []*Coin, renderHeaders bool) { sortlock.Lock() defer sortlock.Unlock() if list == nil { diff --git a/cointop/table.go b/cointop/table.go index 564e426..4b510b7 100644 --- a/cointop/table.go +++ b/cointop/table.go @@ -3,6 +3,7 @@ package cointop import ( "fmt" "math" + "net/url" "strconv" "strings" "time" @@ -168,7 +169,7 @@ func (ct *Cointop) refreshTable() error { } func (ct *Cointop) updateTable() error { - sliced := []*coin{} + sliced := []*Coin{} for i := range ct.allcoinsslugmap { v := ct.allcoinsslugmap[i] @@ -242,7 +243,7 @@ func (ct *Cointop) highlightedRowIndex() int { return idx } -func (ct *Cointop) highlightedRowCoin() *coin { +func (ct *Cointop) highlightedRowCoin() *Coin { idx := ct.highlightedRowIndex() if len(ct.coins) == 0 { return nil @@ -255,24 +256,35 @@ func (ct *Cointop) rowLink() string { if coin == nil { return "" } - slug := strings.ToLower(strings.Replace(coin.Name, " ", "-", -1)) - // TODO: dynamic - return fmt.Sprintf("https://coinmarketcap.com/currencies/%s", slug) + + return ct.api.CoinLink(coin.Name) } func (ct *Cointop) rowLinkShort() string { - coin := ct.highlightedRowCoin() - if coin == nil { - return "" + link := ct.rowLink() + if link != "" { + u, err := url.Parse(link) + if err != nil { + return "" + } + + host := u.Hostname() + host = strings.Replace(host, "www.", "", -1) + path := u.EscapedPath() + parts := strings.Split(path, "/") + if len(parts) > 0 { + path = parts[len(parts)-1] + } + + return fmt.Sprintf("http://%s/.../%s", host, path) } - // TODO: dynamic - slug := strings.ToLower(strings.Replace(coin.Name, " ", "-", -1)) - return fmt.Sprintf("http://coinmarketcap.com/.../%s", slug) + + return "" } -func (ct *Cointop) allCoins() []*coin { +func (ct *Cointop) allCoins() []*Coin { if ct.filterByFavorites { - var list []*coin + var list []*Coin for i := range ct.allcoins { coin := ct.allcoins[i] if coin.Favorite { @@ -283,7 +295,7 @@ func (ct *Cointop) allCoins() []*coin { } if ct.portfoliovisible { - var list []*coin + var list []*Coin for i := range ct.allcoins { coin := ct.allcoins[i] if ct.portfolioEntryExists(coin) { @@ -296,7 +308,7 @@ func (ct *Cointop) allCoins() []*coin { return ct.allcoins } -func (ct *Cointop) coinBySymbol(symbol string) *coin { +func (ct *Cointop) coinBySymbol(symbol string) *Coin { for i := range ct.allcoins { coin := ct.allcoins[i] if coin.Symbol == symbol { diff --git a/cointop/types.go b/cointop/types.go index 01d4d6a..4a511a5 100644 --- a/cointop/types.go +++ b/cointop/types.go @@ -1,6 +1,7 @@ package cointop -type coin struct { +// Coin is the row structure +type Coin struct { ID string Name string Slug string diff --git a/go.mod b/go.mod index 48ee4ab..0c2da60 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,10 @@ module github.com/miguelmota/cointop require ( github.com/BurntSushi/toml v0.3.1 github.com/anaskhan96/soup v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.1 github.com/fatih/color v1.7.0 github.com/gizak/termui v2.3.0+incompatible + github.com/google/pprof v0.0.0-20190502144155-8358a9778bd1 // indirect github.com/jroimartin/gocui v0.4.0 github.com/maruel/panicparse v1.1.2-0.20180806203336-f20d4c4d746f // indirect github.com/mattn/go-colorable v0.1.1 // indirect diff --git a/go.sum b/go.sum index 95f714f..a31976b 100644 --- a/go.sum +++ b/go.sum @@ -9,6 +9,9 @@ github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/gizak/termui v2.3.0+incompatible h1:S8wJoNumYfc/rR5UezUM4HsPEo3RJh0LKdiuDWQpjqw= github.com/gizak/termui v2.3.0+incompatible/go.mod h1:PkJoWUt/zacQKysNfQtcw1RW+eK2SxkieVBtl+4ovLA= +github.com/google/pprof v0.0.0-20190404155422-f8f10df84213/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190502144155-8358a9778bd1/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= github.com/jroimartin/gocui v0.4.0 h1:52jnalstgmc25FmtGcWqa0tcbMEWS6RpFLsOIO+I+E8= github.com/jroimartin/gocui v0.4.0/go.mod h1:7i7bbj99OgFHzo7kB2zPb8pXLqMBSQegY7azfqXMkyY= github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= @@ -36,6 +39,7 @@ github.com/miguelmota/go-coinmarketcap v0.1.4 h1:x3AXc/b8MbFtfAEI5hQphtcbwTm4OAX github.com/miguelmota/go-coinmarketcap v0.1.4/go.mod h1:Jdv/kqtKclIElmoNAZMMJn0DSQv+j7p/H1te/GGnxhA= github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d h1:x3S6kxmy49zXVVyhcnrFqxvNVCBPb2KZ9hV2RBdS840= github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= @@ -45,6 +49,7 @@ github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= golang.org/x/net v0.0.0-20180215212450-dc948dff8834/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -62,3 +67,5 @@ golang.org/x/sys v0.0.0-20190416152802-12500544f89f h1:1ZH9RnjNgLzh6YrsRp/c6ddZ8 golang.org/x/sys v0.0.0-20190416152802-12500544f89f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/h2non/gock.v1 v1.0.14/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 0000000..bc52e96 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2012-2016 Dave Collins + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go new file mode 100644 index 0000000..7929947 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -0,0 +1,145 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is not running on Google App Engine, compiled by GopherJS, and +// "-tags safe" is not added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// Go versions prior to 1.4 are disabled because they use a different layout +// for interfaces which make the implementation of unsafeReflectValue more complex. +// +build !js,!appengine,!safe,!disableunsafe,go1.4 + +package spew + +import ( + "reflect" + "unsafe" +) + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = false + + // ptrSize is the size of a pointer on the current arch. + ptrSize = unsafe.Sizeof((*byte)(nil)) +) + +type flag uintptr + +var ( + // flagRO indicates whether the value field of a reflect.Value + // is read-only. + flagRO flag + + // flagAddr indicates whether the address of the reflect.Value's + // value may be taken. + flagAddr flag +) + +// flagKindMask holds the bits that make up the kind +// part of the flags field. In all the supported versions, +// it is in the lower 5 bits. +const flagKindMask = flag(0x1f) + +// Different versions of Go have used different +// bit layouts for the flags type. This table +// records the known combinations. +var okFlags = []struct { + ro, addr flag +}{{ + // From Go 1.4 to 1.5 + ro: 1 << 5, + addr: 1 << 7, +}, { + // Up to Go tip. + ro: 1<<5 | 1<<6, + addr: 1 << 8, +}} + +var flagValOffset = func() uintptr { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + return field.Offset +}() + +// flagField returns a pointer to the flag field of a reflect.Value. +func flagField(v *reflect.Value) *flag { + return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) +} + +// unsafeReflectValue converts the passed reflect.Value into a one that bypasses +// the typical safety restrictions preventing access to unaddressable and +// unexported data. It works by digging the raw pointer to the underlying +// value out of the protected value and generating a new unprotected (unsafe) +// reflect.Value to it. +// +// This allows us to check for implementations of the Stringer and error +// interfaces to be used for pretty printing ordinarily unaddressable and +// inaccessible values such as unexported struct fields. +func unsafeReflectValue(v reflect.Value) reflect.Value { + if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { + return v + } + flagFieldPtr := flagField(&v) + *flagFieldPtr &^= flagRO + *flagFieldPtr |= flagAddr + return v +} + +// Sanity checks against future reflect package changes +// to the type or semantics of the Value.flag field. +func init() { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { + panic("reflect.Value flag field has changed kind") + } + type t0 int + var t struct { + A t0 + // t0 will have flagEmbedRO set. + t0 + // a will have flagStickyRO set + a t0 + } + vA := reflect.ValueOf(t).FieldByName("A") + va := reflect.ValueOf(t).FieldByName("a") + vt0 := reflect.ValueOf(t).FieldByName("t0") + + // Infer flagRO from the difference between the flags + // for the (otherwise identical) fields in t. + flagPublic := *flagField(&vA) + flagWithRO := *flagField(&va) | *flagField(&vt0) + flagRO = flagPublic ^ flagWithRO + + // Infer flagAddr from the difference between a value + // taken from a pointer and not. + vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") + flagNoPtr := *flagField(&vA) + flagPtr := *flagField(&vPtrA) + flagAddr = flagNoPtr ^ flagPtr + + // Check that the inferred flags tally with one of the known versions. + for _, f := range okFlags { + if flagRO == f.ro && flagAddr == f.addr { + return + } + } + panic("reflect.Value read-only flag has changed semantics") +} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go new file mode 100644 index 0000000..205c28d --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -0,0 +1,38 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is running on Google App Engine, compiled by GopherJS, or +// "-tags safe" is added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// +build js appengine safe disableunsafe !go1.4 + +package spew + +import "reflect" + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = true +) + +// unsafeReflectValue typically converts the passed reflect.Value into a one +// that bypasses the typical safety restrictions preventing access to +// unaddressable and unexported data. However, doing this relies on access to +// the unsafe package. This is a stub version which simply returns the passed +// reflect.Value when the unsafe package is not available. +func unsafeReflectValue(v reflect.Value) reflect.Value { + return v +} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go new file mode 100644 index 0000000..1be8ce9 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "reflect" + "sort" + "strconv" +) + +// Some constants in the form of bytes to avoid string overhead. This mirrors +// the technique used in the fmt package. +var ( + panicBytes = []byte("(PANIC=") + plusBytes = []byte("+") + iBytes = []byte("i") + trueBytes = []byte("true") + falseBytes = []byte("false") + interfaceBytes = []byte("(interface {})") + commaNewlineBytes = []byte(",\n") + newlineBytes = []byte("\n") + openBraceBytes = []byte("{") + openBraceNewlineBytes = []byte("{\n") + closeBraceBytes = []byte("}") + asteriskBytes = []byte("*") + colonBytes = []byte(":") + colonSpaceBytes = []byte(": ") + openParenBytes = []byte("(") + closeParenBytes = []byte(")") + spaceBytes = []byte(" ") + pointerChainBytes = []byte("->") + nilAngleBytes = []byte("") + maxNewlineBytes = []byte("\n") + maxShortBytes = []byte("") + circularBytes = []byte("") + circularShortBytes = []byte("") + invalidAngleBytes = []byte("") + openBracketBytes = []byte("[") + closeBracketBytes = []byte("]") + percentBytes = []byte("%") + precisionBytes = []byte(".") + openAngleBytes = []byte("<") + closeAngleBytes = []byte(">") + openMapBytes = []byte("map[") + closeMapBytes = []byte("]") + lenEqualsBytes = []byte("len=") + capEqualsBytes = []byte("cap=") +) + +// hexDigits is used to map a decimal value to a hex digit. +var hexDigits = "0123456789abcdef" + +// catchPanic handles any panics that might occur during the handleMethods +// calls. +func catchPanic(w io.Writer, v reflect.Value) { + if err := recover(); err != nil { + w.Write(panicBytes) + fmt.Fprintf(w, "%v", err) + w.Write(closeParenBytes) + } +} + +// handleMethods attempts to call the Error and String methods on the underlying +// type the passed reflect.Value represents and outputes the result to Writer w. +// +// It handles panics in any called methods by catching and displaying the error +// as the formatted value. +func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { + // We need an interface to check if the type implements the error or + // Stringer interface. However, the reflect package won't give us an + // interface on certain things like unexported struct fields in order + // to enforce visibility rules. We use unsafe, when it's available, + // to bypass these restrictions since this package does not mutate the + // values. + if !v.CanInterface() { + if UnsafeDisabled { + return false + } + + v = unsafeReflectValue(v) + } + + // Choose whether or not to do error and Stringer interface lookups against + // the base type or a pointer to the base type depending on settings. + // Technically calling one of these methods with a pointer receiver can + // mutate the value, however, types which choose to satisify an error or + // Stringer interface with a pointer receiver should not be mutating their + // state inside these interface methods. + if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { + v = unsafeReflectValue(v) + } + if v.CanAddr() { + v = v.Addr() + } + + // Is it an error or Stringer? + switch iface := v.Interface().(type) { + case error: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.Error())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + + w.Write([]byte(iface.Error())) + return true + + case fmt.Stringer: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.String())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + w.Write([]byte(iface.String())) + return true + } + return false +} + +// printBool outputs a boolean value as true or false to Writer w. +func printBool(w io.Writer, val bool) { + if val { + w.Write(trueBytes) + } else { + w.Write(falseBytes) + } +} + +// printInt outputs a signed integer value to Writer w. +func printInt(w io.Writer, val int64, base int) { + w.Write([]byte(strconv.FormatInt(val, base))) +} + +// printUint outputs an unsigned integer value to Writer w. +func printUint(w io.Writer, val uint64, base int) { + w.Write([]byte(strconv.FormatUint(val, base))) +} + +// printFloat outputs a floating point value using the specified precision, +// which is expected to be 32 or 64bit, to Writer w. +func printFloat(w io.Writer, val float64, precision int) { + w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) +} + +// printComplex outputs a complex value using the specified float precision +// for the real and imaginary parts to Writer w. +func printComplex(w io.Writer, c complex128, floatPrecision int) { + r := real(c) + w.Write(openParenBytes) + w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) + i := imag(c) + if i >= 0 { + w.Write(plusBytes) + } + w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) + w.Write(iBytes) + w.Write(closeParenBytes) +} + +// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' +// prefix to Writer w. +func printHexPtr(w io.Writer, p uintptr) { + // Null pointer. + num := uint64(p) + if num == 0 { + w.Write(nilAngleBytes) + return + } + + // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix + buf := make([]byte, 18) + + // It's simpler to construct the hex string right to left. + base := uint64(16) + i := len(buf) - 1 + for num >= base { + buf[i] = hexDigits[num%base] + num /= base + i-- + } + buf[i] = hexDigits[num] + + // Add '0x' prefix. + i-- + buf[i] = 'x' + i-- + buf[i] = '0' + + // Strip unused leading bytes. + buf = buf[i:] + w.Write(buf) +} + +// valuesSorter implements sort.Interface to allow a slice of reflect.Value +// elements to be sorted. +type valuesSorter struct { + values []reflect.Value + strings []string // either nil or same len and values + cs *ConfigState +} + +// newValuesSorter initializes a valuesSorter instance, which holds a set of +// surrogate keys on which the data should be sorted. It uses flags in +// ConfigState to decide if and how to populate those surrogate keys. +func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { + vs := &valuesSorter{values: values, cs: cs} + if canSortSimply(vs.values[0].Kind()) { + return vs + } + if !cs.DisableMethods { + vs.strings = make([]string, len(values)) + for i := range vs.values { + b := bytes.Buffer{} + if !handleMethods(cs, &b, vs.values[i]) { + vs.strings = nil + break + } + vs.strings[i] = b.String() + } + } + if vs.strings == nil && cs.SpewKeys { + vs.strings = make([]string, len(values)) + for i := range vs.values { + vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) + } + } + return vs +} + +// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted +// directly, or whether it should be considered for sorting by surrogate keys +// (if the ConfigState allows it). +func canSortSimply(kind reflect.Kind) bool { + // This switch parallels valueSortLess, except for the default case. + switch kind { + case reflect.Bool: + return true + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return true + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Float32, reflect.Float64: + return true + case reflect.String: + return true + case reflect.Uintptr: + return true + case reflect.Array: + return true + } + return false +} + +// Len returns the number of values in the slice. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Len() int { + return len(s.values) +} + +// Swap swaps the values at the passed indices. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Swap(i, j int) { + s.values[i], s.values[j] = s.values[j], s.values[i] + if s.strings != nil { + s.strings[i], s.strings[j] = s.strings[j], s.strings[i] + } +} + +// valueSortLess returns whether the first value should sort before the second +// value. It is used by valueSorter.Less as part of the sort.Interface +// implementation. +func valueSortLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Bool: + return !a.Bool() && b.Bool() + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return a.Int() < b.Int() + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return a.Uint() < b.Uint() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.String: + return a.String() < b.String() + case reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Array: + // Compare the contents of both arrays. + l := a.Len() + for i := 0; i < l; i++ { + av := a.Index(i) + bv := b.Index(i) + if av.Interface() == bv.Interface() { + continue + } + return valueSortLess(av, bv) + } + } + return a.String() < b.String() +} + +// Less returns whether the value at index i should sort before the +// value at index j. It is part of the sort.Interface implementation. +func (s *valuesSorter) Less(i, j int) bool { + if s.strings == nil { + return valueSortLess(s.values[i], s.values[j]) + } + return s.strings[i] < s.strings[j] +} + +// sortValues is a sort function that handles both native types and any type that +// can be converted to error or Stringer. Other inputs are sorted according to +// their Value.String() value to ensure display stability. +func sortValues(values []reflect.Value, cs *ConfigState) { + if len(values) == 0 { + return + } + sort.Sort(newValuesSorter(values, cs)) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go new file mode 100644 index 0000000..2e3d22f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/config.go @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// ConfigState houses the configuration options used by spew to format and +// display values. There is a global instance, Config, that is used to control +// all top-level Formatter and Dump functionality. Each ConfigState instance +// provides methods equivalent to the top-level functions. +// +// The zero value for ConfigState provides no indentation. You would typically +// want to set it to a space or a tab. +// +// Alternatively, you can use NewDefaultConfig to get a ConfigState instance +// with default settings. See the documentation of NewDefaultConfig for default +// values. +type ConfigState struct { + // Indent specifies the string to use for each indentation level. The + // global config instance that all top-level functions use set this to a + // single space by default. If you would like more indentation, you might + // set this to a tab with "\t" or perhaps two spaces with " ". + Indent string + + // MaxDepth controls the maximum number of levels to descend into nested + // data structures. The default, 0, means there is no limit. + // + // NOTE: Circular data structures are properly detected, so it is not + // necessary to set this value unless you specifically want to limit deeply + // nested data structures. + MaxDepth int + + // DisableMethods specifies whether or not error and Stringer interfaces are + // invoked for types that implement them. + DisableMethods bool + + // DisablePointerMethods specifies whether or not to check for and invoke + // error and Stringer interfaces on types which only accept a pointer + // receiver when the current type is not a pointer. + // + // NOTE: This might be an unsafe action since calling one of these methods + // with a pointer receiver could technically mutate the value, however, + // in practice, types which choose to satisify an error or Stringer + // interface with a pointer receiver should not be mutating their state + // inside these interface methods. As a result, this option relies on + // access to the unsafe package, so it will not have any effect when + // running in environments without access to the unsafe package such as + // Google App Engine or with the "safe" build tag specified. + DisablePointerMethods bool + + // DisablePointerAddresses specifies whether to disable the printing of + // pointer addresses. This is useful when diffing data structures in tests. + DisablePointerAddresses bool + + // DisableCapacities specifies whether to disable the printing of capacities + // for arrays, slices, maps and channels. This is useful when diffing + // data structures in tests. + DisableCapacities bool + + // ContinueOnMethod specifies whether or not recursion should continue once + // a custom error or Stringer interface is invoked. The default, false, + // means it will print the results of invoking the custom error or Stringer + // interface and return immediately instead of continuing to recurse into + // the internals of the data type. + // + // NOTE: This flag does not have any effect if method invocation is disabled + // via the DisableMethods or DisablePointerMethods options. + ContinueOnMethod bool + + // SortKeys specifies map keys should be sorted before being printed. Use + // this to have a more deterministic, diffable output. Note that only + // native types (bool, int, uint, floats, uintptr and string) and types + // that support the error or Stringer interfaces (if methods are + // enabled) are supported, with other types sorted according to the + // reflect.Value.String() output which guarantees display stability. + SortKeys bool + + // SpewKeys specifies that, as a last resort attempt, map keys should + // be spewed to strings and sorted by those strings. This is only + // considered if SortKeys is true. + SpewKeys bool +} + +// Config is the active configuration of the top-level functions. +// The configuration can be changed by modifying the contents of spew.Config. +var Config = ConfigState{Indent: " "} + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the formatted string as a value that satisfies error. See NewFormatter +// for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, c.convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, c.convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, c.convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a Formatter interface returned by c.NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Print(a ...interface{}) (n int, err error) { + return fmt.Print(c.convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, c.convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Println(a ...interface{}) (n int, err error) { + return fmt.Println(c.convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprint(a ...interface{}) string { + return fmt.Sprint(c.convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, c.convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a Formatter interface returned by c.NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintln(a ...interface{}) string { + return fmt.Sprintln(c.convertArgs(a)...) +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +c.Printf, c.Println, or c.Printf. +*/ +func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(c, v) +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { + fdump(c, w, a...) +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by modifying the public members +of c. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func (c *ConfigState) Dump(a ...interface{}) { + fdump(c, os.Stdout, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func (c *ConfigState) Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(c, &buf, a...) + return buf.String() +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a spew Formatter interface using +// the ConfigState associated with s. +func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = newFormatter(c, arg) + } + return formatters +} + +// NewDefaultConfig returns a ConfigState with the following default settings. +// +// Indent: " " +// MaxDepth: 0 +// DisableMethods: false +// DisablePointerMethods: false +// ContinueOnMethod: false +// SortKeys: false +func NewDefaultConfig() *ConfigState { + return &ConfigState{Indent: " "} +} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go new file mode 100644 index 0000000..aacaac6 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/doc.go @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Package spew implements a deep pretty printer for Go data structures to aid in +debugging. + +A quick overview of the additional features spew provides over the built-in +printing facilities for Go data types are as follows: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output (only when using + Dump style) + +There are two different approaches spew allows for dumping Go data structures: + + * Dump style which prints with newlines, customizable indentation, + and additional debug information such as types and all pointer addresses + used to indirect to the final value + * A custom Formatter interface that integrates cleanly with the standard fmt + package and replaces %v, %+v, %#v, and %#+v to provide inline printing + similar to the default %v while providing the additional functionality + outlined above and passing unsupported format verbs such as %x and %q + along to fmt + +Quick Start + +This section demonstrates how to quickly get started with spew. See the +sections below for further details on formatting and configuration options. + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + spew.Dump(myVar1, myVar2, ...) + spew.Fdump(someWriter, myVar1, myVar2, ...) + str := spew.Sdump(myVar1, myVar2, ...) + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with +%v (most compact), %+v (adds pointer addresses), %#v (adds types), or +%#+v (adds types and pointer addresses): + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available +via the spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +The following configuration options are available: + * Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + + * MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + + * DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + + * DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. + Pointer method invocation is enabled by default. + + * DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + + * DisableCapacities + DisableCapacities specifies whether to disable the printing of + capacities for arrays, slices, maps and channels. This is useful when + diffing data structures in tests. + + * ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + + * SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are + supported with other types sorted according to the + reflect.Value.String() output which guarantees display + stability. Natural map order is used by default. + + * SpewKeys + Specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only + considered if SortKeys is true. + +Dump Usage + +Simply call spew.Dump with a list of variables you want to dump: + + spew.Dump(myVar1, myVar2, ...) + +You may also call spew.Fdump if you would prefer to output to an arbitrary +io.Writer. For example, to dump to standard error: + + spew.Fdump(os.Stderr, myVar1, myVar2, ...) + +A third option is to call spew.Sdump to get the formatted output as a string: + + str := spew.Sdump(myVar1, myVar2, ...) + +Sample Dump Output + +See the Dump example for details on the setup of the types and variables being +shown here. + + (main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) (len=1) { + (string) (len=3) "one": (bool) true + } + } + +Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C +command as shown. + ([]uint8) (len=32 cap=32) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| + } + +Custom Formatter + +Spew provides a custom formatter that implements the fmt.Formatter interface +so that it integrates cleanly with standard fmt package printing functions. The +formatter is useful for inline printing of smaller data types similar to the +standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Custom Formatter Usage + +The simplest way to make use of the spew custom formatter is to call one of the +convenience functions such as spew.Printf, spew.Println, or spew.Printf. The +functions have syntax you are most likely already familiar with: + + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Println(myVar, myVar2) + spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +See the Index for the full list convenience functions. + +Sample Formatter Output + +Double pointer to a uint8: + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 + +Pointer to circular struct with a uint8 field and a pointer to itself: + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} + +See the Printf example for details on the setup of variables being shown +here. + +Errors + +Since it is possible for custom Stringer/error interfaces to panic, spew +detects them and handles them internally by printing the panic information +inline with the output. Since spew is intended to provide deep pretty printing +capabilities on structures, it intentionally does not return any errors. +*/ +package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go new file mode 100644 index 0000000..f78d89f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "os" + "reflect" + "regexp" + "strconv" + "strings" +) + +var ( + // uint8Type is a reflect.Type representing a uint8. It is used to + // convert cgo types to uint8 slices for hexdumping. + uint8Type = reflect.TypeOf(uint8(0)) + + // cCharRE is a regular expression that matches a cgo char. + // It is used to detect character arrays to hexdump them. + cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) + + // cUnsignedCharRE is a regular expression that matches a cgo unsigned + // char. It is used to detect unsigned character arrays to hexdump + // them. + cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) + + // cUint8tCharRE is a regular expression that matches a cgo uint8_t. + // It is used to detect uint8_t arrays to hexdump them. + cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) +) + +// dumpState contains information about the state of a dump operation. +type dumpState struct { + w io.Writer + depth int + pointers map[uintptr]int + ignoreNextType bool + ignoreNextIndent bool + cs *ConfigState +} + +// indent performs indentation according to the depth level and cs.Indent +// option. +func (d *dumpState) indent() { + if d.ignoreNextIndent { + d.ignoreNextIndent = false + return + } + d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) +} + +// unpackValue returns values inside of non-nil interfaces when possible. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface && !v.IsNil() { + v = v.Elem() + } + return v +} + +// dumpPtr handles formatting of pointers by indirecting them as necessary. +func (d *dumpState) dumpPtr(v reflect.Value) { + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range d.pointers { + if depth >= d.depth { + delete(d.pointers, k) + } + } + + // Keep list of all dereferenced pointers to show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by dereferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := d.pointers[addr]; ok && pd < d.depth { + cycleFound = true + indirects-- + break + } + d.pointers[addr] = d.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type information. + d.w.Write(openParenBytes) + d.w.Write(bytes.Repeat(asteriskBytes, indirects)) + d.w.Write([]byte(ve.Type().String())) + d.w.Write(closeParenBytes) + + // Display pointer information. + if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { + d.w.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + d.w.Write(pointerChainBytes) + } + printHexPtr(d.w, addr) + } + d.w.Write(closeParenBytes) + } + + // Display dereferenced value. + d.w.Write(openParenBytes) + switch { + case nilFound: + d.w.Write(nilAngleBytes) + + case cycleFound: + d.w.Write(circularBytes) + + default: + d.ignoreNextType = true + d.dump(ve) + } + d.w.Write(closeParenBytes) +} + +// dumpSlice handles formatting of arrays and slices. Byte (uint8 under +// reflection) arrays and slices are dumped in hexdump -C fashion. +func (d *dumpState) dumpSlice(v reflect.Value) { + // Determine whether this type should be hex dumped or not. Also, + // for types which should be hexdumped, try to use the underlying data + // first, then fall back to trying to convert them to a uint8 slice. + var buf []uint8 + doConvert := false + doHexDump := false + numEntries := v.Len() + if numEntries > 0 { + vt := v.Index(0).Type() + vts := vt.String() + switch { + // C types that need to be converted. + case cCharRE.MatchString(vts): + fallthrough + case cUnsignedCharRE.MatchString(vts): + fallthrough + case cUint8tCharRE.MatchString(vts): + doConvert = true + + // Try to use existing uint8 slices and fall back to converting + // and copying if that fails. + case vt.Kind() == reflect.Uint8: + // We need an addressable interface to convert the type + // to a byte slice. However, the reflect package won't + // give us an interface on certain things like + // unexported struct fields in order to enforce + // visibility rules. We use unsafe, when available, to + // bypass these restrictions since this package does not + // mutate the values. + vs := v + if !vs.CanInterface() || !vs.CanAddr() { + vs = unsafeReflectValue(vs) + } + if !UnsafeDisabled { + vs = vs.Slice(0, numEntries) + + // Use the existing uint8 slice if it can be + // type asserted. + iface := vs.Interface() + if slice, ok := iface.([]uint8); ok { + buf = slice + doHexDump = true + break + } + } + + // The underlying data needs to be converted if it can't + // be type asserted to a uint8 slice. + doConvert = true + } + + // Copy and convert the underlying type if needed. + if doConvert && vt.ConvertibleTo(uint8Type) { + // Convert and copy each element into a uint8 byte + // slice. + buf = make([]uint8, numEntries) + for i := 0; i < numEntries; i++ { + vv := v.Index(i) + buf[i] = uint8(vv.Convert(uint8Type).Uint()) + } + doHexDump = true + } + } + + // Hexdump the entire slice as needed. + if doHexDump { + indent := strings.Repeat(d.cs.Indent, d.depth) + str := indent + hex.Dump(buf) + str = strings.Replace(str, "\n", "\n"+indent, -1) + str = strings.TrimRight(str, d.cs.Indent) + d.w.Write([]byte(str)) + return + } + + // Recursively call dump for each item. + for i := 0; i < numEntries; i++ { + d.dump(d.unpackValue(v.Index(i))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } +} + +// dump is the main workhorse for dumping a value. It uses the passed reflect +// value to figure out what kind of object we are dealing with and formats it +// appropriately. It is a recursive function, however circular data structures +// are detected and handled properly. +func (d *dumpState) dump(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + d.w.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + d.indent() + d.dumpPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !d.ignoreNextType { + d.indent() + d.w.Write(openParenBytes) + d.w.Write([]byte(v.Type().String())) + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + d.ignoreNextType = false + + // Display length and capacity if the built-in len and cap functions + // work with the value's kind and the len/cap itself is non-zero. + valueLen, valueCap := 0, 0 + switch v.Kind() { + case reflect.Array, reflect.Slice, reflect.Chan: + valueLen, valueCap = v.Len(), v.Cap() + case reflect.Map, reflect.String: + valueLen = v.Len() + } + if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { + d.w.Write(openParenBytes) + if valueLen != 0 { + d.w.Write(lenEqualsBytes) + printInt(d.w, int64(valueLen), 10) + } + if !d.cs.DisableCapacities && valueCap != 0 { + if valueLen != 0 { + d.w.Write(spaceBytes) + } + d.w.Write(capEqualsBytes) + printInt(d.w, int64(valueCap), 10) + } + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + + // Call Stringer/error interfaces if they exist and the handle methods flag + // is enabled + if !d.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(d.cs, d.w, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(d.w, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(d.w, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(d.w, v.Uint(), 10) + + case reflect.Float32: + printFloat(d.w, v.Float(), 32) + + case reflect.Float64: + printFloat(d.w, v.Float(), 64) + + case reflect.Complex64: + printComplex(d.w, v.Complex(), 32) + + case reflect.Complex128: + printComplex(d.w, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + d.dumpSlice(v) + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.String: + d.w.Write([]byte(strconv.Quote(v.String()))) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + d.w.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + numEntries := v.Len() + keys := v.MapKeys() + if d.cs.SortKeys { + sortValues(keys, d.cs) + } + for i, key := range keys { + d.dump(d.unpackValue(key)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.MapIndex(key))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Struct: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + vt := v.Type() + numFields := v.NumField() + for i := 0; i < numFields; i++ { + d.indent() + vtf := vt.Field(i) + d.w.Write([]byte(vtf.Name)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.Field(i))) + if i < (numFields - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(d.w, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(d.w, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it in case any new + // types are added. + default: + if v.CanInterface() { + fmt.Fprintf(d.w, "%v", v.Interface()) + } else { + fmt.Fprintf(d.w, "%v", v.String()) + } + } +} + +// fdump is a helper function to consolidate the logic from the various public +// methods which take varying writers and config states. +func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { + for _, arg := range a { + if arg == nil { + w.Write(interfaceBytes) + w.Write(spaceBytes) + w.Write(nilAngleBytes) + w.Write(newlineBytes) + continue + } + + d := dumpState{w: w, cs: cs} + d.pointers = make(map[uintptr]int) + d.dump(reflect.ValueOf(arg)) + d.w.Write(newlineBytes) + } +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func Fdump(w io.Writer, a ...interface{}) { + fdump(&Config, w, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(&Config, &buf, a...) + return buf.String() +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by an exported package global, +spew.Config. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func Dump(a ...interface{}) { + fdump(&Config, os.Stdout, a...) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go new file mode 100644 index 0000000..b04edb7 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" +) + +// supportedFlags is a list of all the character flags supported by fmt package. +const supportedFlags = "0-+# " + +// formatState implements the fmt.Formatter interface and contains information +// about the state of a formatting operation. The NewFormatter function can +// be used to get a new Formatter which can be used directly as arguments +// in standard fmt package printing calls. +type formatState struct { + value interface{} + fs fmt.State + depth int + pointers map[uintptr]int + ignoreNextType bool + cs *ConfigState +} + +// buildDefaultFormat recreates the original format string without precision +// and width information to pass in to fmt.Sprintf in the case of an +// unrecognized type. Unless new types are added to the language, this +// function won't ever be called. +func (f *formatState) buildDefaultFormat() (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + buf.WriteRune('v') + + format = buf.String() + return format +} + +// constructOrigFormat recreates the original format string including precision +// and width information to pass along to the standard fmt package. This allows +// automatic deferral of all format strings this package doesn't support. +func (f *formatState) constructOrigFormat(verb rune) (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + if width, ok := f.fs.Width(); ok { + buf.WriteString(strconv.Itoa(width)) + } + + if precision, ok := f.fs.Precision(); ok { + buf.Write(precisionBytes) + buf.WriteString(strconv.Itoa(precision)) + } + + buf.WriteRune(verb) + + format = buf.String() + return format +} + +// unpackValue returns values inside of non-nil interfaces when possible and +// ensures that types for values which have been unpacked from an interface +// are displayed when the show types flag is also set. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (f *formatState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface { + f.ignoreNextType = false + if !v.IsNil() { + v = v.Elem() + } + } + return v +} + +// formatPtr handles formatting of pointers by indirecting them as necessary. +func (f *formatState) formatPtr(v reflect.Value) { + // Display nil if top level pointer is nil. + showTypes := f.fs.Flag('#') + if v.IsNil() && (!showTypes || f.ignoreNextType) { + f.fs.Write(nilAngleBytes) + return + } + + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range f.pointers { + if depth >= f.depth { + delete(f.pointers, k) + } + } + + // Keep list of all dereferenced pointers to possibly show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by derferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := f.pointers[addr]; ok && pd < f.depth { + cycleFound = true + indirects-- + break + } + f.pointers[addr] = f.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type or indirection level depending on flags. + if showTypes && !f.ignoreNextType { + f.fs.Write(openParenBytes) + f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) + f.fs.Write([]byte(ve.Type().String())) + f.fs.Write(closeParenBytes) + } else { + if nilFound || cycleFound { + indirects += strings.Count(ve.Type().String(), "*") + } + f.fs.Write(openAngleBytes) + f.fs.Write([]byte(strings.Repeat("*", indirects))) + f.fs.Write(closeAngleBytes) + } + + // Display pointer information depending on flags. + if f.fs.Flag('+') && (len(pointerChain) > 0) { + f.fs.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + f.fs.Write(pointerChainBytes) + } + printHexPtr(f.fs, addr) + } + f.fs.Write(closeParenBytes) + } + + // Display dereferenced value. + switch { + case nilFound: + f.fs.Write(nilAngleBytes) + + case cycleFound: + f.fs.Write(circularShortBytes) + + default: + f.ignoreNextType = true + f.format(ve) + } +} + +// format is the main workhorse for providing the Formatter interface. It +// uses the passed reflect value to figure out what kind of object we are +// dealing with and formats it appropriately. It is a recursive function, +// however circular data structures are detected and handled properly. +func (f *formatState) format(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + f.fs.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + f.formatPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !f.ignoreNextType && f.fs.Flag('#') { + f.fs.Write(openParenBytes) + f.fs.Write([]byte(v.Type().String())) + f.fs.Write(closeParenBytes) + } + f.ignoreNextType = false + + // Call Stringer/error interfaces if they exist and the handle methods + // flag is enabled. + if !f.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(f.cs, f.fs, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(f.fs, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(f.fs, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(f.fs, v.Uint(), 10) + + case reflect.Float32: + printFloat(f.fs, v.Float(), 32) + + case reflect.Float64: + printFloat(f.fs, v.Float(), 64) + + case reflect.Complex64: + printComplex(f.fs, v.Complex(), 32) + + case reflect.Complex128: + printComplex(f.fs, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + f.fs.Write(openBracketBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + numEntries := v.Len() + for i := 0; i < numEntries; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(v.Index(i))) + } + } + f.depth-- + f.fs.Write(closeBracketBytes) + + case reflect.String: + f.fs.Write([]byte(v.String())) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + f.fs.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + + f.fs.Write(openMapBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + keys := v.MapKeys() + if f.cs.SortKeys { + sortValues(keys, f.cs) + } + for i, key := range keys { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(key)) + f.fs.Write(colonBytes) + f.ignoreNextType = true + f.format(f.unpackValue(v.MapIndex(key))) + } + } + f.depth-- + f.fs.Write(closeMapBytes) + + case reflect.Struct: + numFields := v.NumField() + f.fs.Write(openBraceBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + vt := v.Type() + for i := 0; i < numFields; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + vtf := vt.Field(i) + if f.fs.Flag('+') || f.fs.Flag('#') { + f.fs.Write([]byte(vtf.Name)) + f.fs.Write(colonBytes) + } + f.format(f.unpackValue(v.Field(i))) + } + } + f.depth-- + f.fs.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(f.fs, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(f.fs, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it if any get added. + default: + format := f.buildDefaultFormat() + if v.CanInterface() { + fmt.Fprintf(f.fs, format, v.Interface()) + } else { + fmt.Fprintf(f.fs, format, v.String()) + } + } +} + +// Format satisfies the fmt.Formatter interface. See NewFormatter for usage +// details. +func (f *formatState) Format(fs fmt.State, verb rune) { + f.fs = fs + + // Use standard formatting for verbs that are not v. + if verb != 'v' { + format := f.constructOrigFormat(verb) + fmt.Fprintf(fs, format, f.value) + return + } + + if f.value == nil { + if fs.Flag('#') { + fs.Write(interfaceBytes) + } + fs.Write(nilAngleBytes) + return + } + + f.format(reflect.ValueOf(f.value)) +} + +// newFormatter is a helper function to consolidate the logic from the various +// public methods which take varying config states. +func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { + fs := &formatState{value: v, cs: cs} + fs.pointers = make(map[uintptr]int) + return fs +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +Printf, Println, or Fprintf. +*/ +func NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(&Config, v) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go new file mode 100644 index 0000000..32c0e33 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/spew.go @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "fmt" + "io" +) + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the formatted string as a value that satisfies error. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a default Formatter interface returned by NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) +func Print(a ...interface{}) (n int, err error) { + return fmt.Print(convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) +func Println(a ...interface{}) (n int, err error) { + return fmt.Println(convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprint(a ...interface{}) string { + return fmt.Sprint(convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintln(a ...interface{}) string { + return fmt.Sprintln(convertArgs(a)...) +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a default spew Formatter interface. +func convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = NewFormatter(arg) + } + return formatters +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5e488c5..61c6510 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -2,6 +2,8 @@ github.com/BurntSushi/toml # github.com/anaskhan96/soup v1.1.1 github.com/anaskhan96/soup +# github.com/davecgh/go-spew v1.1.1 +github.com/davecgh/go-spew/spew # github.com/fatih/color v1.7.0 github.com/fatih/color # github.com/gizak/termui v2.3.0+incompatible @@ -30,6 +32,10 @@ github.com/nsf/termbox-go github.com/patrickmn/go-cache # github.com/sirupsen/logrus v1.4.1 github.com/sirupsen/logrus +# github.com/superoo7/go-gecko v0.0.0-20190508102000-07de9a7cf28c +github.com/superoo7/go-gecko/v3 +github.com/superoo7/go-gecko/v3/types +github.com/superoo7/go-gecko/format # golang.org/x/net v0.0.0-20190415214537-1da14a5a36f2 golang.org/x/net/html golang.org/x/net/html/atom