~shulhan/asciidoctor-go

ref: v0.1.0 asciidoctor-go/author.go -rw-r--r-- 1.6 KiB
4c1ded16Shulhan Release asciidoctor-go v0.1.0 (2021-03-06) 4 months ago
                                                                                
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package asciidoctor

import (
	"bytes"
	"strings"
)

//
// Author of document.
//
type Author struct {
	FirstName  string
	MiddleName string
	LastName   string
	Initials   string
	Email      string
}

//
// parseAuthor parse raw author into object.
//
func parseAuthor(raw string) (author *Author) {
	author = &Author{}

	raw = strings.TrimSpace(raw)
	if raw[len(raw)-1] == '>' {
		idx := strings.IndexByte(raw, '<')
		if idx > 0 {
			author.Email = raw[idx+1 : len(raw)-1]
			raw = strings.TrimSpace(raw[:idx])
		}
	}

	names := strings.Split(raw, " ")
	if len(names) == 0 {
		return
	}

	var initials bytes.Buffer
	author.FirstName = strings.ReplaceAll(names[0], "_", " ")
	initials.WriteByte(author.FirstName[0])

	if len(names) >= 2 {
		lastIdx := len(names) - 1
		author.LastName = strings.ReplaceAll(names[lastIdx], "_", " ")

		author.MiddleName = strings.ReplaceAll(
			strings.Join(names[1:lastIdx], " "), "_", " ",
		)

		if len(author.MiddleName) > 0 {
			initials.WriteByte(author.MiddleName[0])
		}
		initials.WriteByte(author.LastName[0])
	}

	author.Initials = initials.String()

	return author
}

//
// FullName return the concatenation of author first, middle, and last name.
//
func (author *Author) FullName() string {
	var sb strings.Builder

	sb.WriteString(author.FirstName)
	if len(author.MiddleName) > 0 {
		sb.WriteString(" " + author.MiddleName)
	}
	if len(author.LastName) > 0 {
		sb.WriteString(" " + author.LastName)
	}
	return sb.String()
}