]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - cli/actions.js
Add ldap auth
[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 if (server[server.length-1] === '/') server = server.slice(0, -1);
48
49 console.log('Using server', server);
50 config.set('server', server);
51 }
52
53 function put(filePath, otherFilePaths, options) {
54 checkConfig();
55
56 var files = collectFiles([ filePath ].concat(otherFilePaths));
57
58 async.eachSeries(files, function (file, callback) {
59 var relativeFilePath = path.resolve(file).slice(process.cwd().length + 1);
60
61 console.log('Uploading file %s -> %s', relativeFilePath.cyan, ((options.destination ? options.destination : '') + '/' + relativeFilePath).cyan);
62
63 superagent.put(config.server() + API + relativeFilePath).attach('file', file).end(callback);
64 }, function (error) {
65 if (error) {
66 console.log('Failed to put file.', error);
67 process.exit(1);
68 }
69
70 console.log('Done');
71 });
72 }
73
74 function get(filePath) {
75 checkConfig();
76
77 var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
78 superagent.get(config.server() + API + relativeFilePath).end(function (error, result) {
79 if (error) return console.log('Failed', result ? result.body : error);
80
81 if (result.body && result.body.entries) {
82 console.log('Files:');
83 result.body.entries.forEach(function (entry) {
84 console.log('\t %s', entry);
85 });
86 } else {
87 console.log(result.text);
88 }
89 });
90 }
91
92 function del(filePath) {
93 checkConfig();
94
95 var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
96 superagent.del(config.server() + API + relativeFilePath).end(function (error, result) {
97 if (error.status === 404) return console.log('No such file or directory');
98 if (error) return console.log('Failed', result ? result.body : error);
99 console.log('Success', result.body);
100 });
101 }