Guest User

Untitled

a guest
Oct 23rd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. const daggy = require('daggy');
  2. const Task = require('data.task');
  3. const path = require('path');
  4. const fs = require('fs');
  5. const { sequence } = require('ramda');
  6.  
  7. // type Entity
  8. // = File String
  9. // | Dir String (List Entity)
  10. const Entity = daggy.taggedSum('Entity', {
  11. File: ['name'],
  12. Dir: ['name', 'items'],
  13. });
  14.  
  15.  
  16. Entity.prototype.inspect = function inspect() {
  17. return this.cata({
  18. File: name => `File(${name})`,
  19. Dir: (name, items) => `Dir(${name}, ${items.map(x => x.inspect())})`,
  20. });
  21. };
  22.  
  23.  
  24. // -- isDir :: Path -> Task e Bool
  25. const isDir = entityPath =>
  26. new Task((rej, res) =>
  27. fs.stat(entityPath, (err, stats) => {
  28. return err ? rej(err) : res(stats.isDirectory());
  29. }));
  30.  
  31.  
  32. // -- readdir :: Path -> Task e [String]
  33. const readdir = dirPath =>
  34. new Task((rej, res) =>
  35. fs.readdir(dirPath, (err, items) => {
  36. return err ? rej(err) : res(items);
  37. }));
  38.  
  39.  
  40. // -- itemToEntity :: (String, Path) -> Bool -> Task e Entity
  41. const itemToEntity = (item, newPath) => (isItDir) => {
  42. return isItDir
  43. ? readDir2TaskListEntity(newPath).map(items => Entity.Dir(item, items))
  44. : Task.of(Entity.File(item));
  45. };
  46.  
  47.  
  48. // -- items2Entities :: (Path, List String) -> List (Task e Entity)
  49. const listItem2ListTaskEntity = (dirPath, items) =>
  50. items.map((item) => {
  51. const newPath = path.join(dirPath, item);
  52. return isDir(newPath)
  53. .chain(itemToEntity(item, newPath));
  54. });
  55.  
  56.  
  57. // -- readDir2TaskListEntity :: Path -> Task e (List Entity)
  58. const readDir2TaskListEntity = dirPath =>
  59. readdir(dirPath)
  60. .chain(items => sequence(Task.of, listItem2ListTaskEntity(dirPath, items)));
  61.  
  62.  
  63. // -- main :: String -> Path -> Entity
  64. const main = (dirName, rootPath) =>
  65. readDir2TaskListEntity(path.join(rootPath, dirName))
  66. .map(items => Entity.Dir(dirName, items));
  67.  
  68. // Program
  69.  
  70. main('test', __dirname).fork(
  71. console.log,
  72. console.error
  73. );
Add Comment
Please, Sign In to add comment