Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mrclmr committed Jun 5, 2024
0 parents commit 7712078
Show file tree
Hide file tree
Showing 8 changed files with 669 additions and 0 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/lint_test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: lint and test

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:

build:
runs-on: ubuntu-latest
steps:

- name: Check out
uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'

- name: Lint
uses: golangci/golangci-lint-action@v6
with:
# Require: The version of golangci-lint to use.
version: latest

- name: Test
run: go test
7 changes: 7 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
linters:
enable:
- revive
- gofumpt
- errorlint
- godot
- errname
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2017 Marcel Meyer [email protected]

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Annotate

```
The quick brown fox jumps over the lazy dog
↑ ↑ ↑
│ └─ adjective └─ adjective
└─ adjective
```

## Installation

```
go get github.com/meyermarcel/annotate
```

## Example

```go
package main

import (
"fmt"

"github.com/meyermarcel/annotate"
)

func main() {
fmt.Println("The quick brown fox jumps over the lazy dog")
fmt.Println(annotate.String([]*annotate.Annotation{
{Col: 6, Lines: []string{"adjective"}},
{Col: 12, Lines: []string{"adjective"}},
{Col: 36, Lines: []string{"adjective"}},
}))
}
```

```
The quick brown fox jumps over the lazy dog
↑ ↑ ↑
│ └─ adjective └─ adjective
└─ adjective
```
262 changes: 262 additions & 0 deletions annotation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
package annotate

import (
"fmt"
"io"
"slices"
"strings"
"unicode/utf8"
)

type Value struct {
Value string
Annotation *Annotation
}

type Annotation struct {
Col int
Lines []string
row int
lines []*line
pipeLeadingSpaces []int
}

type line struct {
length int
leadingSpaces int
}

type section int

// # | column |0123456789...
// ----+------------------------+-------------------------------
// row | section | ↓ column position of annotation
// - | not relevant | ↑
// 0···| above··················|···██│
// 1 | above | ██│
// 2···| linesFirstTwo··········|···██└─ line1············row position of annotation
// 3 | linesFirstTwo | █████line2
// 4···| linesAfterSecond·······|······██line3
// 5 | linesAfterSecond | ██line4
// 6···| trailingSpaceLines(1)··|······███████
// 7 | noAnnotation |
// 8···| noAnnotation···········|··················
// ----+------------------------+-------------------------------
// # | | █ = needed space.
const (
above section = iota
linesFirstTwo
linesAfterSecond
trailingSpaceLines
noAnnotation
)

func (a *Annotation) AddLines(lines ...string) {
a.Lines = append(a.Lines, lines...)
}

func String(annotations ...*Annotation) string {
b := &strings.Builder{}
_ = Write(b, annotations...)
return b.String()
}

func Write(w io.Writer, annotations ...*Annotation) error {
annotations = slices.CompactFunc(annotations, func(a1 *Annotation, a2 *Annotation) bool {
return a1.Col == a2.Col
})

if len(annotations) == 0 {
return nil
}

slices.SortFunc(annotations, func(a *Annotation, b *Annotation) int {
return a.Col - b.Col
})

for _, a := range annotations {
if len(a.Lines) == 0 {
a.lines = append(a.lines, &line{})
break
}
a.lines = make([]*line, len(a.Lines))
for i := range a.Lines {
a.lines[i] = &line{
// 3 for "└─ " or " " (indentation)
length: 3 + utf8.RuneCountInString(a.Lines[i]),
leadingSpaces: a.Col,
}
}
a.pipeLeadingSpaces = make([]int, 0)
}

// Start with second last annotation index and decrement.
// The last annotation will always be on row=0 and needs
// no adjustment.
for aIdxDecr := len(annotations) - 2; 0 <= aIdxDecr; aIdxDecr-- {
setRow(annotations[aIdxDecr], annotations[aIdxDecr+1:])
}

return write(w, annotations)
}

func setRow(a *Annotation, rightAnnotations []*Annotation) {
row := 0

for {
rowBefore := row - 1
if rowBefore != -1 {
setSpace(rowBefore, a, rightAnnotations)
}

annotationFits := checkLinesAndSetSpaces(row, a, rightAnnotations)
if annotationFits {
return
}
row++
}
}

