File: header.go

package info (click to toggle)
golang-github-wellington-go-libsass 0.9.2%2Bgit20181130.4ef5b9d-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,128 kB
  • sloc: cpp: 28,607; ansic: 839; makefile: 44
file content (97 lines) | stat: -rw-r--r-- 1,836 bytes parent folder | download | duplicates (2)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package libsass

import (
	"strconv"
	"sync"

	"github.com/wellington/go-libsass/libs"
)

var globalHeaders []string

// RegisterHeader fifo
func RegisterHeader(body string) {
	ghMu.Lock()
	globalHeaders = append(globalHeaders, body)
	ghMu.Unlock()
}

type Header struct {
	idx     *string
	Content string
}

type Headers struct {
	wg      sync.WaitGroup
	closing chan struct{}
	sync.RWMutex
	h []Header
	// idx is a pointer for libsass to lookup these Headers
	idx int
}

// NewHeaders instantiates a Headers for prefixing Sass to input
// See: https://github.com/sass/libsass/wiki/API-Sass-Importer
func NewHeaders() *Headers {
	h := &Headers{
		closing: make(chan struct{}),
	}
	return h
}

func (hdrs *Headers) Bind(opts libs.SassOptions) {
	// Push the headers into the local array
	ghMu.RLock()
	for _, gh := range globalHeaders {
		if !hdrs.Has(gh) {
			hdrs.Add(gh)
		}
	}
	ghMu.RUnlock()

	// Loop through headers creating ImportEntry
	entries := make([]libs.ImportEntry, hdrs.Len())
	hdrs.RLock()
	for i, ent := range hdrs.h {
		uniquename := "hdr" + strconv.FormatInt(int64(i), 10)
		entries[i] = libs.ImportEntry{
			// Each entry requires a unique identifier
			// https://github.com/sass/libsass/issues/1292
			Path:   uniquename,
			Source: ent.Content,
			SrcMap: "",
		}
	}
	hdrs.RUnlock()
	// Preserve reference to libs address to these entries
	hdrs.idx = libs.BindHeader(opts, entries)
}

func (hdrs *Headers) Close() {
	// Clean up memory reserved for headers
	libs.RemoveHeaders(hdrs.idx)
	close(hdrs.closing)
	hdrs.wg.Wait()
}

func (h *Headers) Add(s string) {
	h.Lock()
	defer h.Unlock()

	h.h = append(h.h, Header{
		Content: s,
	})
}

func (h *Headers) Has(s string) bool {
	for _, c := range h.h {
		if s == c.Content {
			return true
		}
	}
	return false
}

func (h *Headers) Len() int {
	return len(h.h)
}