all repos — site @ eb5ceb8bad0a830d8f6f0b952e745147eec092f6

source for my site, found at icyphox.sh

bin/replace.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
// replace -- in-place edit a post
// usage: replace [old string] [new string]

package main

import (
	"fmt"
	"log"
	"os"
	"strings"
)

const dir = "pages/blog/"

func main() {
	if len(os.Args) != 3 {
		fmt.Println("usage: replace [old string] [new string]")
		os.Exit(1)
	}

	oldStr, newStr := os.Args[1], os.Args[2]

	posts, err := os.ReadDir(dir)
	if err != nil {
		log.Fatalln(err)
	}
	for _, p := range posts {
		path := dir + p.Name()
		input, err := os.ReadFile(path)
		if err != nil {
			log.Fatalln(err)
		}

		lines := strings.Split(string(input), "\n")
		for i, line := range lines {
			if strings.Contains(line, oldStr) {
				line = strings.ReplaceAll(line, oldStr, newStr)
				lines[i] = line
			}
		}
		output := strings.Join(lines, "\n")
		err = os.WriteFile(path, []byte(output), 644)
		if err != nil {
			log.Fatalln(err)
		}
	}
}