Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

fix: allow writing starting at offset beyond file length #71

Merged
merged 1 commit into from
Jan 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/core/write.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const write = async (context, source, destination, options) => {

// pad start of file if necessary
if (options.offset > 0) {
if (destination.unixfs && destination.unixfs.fileSize() > options.offset) {
if (destination.unixfs) {
log(`Writing first ${options.offset} bytes of original file`)

sources.push(
Expand All @@ -139,6 +139,15 @@ const write = async (context, source, destination, options) => {
})
}
)

if (destination.unixfs.fileSize() < options.offset) {
const extra = options.offset - destination.unixfs.fileSize()

log(`Writing zeros for extra ${extra} bytes`)
sources.push(
asyncZeroes(extra)
)
}
} else {
log(`Writing zeros for first ${options.offset} bytes`)
sources.push(
Expand Down
10 changes: 6 additions & 4 deletions test/core/write.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,11 +373,13 @@ describe('write', () => {
const stats = await mfs.stat(path)
expect(stats.size).to.equal(newContent.length + offset)

const buffer = Buffer.concat(await all(mfs.read(path, {
offset: offset - 5
})))
const buffer = Buffer.concat(await all(mfs.read(path)))

if (content[Symbol.asyncIterator]) {
content = Buffer.concat(await all(content))
}

expect(buffer).to.deep.equal(Buffer.concat([Buffer.from([0, 0, 0, 0, 0]), newContent]))
expect(buffer).to.deep.equal(Buffer.concat([content, Buffer.from([0, 0, 0, 0, 0]), newContent]))
})
})

Expand Down