build: refractor internal tools.

This commit is contained in:
Alexandre Pujol 2024-03-10 19:07:55 +00:00
parent df21886965
commit b0d52d68f4
No known key found for this signature in database
GPG key ID: C5469996F0DF68EC
3 changed files with 29 additions and 5 deletions

View file

@ -1,72 +0,0 @@
// apparmor.d - Full set of apparmor profiles
// Copyright (C) 2023-2024 Alexandre Pujol <alexandre@pujol.io>
// SPDX-License-Identifier: GPL-2.0-only
package util
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/arduino/go-paths-helper"
)
// Either or not to extract the file
func toExtrat(name string, subfolders []string) bool {
for _, subfolder := range subfolders {
if strings.HasPrefix(name, subfolder) {
return true
}
}
return false
}
// Extract part of an archive to a destination directory
func ExtratTo(src *paths.Path, dst *paths.Path, subfolders []string) error {
gzIn, err := src.Open()
if err != nil {
return fmt.Errorf("opening %s: %w", src, err)
}
defer gzIn.Close()
in, err := gzip.NewReader(gzIn)
if err != nil {
return fmt.Errorf("decoding %s: %w", src, err)
}
defer in.Close()
if err := dst.MkdirAll(); err != nil {
return fmt.Errorf("creating %s: %w", src, err)
}
tarIn := tar.NewReader(in)
for {
header, err := tarIn.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if header.Typeflag == tar.TypeReg {
if !toExtrat(header.Name, subfolders) {
continue
}
path := dst.Join(filepath.Base(header.Name))
file, err := path.Create()
if err != nil {
return fmt.Errorf("creating %s: %w", file.Name(), err)
}
if _, err := io.Copy(file, tarIn); err != nil {
return fmt.Errorf("extracting %s: %w", file.Name(), err)
}
file.Close()
}
}
return nil
}

View file

@ -61,7 +61,7 @@ func TestToRegexRepl(t *testing.T) {
tests := []struct {
name string
in []string
want []RegexRepl
want RegexReplList
}{
{
name: "",
@ -83,3 +83,28 @@ func TestToRegexRepl(t *testing.T) {
})
}
}
func TestRegexReplList_Replace(t *testing.T) {
tests := []struct {
name string
rr RegexReplList
str string
want string
}{
{
name: "default",
rr: []RegexRepl{
{Regex: regexp.MustCompile(`^/foo`), Repl: "/bar"},
},
str: "/foo",
want: "/bar",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.rr.Replace(tt.str); got != tt.want {
t.Errorf("RegexReplList.Replace() = %v, want %v", got, tt.want)
}
})
}
}