Skip to content

Commit ce576eb

Browse files
committed
functionality to load tar images
1 parent 693e051 commit ce576eb

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

image.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,30 @@ func extractLayer(reader io.Reader, rootfs string) error {
155155
return fmt.Errorf("failed to extract layer: %w", err)
156156
}
157157
return nil
158+
}
159+
160+
// LoadImageFromTar loads a container image from a .tar file
161+
func LoadImageFromTar(tarFilePath string, imageName string) (*Image, error) {
162+
rootfs := filepath.Join("/tmp/basic-docker/images", imageName, "rootfs")
163+
if err := os.MkdirAll(rootfs, 0755); err != nil {
164+
return nil, fmt.Errorf("failed to create rootfs: %w", err)
165+
}
166+
167+
// Extract the tar file to the rootfs directory
168+
tarFile, err := os.Open(tarFilePath)
169+
if err != nil {
170+
return nil, fmt.Errorf("failed to open tar file: %w", err)
171+
}
172+
defer tarFile.Close()
173+
174+
cmd := exec.Command("tar", "-x", "-C", rootfs, "-f", tarFilePath)
175+
if err := cmd.Run(); err != nil {
176+
return nil, fmt.Errorf("failed to extract tar file: %w", err)
177+
}
178+
179+
return &Image{
180+
Name: imageName,
181+
RootFS: rootfs,
182+
Layers: []string{"base"},
183+
}, nil
158184
}

main.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,23 @@ func main() {
270270
err := DetachContainerFromNetwork(os.Args[2], os.Args[3])
271271
if err != nil {
272272
fmt.Printf("Error: %s\n", err)
273+
return
274+
}
275+
case "load":
276+
if len(os.Args) < 3 {
277+
fmt.Println("Error: Tar file path required for load")
278+
os.Exit(1)
279+
}
280+
tarFilePath := os.Args[2]
281+
imageName := strings.TrimSuffix(filepath.Base(tarFilePath), ".tar")
282+
283+
fmt.Printf("Loading image from '%s'...\n", tarFilePath)
284+
image, err := LoadImageFromTar(tarFilePath, imageName)
285+
if err != nil {
286+
fmt.Printf("Error: Failed to load image from '%s': %v\n", tarFilePath, err)
287+
os.Exit(1)
273288
}
289+
fmt.Printf("Image '%s' loaded successfully.\n", image.Name)
274290
default:
275291
printUsage()
276292
os.Exit(1)
@@ -289,6 +305,7 @@ func printUsage() {
289305
fmt.Println(" basic-docker network-delete <network-id> Delete a network by ID")
290306
fmt.Println(" basic-docker network-attach <network-id> <container-id> Attach a container to a network")
291307
fmt.Println(" basic-docker network-detach <network-id> <container-id> Detach a container from a network")
308+
fmt.Println(" basic-docker load <tar-file-path> Load an image from a tar file")
292309
}
293310

294311
func printSystemInfo() {

0 commit comments

Comments
 (0)