This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathadd.js
96 lines (85 loc) · 2.47 KB
/
add.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict'
const Command = require('ronin').Command
const utils = require('../../utils')
const debug = require('debug')
const log = debug('cli:version')
log.error = debug('cli:version:error')
const bs58 = require('bs58')
const fs = require('fs')
const parallelLimit = require('run-parallel-limit')
const path = require('path')
const glob = require('glob')
function checkPath (inPath, recursive) {
// This function is to check for the following possible inputs
// 1) "." add the cwd but throw error for no recursion flag
// 2) "." -r return the cwd
// 3) "/some/path" but throw error for no recursion
// 4) "/some/path" -r
// 5) No path, throw err
// 6) filename.type return the cwd + filename
if (!inPath) {
throw new Error('Error: Argument \'path\' is required')
}
if (inPath === '.') {
inPath = process.cwd()
}
if (fs.statSync(inPath).isDirectory() && recursive === false) {
throw new Error(`Error: ${inPath} is a directory, use the '-r' flag to specify directories`)
}
return inPath
}
module.exports = Command.extend({
desc: 'Add a file to IPFS using the UnixFS data format',
options: {
recursive: {
alias: 'r',
type: 'boolean',
default: false
}
},
run: (recursive, inPath) => {
let rs
inPath = checkPath(inPath, recursive)
glob(path.join(inPath, '/**/*'), (err, res) => {
if (err) {
throw err
}
utils.getIPFS((err, ipfs) => {
if (err) {
throw err
}
const i = ipfs.files.add()
var filePair
i.on('data', (file) => {
console.log('added', bs58.encode(file.multihash).toString(), file.path)
})
i.once('end', () => {
return
})
if (res.length !== 0) {
const index = inPath.lastIndexOf('/')
parallelLimit(res.map((element) => (callback) => {
if (!fs.statSync(element).isDirectory()) {
i.write({
path: element.substring(index + 1, element.length),
stream: fs.createReadStream(element)
})
}
callback()
}), 10, (err) => {
if (err) {
throw err
}
i.end()
})
} else {
rs = fs.createReadStream(inPath)
inPath = inPath.substring(inPath.lastIndexOf('/') + 1, inPath.length)
filePair = {path: inPath, stream: rs}
i.write(filePair)
i.end()
}
})
})
}
})