jx/internal/transport/file.go
Matthew Rich bcf4e768ff
Some checks are pending
Lint / golangci-lint (push) Waiting to run
Declarative Tests / test (push) Waiting to run
Declarative Tests / build-fedora (push) Waiting to run
Declarative Tests / build-ubuntu-focal (push) Waiting to run
Fix an issue with the package resource where a missing package would cause a fatal error
WIP: add support container image build using local filesytem contexts or contextes generated from resource definitions
WIP: added support for the create command in the exec resource
Fix a type matching error in `types` package use of generics
2024-07-22 15:03:22 -07:00

131 lines
2.4 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package transport
import (
_ "errors"
"path/filepath"
"io"
"os"
"net/url"
"strings"
"fmt"
"compress/gzip"
)
type File struct {
uri *url.URL
path string
exttype string
fileext string
readHandle *os.File
writeHandle *os.File
gzip bool
gzipWriter io.WriteCloser
gzipReader io.ReadCloser
}
func FilePath(u *url.URL) string {
return filepath.Join(u.Hostname(), u.Path)
}
func FileExists(u *url.URL) bool {
_, err := os.Stat(FilePath(u))
return err == nil
}
func NewFile(u *url.URL) (f *File, err error) {
f = &File {
uri: u,
path: FilePath(u),
}
f.extension()
f.DetectGzip()
if f.path == "" || f.path == "-" {
f.readHandle = os.Stdin
f.writeHandle = os.Stdout
} else {
if f.readHandle, err = os.OpenFile(f.Path(), os.O_RDWR|os.O_CREATE, 0644); err != nil {
return
}
f.writeHandle = f.readHandle
}
if f.Gzip() {
f.gzipWriter = gzip.NewWriter(f.writeHandle)
if f.gzipReader, err = gzip.NewReader(f.readHandle); err != nil {
return
}
}
return
}
func (f *File) extension() {
elements := strings.Split(f.path, ".")
numberOfElements := len(elements)
if numberOfElements > 1 {
if numberOfElements > 2 {
f.exttype = elements[numberOfElements - 2]
f.fileext = elements[numberOfElements - 1]
}
f.exttype = elements[numberOfElements - 1]
}
}
func (f *File) DetectGzip() {
f.gzip = (f.uri.Query().Get("gzip") == "true" || f.fileext == "gz")
}
func (f *File) URI() *url.URL {
return f.uri
}
func (f *File) Path() string {
return f.path
}
func (f *File) Signature() (documentSignature string) {
if signatureResp, signatureErr := os.Open(fmt.Sprintf("%s.sig", f.uri.String())); signatureErr == nil {
defer signatureResp.Close()
readSignatureBody, readSignatureErr := io.ReadAll(signatureResp)
if readSignatureErr == nil {
documentSignature = string(readSignatureBody)
} else {
panic(readSignatureErr)
}
} else {
panic(signatureErr)
}
return documentSignature
}
func (f *File) ContentType() string {
if f.uri.Scheme != "file" {
return f.uri.Scheme
}
return f.exttype
}
func (f *File) SetGzip(gzip bool) {
f.gzip = gzip
}
func (f *File) Gzip() bool {
return f.gzip
}
func (f *File) Reader() io.ReadCloser {
if f.Gzip() {
return f.gzipReader
}
return f.readHandle
}
func (f *File) Writer() io.WriteCloser {
if f.Gzip() {
return f.gzipWriter
}
return f.writeHandle
}