Skip to content
This repository was archived by the owner on Feb 12, 2024. It is now read-only.

Commit fa9158e

Browse files
author
Alan Shaw
committed
feat: add addFromFs method
This PR adds a new method [`addFromFs`](https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#addfromfs) allowing users to more easily add files from their file system without having to specify every single file to add. In the browser the user will receive a "not available" error. I've pulled out a module `glob-source.js` - call it with some file paths and it returns a pull stream source that can be piped to `ipfs.addPullStream`. This PR comes with the following added benefits: * `ipfs add` on the CLI uses `glob-source.js` - **nice and DRY** * `glob-source.js` uses the events that the `glob` module provides allowing the globbing to be a `pull-pushable`, which means that matched paths can begin to be added before all the globbing is done - **faster** * `ipfs add` now supports adding multiple paths, fixes #1625 - **better** * `ipfs add --progress=false` doesn't calculate the total size of the files to be added anymore! It didn't need to do that as the total was completely discarded when progress was disabled. It means we can add BIGGER directories without running into memory issues - **stronger** License: MIT Signed-off-by: Alan Shaw <[email protected]>
1 parent 9ecabdf commit fa9158e

File tree

7 files changed

+180
-103
lines changed

7 files changed

+180
-103
lines changed

package.json

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@
9494
"datastore-core": "~0.6.0",
9595
"datastore-pubsub": "~0.1.1",
9696
"debug": "^4.1.0",
97-
"deep-extend": "~0.6.0",
9897
"err-code": "^1.1.2",
9998
"file-type": "^10.2.0",
10099
"fnv1a": "^1.0.1",
@@ -160,16 +159,14 @@
160159
"promisify-es6": "^1.0.3",
161160
"protons": "^1.0.1",
162161
"pull-abortable": "^4.1.1",
163-
"pull-catch": "^1.0.0",
162+
"pull-cat": "^1.1.11",
164163
"pull-defer": "~0.2.3",
165164
"pull-file": "^1.1.0",
166165
"pull-ndjson": "~0.1.1",
167-
"pull-paramap": "^1.2.2",
168166
"pull-pushable": "^2.2.0",
169167
"pull-sort": "^1.0.1",
170168
"pull-stream": "^3.6.9",
171169
"pull-stream-to-stream": "^1.3.4",
172-
"pull-zip": "^2.0.1",
173170
"pump": "^3.0.0",
174171
"read-pkg-up": "^4.0.0",
175172
"readable-stream": "3.0.6",

src/cli/commands/add.js

Lines changed: 30 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,41 @@
11
'use strict'
22

3-
const fs = require('fs')
4-
const path = require('path')
5-
const glob = require('glob')
63
const sortBy = require('lodash/sortBy')
74
const pull = require('pull-stream')
8-
const paramap = require('pull-paramap')
9-
const zip = require('pull-zip')
105
const getFolderSize = require('get-folder-size')
116
const byteman = require('byteman')
12-
const waterfall = require('async/waterfall')
7+
const reduce = require('async/reduce')
138
const mh = require('multihashes')
149
const utils = require('../utils')
1510
const print = require('../utils').print
1611
const createProgressBar = require('../utils').createProgressBar
12+
const globSource = require('../../utils/files/glob-source')
1713

18-
function checkPath (inPath, recursive) {
19-
// This function is to check for the following possible inputs
20-
// 1) "." add the cwd but throw error for no recursion flag
21-
// 2) "." -r return the cwd
22-
// 3) "/some/path" but throw error for no recursion
23-
// 4) "/some/path" -r
24-
// 5) No path, throw err
25-
// 6) filename.type return the cwd + filename
26-
27-
if (!inPath) {
28-
throw new Error('Error: Argument \'path\' is required')
29-
}
30-
31-
if (inPath === '.') {
32-
inPath = process.cwd()
33-
}
34-
35-
// Convert to POSIX format
36-
inPath = inPath
37-
.split(path.sep)
38-
.join('/')
39-
40-
// Strips trailing slash from path.
41-
inPath = inPath.replace(/\/$/, '')
42-
43-
if (fs.statSync(inPath).isDirectory() && recursive === false) {
44-
throw new Error(`Error: ${inPath} is a directory, use the '-r' flag to specify directories`)
45-
}
46-
47-
return inPath
48-
}
49-
50-
function getTotalBytes (path, recursive, cb) {
51-
if (recursive) {
52-
getFolderSize(path, cb)
53-
} else {
54-
fs.stat(path, (err, stat) => cb(err, stat.size))
55-
}
14+
function getTotalBytes (paths, cb) {
15+
reduce(paths, 0, (total, path, cb) => {
16+
getFolderSize(path, (err, size) => {
17+
if (err) return cb(err)
18+
cb(null, total + size)
19+
})
20+
}, cb)
5621
}
5722

58-
function addPipeline (index, addStream, list, argv) {
23+
function addPipeline (paths, addStream, options) {
5924
const {
25+
recursive,
6026
quiet,
6127
quieter,
6228
silent
63-
} = argv
29+
} = options
6430
pull(
65-
zip(
66-
pull.values(list),
67-
pull(
68-
pull.values(list),
69-
paramap(fs.stat.bind(fs), 50)
70-
)
71-
),
72-
pull.map((pair) => ({
73-
path: pair[0],
74-
isDirectory: pair[1].isDirectory()
75-
})),
76-
pull.filter((file) => !file.isDirectory),
77-
pull.map((file) => ({
78-
path: file.path.substring(index, file.path.length),
79-
content: fs.createReadStream(file.path)
80-
})),
31+
globSource(...paths, { recursive }),
8132
addStream,
8233
pull.collect((err, added) => {
8334
if (err) {
35+
// Tweak the error message and add more relevant infor for the CLI
36+
if (err.code === 'ERR_DIR_NON_RECURSIVE') {
37+
err.message = `'${err.path}' is a directory, use the '-r' flag to specify directories`
38+
}
8439
throw err
8540
}
8641

@@ -102,7 +57,7 @@ function addPipeline (index, addStream, list, argv) {
10257
}
10358

10459
module.exports = {
105-
command: 'add <file>',
60+
command: 'add <file...>',
10661

10762
describe: 'Add a file to IPFS using the UnixFS data format',
10863

@@ -186,8 +141,7 @@ module.exports = {
186141
},
187142

188143
handler (argv) {
189-
const inPath = checkPath(argv.file, argv.recursive)
190-
const index = inPath.lastIndexOf('/') + 1
144+
const { ipfs } = argv
191145
const options = {
192146
strategy: argv.trickle ? 'trickle' : 'balanced',
193147
shardSplitThreshold: argv.enableShardingExperiment
@@ -205,38 +159,21 @@ module.exports = {
205159
if (options.enableShardingExperiment && utils.isDaemonOn()) {
206160
throw new Error('Error: Enabling the sharding experiment should be done on the daemon')
207161
}
208-
const ipfs = argv.ipfs
209162

210-
let list
211-
waterfall([
212-
(next) => {
213-
if (fs.statSync(inPath).isDirectory()) {
214-
return glob('**/*', { cwd: inPath }, next)
215-
}
216-
next(null, [])
217-
},
218-
(globResult, next) => {
219-
if (globResult.length === 0) {
220-
list = [inPath]
221-
} else {
222-
list = globResult.map((f) => inPath + '/' + f)
223-
}
224-
getTotalBytes(inPath, argv.recursive, next)
225-
},
226-
(totalBytes, next) => {
227-
if (argv.progress) {
228-
const bar = createProgressBar(totalBytes)
229-
options.progress = function (byteLength) {
230-
bar.update(byteLength / totalBytes, { progress: byteman(byteLength, 2, 'MB') })
231-
}
232-
}
163+
if (!argv.progress) {
164+
return addPipeline(argv.file, ipfs.addPullStream(options), argv)
165+
}
233166

234-
next(null, ipfs.addPullStream(options))
235-
}
236-
], (err, addStream) => {
167+
getTotalBytes(argv.file, (err, totalBytes) => {
237168
if (err) throw err
238169

239-
addPipeline(index, addStream, list, argv)
170+
const bar = createProgressBar(totalBytes)
171+
172+
options.progress = byteLength => {
173+
bar.update(byteLength / totalBytes, { progress: byteman(byteLength, 2, 'MB') })
174+
}
175+
176+
addPipeline(argv.file, ipfs.addPullStream(options), argv)
240177
})
241178
}
242179
}
Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
11
'use strict'
22

3-
module.exports = () => null
3+
const promisify = require('promisify-es6')
4+
5+
module.exports = self => {
6+
return promisify((...args) => {
7+
const callback = args.pop()
8+
callback(new Error('not available in the browser'))
9+
})
10+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
'use strict'
2+
3+
const promisify = require('promisify-es6')
4+
const pull = require('pull-stream')
5+
const globSource = require('../../utils/files/glob-source')
6+
const isString = require('lodash/isString')
7+
8+
module.exports = self => {
9+
return promisify((...args) => {
10+
const callback = args.pop()
11+
const options = isString(args[args.length - 1]) ? {} : args.pop()
12+
const paths = args
13+
14+
pull(
15+
globSource(...paths, options),
16+
self.addPullStream(options),
17+
pull.collect(callback)
18+
)
19+
})
20+
}

src/utils/files/glob-source.js

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
'use strict'
2+
3+
const fs = require('fs')
4+
const Path = require('path')
5+
const isString = require('lodash/isString')
6+
const pull = require('pull-stream')
7+
const glob = require('glob')
8+
const cat = require('pull-cat')
9+
const defer = require('pull-defer')
10+
const pushable = require('pull-pushable')
11+
const map = require('async/map')
12+
const parallel = require('async/parallel')
13+
const errCode = require('err-code')
14+
15+
/**
16+
* Create a pull stream source that can be piped to ipfs.addPullStream for the
17+
* provided file paths.
18+
*
19+
* @param ...paths {String} File system path(s) to glob from
20+
* @param [options] {Object} Optional options
21+
* @param [options.recursive] Recursively glob all paths in directories
22+
*/
23+
module.exports = (...args) => {
24+
const options = isString(args[args.length - 1]) ? {} : args.pop()
25+
const paths = args
26+
const deferred = defer.source()
27+
28+
const globSourceOptions = {
29+
recursive: options.recursive,
30+
glob: {
31+
dot: Boolean(options.hidden),
32+
ignore: Array.isArray(options.ignore) ? options.ignore : [],
33+
follow: options.followSymlinks != null ? options.followSymlinks : true
34+
}
35+
}
36+
37+
// Check the input paths comply with options.recursive and convert to glob sources
38+
map(paths, normalizePathWithType, (err, results) => {
39+
if (err) return deferred.abort(err)
40+
41+
try {
42+
const sources = results.map(res => toGlobSource(res, globSourceOptions))
43+
return deferred.resolve(cat(sources))
44+
} catch (err) {
45+
return deferred.abort(err)
46+
}
47+
})
48+
49+
return pull(
50+
deferred,
51+
pull.map(({ path, contentPath }) => ({
52+
path,
53+
content: fs.createReadStream(contentPath)
54+
}))
55+
)
56+
}
57+
58+
function toGlobSource ({ path, type }, options) {
59+
options = options || {}
60+
61+
const baseName = Path.basename(path)
62+
63+
if (type === 'file') {
64+
return pull.values([{ path: baseName, contentPath: path }])
65+
}
66+
67+
if (type === 'dir' && !options.recursive) {
68+
throw errCode(
69+
new Error(`'${path}' is a directory and recursive option not set`),
70+
'ERR_DIR_NON_RECURSIVE',
71+
{ path }
72+
)
73+
}
74+
75+
const globOptions = Object.assign({}, options.glob, {
76+
cwd: path,
77+
nodir: true,
78+
realpath: false,
79+
absolute: false
80+
})
81+
82+
// TODO: want to use pull-glob but it doesn't have the features...
83+
const pusher = pushable()
84+
85+
glob('**/*', globOptions)
86+
.on('match', m => pusher.push(m))
87+
.on('end', () => pusher.end())
88+
.on('abort', () => pusher.end())
89+
.on('error', err => pusher.end(err))
90+
91+
return pull(
92+
pusher,
93+
pull.map(p => ({
94+
path: Path.join(baseName, p),
95+
contentPath: Path.join(path, p)
96+
}))
97+
)
98+
}
99+
100+
function normalizePathWithType (path, cb) {
101+
parallel({
102+
stat: cb => fs.stat(path, cb),
103+
realpath: cb => fs.realpath(path, cb)
104+
}, (err, res) => {
105+
if (err) return cb(err)
106+
cb(null, { path: res.realpath, type: res.stat.isDirectory() ? 'dir' : 'file' })
107+
})
108+
}

test/cli/files.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,18 @@ describe('files', () => runOnAndOff((thing) => {
143143
})
144144
})
145145

146+
it('add multiple', function () {
147+
this.timeout(30 * 1000)
148+
149+
return ipfs('add', 'src/init-files/init-docs/readme', 'test/fixtures/odd-name-[v0]/odd name [v1]/hello', '--wrap-with-directory')
150+
.then((out) => {
151+
expect(out)
152+
.to.include('added QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB readme\n')
153+
expect(out)
154+
.to.include('added QmT78zSuBmuS4z925WZfrqQ1qHaJ56DQaTfyMUF7F8ff5o hello\n')
155+
})
156+
})
157+
146158
it('add alias', function () {
147159
this.timeout(30 * 1000)
148160

@@ -278,7 +290,7 @@ describe('files', () => runOnAndOff((thing) => {
278290
it('add --quieter', function () {
279291
this.timeout(30 * 1000)
280292

281-
return ipfs('add -Q -w test/fixtures/test-data/hello test/test-data/node.json')
293+
return ipfs('add -Q -w test/fixtures/test-data/hello')
282294
.then((out) => {
283295
expect(out)
284296
.to.eql('QmYRMUVULBfj7WrdPESnwnyZmtayN6Sdrwh1nKcQ9QgQeZ\n')

test/core/interface.spec.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,7 @@ describe('interface-ipfs-core tests', () => {
7979
})
8080

8181
tests.filesRegular(defaultCommonFactory, {
82-
skip: isNode ? [{
83-
name: 'addFromFs',
84-
reason: 'TODO: not implemented yet'
85-
}] : [{
82+
skip: isNode ? null : [{
8683
name: 'addFromStream',
8784
reason: 'Not designed to run in the browser'
8885
}, {

0 commit comments

Comments
 (0)