add some commands
Chat under construction still
This commit is contained in:
+167
@@ -0,0 +1,167 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
nickname string
|
||||
clients []*client
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
type client struct {
|
||||
conn net.Conn
|
||||
nickname string
|
||||
}
|
||||
|
||||
// chatCmd represents the chat command
|
||||
var chatCmd = &cobra.Command{
|
||||
Use: "chat",
|
||||
Short: "Start a chat server or connect to other peers",
|
||||
Long: `Start a chat server or connect to other peers.
|
||||
If no arguments are provided, it starts a chat server.
|
||||
If an address is provided, it connects to the specified chat server.
|
||||
You can specify your nickname using the --nickname (-n) flag.`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if len(args) == 0 {
|
||||
startChatServer()
|
||||
} else {
|
||||
address := args[0]
|
||||
startChatClient(address)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(chatCmd)
|
||||
chatCmd.Flags().StringVarP(&nickname, "nickname", "n", "", "Nickname for the user")
|
||||
}
|
||||
|
||||
func startChatServer() {
|
||||
listener, err := net.Listen("tcp", "localhost:8080")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to start chat server: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
fmt.Println("Chat server started. Listening on localhost:8080")
|
||||
|
||||
// Start a goroutine to handle server input
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
msg := scanner.Text()
|
||||
broadcastMessage(nil, "Server: "+msg+"\n")
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
log.Fatalf("Error reading server input: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
log.Printf("Failed to accept connection: %v", err)
|
||||
continue
|
||||
}
|
||||
go handleClient(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func handleClient(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
|
||||
nickname, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Printf("Error reading nickname: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("New connection from %s with nickname: %s", conn.RemoteAddr().String(), nickname)
|
||||
|
||||
for {
|
||||
message, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Printf("Error reading message: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[%s]: %s", nickname, message)
|
||||
broadcastMessage(nil, fmt.Sprintf("[%s]: %s", nickname, message))
|
||||
}
|
||||
}
|
||||
|
||||
func removeClient(c *client) {
|
||||
for i, cl := range clients {
|
||||
if cl == c {
|
||||
clients = append(clients[:i], clients[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func broadcastMessage(sender *client, message string) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
for _, cl := range clients {
|
||||
if cl != sender {
|
||||
_, err := cl.conn.Write([]byte(message))
|
||||
if err != nil {
|
||||
log.Printf("Error broadcasting message: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startChatClient(address string) {
|
||||
conn, err := net.Dial("tcp", address)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to chat server: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
fmt.Print("Enter your nickname: ")
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
if !scanner.Scan() {
|
||||
log.Fatal("Failed to read nickname from stdin")
|
||||
}
|
||||
nickname := scanner.Text() + ": "
|
||||
|
||||
// Send nickname to server
|
||||
if _, err := fmt.Fprintf(conn, "%s\n", nickname); err != nil {
|
||||
log.Fatalf("Failed to send nickname to server: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
reader := bufio.NewReader(conn)
|
||||
for {
|
||||
message, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Printf("Error reading message: %v", err)
|
||||
return
|
||||
}
|
||||
fmt.Print(message)
|
||||
}
|
||||
}()
|
||||
|
||||
for scanner.Scan() {
|
||||
msg := scanner.Text()
|
||||
if _, err := fmt.Fprintf(conn, "%s\n", msg); err != nil {
|
||||
log.Fatalf("Failed to send message to server: %v", err)
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
log.Fatalf("Error reading standard input: %v", err)
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// envCmd represents the env command
|
||||
var envCmd = &cobra.Command{
|
||||
Use: "env [action] [key] [value]",
|
||||
Short: "Manage environment variables",
|
||||
Long: `Manage environment variables.
|
||||
Actions:
|
||||
- list: List all environment variables.
|
||||
- set: Set an environment variable.
|
||||
- unset: Unset an environment variable.`,
|
||||
Args: cobra.RangeArgs(1, 3),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
action := args[0]
|
||||
switch action {
|
||||
case "list":
|
||||
listEnvVariables()
|
||||
case "set":
|
||||
if len(args) != 3 {
|
||||
fmt.Println("Usage: dttt env set [key] [value]")
|
||||
return
|
||||
}
|
||||
key := args[1]
|
||||
value := args[2]
|
||||
setEnvVariable(key, value)
|
||||
case "unset":
|
||||
if len(args) != 2 {
|
||||
fmt.Println("Usage: dttt env unset [key]")
|
||||
return
|
||||
}
|
||||
key := args[1]
|
||||
unsetEnvVariable(key)
|
||||
default:
|
||||
fmt.Println("Invalid action. Available actions: list, set, unset")
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(envCmd)
|
||||
}
|
||||
|
||||
func listEnvVariables() {
|
||||
fmt.Println("Environment variables:")
|
||||
for _, env := range os.Environ() {
|
||||
pair := strings.SplitN(env, "=", 2)
|
||||
fmt.Printf("%s=%s\n", pair[0], pair[1])
|
||||
}
|
||||
}
|
||||
|
||||
func setEnvVariable(key, value string) {
|
||||
err := os.Setenv(key, value)
|
||||
if err != nil {
|
||||
log.Fatalf("Error setting environment variable: %v", err)
|
||||
}
|
||||
fmt.Printf("Environment variable %s set to %s\n", key, value)
|
||||
}
|
||||
|
||||
func unsetEnvVariable(key string) {
|
||||
err := os.Unsetenv(key)
|
||||
if err != nil {
|
||||
log.Fatalf("Error unsetting environment variable: %v", err)
|
||||
}
|
||||
fmt.Printf("Environment variable %s unset\n", key)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// renameCmd represents the rename command
|
||||
var renameCmd = &cobra.Command{
|
||||
Use: "rename",
|
||||
Short: "Rename files in bulk based on specified patterns",
|
||||
Long: `Rename files in bulk based on specified patterns.
|
||||
Example usage: dttt rename --pattern "prefix_###.jpg" --start 1 --directory ./images`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// Handle command logic here
|
||||
directory, _ := cmd.Flags().GetString("directory")
|
||||
pattern, _ := cmd.Flags().GetString("pattern")
|
||||
start, _ := cmd.Flags().GetInt("start")
|
||||
|
||||
// Check if required flags are provided
|
||||
if directory == "" || pattern == "" {
|
||||
cmd.Help()
|
||||
return
|
||||
}
|
||||
|
||||
// Implement the renaming logic
|
||||
renameFiles(directory, pattern, start)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(renameCmd)
|
||||
|
||||
// Define flags and configuration settings for the command
|
||||
renameCmd.Flags().StringP("directory", "d", ".", "Directory containing the files to rename")
|
||||
renameCmd.Flags().StringP("pattern", "p", "", "Pattern for renaming files. Use '###' as a placeholder for numeric sequence.")
|
||||
renameCmd.Flags().IntP("start", "s", 1, "Start index for numeric sequence in the renaming pattern")
|
||||
}
|
||||
|
||||
// Function to rename files in bulk based on the specified pattern
|
||||
func renameFiles(directory, pattern string, start int) {
|
||||
// List files in the specified directory
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Iterate through each file in the directory
|
||||
for i, file := range files {
|
||||
// Generate the new filename based on the pattern
|
||||
newName := strings.Replace(pattern, "###", fmt.Sprintf("%d", start+i), 1)
|
||||
|
||||
// Rename the file
|
||||
err := os.Rename(file.Name(), newName)
|
||||
if err != nil {
|
||||
fmt.Println("Error renaming file:", err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Renamed %s to %s\n", file.Name(), newName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/nfnt/resize"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// resizeCmd represents the resize command
|
||||
var resizeCmd = &cobra.Command{
|
||||
Use: "resize [input_file] [output_file] [width]",
|
||||
Short: "Resize an image to the specified width",
|
||||
Long: `Resize an image to the specified width using Lanczos3 interpolation.
|
||||
Example: dttt resize input.jpg output.jpg 300`,
|
||||
Args: cobra.ExactArgs(3),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if len(args) == 0 {
|
||||
cmd.Help()
|
||||
return
|
||||
}
|
||||
|
||||
inputFile := args[0]
|
||||
outputFile := args[1]
|
||||
widthStr := args[2]
|
||||
|
||||
width, err := strconv.Atoi(widthStr)
|
||||
if err != nil {
|
||||
log.Fatal("Invalid width:", err)
|
||||
}
|
||||
|
||||
resizeImage(inputFile, outputFile, width)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(resizeCmd)
|
||||
}
|
||||
|
||||
func resizeImage(inputFile, outputFile string, width int) {
|
||||
// Open the input image file
|
||||
input, err := os.Open(inputFile)
|
||||
if err != nil {
|
||||
log.Fatal("Error opening input file:", err)
|
||||
}
|
||||
defer input.Close()
|
||||
|
||||
// Decode the input image file
|
||||
img, _, err := image.Decode(input)
|
||||
if err != nil {
|
||||
log.Fatal("Error decoding input image:", err)
|
||||
}
|
||||
|
||||
// Resize the image to the target width
|
||||
resizedImg := resize.Resize(uint(width), 0, img, resize.Lanczos3)
|
||||
|
||||
// Create the output image file
|
||||
output, err := os.Create(outputFile)
|
||||
if err != nil {
|
||||
log.Fatal("Error creating output file:", err)
|
||||
}
|
||||
defer output.Close()
|
||||
|
||||
// Write the resized image to the output file
|
||||
if err := jpeg.Encode(output, resizedImg, nil); err != nil {
|
||||
log.Fatal("Error encoding resized image:", err)
|
||||
}
|
||||
|
||||
fmt.Println("Image resized successfully!")
|
||||
}
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
|
||||
|
||||
*/
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var cfgFile string
|
||||
|
||||
// rootCmd represents the base command when called without any subcommands
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "dttt",
|
||||
Short: "A brief description of your application",
|
||||
Long: `A longer description that spans multiple lines and likely contains
|
||||
examples and usage of using your application. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
// Uncomment the following line if your bare application
|
||||
// has an action associated with it:
|
||||
// Run: func(cmd *cobra.Command, args []string) { },
|
||||
}
|
||||
|
||||
// Execute adds all child commands to the root command and sets flags appropriately.
|
||||
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||
func Execute() {
|
||||
err := rootCmd.Execute()
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
// Here you will define your flags and configuration settings.
|
||||
// Cobra supports persistent flags, which, if defined here,
|
||||
// will be global for your application.
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.dttt.yaml)")
|
||||
|
||||
// Cobra also supports local flags, which will only run
|
||||
// when this action is called directly.
|
||||
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := os.UserHomeDir()
|
||||
cobra.CheckErr(err)
|
||||
|
||||
// Search config in home directory with name ".dttt" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigType("yaml")
|
||||
viper.SetConfigName(".dttt")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// serverCmd represents the server command
|
||||
var serverCmd = &cobra.Command{
|
||||
Use: "server [directory]",
|
||||
Short: "Start a simple HTTP server to serve files from the specified directory",
|
||||
Long: `Start a simple HTTP server to serve files from the specified directory.
|
||||
If no directory is provided, the current directory is used by default.
|
||||
|
||||
You can specify the port number using the --port (-p) flag. If not provided, the default port is 8080.`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
var directory string
|
||||
if len(args) == 1 {
|
||||
directory = args[0]
|
||||
} else {
|
||||
directory, _ = os.Getwd()
|
||||
}
|
||||
|
||||
directory, err := filepath.Abs(directory)
|
||||
if err != nil {
|
||||
log.Fatalf("Error getting absolute path: %v", err)
|
||||
}
|
||||
|
||||
port, err := cmd.Flags().GetInt("port")
|
||||
if err != nil {
|
||||
log.Fatalf("Error getting port number: %v", err)
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf(":%d", port)
|
||||
|
||||
fmt.Printf("Starting HTTP server for directory: %s\n", directory)
|
||||
http.Handle("/", http.FileServer(http.Dir(directory)))
|
||||
fmt.Printf("Server listening on %s\n", addr)
|
||||
if err := http.ListenAndServe(addr, nil); err != nil {
|
||||
log.Fatalf("Error starting HTTP server: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(serverCmd)
|
||||
serverCmd.Flags().IntP("port", "p", 8080, "Port number for the HTTP server")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user