Commit 9e9c9a0

Karn Wong <karn@karnwong.me>
2024-03-03 14:29:39
qrcode: accept input from clipboard
1 parent 1c98300
cmd/generate/generate_passphrase.go
@@ -33,7 +33,7 @@ var generatePassphraseCmd = &cobra.Command{
 		if err != nil {
 			slog.Error("Error generating passphrase")
 		}
-		utils.CopyToClipboard(passphrase)
+		utils.WriteToClipboard(passphrase)
 		fmt.Printf("%s\n", passphrase)
 	},
 }
cmd/generate/generate_password.go
@@ -31,7 +31,7 @@ var generatePasswordCmd = &cobra.Command{
 		if err != nil {
 			slog.Error("Error generating password")
 		}
-		utils.CopyToClipboard(password)
+		utils.WriteToClipboard(password)
 		fmt.Printf("%s\n", password)
 	},
 }
cmd/generate/generate_qrcode.go
@@ -3,9 +3,9 @@ package generate
 import (
 	"fmt"
 	"os"
+	"strings"
 
 	"github.com/kahnwong/swissknife/cmd/utils"
-
 	qrcode "github.com/skip2/go-qrcode"
 	"github.com/spf13/cobra"
 )
@@ -26,7 +26,7 @@ func generateQRCode(url string) (string, error) {
 	}
 
 	// copy to clipboard
-	utils.CopyToClipboardImage(png)
+	utils.WriteToClipboardImage(png)
 
 	// for stdout
 	//content := q.ToString(false)
@@ -38,16 +38,30 @@ func generateQRCode(url string) (string, error) {
 var generateQRCodeCmd = &cobra.Command{
 	Use:   "qrcode",
 	Short: "Generate QR code",
-	Long:  `Generate QR code from URL and copy resulting image to clipboard.`,
+	Long:  `Generate QR code from URL (either as an arg or from clipboard) and copy resulting image to clipboard.`,
 	Run: func(cmd *cobra.Command, args []string) {
-		//init
+		// set URL
+		var url string
 		if len(args) == 0 {
-			fmt.Println("Please specify URL")
-			os.Exit(1)
+			urlFromClipboard := utils.ReadFromClipboard()
+			if urlFromClipboard != "" {
+				if strings.HasPrefix(urlFromClipboard, "https://") {
+					url = urlFromClipboard
+				}
+			}
+		}
+		if url == "" {
+			if len(args) == 0 {
+				fmt.Println("Please specify URL")
+				os.Exit(1)
+			} else if len(args) == 1 {
+				url = args[0]
+			}
 		}
+		fmt.Println(url)
 
 		// main
-		qrcodeStr, err := generateQRCode(args[0])
+		qrcodeStr, err := generateQRCode(url)
 		if err != nil {
 			fmt.Print(err)
 		}
cmd/utils/copy_to_clipboard.go → cmd/utils/clipboard.go
@@ -4,16 +4,27 @@ import (
 	"golang.design/x/clipboard"
 )
 
-func CopyToClipboard(text string) {
+func WriteToClipboard(text string) {
 	err := clipboard.Init() // clipboard doesn't work from ssh session
 	if err == nil {         // clipboard doesn't work from ssh session
 		clipboard.Write(clipboard.FmtText, []byte(text))
 	}
 }
 
-func CopyToClipboardImage(bytes []byte) {
+func WriteToClipboardImage(bytes []byte) {
 	err := clipboard.Init()
 	if err == nil {
 		clipboard.Write(clipboard.FmtImage, bytes)
 	}
 }
+
+func ReadFromClipboard() string {
+	err := clipboard.Init()
+	if err == nil {
+
+		s := clipboard.Read(clipboard.FmtText)
+		return string(s)
+	}
+
+	return ""
+}