package main import ( "bufio" "fmt" "io/ioutil" "net/http" "os" "os/user" "path/filepath" "regexp" "strings" "github.com/atotto/clipboard" ) func main() { if len(os.Args) < 2 { fmt.Println("Usage: quicknote [-c] [markdown-file]") os.Exit(1) } url := "" markdownFile := "" if os.Args[1] == "-c" { urlFromClipboard, err := clipboard.ReadAll() if err != nil { fmt.Printf("Error getting URL from clipboard: %v\n", err) os.Exit(1) } url = strings.TrimSpace(urlFromClipboard) } else { url = os.Args[1] } if len(os.Args) == 2 || (len(os.Args) == 3 && os.Args[1] == "-c") { usr, err := user.Current() if err != nil { fmt.Printf("Error getting user home directory: %v\n", err) os.Exit(1) } markdownFile = filepath.Join(usr.HomeDir, "Documents", "Notes", "quicknote.md") } else { markdownFile = os.Args[2] } resp, err := http.Get(url) if err != nil { fmt.Printf("Error fetching URL: %v\n", err) os.Exit(1) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) os.Exit(1) } htmlContent := string(body) title, err := extractTitle(htmlContent) if err != nil { fmt.Printf("Error: %v\n", err) title = promptForTitle() } markdownLink := fmt.Sprintf("- [%s](%s)\n", title, url) err = appendToFile(markdownFile, markdownLink) if err != nil { fmt.Printf("Error appending to file: %v\n", err) os.Exit(1) } } func extractTitle(html string) (string, error) { re := regexp.MustCompile(`(?i)<\s*title\s*>(.*?)<\s*/\s*title\s*>`) match := re.FindStringSubmatch(html) if len(match) > 0 { title := strings.TrimSpace(match[1]) if title != "" { return title, nil } return "", fmt.Errorf("title tag is empty") } return "", fmt.Errorf("title tag is not present") } func promptForTitle() string { reader := bufio.NewReader(os.Stdin) fmt.Print("Please enter a title for the URL: ") title, _ := reader.ReadString('\n') return strings.TrimSpace(title) } func appendToFile(filename, content string) error { f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() if _, err := f.WriteString(content); err != nil { return err } return nil }