filesystem.scm 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. (library (lib filesystem)
  2. (export exists?
  3. existing-readable?
  4. directory?
  5. get-files-from-directory)
  6. (import
  7. (except (rnrs base) let-values)
  8. (only (guile)
  9. lambda* λ
  10. ;; exceptions
  11. raise-exception make-exception
  12. ;; file system
  13. access?
  14. stat stat:type
  15. F_OK R_OK
  16. )
  17. (ice-9 exceptions)
  18. (ice-9 ftw)
  19. (ice-9 match)
  20. (srfi srfi-1)
  21. (fslib)
  22. (lib string-procs)
  23. (lib list-procs)
  24. (prefix (lib logger) log:)))
  25. (define exists?
  26. (λ (location)
  27. (access? location F_OK)))
  28. (define existing-readable?
  29. (λ (location)
  30. (access? location R_OK)))
  31. (define get-file-system-item-type
  32. (λ (location)
  33. (stat:type (stat location))))
  34. (define directory?
  35. (λ (location)
  36. (symbol=? (get-file-system-item-type location)
  37. 'directory)))
  38. (define file?
  39. (λ (location)
  40. (symbol=? (get-file-system-item-type location)
  41. 'regular)))
  42. ;; From: https://www.gnu.org/software/guile/manual/html_node/File-Tree-Walk.html
  43. (define remove-stat
  44. ;; Remove the `stat' object the `file-system-tree' provides
  45. ;; for each file in the tree.
  46. (match-lambda
  47. [(name stat) ; flat file
  48. name]
  49. [(name stat children ...) ; directory
  50. (list name (map remove-stat children))]))
  51. (define get-files-from-directory
  52. (lambda* (directory-location
  53. #:key
  54. (filter-proc (λ (fname) #t)))
  55. ;; todo 1: check if directory-location really points to a
  56. ;; directory.
  57. (let ([stat-result (stat directory-location)]
  58. [actual-filter-proc
  59. (λ (fname)
  60. (and (not (string=? fname "."))
  61. (not (string=? fname ".."))
  62. (file? (fsing-join directory-location fname))
  63. (filter-proc fname)))])
  64. (cond
  65. [(directory? directory-location)
  66. (filter actual-filter-proc
  67. (scandir directory-location))]
  68. [else
  69. (raise-exception
  70. (make-exception
  71. (make-non-continuable-error)
  72. (make-exception-with-message "not a directory")
  73. (make-exception-with-irritants directory-location)
  74. (make-exception-with-origin 'get-files-from-directory)))]))))