Skip to content

Commit

Permalink
rename fetch to pull & fix commands pull & push
Browse files Browse the repository at this point in the history
  • Loading branch information
gi8lino committed Dec 20, 2023
1 parent 22d3dd3 commit e52c9e9
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 45 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ Push data to the `vimbin` server:
| `-u`, `--url` `URL` | The URL of the vimbin server |
| `-h`, `--help` | help for push |

### Fetch
### Pull

Fetch the latest data from the `vimbin` server:
Pull the latest data from the `vimbin` server:

```bash
./vimbin fetch
./vimbin pull
```

**Flags:**
Expand Down
51 changes: 33 additions & 18 deletions cmd/fetch.go → cmd/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,49 +18,64 @@ package cmd
import (
"fmt"
"io"
"os"
"net/http"
"strings"
"vimbin/internal/config"
"vimbin/internal/utils"

"github.com/rs/zerolog/log"

"github.com/spf13/cobra"
)

// fetchCmd represents the 'fetch' command for retrieving the latest data from the vimbin server.
var fetchCmd = &cobra.Command{
Use: "fetch",
Short: "Fetches the latest data from the vimbin server",
Long: `The 'fetch' command retrieves the latest content from the vimbin server specified by the provided URL.
// pullCmd represents the 'fetch' command for retrieving the latest data from the vimbin server.
var pullCmd = &cobra.Command{
Use: "pull",
Short: "Pulls the latest data from the vimbin server",
Long: `The 'pull' command retrieves the latest content from the vimbin server specified by the provided URL.
It makes a GET request to the server and prints the response body to the console.
Example:
vimbin fetch --url http://example.com`,
vimbin pull --url http://example.com`,
Run: func(cmd *cobra.Command, args []string) {
url := strings.TrimSuffix(config.App.Server.Api.Address, "/")

if url == "" {
log.Error().Msg("URL is empty")
os.Exit(1)
log.Fatal().Msg("URL is empty")
}
url += "/fetch"
log.Debug().Msgf("URL: %s", url)

apiToken := config.App.Server.Api.Token.Get()
if apiToken == "" {
log.Fatal().Msg("API token is empty")
}

httpClient := utils.CreateHTTPClient(config.App.Server.Api.SkipInsecureVerify)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal().Msgf("Error creating HTTP request: %v", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", apiToken)

// Make a GET request to the vimbin server
response, err := httpClient.Get(url)
response, err := httpClient.Do(req)
if err != nil {
log.Error().Msgf("Error making GET request: %s", err)
return
}
defer response.Body.Close()

// Check for successful response
if response.StatusCode != http.StatusOK {
log.Fatal().Msgf("Unexpected status code %d", response.StatusCode)
}

// Read the response body
body, err := io.ReadAll(response.Body)
if err != nil {
log.Error().Msgf("Error reading response body: %s", err)
return
log.Fatal().Msgf("Error reading response body: %s", err)
}

// Print the content to the console
Expand All @@ -69,10 +84,10 @@ Example:
}

func init() {
// Add 'fetchCmd' to the root command
rootCmd.AddCommand(fetchCmd)
// Add 'pullCmd' to the root command
rootCmd.AddCommand(pullCmd)

// Define command-line flags for 'fetchCmd'
fetchCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server")
fetchCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification")
// Define command-line flags for 'pullCmd'
pullCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server")
pullCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification")
}
50 changes: 27 additions & 23 deletions cmd/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"fmt"
"io"
"net/http"
"os"
"strings"
"vimbin/internal/config"
"vimbin/internal/utils"
Expand Down Expand Up @@ -49,68 +48,73 @@ Examples:
Run: func(cmd *cobra.Command, args []string) {
// Check if at least one character is provided
if len(args) < 1 {
log.Error().Msg("You must push at least one character.")
os.Exit(1)
log.Fatal().Msg("You must push at least one character.")
}

url := strings.TrimSuffix(config.App.Server.Api.Address, "/")
if url == "" {
log.Error().Msg("URL is empty")
os.Exit(1)
log.Fatal().Msg("URL is empty")
}

apiToken := config.App.Server.Api.Token.Get()
if apiToken == "" {
log.Fatal().Msg("API token is empty")
}

// Concatenate input arguments into a single string
body := strings.Join(args, "\n")
input := strings.Join(args, "\n")

// Build the URL based on the "append" flag
if appendFlag {
url += "/append"
body = "\n" + body
input = "\n" + input
} else {
url += "/save"
}

// Prepare content for the POST request
content := map[string]string{"content": body}
content := map[string]string{"content": input}
requestBody, err := json.Marshal(content)
if err != nil {
log.Error().Msgf("Error encoding JSON: %s", err)
os.Exit(1)
log.Fatal().Msgf("Error encoding JSON: %s", err)
}

httpClient := utils.CreateHTTPClient(config.App.Server.Api.SkipInsecureVerify)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
if err != nil {
log.Fatal().Msgf("Error creating HTTP request: %v", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", apiToken)

// Make the POST request to the vimbin server
response, err := httpClient.Post(url, "application/json", bytes.NewBuffer(requestBody))
response, err := httpClient.Do(req)
if err != nil {
log.Error().Msgf("Error making POST request: %s", err)
os.Exit(1)
log.Fatal().Msgf("Error making POST request: %s", err)
}
defer response.Body.Close()

// Check for successful response
if response.StatusCode != http.StatusOK {
log.Error().Msgf("Unexpected status code %d", response.StatusCode)
os.Exit(1)
log.Fatal().Msgf("Unexpected status code %d", response.StatusCode)
}

// Read and print the response body
var responseBodyBuffer bytes.Buffer
_, err = io.Copy(&responseBodyBuffer, response.Body)
body, err := io.ReadAll(response.Body)
if err != nil {
log.Error().Msgf("Error reading response body: %s", err)
os.Exit(1)
log.Fatal().Msgf("Error reading response body: %s", err)
}

fmt.Println(responseBodyBuffer.String())
// Print the content to the console
fmt.Println(string(body))
},
}

func init() {
// Add 'fetchCmd' to the root command
// Add 'pullCmd' to the root command
rootCmd.AddCommand(pushCmd)

// Define command-line flags for 'fetchCmd'
// Define command-line flags for 'pullCmd'
pushCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server")
pushCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification")
pushCmd.PersistentFlags().BoolVarP(&appendFlag, "append", "a", false, "Append content to the existing content")
Expand Down
10 changes: 9 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
)

const (
version = "v0.0.14"
version = "v0.0.16"
)

var (
Expand All @@ -53,6 +53,9 @@ var rootCmd = &cobra.Command{
- push: Quickly send text to the vimbin server from the command line. This allows for easy integration
with other tools and scripts, streamlining the process of sharing content through vimbin.
- pull: Retrieve the latest content from the vimbin server. This allows for easy integration with other
tools and scripts, streamlining the process of retrieving content from vimbin.
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// PersistentPreRun is executed before any subcommand is executed.
Expand All @@ -65,6 +68,7 @@ var rootCmd = &cobra.Command{

// Configure zerolog
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zerolog.SetGlobalLevel(zerolog.InfoLevel)
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
log.Logger = zerolog.New(output).With().Timestamp().Logger()

Expand All @@ -85,9 +89,13 @@ var rootCmd = &cobra.Command{
log.Debug().Msgf("Trace output enabled")
}

// Save token to config
if token := cmd.Flag("token").Value.String(); token != "" {
config.App.Server.Api.Token.Set(token)
}

config.App.Version = version
log.Debug().Msgf("Version: %s", config.App.Version)
},
Run: func(cmd *cobra.Command, args []string) {
// Run is executed if no subcommand is specified.
Expand Down
1 change: 1 addition & 0 deletions internal/config/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ var App Config

// Config represents the application configuration.
type Config struct {
Version string `mapstructure:"-"` // Version is the version of the application.
HtmlTemplate *template.Template `mapstructure:"-"` // HtmlTemplate contains the HTML template content.
Server Server `mapstructure:"server"` // Server represents the server configuration.
Storage Storage `mapstructure:"storage"` // Storage represents the storage configuration.
Expand Down
1 change: 1 addition & 0 deletions internal/handlers/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func Home(w http.ResponseWriter, r *http.Request) {
Content: config.App.Storage.Content.Get(),
Token: config.App.Server.Api.Token.Get(),
Theme: config.App.Server.Web.Theme,
Version: config.App.Version,
}

if err := config.App.HtmlTemplate.Execute(w, page); err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/handlers/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ type Page struct {
Content string // Content is the content of the page.
Token string // Token is the API token.
Theme string // Theme is the theme of the page.
Version string // Version is the version of the application.
}
1 change: 1 addition & 0 deletions web/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="version" content="{{.Version}}" />

<title>vimbin - a pastebin with vim motion</title>
<meta charset="utf-8" />
Expand Down

0 comments on commit e52c9e9

Please sign in to comment.