Skip to content

Commit

Permalink
Merge pull request #21 from eddort/refactor/container
Browse files Browse the repository at this point in the history
Refactor/container
  • Loading branch information
eddort authored Jun 7, 2024
2 parents 2940f6c + 4442a33 commit 1850ed8
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 66 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: build

on:
pull_request:
push:

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.21
cache: true
- run: go test -v ./...
35 changes: 35 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#
# Releaser workflow setup
# https://goreleaser.com/ci/actions/
#
name: release

# run only on tags
on:
push:
tags:
- 'v*'

permissions:
contents: write # needed to write releases
id-token: write # needed for keyless signing

jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # this is important, otherwise it won't checkout the full tree (i.e. no previous tags)
- uses: actions/setup-go@v5
with:
go-version: 1.21
cache: true
- uses: sigstore/[email protected] # installs cosign
- uses: anchore/sbom-action/[email protected] # installs syft
- uses: goreleaser/goreleaser-action@v6 # run goreleaser
with:
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
69 changes: 69 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#
# Example keyless signing with SBOMs goreleaser config.
#
# See also: .github/workflows/release.yml

version: 2

project_name: supply-chain-example

# setups builds for linux and darwin on amd64 and arm64
# https://goreleaser.com/customization/build
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- darwin
goarch:
- amd64
- arm64
# ensures mod timestamp to be the commit timestamp
mod_timestamp: "{{ .CommitTimestamp }}"
flags:
# trims path
- -trimpath
ldflags:
# use commit date instead of current date as main.date
# only needed if you actually use those things in your main package, otherwise can be ignored.
- -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{ .CommitDate }}

# proxies from the go mod proxy before building
# https://goreleaser.com/customization/gomod
gomod:
proxy: true

# config the checksum filename
# https://goreleaser.com/customization/checksum
checksum:
name_template: "checksums.txt"

# create a source tarball
# https://goreleaser.com/customization/source/
source:
enabled: true

# creates SBOMs of all archives and the source tarball using syft
# https://goreleaser.com/customization/sbom
sboms:
- artifacts: archive
- id: source # Two different sbom configurations need two different IDs
artifacts: source

# signs the checksum file
# all files (including the sboms) are included in the checksum, so we don't need to sign each one if we don't want to
# https://goreleaser.com/customization/sign
signs:
- cmd: cosign
env:
- COSIGN_EXPERIMENTAL=1
certificate: "${artifact}.pem"
args:
- sign-blob
- "--output-certificate=${certificate}"
- "--output-signature=${signature}"
- "${artifact}"
- "--yes" # needed on cosign 2.0.0+
artifacts: checksum
output: true

75 changes: 9 additions & 66 deletions internal/docker/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import (
"archive/tar"
"bytes"
"context"
"crypto/sha256"
"cubx/internal/streams"
"encoding/hex"
"fmt"
"io"
"os"
Expand All @@ -17,42 +15,6 @@ import (
"github.com/docker/docker/pkg/jsonmessage"
)

// Function for calculating the hash sum of a directory
func HashDirectory(dir string) (string, error) {
hash := sha256.New()

err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// Add file information to the hash
hash.Write([]byte(info.Name()))
hash.Write([]byte(info.Mode().String()))
hash.Write([]byte(info.ModTime().String()))

// If it's a file, add its contents to the hash
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()

if _, err := io.Copy(hash, file); err != nil {
return err
}
}
return nil
})

if err != nil {
return "", err
}

return hex.EncodeToString(hash.Sum(nil)), nil
}

// Function for creating a tar archive from a directory
func tarDirectory(dir string) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
Expand Down Expand Up @@ -116,27 +78,22 @@ func PrintTarContents(buf *bytes.Buffer) error {

// Basic function to build a Docker image with hash validation
func BuildImage(dockerfilePath, imageTag, contextDir string) error {
fmt.Println("context build: ", contextDir)
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
// TODO: force rebuild
found, err := imageExists(ctx, cli, imageTag)
if err != nil {
return err
}

// currentHash, err := hashDirectory(contextDir)
// if err != nil {
// return err
// }

// hashFilePath := filepath.Join(contextDir, ".context_hash")

// previousHash, err := os.ReadFile(hashFilePath)
// if err != nil && !os.IsNotExist(err) {
// return err
// }
if found {
return nil
}

// if string(previousHash) != currentHash {
// fmt.Println("Context has changed, creating new tar archive...")
fmt.Println("context build:", contextDir)

tarBuf, err := tarDirectory(contextDir)
if err != nil {
Expand All @@ -147,7 +104,6 @@ func BuildImage(dockerfilePath, imageTag, contextDir string) error {
Dockerfile: filepath.Base(dockerfilePath),
Tags: []string{imageTag},
Remove: true,
// NoCache: true,
}

buildResponse, err := cli.ImageBuild(ctx, tarBuf, buildOptions)
Expand All @@ -159,19 +115,6 @@ func BuildImage(dockerfilePath, imageTag, contextDir string) error {
if err != nil {
return err
}
// Save the new hash to a file
// if err := os.WriteFile(hashFilePath, []byte(currentHash), 0644); err != nil {
// return err
// }

// Reading the response from the image builder
// _, err = io.Copy(os.Stdout, buildResponse.Body)
// if err != nil {
// return err
// }
// } else {
// fmt.Println("Context has not changed, skipping tar archive creation.")
// }

return nil
}
4 changes: 4 additions & 0 deletions internal/docker/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ func getCWD() (string, error) {

func getENV(currentCWD string) []string {
containerENVS := []string{}
termEnv := os.Getenv("TERM")
if termEnv != "" {
containerENVS = append(containerENVS, fmt.Sprintf("TERM=%s", termEnv))
}

containerENVS = append(containerENVS, fmt.Sprintf("CUBX_HOST_CWD=%s", currentCWD))
// TODO: pass env from .cubx/config
Expand Down

0 comments on commit 1850ed8

Please sign in to comment.