~sbinet/star-tex

star-tex/kpath/kpath.go -rw-r--r-- 5.4 KiB
9bb27e8aSebastien Binet ci: bump to freebsd/latest 7 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright ©2021 The star-tex Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package kpath provides tools to locate TeX related files.
//
// It loosely mimicks Kpathsea, as described in:
//  - https://texdoc.org/serve/kpathsea/0
package kpath // import "star-tex.org/x/tex/kpath"

import (
	"fmt"
	"io"
	"io/fs"
	"os"
	stdpath "path"
	"strings"
	"sync"

	"star-tex.org/x/tex/internal/tds"
)

var (
	once   sync.Once
	tdsCtx Context
)

// New returns a minimal kpath context initialized with the content of
// a minimal TeX Directory Structure.
func New() Context {
	once.Do(func() {
		tdsCtx, _ = NewFromFS(tds.FS)
	})
	return tdsCtx
}

// Context holds state to efficiently search for files in a TDS
// (TeX Directory Structure), as described in:
//  - http://tug.org/tds/tds.pdf
type Context struct {
	exts strset              // known common suffices
	db   map[string][]string // db of filename->dirs
	fs   fs.FS
}

func (ctx *Context) init(root fs.FS) {
	if ctx.exts.db == nil {
		ctx.exts = strsets["tex"]
	}
	if ctx.db == nil {
		ctx.db = make(map[string][]string)
	}
	ctx.fs = root
}

// // NewFromDB creates a kpath search from a TeX .cnf configuration file.
// func NewFromConfig(cfg io.Reader) (Context, error) {
// 	ctx, err := parseConfig(cfg)
// 	if err != nil {
// 		return Context{}, fmt.Errorf("kpath: could not parse config: %w", err)
// 	}
//
// 	ctx.init()
// 	return ctx, nil
// }

// NewFromDB creates a kpath search from a TeX ls-R db file.
func NewFromDB(r io.Reader) (Context, error) {
	return newFromDB(os.DirFS("/"), r)
}

func newFromDB(root fs.FS, r io.Reader) (Context, error) {
	dir := "/"
	if f, ok := r.(interface{ Name() string }); ok {
		dir = stdpath.Dir(f.Name())
	}
	ctx, err := parseDB(dir, r)
	if err != nil {
		return Context{}, fmt.Errorf("kpath: could not parse db file: %w", err)
	}

	ctx.init(root)
	return ctx, nil
}

// NewFromFS creates a kpath search context from the provided filesystem.
//
// NewFromFS checks first whether an ls-R database exists at the root of the
// provided filesystem, and otherwise walks the whole fs.
func NewFromFS(fsys fs.FS) (Context, error) {
	var ctx Context
	ctx.init(fsys)

	if _, err := fs.Stat(fsys, "ls-R"); err == nil {
		db, err := fsys.Open("ls-R")
		if err != nil {
			return ctx, fmt.Errorf("kpath: could not open db file: %w", err)
		}
		defer db.Close()
		return newFromDB(fsys, db)
	}

	err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			return nil
		}
		fname := stdpath.Base(path)
		ctx.db[fname] = append(ctx.db[fname], path)
		return nil
	})
	if err != nil {
		return ctx, fmt.Errorf("kpath: could not walk fs: %w", err)
	}

	return ctx, nil
}

// FS returns the underlying filesystem this context is using.
func (ctx Context) FS() fs.FS {
	return ctx.fs
}

// Open opens the named file for reading.
func (ctx Context) Open(name string) (fs.File, error) {
	f, err := ctx.fs.Open(name)
	if err == nil {
		return f, nil
	}
	// FIXME(sbinet): ctx.fs.Open may fail to open the named file because
	// of absolute vs relative path issues.
	// e.g.:
	//  - ctx.fs is rooted at /usr/share/texmf-dist
	//  - one requests /usr/share/texmf-dist/foo.txt (which exists)
	// Name is thus "/usr/share/texmf-dist/foo.txt",
	// but from the POV of ctx.fs, only "foo.txt" exists.
	// Giving the absolute path from "/" won't work.
	//
	// In the meantime, resort to just calling to os.Open.
	return os.Open(name)
}

// Find returns the full path to the named file if it could be found within the
// TeXMF distribution system.
// Find returns an error if no file or more than one file were found.
func (ctx Context) Find(name string) (string, error) {
	names, err := ctx.FindAll(name)
	if err != nil {
		return "", err
	}

	switch n := len(names); n {
	case 1:
		return names[0], nil
	case 0:
		return "", fmt.Errorf("kpath: could not find a match for %q", name)
	default:
		return "", fmt.Errorf("kpath: too many hits for file %q (n=%d)", name, n)
	}
}

// FindAll returns the full path to all the files matching name that could be
// found within the TeXMF distribution system.
// Find returns an error if no file was found.
func (ctx Context) FindAll(name string) ([]string, error) {
	// TODO(sbinet): handle (all) standard exts.
	// TODO(sbinet): handle multi-root TEXMFs

	orig := name
	name = strings.Replace(name, "\\", "/", -1)
	var (
		subdir = strings.Contains(name, "/")
		ext    = stdpath.Ext(name)
	)
	switch ext {
	case "":
		// try some extensions.
		for _, ext := range ctx.exts.ks {
			names, ok := ctx.lookup(name+ext, subdir)
			if ok {
				return names, nil
			}
		}

		names, ok := ctx.lookup(name, subdir)
		if ok {
			return names, nil
		}

	default:

		if !ctx.exts.has(ext) {
			for _, ext := range ctx.exts.ks {
				names, ok := ctx.lookup(name+ext, subdir)
				if ok {
					return names, nil
				}
			}
		}

		names, ok := ctx.lookup(name, subdir)
		if ok {
			return names, nil
		}
	}

	return nil, fmt.Errorf("kpath: could not find file %q", orig)
}

func (s Context) lookup(name string, subdir bool) ([]string, bool) {
	if !subdir {
		names, ok := s.db[name]
		return names, ok
	}

	var (
		ok    = false
		names = make([]string, 0, 16)
	)
	for _, vs := range s.db {
		for _, v := range vs {
			if !strings.HasSuffix(v, name) {
				continue
			}
			names = append(names, v)
			ok = true
		}
	}

	return names, ok
}