| 1 | package knot |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // DeriveID is the ID a knot of type t with slug gets: the type's prefix |
| 11 | // and the first 7 hex digits of the SHA-256 of the slug, the rule the |
| 12 | // archived graph follows (archive/.the-valley/README.md). |
| 13 | func DeriveID(t Type, slug string) string { |
| 14 | sum := sha256.Sum256([]byte(slug)) |
| 15 | return t.Prefix + "-" + hex.EncodeToString(sum[:])[:7] |
| 16 | } |
| 17 | |
| 18 | // Slug is the slug a title gives: its letters and digits in lowercase, |
| 19 | // every other run of characters one hyphen, cut to MaxSlug bytes at a |
| 20 | // hyphen where one is near. A title with no ASCII letter or digit gives |
| 21 | // "knot". |
| 22 | func Slug(title string) string { |
| 23 | var b strings.Builder |
| 24 | hyphen := false |
| 25 | for _, r := range strings.ToLower(title) { |
| 26 | switch { |
| 27 | case r >= 'a' && r <= 'z' || r >= '0' && r <= '9': |
| 28 | if hyphen && b.Len() > 0 { |
| 29 | b.WriteByte('-') |
| 30 | } |
| 31 | hyphen = false |
| 32 | b.WriteRune(r) |
| 33 | default: |
| 34 | hyphen = true |
| 35 | } |
| 36 | } |
| 37 | return cut(b.String(), MaxSlug) |
| 38 | } |
| 39 | |
| 40 | // cut is a slug cut to at most n bytes, at its last hyphen within them |
| 41 | // when that keeps more than half, and with no hyphen at its end. |
| 42 | func cut(slug string, n int) string { |
| 43 | if len(slug) > n { |
| 44 | slug = slug[:n] |
| 45 | if i := strings.LastIndexByte(slug, '-'); i > n/2 { |
| 46 | slug = slug[:i] |
| 47 | } |
| 48 | slug = strings.TrimRight(slug, "-") |
| 49 | } |
| 50 | if slug == "" { |
| 51 | return "knot" |
| 52 | } |
| 53 | return slug |
| 54 | } |
| 55 | |
| 56 | // NewID is the ID and slug a new knot of type t titled title gets in a |
| 57 | // graph where taken reports the IDs already used. When the title's slug |
| 58 | // gives an ID that is taken, the slug gains a suffix, -2, -3 and on, until |
| 59 | // the ID it gives is free. |
| 60 | func NewID(t Type, title string, taken func(id string) bool) (id, slug string) { |
| 61 | base := Slug(title) |
| 62 | slug = base |
| 63 | for n := 2; ; n++ { |
| 64 | id = DeriveID(t, slug) |
| 65 | if !taken(id) { |
| 66 | return id, slug |
| 67 | } |
| 68 | suffix := "-" + strconv.Itoa(n) |
| 69 | slug = cut(base, MaxSlug-len(suffix)) + suffix |
| 70 | } |
| 71 | } |