Base chargement/parsing fichiers Desktop

This commit is contained in:
wpetit 2015-08-27 17:35:00 +02:00
parent 011168b6a1
commit 8f2ed91f1a

104
js/fs.js Normal file
View File

@ -0,0 +1,104 @@
(function(Pitaya) {
"use strict";
var ini = require('ini');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var FS = Pitaya.FS = {};
FS.loadAllDesktopFiles = function(rootDirs) {
return FS.findAllDesktopFiles(rootDirs)
.then(function(filePaths) {
var promises = filePaths.map(function(path) {
return FS.loadDesktopFile(path);
});
return Promise.all(promises)
.then(function(desktopFiles) {
return desktopFiles.map(function(desktop, i) {
return {
path: filePaths[i],
desktop: desktop
};
});
})
;
})
;
};
FS.findAllDesktopFiles = function(rootDirs) {
if(!Array.isArray(rootDirs)) {
rootDirs = [rootDirs];
}
var promises = rootDirs.map(function(rootDir) {
var globPath = path.join(rootDir, '**/*.desktop');
return new Promise(function(resolve, reject) {
glob(globPath, function(err, files) {
if(err) return reject(err);
return resolve(files);
});
});
});
return Promise.all(promises)
.then(function(apps) {
return uniq(flatten(apps));
})
;
};
FS.loadDesktopFile = function(filePath) {
return new Promise(function(resolve, reject) {
fs.readFile(filePath, 'utf8', function(err, content) {
if(err) return reject(err);
try {
var decoded = ini.decode(content);
return resolve(decoded);
} catch(err) {
return reject(err);
}
});
});
};
// Array helpers
function flatten(arr) {
return arr.reduce(function(result, item) {
result = result.concat.apply(result, Array.isArray(item) ? flatten(item) : [item]);
return result;
}, []);
}
function uniq(arr) {
return arr.reduce(function(result, item) {
if(result.indexOf(item) === -1) {
result.push(item);
}
return result;
}, []);
}
}(Pitaya = global.Pitaya || {}));
Pitaya.FS.loadAllDesktopFiles(['/usr/share/applications', '/home/william/.local/share/applications'])
.then(function(apps) {
console.log(apps[5])
})
;