4/11/2018 - 6:21 AM

clojure实现git gc垃圾回收处理 file io clj 文件处理

clojure实现git gc垃圾回收处理 file io clj 文件处理

#!/usr/bin/env lein-exec
;; This script goes through all git directories                                                                 
;; recursively and executes "git gc" to each                                                                    

(import '(java.nio.file Path Paths Files))
(use '[ :only (sh with-sh-dir)])

(defn resolve-path [name]
  ;; resolves a string to a `java.nio.file.Path`                                                                
  (Paths/get name (into-array String [])))

(defn exists [path]
  (Files/exists path (into-array java.nio.file.LinkOption [])))

(defn is-directory [path]
  (Files/isDirectory path (into-array java.nio.file.LinkOption [])))

(defn git-dir [path]
  ;; simple check if the directory `path` is git managed                                                        
  (and (is-directory path)
       (exists (.resolve path "HEAD"))
       (exists (.resolve path "objects"))
       (exists (.resolve path "refs"))))

(defn list-dir [path]
  ;; list the contents of a given directory (Path)                                                              
  (with-open [dirstream (Files/newDirectoryStream path)]
    (vec (iterator-seq (.iterator dirstream)))))

(defn with-subdirs [path f]
  ;; applies `f` to `path` and  every subdir                                                                    
  (f path)
  (doseq [e (filter is-directory (list-dir path))] (with-subdirs e f)))

(defn git-gc [dir]
  ;;perform "git gc" command in `dir`                                                                           
  (when (git-dir dir)
    (println (str "Perform git gc on " dir))
    (with-sh-dir (str (.toAbsolutePath dir))
      (sh "git" "gc"))))

(defn recur-git-gc [path]
  (with-subdirs path git-gc))

;; -------------------------------------------------------------------------                                    

(recur-git-gc (resolve-path (first (rest *command-line-args*))))