Browse Source

Generate friendly ids by default

Lucas Stadler 9 years ago
parent
commit
ed66257573
1 changed files with 50 additions and 0 deletions
  1. 50 0
      go/blog/blog.go

+ 50 - 0
go/blog/blog.go

11
	"io/ioutil"
11
	"io/ioutil"
12
	"net/url"
12
	"net/url"
13
	"os"
13
	"os"
14
	"strings"
15
	"unicode"
14
16
15
	"github.com/russross/blackfriday"
17
	"github.com/russross/blackfriday"
16
	"gopkg.in/yaml.v2"
18
	"gopkg.in/yaml.v2"
27
29
28
var flags struct {
30
var flags struct {
29
	writeBack bool
31
	writeBack bool
32
	hashIds   bool
30
	reverse   bool
33
	reverse   bool
31
	css       string
34
	css       string
32
	title     string
35
	title     string
72
75
73
func init() {
76
func init() {
74
	flag.BoolVar(&flags.writeBack, "write-back", false, "Rewrite the YAML file with the generated ids")
77
	flag.BoolVar(&flags.writeBack, "write-back", false, "Rewrite the YAML file with the generated ids")
78
	flag.BoolVar(&flags.hashIds, "hash-ids", false, "Use hash-based post ids")
75
	flag.BoolVar(&flags.reverse, "reverse", false, "Reverse the order of the articles in the file")
79
	flag.BoolVar(&flags.reverse, "reverse", false, "Reverse the order of the articles in the file")
76
	flag.StringVar(&flags.css, "css", defaultStyle, "Custom `css` styles to use")
80
	flag.StringVar(&flags.css, "css", defaultStyle, "Custom `css` styles to use")
77
	flag.StringVar(&flags.title, "title", "A blog", "Custom `title` to use")
81
	flag.StringVar(&flags.title, "title", "A blog", "Custom `title` to use")
292
}
296
}
293
297
294
func generateId(p Post) string {
298
func generateId(p Post) string {
299
	if flags.hashIds {
300
		return hashId(p)
301
	}
302
	return slugId(p)
303
}
304
305
func hashId(p Post) string {
295
	h := md5.New()
306
	h := md5.New()
296
	io.WriteString(h, p.Title)
307
	io.WriteString(h, p.Title)
297
	io.WriteString(h, p.Content)
308
	io.WriteString(h, p.Content)
308
319
309
	return hex.EncodeToString(buf)
320
	return hex.EncodeToString(buf)
310
}
321
}
322
323
var usedSlugs = map[string]int{}
324
325
func slugId(p Post) string {
326
	slug := toSlug(p.Title)
327
	n, ok := usedSlugs[slug]
328
	if ok {
329
		n += 1
330
	} else {
331
		n = 1
332
	}
333
	usedSlugs[slug] = n
334
335
	if slug != "" && n == 1 {
336
		return slug
337
	} else if slug == "" {
338
		return fmt.Sprintf("%d", n)
339
	}
340
	return fmt.Sprintf("%s-%d", slug, n)
341
}
342
343
func toSlug(s string) string {
344
	lastChar := ' '
345
	s = strings.Map(func(ch rune) rune {
346
		var newChar rune
347
		switch {
348
		case unicode.IsLetter(ch) || unicode.IsDigit(ch):
349
			newChar = unicode.ToLower(ch)
350
		default:
351
			if lastChar == '-' {
352
				return -1
353
			}
354
			newChar = '-'
355
		}
356
		lastChar = newChar
357
		return newChar
358
	}, s)
359
	return strings.Trim(s, "-")
360
}