Browse Source

refactor: extractor

Yeuoly 10 months ago
parent
commit
71a9795be4
2 changed files with 37 additions and 23 deletions
  1. 3 23
      internal/core/plugin_manager/watcher.go
  2. 34 0
      internal/core/plugin_packager/decoder/zip.go

+ 3 - 23
internal/core/plugin_manager/watcher.go

@@ -184,29 +184,9 @@ func (p *PluginManager) loadPlugin(plugin_path string) (*pluginRuntimeWithDecode
 		return nil, errors.Join(fmt.Errorf("plugin working directory already exists: %s", plugin_working_path), err)
 	}
 
-	// copy to working directory
-	if err := decoder.Walk(func(filename, dir string) error {
-		working_path := path.Join(plugin_working_path, dir)
-		// check if directory exists
-		if err := os.MkdirAll(working_path, 0755); err != nil {
-			return err
-		}
-
-		bytes, err := decoder.ReadFile(filename)
-		if err != nil {
-			return err
-		}
-
-		filename = path.Join(working_path, filename)
-
-		// copy file
-		if err := os.WriteFile(filename, bytes, 0644); err != nil {
-			return err
-		}
-
-		return nil
-	}); err != nil {
-		return nil, errors.Join(fmt.Errorf("copy plugin to working directory error: %v", err), err)
+	// extract to working directory
+	if err := decoder.ExtractTo(plugin_working_path); err != nil {
+		return nil, errors.Join(fmt.Errorf("extract plugin to working directory error: %v", err), err)
 	}
 
 	return &pluginRuntimeWithDecoder{

+ 34 - 0
internal/core/plugin_packager/decoder/zip.go

@@ -3,8 +3,11 @@ package decoder
 import (
 	"archive/zip"
 	"bytes"
+	"errors"
+	"fmt"
 	"io"
 	"io/fs"
+	"os"
 	"path"
 	"strings"
 
@@ -195,3 +198,34 @@ func (z *ZipPluginDecoder) Checksum() (string, error) {
 func (z *ZipPluginDecoder) UniqueIdentity() (plugin_entities.PluginUniqueIdentifier, error) {
 	return z.PluginDecoderHelper.UniqueIdentity(z)
 }
+
+func (z *ZipPluginDecoder) ExtractTo(dst string) error {
+	// copy to working directory
+	if err := z.Walk(func(filename, dir string) error {
+		working_path := path.Join(dst, dir)
+		// check if directory exists
+		if err := os.MkdirAll(working_path, 0755); err != nil {
+			return err
+		}
+
+		bytes, err := z.ReadFile(filename)
+		if err != nil {
+			return err
+		}
+
+		filename = path.Join(working_path, filename)
+
+		// copy file
+		if err := os.WriteFile(filename, bytes, 0644); err != nil {
+			return err
+		}
+
+		return nil
+	}); err != nil {
+		// if error, delete the working directory
+		os.RemoveAll(dst)
+		return errors.Join(fmt.Errorf("copy plugin to working directory error: %v", err), err)
+	}
+
+	return nil
+}