-
Notifications
You must be signed in to change notification settings - Fork 865
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
21 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,56 +1,41 @@ | ||
import path from 'path' | ||
import fs from 'fs' | ||
|
||
function join (...parts) { | ||
const replace = new RegExp('/{1,}', 'g') | ||
return parts.join('/').replace(replace, '/') | ||
} | ||
|
||
function clean (files, root) { | ||
const res = [] | ||
|
||
files.forEach((file) => { | ||
const stat = fs.lstatSync(file) | ||
const dst = join(root, path.basename(file)) | ||
|
||
if (stat.isDirectory()) { | ||
const files = clean(fs.readdirSync(file).map(f => path.join(file, f)), dst) | ||
res.push({dir: true, dst: dst}, ...files) | ||
} else { | ||
res.push({ | ||
dst: dst, | ||
src: file | ||
}) | ||
} | ||
}) | ||
|
||
return res | ||
let adding = 0 | ||
|
||
async function add (files, root, ipfs) { | ||
for (const file of files) { | ||
const res = await ipfs().add([file], {recursive: true, wrap: true}) | ||
const f = res[res.length - 1] | ||
const src = `/ipfs/${f.hash}` | ||
const dst = join(root, path.basename(f.path)) | ||
|
||
await ipfs().files.cp([src, dst]) | ||
} | ||
} | ||
|
||
export default function uploadFiles (opts) { | ||
let {ipfs, debug, send} = opts | ||
let adding = 0 | ||
|
||
const sendAdding = () => { send('adding', adding > 0) } | ||
const inc = () => { adding++; sendAdding() } | ||
const dec = () => { adding--; sendAdding() } | ||
|
||
const anyway = () => { | ||
dec() | ||
send('files-updated') | ||
} | ||
|
||
return (event, files, root = '/') => { | ||
debug('Uploading files', {files}) | ||
files = clean(files, root) | ||
|
||
inc() | ||
Promise.all(files.map(file => { | ||
if (file.dir) { | ||
return ipfs().files.mkdir(file.dst) | ||
} | ||
|
||
return ipfs().files.write(file.dst, file.src, {create: true}) | ||
})).then(() => { | ||
dec() | ||
send('files-updated') | ||
}).catch((e) => { | ||
debug(e.stack) | ||
}) | ||
|
||
add(files, root, ipfs) | ||
.then(anyway) | ||
.catch((e) => { anyway(); debug(e.stack) }) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters