Created
March 31, 2025 20:36
-
-
Save bradfitz/e54f03fd4c34763a8b9962f81d2a16fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"flag" | |
"io/fs" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func main() { | |
flag.Parse() | |
var sect string | |
switch flag.NArg() { | |
case 0: | |
case 1: | |
sect = flag.Arg(0) | |
default: | |
log.Fatalf("Too many arguments provided. Usage: getmd [section]") | |
} | |
home, err := os.UserHomeDir() | |
if err != nil { | |
log.Fatalf("Failed to get home directory: %v") | |
} | |
downloads := filepath.Join(home, "Downloads") | |
des, err := os.ReadDir(downloads) | |
if err != nil { | |
log.Fatal(err) | |
} | |
var recent fs.DirEntry | |
var recentInfo fs.FileInfo | |
for _, de := range des { | |
if !strings.HasSuffix(de.Name(), ".md") { | |
continue | |
} | |
fi, err := de.Info() | |
if err != nil { | |
continue | |
} | |
if !fi.Mode().IsRegular() { | |
continue | |
} | |
if recent == nil || fi.ModTime().After(recentInfo.ModTime()) { | |
recent = de | |
recentInfo = fi | |
} | |
} | |
if recent == nil { | |
log.Println("No *.md files found in Downloads.") | |
return | |
} | |
contents, err := os.ReadFile(filepath.Join(downloads, recent.Name())) | |
if err != nil { | |
log.Fatalf("Failed to read file %s: %v", recent.Name(), err) | |
} | |
if sect != "" { | |
var out bytes.Buffer | |
var in bool | |
start := `\<` + sect + `\>` | |
end := `\</` + sect + `\>` | |
for _, line := range strings.Split(string(contents), "\n") { | |
if !in { | |
in = strings.TrimSpace(line) == start | |
continue | |
} | |
if strings.TrimSpace(line) == end { | |
break | |
} | |
out.WriteString(line) | |
out.WriteString("\n") | |
} | |
contents = out.Bytes() | |
} | |
os.Stdout.Write(contents) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment