Skip to content

Commit 83be1df

Browse files
committed
Allows to open disk from already existing os.File descriptor
I.e. in some fs.FS compliant VFS, given that vfs.Open("some.img") returns fs.File
1 parent f66ea89 commit 83be1df

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

diskfs.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ package diskfs
105105
import (
106106
"errors"
107107
"fmt"
108+
"io/fs"
108109
"os"
109110

110111
log "github.com/sirupsen/logrus"
@@ -332,6 +333,29 @@ func Open(device string, opts ...OpenOpt) (*disk.Disk, error) {
332333
return initDisk(f, ReadWriteExclusive, opt.sectorSize)
333334
}
334335

336+
// Open a Disk using provided fs.File to a device in read-only mode
337+
// Use OpenOpt to control options, such as sector size or open mode.
338+
func OpenFile(f fs.File, opts ...OpenOpt) (*disk.Disk, error) {
339+
340+
opt := &openOpts{
341+
mode: ReadOnly,
342+
sectorSize: SectorSizeDefault,
343+
}
344+
345+
for _, o := range opts {
346+
if err := o(opt); err != nil {
347+
return nil, err
348+
}
349+
}
350+
351+
if osFile, ok := f.(*os.File); ok {
352+
return initDisk(osFile, opt.mode, opt.sectorSize)
353+
}
354+
355+
fi, _ := f.Stat()
356+
return nil, fmt.Errorf("could not open device image %s with mode %v", fi.Name(), opt.mode)
357+
}
358+
335359
// Create a Disk from a path to a device
336360
// Should pass a path to a block device e.g. /dev/sda or a path to a file /tmp/foo.img
337361
// The provided device must not exist at the time you call Create()

0 commit comments

Comments
 (0)