Skip to content

Instantly share code, notes, and snippets.

@kstieger
Created March 2, 2020 19:44
Show Gist options
  • Save kstieger/66399edf56ca967b9ac232e6c438c4cd to your computer and use it in GitHub Desktop.
Save kstieger/66399edf56ca967b9ac232e6c438c4cd to your computer and use it in GitHub Desktop.
Create iso file in pure go
package main
import (
"flag"
"fmt"
diskfs "github.com/diskfs/go-diskfs"
"github.com/diskfs/go-diskfs/disk"
"github.com/diskfs/go-diskfs/filesystem"
"github.com/diskfs/go-diskfs/filesystem/iso9660"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
var debug bool
func dlog(s string) {
if debug {
fmt.Fprintf(os.Stderr, "DEBUG: %v\n", s)
}
}
func mkIso(isoname, volumelabel string, files map[string][]byte) (string, error) {
var err error
var storageSize int64
var diskSize int64
var blockSize int64 = 2048
volLabel := volumelabel
for file := range files {
storageSize += int64(len(files[file])) + blockSize // for each file filelength + blocksize
}
diskImg := fmt.Sprintf("%v.iso", isoname)
diskSize = storageSize + (1024 * 1024) // storagesize plus 1 MB; to be on the safe side
mydisk, err := diskfs.Create(diskImg, diskSize, diskfs.Raw)
check(err)
// the following line is required for an ISO, which may have logical block sizes
// only of 2048, 4096, 8192
mydisk.LogicalBlocksize = blockSize
fspec := disk.FilesystemSpec{
Partition: 0,
FSType: filesystem.TypeISO9660,
VolumeLabel: volLabel}
fs, err := mydisk.CreateFilesystem(fspec)
check(err)
for file := range files {
dest, err := fs.OpenFile(file, os.O_CREATE|os.O_RDWR)
check(err)
_, err = dest.Write(files[file])
check(err)
dlog(fmt.Sprintf("Wrote file: %v/%v", isoname, file))
}
iso, ok := fs.(*iso9660.FileSystem)
if !ok {
check(fmt.Errorf("not an iso9660 filesystem"))
}
err = iso.Finalize(iso9660.FinalizeOptions{
RockRidge: true, // RockRidge to allow dashes in filenames
VolumeIdentifier: volLabel}, // Volumelabel for mounting
)
check(err)
return diskImg, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment