package Package import ( "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strconv" "strings" bolt "go.etcd.io/bbolt" "PackageManager/Archive" "PackageManager/Client/Database" "PackageManager/Client/Filesystem" "PackageManager/Color" "PackageManager/Helper" "PackageManager/Variables" ) func writeManifestFile(path, name, version string) error { var ( cmd *exec.Cmd manifest string filePath string e error ) manifest = fmt.Sprintf(`name: "%s" version: "%s" dependancies: - pkg1: v1.0.0 - pkg2: v1.0.0 `, name, version) filePath = filepath.Join(path, "manifest.yml") e = ioutil.WriteFile(filePath, []byte(manifest), 0644) if e != nil { return e } cmd = exec.Command(Variables.Editor, filePath) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout return cmd.Run() } func CreatePackage() error { var ( picksBucket *bolt.Bucket pickedFiles []string pkgFiles []string choices string choicesSplit []string pkgName string pkgVersion string pkgNameVersion string tmpDir string index int e error ) fmt.Println("Initialising package creation...") e = Database.FsDB.View(func(tx *bolt.Tx) error { picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket.ForEach(func(k, v []byte) error { pickedFiles = append(pickedFiles, string(k)) return nil }) return nil }) fmt.Println("Added files:") Filesystem.PrintFiles(pickedFiles, Color.Green, true) fmt.Println("Please select the files you would like to use to create the package. Leave empty for all.") choices = Helper.Input() if choices == "" { pkgFiles = pickedFiles } else { choicesSplit = strings.Split(choices, ",") for _, i := range choicesSplit { index, e = strconv.Atoi(i) if e != nil { // TODO: Handle this error panic(e) } if len(pickedFiles) < index { return errors.New("Invalid choice") } pkgFiles = append(pkgFiles, pickedFiles[index]) } } fmt.Println("Please enter the package name:") pkgName = Helper.Input() if pkgName == "" { return errors.New("Invalid package name") } fmt.Println("Please enter the package version:") pkgVersion = Helper.Input() if pkgVersion == "" { return errors.New("Invalid package name") } fmt.Printf("Package Name: %s\n", pkgName) fmt.Printf("Package Version: %s\n", pkgVersion) fmt.Println("Files to be added") Filesystem.PrintFiles(pkgFiles, Color.Green, false) fmt.Println("Is this correct? [y/N]") if strings.ToLower(Helper.Input()) != "y" { return errors.New("User aborted") } pkgNameVersion = fmt.Sprintf("%s-%s", pkgName, pkgVersion) tmpDir, e = ioutil.TempDir("/tmp", pkgNameVersion) if e != nil { return e } defer os.RemoveAll(tmpDir) for _, file := range pkgFiles { Filesystem.CopyFile(file, filepath.Join(tmpDir, file)) } e = writeManifestFile(tmpDir, pkgName, pkgVersion) if e != nil { return e } e = Archive.TarGzip(tmpDir, pkgNameVersion+".tar.gz") if e != nil { return e } fmt.Printf( Color.Green("\nSuccessfully created package %s\n"), pkgNameVersion, ) return nil }