github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/archive/create_service.go (about)

     1  // Copyright 2016-2022 The Libsacloud Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package archive
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  
    23  	archiveBuilder "github.com/sacloud/libsacloud/v2/helper/builder/archive"
    24  	"github.com/sacloud/libsacloud/v2/sacloud"
    25  )
    26  
    27  func (s *Service) Create(req *CreateRequest) (*sacloud.Archive, error) {
    28  	return s.CreateWithContext(context.Background(), req)
    29  }
    30  
    31  func (s *Service) CreateWithContext(ctx context.Context, req *CreateRequest) (*sacloud.Archive, error) {
    32  	if err := req.Validate(); err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	var reader io.Reader
    37  	switch req.SourcePath {
    38  	case "":
    39  		reader = req.SourceReader
    40  	default:
    41  		file, err := os.Open(req.SourcePath)
    42  		if err != nil {
    43  			return nil, fmt.Errorf("reading source file[%s] failed: %s", req.SourcePath, err)
    44  		}
    45  		defer file.Close() // nolint
    46  		reader = file
    47  	}
    48  
    49  	builder := (&archiveBuilder.Director{
    50  		Name:              req.Name,
    51  		Description:       req.Description,
    52  		Tags:              req.Tags,
    53  		IconID:            req.IconID,
    54  		SizeGB:            req.SizeGB,
    55  		SourceReader:      reader,
    56  		SourceDiskID:      req.SourceDiskID,
    57  		SourceArchiveID:   req.SourceArchiveID,
    58  		SourceArchiveZone: req.SourceArchiveZone,
    59  		SourceSharedKey:   "",
    60  		NoWait:            req.NoWait,
    61  		Client:            archiveBuilder.NewAPIClient(s.caller),
    62  	}).Builder()
    63  	if err := builder.Validate(ctx, req.Zone); err != nil {
    64  		return nil, err
    65  	}
    66  	return builder.Build(ctx, req.Zone)
    67  }