]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - cli/actions.js
Add welcome screen
[perso/Immae/Projets/Nodejs/Surfer.git] / cli / actions.js
1 'use strict';
2
3 exports.login = login;
4 exports.put = put;
5 exports.get = get;
6 exports.del = del;
7
8 var superagent = require('superagent'),
9 config = require('./config'),
10 async = require('async'),
11 fs = require('fs'),
12 path = require('path');
13
14 require('colors');
15
16 var API = '/api/files/';
17
18 function checkConfig() {
19 if (!config.server()) {
20 console.log('You have run "login" first');
21 process.exit(1);
22 }
23
24 console.log('Using server %s', config.server().yellow);
25 }
26
27 function collectFiles(filesOrFolders) {
28 var tmp = [];
29
30 filesOrFolders.forEach(function (filePath) {
31 var stat = fs.statSync(filePath);
32
33 if (stat.isFile()) {
34 tmp.push(filePath);
35 } else if (stat.isDirectory()) {
36 var files = fs.readdirSync(filePath).map(function (file) { return path.join(filePath, file); });
37 tmp = tmp.concat(collectFiles(files));
38 } else {
39 console.log('Skipping %s', filePath.cyan);
40 }
41 });
42
43 return tmp;
44 }
45
46 function login(server) {
47 console.log('Using server', server);
48 config.set('server', server);
49 }
50
51 function put(filePath, otherFilePaths, options) {
52 checkConfig();
53
54 var files = collectFiles([ filePath ].concat(otherFilePaths));
55
56 async.eachSeries(files, function (file, callback) {
57 var relativeFilePath = path.resolve(file).slice(process.cwd().length + 1);
58
59 console.log('Uploading file %s -> %s', relativeFilePath.cyan, ((options.destination ? options.destination : '') + '/' + relativeFilePath).cyan);
60
61 superagent.put(config.server() + API + relativeFilePath).attach('file', file).end(callback);
62 }, function (error) {
63 if (error) {
64 console.log('Failed to put file.', error);
65 process.exit(1);
66 }
67
68 console.log('Done');
69 });
70 }
71
72 function get(filePath) {
73 checkConfig();
74
75 var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
76 superagent.get(config.server() + API + relativeFilePath).end(function (error, result) {
77 if (error) return console.log('Failed', result ? result.body : error);
78
79 if (result.body && result.body.entries) {
80 console.log('Files:');
81 result.body.entries.forEach(function (entry) {
82 console.log('\t %s', entry);
83 });
84 } else {
85 console.log(result.text);
86 }
87 });
88 }
89
90 function del(filePath) {
91 checkConfig();
92
93 var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
94 superagent.del(config.server() + API + relativeFilePath).end(function (error, result) {
95 if (error.status === 404) return console.log('No such file or directory');
96 if (error) return console.log('Failed', result ? result.body : error);
97 console.log('Success', result.body);
98 });
99 }