func setSpace(rowBefore int, a *Annotation, rightAnnotations []*Annotation) {
rightA, s := closestAnnotation(rowBefore, rightAnnotations, 0)
switch s {
case above:
rightA.pipeLeadingSpaces[rowBefore] = rightA.Col - a.Col - 1
case linesFirstTwo, linesAfterSecond:
rightA.lines[rowBefore-rightA.row].leadingSpaces = rightA.Col - a.Col - 1
case noAnnotation, trailingSpaceLines:
// Do nothing
}
}

func checkLinesAndSetSpaces(row int, a *Annotation, rightAnnotations []*Annotation) bool {
for aLineIdx := 0; aLineIdx < len(a.lines); aLineIdx++ {
lineFits := checkLineAndSetSpace(row, aLineIdx, a, rightAnnotations)
if !lineFits {
return false
}
}
return true
}

func checkLineAndSetSpace(row, aLineIdx int, a *Annotation, rightAnnotations []*Annotation) bool {
rowPlusLineIdx := row + aLineIdx

closestA, s := closestAnnotation(rowPlusLineIdx, rightAnnotations, 1)
if s == noAnnotation {
return true
}

lineLength := a.lines[aLineIdx].length

remainingSpaces := closestA.Col - a.Col - lineLength

// | ↑
// above | ██│
// above | ██│
// linesFirstTwo | ██└─ line1
// linesFirstTwo | ██ line2
// linesAfterSecond | line3
//
// █ = needed space
if s == above || s == linesFirstTwo {
remainingSpaces -= 2
}

if remainingSpaces < 0 {
a.row++
a.pipeLeadingSpaces = append(a.pipeLeadingSpaces, a.Col)
return false
}

switch s {
case above:
closestA.pipeLeadingSpaces[rowPlusLineIdx] = remainingSpaces + 2
case linesFirstTwo:
closestA.lines[rowPlusLineIdx-closestA.row].leadingSpaces = remainingSpaces + 2
case linesAfterSecond:
closestA.lines[rowPlusLineIdx-closestA.row].leadingSpaces = remainingSpaces
case trailingSpaceLines:
closestA2, s2 := closestAnnotation(rowPlusLineIdx, rightAnnotations, 0)
if s2 == noAnnotation {
return true
}
if s2 == above {
closestA2.pipeLeadingSpaces[rowPlusLineIdx] = closestA2.Col - a.Col - lineLength
break
}
closestA2.lines[rowPlusLineIdx-closestA2.row].leadingSpaces = closestA2.Col - a.Col - lineLength
default:
panic("should never be reached")
}
return true
}

func closestAnnotation(row int, nextAnnotations []*Annotation, trailingVerticalSpaceLinesCount int) (*Annotation, section) {
for _, a := range nextAnnotations {
if row < a.row {
return a, above
}
if a.row <= row && row < a.row+len(a.lines) && row < 2 {
return a, linesFirstTwo
}
if 2 <= row && row < a.row+len(a.lines) {
return a, linesAfterSecond
}
if a.row+len(a.lines) <= row && row < a.row+len(a.lines)+trailingVerticalSpaceLinesCount {
return a, trailingSpaceLines
}

}
return nil, noAnnotation
}

func write(writer io.Writer, annotations []*Annotation) error {
lastColPos := 0
rowCount := 0

b := &strings.Builder{}

for _, a := range annotations {
b.WriteString(strings.Repeat(" ", a.Col-lastColPos))
b.WriteString("↑")
lastColPos = a.Col + 1

// Also use this loop to calculate rowCount
rowCount = max(rowCount, a.row+len(a.lines))
}
b.WriteString("\n")
_, err := fmt.Fprint(writer, b.String())
if err != nil {
return err
}
b.Reset()

for row := 0; row < rowCount; row++ {
for _, a := range annotations {
switch {
case row < a.row:
b.WriteString(strings.Repeat(" ", a.pipeLeadingSpaces[row]))
b.WriteString("│")
case row == a.row:
b.WriteString(strings.Repeat(" ", a.lines[row-a.row].leadingSpaces))
b.WriteString("└─ ")
if len(a.Lines) != 0 {
b.WriteString(a.Lines[0])
}
case row < a.row+len(a.lines):
b.WriteString(strings.Repeat(" ", a.lines[row-a.row].leadingSpaces))
b.WriteString(" ")
b.WriteString(a.Lines[row-a.row])
}
}
b.WriteString("\n")
_, err = fmt.Fprint(writer, b.String())
if err != nil {
return err
}
b.Reset()
}

return nil
}
Loading

0 comments on commit 7712078

Please sign in to comment.