Skip to content

Commit

Permalink
feat: add OptCreateWithCloseOnUnload
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Hughes committed Aug 13, 2021
1 parent 857fcbc commit f85ecd8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
28 changes: 22 additions & 6 deletions pkg/sif/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,10 @@ func (f *FileImage) writeHeader() error {

// createOpts accumulates container creation options.
type createOpts struct {
id uuid.UUID
dis []DescriptorInput
t time.Time
id uuid.UUID
dis []DescriptorInput
t time.Time
closeOnUnload bool
}

// CreateOpt are used to specify container creation options.
Expand Down Expand Up @@ -168,6 +169,15 @@ func OptCreateWithTime(t time.Time) CreateOpt {
}
}

// OptCreateWithCloseOnUnload specifies whether the ReadWriter should be closed by UnloadContainer.
// By default, the ReadWriter will be closed if it implements the io.Closer interface.
func OptCreateWithCloseOnUnload(b bool) CreateOpt {
return func(co *createOpts) error {
co.closeOnUnload = b
return nil
}
}

// createContainer creates a new SIF container file in rw, according to opts.
func createContainer(rw ReadWriter, co createOpts) (*FileImage, error) {
h := header{
Expand Down Expand Up @@ -215,16 +225,18 @@ func createContainer(rw ReadWriter, co createOpts) (*FileImage, error) {
// CreateContainer creates a new SIF container in rw, according to opts.
//
// On success, a FileImage is returned. The caller must call UnloadContainer to ensure resources
// are released.
// are released. By default, UnloadContainer will close rw if it implements the io.Closer
// interface. To change this behavior, consider using OptCreateWithCloseOnUnload.
func CreateContainer(rw ReadWriter, opts ...CreateOpt) (*FileImage, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, err
}

co := createOpts{
id: id,
t: time.Now(),
id: id,
t: time.Now(),
closeOnUnload: true,
}

for _, opt := range opts {
Expand All @@ -237,6 +249,8 @@ func CreateContainer(rw ReadWriter, opts ...CreateOpt) (*FileImage, error) {
if err != nil {
return nil, fmt.Errorf("%w", err)
}

f.closeOnUnload = co.closeOnUnload
return f, nil
}

Expand All @@ -255,6 +269,8 @@ func CreateContainerAtPath(path string, opts ...CreateOpt) (*FileImage, error) {
fp.Close()
os.Remove(fp.Name())
}

f.closeOnUnload = true
return f, err
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/sif/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func TestCreateContainer(t *testing.T) {
defer tf.Close()

// test container creation without any input descriptors
f, err := CreateContainer(tf)
f, err := CreateContainer(tf, OptCreateWithCloseOnUnload(true))
if err != nil {
t.Fatalf("failed to create container: %v", err)
}
Expand Down

0 comments on commit f85ecd8

Please sign in to comment.