Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/ioutilx/ioutilx.go
2639 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package ioutilx
5
6
import (
7
"context"
8
"errors"
9
"fmt"
10
"io"
11
"os/exec"
12
"path/filepath"
13
"strings"
14
15
"github.com/sirupsen/logrus"
16
"golang.org/x/text/encoding/unicode"
17
"golang.org/x/text/transform"
18
)
19
20
// ReadAtMaximum reads n at maximum.
21
func ReadAtMaximum(r io.Reader, n int64) ([]byte, error) {
22
lr := &io.LimitedReader{
23
R: r,
24
N: n,
25
}
26
b, err := io.ReadAll(lr)
27
if err != nil {
28
if errors.Is(err, io.EOF) && lr.N <= 0 {
29
err = fmt.Errorf("exceeded the limit (%d bytes): %w", n, err)
30
}
31
}
32
return b, err
33
}
34
35
// FromUTF16le returns an io.Reader for UTF16le data.
36
// Windows uses little endian by default, use unicode.UseBOM policy to retrieve BOM from the text,
37
// and unicode.LittleEndian as a fallback.
38
func FromUTF16le(r io.Reader) io.Reader {
39
o := transform.NewReader(r, unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewDecoder())
40
return o
41
}
42
43
// FromUTF16leToString reads from Unicode 16 LE encoded data from an io.Reader and returns a string.
44
func FromUTF16leToString(r io.Reader) (string, error) {
45
out, err := io.ReadAll(FromUTF16le(r))
46
if err != nil {
47
return "", err
48
}
49
50
return string(out), nil
51
}
52
53
func WindowsSubsystemPath(ctx context.Context, orig string) (string, error) {
54
out, err := exec.CommandContext(ctx, "cygpath", filepath.ToSlash(orig)).CombinedOutput()
55
if err != nil {
56
logrus.WithError(err).Errorf("failed to convert path to mingw, maybe not using Git ssh?")
57
return "", err
58
}
59
return strings.TrimSpace(string(out)), nil
60
}
61
62
func WindowsSubsystemPathForLinux(ctx context.Context, orig, distro string) (string, error) {
63
out, err := exec.CommandContext(ctx, "wsl", "-d", distro, "--exec", "wslpath", filepath.ToSlash(orig)).CombinedOutput()
64
if err != nil {
65
logrus.WithError(err).Errorf("failed to convert path to mingw, maybe wsl command is not operational?")
66
return "", err
67
}
68
return strings.TrimSpace(string(out)), nil
69
}
70
71