File: operations.go

package info (click to toggle)
golang-code.forgejo-f3-gof3 3.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,952 kB
  • sloc: sh: 100; makefile: 65
file content (61 lines) | stat: -rw-r--r-- 1,464 bytes parent folder | download
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
// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package path

import (
	"path/filepath"
	"strings"

	"code.forgejo.org/f3/gof3/v3/id"
	"code.forgejo.org/f3/gof3/v3/kind"
)

func PathAbsoluteString(current, destination string) string {
	if !strings.HasPrefix(destination, "/") {
		return filepath.Clean(current + "/" + destination)
	}
	return filepath.Clean(destination)
}

func PathAbsolute(allocator PathElementAllocator, current, destination string) Path {
	return NewPathFromString(allocator, PathAbsoluteString(current, destination))
}

func PathRelativeString(current, destination string) string {
	r, err := filepath.Rel(current, destination)
	if err != nil {
		panic(err)
	}
	return r
}

func NewPathFromString(allocator PathElementAllocator, pathString string) Path {
	pathString = filepath.Clean(pathString)
	if pathString == "." {
		e := allocator()
		e.SetID(id.NewNodeID("."))
		return NewPath(e)
	}
	path := make([]PathElement, 0, 10)
	if strings.HasPrefix(pathString, "/") {
		root := allocator()
		root.SetKind(kind.KindRoot)
		path = append(path, root)
		pathString = pathString[1:]
	}
	if pathString == "" {
		return NewPath(path...)
	}
	for _, i := range strings.Split(pathString, "/") {
		e := allocator()
		e.SetID(id.NewNodeID(i))
		path = append(path, e)
	}
	return NewPath(path...)
}

func NewPath(nodes ...PathElement) Path {
	return Implementation(nodes)
}