├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── ReleaseNotes.md ├── profiles.clj ├── project.clj ├── src ├── com │ └── palletops │ │ ├── ns_reload.clj │ │ └── ns_reload │ │ ├── hooks.clj │ │ └── repl.clj ├── ns-reload │ └── profiles.clj └── ns_reload │ └── plugin.clj └── test └── com └── palletops ├── ns_reload └── hooks_test.clj └── ns_reload_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | lein: lein2 3 | before_script: 4 | - lein2 version 5 | script: lein2 test 6 | after_success: 7 | - lein2 pallet-release push 8 | env: 9 | global: 10 | secure: NdD+h28d8fh2puhThny6aDMg/OobSRR28Qv7bNfLNi+Z3ZDYMbAXh2+ggMMoJrtQrhdV+KyRdg8tAPHfhagK+XntoWQAwD53x7Z0li0ejwdXpdwe+xWNAKnoONRiVfP0ir2vmk9TjV+wX9rq2yAmF0Dpvue7gCAq8dV6OffgYSc= 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ns-reload 2 | 3 | A Clojure library to reload namespaces correctly. 4 | 5 | ## Installation 6 | 7 | Add `[[com.palletops/ns-reload "0.1.0"]]` to your 8 | `:plugins` in the `:user` profile of `profiles.clj`. 9 | 10 | ## Usage 11 | 12 | ```clj 13 | (require '[com.palletops.ns-reload :refer :as deps]) 14 | ``` 15 | 16 | To reload a namespace, e.g. your-ns, and all the namespaces that depend on it: 17 | 18 | ```clj 19 | (deps/reload 'your-ns) 20 | ``` 21 | 22 | 23 | ## Plugin Based Configuration 24 | 25 | The plugin can be configured using the `:ns-reload` project key. 26 | The key is specified as a map which may contain the following keys: 27 | 28 | `:options` 29 | : a map with `:verbose` and `:unload` boolean values. If `:unload` is 30 | set to true, then namespaces will be unloaded before being reloaded. 31 | 32 | `:ns-filters` 33 | : a map (or sequence of pairs) specifying filters to be applied to 34 | namespaces that are determined to require reloading. Defaults to 35 | reloading all namespaces. 36 | 37 | `:reload-filters` 38 | : a map (or sequence of pairs) specifying filters to be applied to a 39 | namespace that has been redefined, to determine if dependent 40 | namespaces should be loaded. Defaults to false. Requires editor 41 | integration for automated reloading to function. 42 | 43 | `:pre-reload-hook` 44 | : a symbol for a function to be called before dependent namespaces are 45 | reloaded. Can be used to automatically stop components, etc. 46 | 47 | `:post-reload-hook` 48 | : a symbol for a function to be called after dependent namespaces are 49 | reloaded. Can be used to restart components, etc. 50 | 51 | Filters are specified with keyword and value. Valid filters are: 52 | 53 | `:constantly` 54 | : a constant boolean value 55 | 56 | `:excludes` 57 | : a sequence of namespace symbols to exclude 58 | 59 | `:includes` 60 | : a sequence of namespace symbols to include 61 | 62 | `:exclude-regex` 63 | : a regex which will exclude matching namespaces 64 | 65 | `:include-regex` 66 | : a regex which will include matching namespaces 67 | 68 | As an example: 69 | 70 | ```clj 71 | :ns-reload 72 | {:options {:verbose true} 73 | :ns-filters {:exclude-regex #"clojure.tools.nrepl.*"} 74 | :reload-filters {:constantly true}} 75 | ``` 76 | 77 | ## lein-shorthand integration 78 | 79 | The `:plugin.ns-reload/shorthand` profile provides mappings for 80 | `reload` and `reload-dependents` into the `.` namespace. 81 | 82 | To use the profile, add it to your :repl profile. 83 | 84 | ```clj 85 | :repl [:plugin.ns-reload/shorthand] 86 | ``` 87 | 88 | You can then call (./reload 'my-ns) to reload a namespace and all its 89 | dependents. 90 | 91 | ## Cider Integration 92 | 93 | To automatically reload dependent namespaces when loading files in 94 | Cider, add the following to your emacs configuration. 95 | 96 | ```lisp 97 | (defun my-reload-dependents () 98 | (let* ((buf (get-buffer (cider-current-repl-buffer))) 99 | (ns (with-current-buffer buf nrepl-buffer-ns))) 100 | (cider-tooling-eval 101 | (format 102 | "(when-let [rd (resolve 'com.palletops.ns-reload.repl/ns-reload-hook)] 103 | (@rd '%s {))" 104 | (cider-current-ns)) 105 | (cider-interactive-eval-handler buf) 106 | ns))) 107 | 108 | (add-hook 'cider-file-loaded-hook 'my-reload-dependents) 109 | ``` 110 | ## Integration with ns-tracker 111 | 112 | [ns-tracker][ns-tacker] watches your files and notifies you of 113 | namespaces that are out of date. 114 | 115 | ```clj 116 | (let [modified-namespaces (ns-tracker.core/ns-tracker ["src" "test"])] 117 | (doseq [ns-sym (modified-namespaces)] 118 | (com.palletops.ns-reload.repl/ns-reload-hook ns-sym {}))) 119 | ``` 120 | 121 | ## How it Works 122 | 123 | `ns-reload` works by tracking dependencies using information 124 | returned by `ns-refers`, `ns-aliases` and `ns-imports`. 125 | 126 | There are two sources of missing dependency information with this approach. 127 | 128 | Firstly if a namespaces `require`s another namespace without an alias 129 | and without referring anything, then the dependency is not recorded 130 | anywhere. `ns-reload` works around this by hooking 131 | `clojure.core/load-lib` and always adding an alias in this situation. 132 | 133 | Secondly, macros can inject dependencies into a namespace. 134 | `ns-reload` provides a hook for `clojure.core/defmacro` that 135 | adds a require for the namespace of any fully qualified symbol 136 | returned by the macro. 137 | 138 | These hooks are installed by the plugin for the repl task. 139 | 140 | ## Comparison with tools.namespace 141 | 142 | `ns-reload` works by tracking dependencies from the data 143 | available in namespaces themselves, without touching any files on 144 | disk. `tools.namespace` works by reading the `ns` forms from the 145 | source files. 146 | 147 | ## License 148 | 149 | Copyright © 2014 Hugo Duncan 150 | 151 | Distributed under the Eclipse Public License either version 1.0 or (at 152 | your option) any later version. 153 | -------------------------------------------------------------------------------- /ReleaseNotes.md: -------------------------------------------------------------------------------- 1 | ## 0.1.0 2 | 3 | - Initial release 4 | -------------------------------------------------------------------------------- /profiles.clj: -------------------------------------------------------------------------------- 1 | {:dev {:plugins [[lein-pallet-release "RELEASE"]]}} 2 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.palletops/ns-reload "0.1.1-SNAPSHOT" 2 | :description "A library for namespace dependencies." 3 | :url "https://github.com/palletops/ns-reload" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[robert/hooke "1.3.0"]] 7 | :profiles {:provided {:dependencies [[org.clojure/clojure "1.6.0"] 8 | [leiningen-core "2.5.0"]]}}) 9 | -------------------------------------------------------------------------------- /src/com/palletops/ns_reload.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.ns-reload 2 | "Calculate a dependency graph for your loaded namespaces. Can 3 | reload your dependencies." 4 | (:require [clojure.set :as set] 5 | [clojure.string :as string] 6 | [clojure.walk :as walk])) 7 | 8 | ;;; Namespace Dependencies 9 | (defn package-dependencies 10 | "Returns the packages on which the namespace depends." 11 | [ns] 12 | (->> 13 | (ns-imports ns) 14 | vals 15 | (map 16 | ;; can throw if mixed pre/post 1.2.1 types are on the classpath due to 17 | ;; changes in defrecord and deftype mangling 18 | #(try (symbol (.getName (.getPackage ^Class %))) (catch Exception _))) 19 | distinct 20 | (filter identity) 21 | (filter (set (map ns-name (all-ns)))))) 22 | 23 | (defn refered-dependencies 24 | "Calculate the namespaces that are refered for a given namespace." 25 | [ns] 26 | (distinct (map (comp ns-name :ns meta val) (ns-refers ns)))) 27 | 28 | (defn aliased-dependencies 29 | "Calculate the namespaces that are aliased for a given namespace." 30 | [ns] 31 | (->> (ns-aliases ns) vals (map ns-name) distinct)) 32 | 33 | (defn namespace-dependencies 34 | "Calculate the namespaces that the given namespace directly depends on." 35 | [ns] 36 | (distinct 37 | (concat 38 | (refered-dependencies ns) 39 | (aliased-dependencies ns)))) 40 | 41 | (defn depends-on? [ns-sym dependency-ns-sym] 42 | {:pre [(symbol? dependency-ns-sym)]} 43 | (some #(= dependency-ns-sym %) (namespace-dependencies ns-sym))) 44 | 45 | (defn direct-dependencies 46 | "Calculate namespace dependencies based on namespace information. 47 | This reduces a map, from namespace symbol, to a set of symbols for the direct 48 | namespace dependencies of that namespace." 49 | [] 50 | (-> (reduce 51 | (fn [dependencies ns] 52 | (assoc dependencies 53 | (ns-name ns) 54 | (disj (set (namespace-dependencies ns)) (ns-name ns)))) 55 | {} 56 | (all-ns)) 57 | ;; Patch for circular dependency in core 58 | (update-in ['clojure.core] disj 'clojure.java.io))) 59 | 60 | (def ^:private ^:dynamic *circular* nil) 61 | 62 | (defn dependency-graph* 63 | "Given a map of direct dependencies, construct a dependency graph for ns-sym." 64 | [direct-dependencies ns-sym seen] 65 | (if-not (some #(= ns-sym %) seen) 66 | (let [seen (conj seen ns-sym) 67 | children (direct-dependencies ns-sym) 68 | r (fn [ns-sym] (dependency-graph* direct-dependencies ns-sym seen))] 69 | (zipmap children (map r children))) 70 | (let [p (->> seen 71 | (split-with #(not= ns-sym %)) 72 | last 73 | vec)] 74 | (set! *circular* (conj *circular* 75 | (conj p ns-sym))) 76 | nil))) 77 | 78 | (defn dependency-graph 79 | "Given a map of direct dependencies, construct a dependency graph for ns-sym." 80 | [direct-dependencies ns-sym] 81 | (binding [*circular* #{}] 82 | (let [r (dependency-graph* direct-dependencies ns-sym [])] 83 | (when (seq *circular*) 84 | (println "WARN: circular dependencies:") 85 | (doseq [c *circular*] 86 | (println c))) 87 | r))) 88 | 89 | (defn direct-dependents 90 | "Build a map of direct dependents (the inverse of direct-dependencies)." 91 | [direct-dependencies] 92 | (reduce-kv 93 | (fn [m k v] 94 | (reduce 95 | (fn [m d] 96 | (update-in m [d] (fnil conj #{}) k)) 97 | m 98 | v)) 99 | {} 100 | direct-dependencies)) 101 | 102 | (defn ordered-dependencies 103 | "Return a sequence of dependencies from a dependency graph, in a 104 | deepest first order. Will contain repeated namespaces." 105 | [graph] 106 | (mapcat 107 | (fn [[k v]] 108 | (conj (vec (ordered-dependencies v)) k)) 109 | graph)) 110 | 111 | (defn required-namespaces 112 | "Return a sequence of namespaces that the `ns-sym` namespace depends on. 113 | The sequence will be in dependency order (deepest first)." 114 | [ns-sym] 115 | (->> ns-sym 116 | (dependency-graph (direct-dependencies)) 117 | ordered-dependencies 118 | distinct)) 119 | 120 | (defn dependent-namespaces 121 | "Return a sequence of namespaces that depend on the `ns-sym` namespace'. 122 | The sequence will be in dependency order (nearest dependency first)." 123 | [ns-sym] 124 | (->> ns-sym 125 | (dependency-graph (direct-dependents (direct-dependencies))) 126 | ordered-dependencies 127 | reverse 128 | distinct)) 129 | 130 | 131 | ;;; Namespace unloading and reloading 132 | 133 | (defn unload-ns 134 | "Unload the namespace, ns-sym." 135 | [ns-sym] 136 | (remove-ns ns-sym) 137 | (dosync (commute @#'clojure.core/*loaded-libs* disj ns-sym)) 138 | nil) 139 | 140 | ;; core.async injects these through macros 141 | ;; into user code (via the analyzer) 142 | ;; (.startsWith (name %) "clojure.core.cache") 143 | ;; (.startsWith (name %) "clojure.core.memoize") 144 | 145 | (defn reload-ns 146 | "Reload all the given namespaces, filtering those that filter-ns? 147 | returns true for." 148 | [ns-sym {:keys [unload verbose]}] 149 | (when verbose 150 | (println "Reloading" ns-sym)) 151 | (when unload 152 | (unload-ns ns-sym)) 153 | (require ns-sym :reload)) 154 | 155 | (defn reload-namespaces 156 | "Reload all the given namespaces, filtering those that filter-ns? 157 | returns true for." 158 | [namespaces {:keys [filter-ns? unload verbose] 159 | :or {filter-ns? #(not (or (.startsWith (name %) "clojure.tools") 160 | (= 'user %)))} 161 | :as options}] 162 | (doseq [n namespaces 163 | :when (filter-ns? n)] 164 | (reload-ns n (select-keys options [:unload :verbose])))) 165 | 166 | (defn reload-all 167 | "Reload all required and dependent namespaces, filtering those that 168 | filter-ns? returns true for." 169 | ([ns-sym {:keys [filter-ns? unload verbose]}] 170 | (reload-namespaces (concat (required-namespaces ns-sym) 171 | [ns-sym] 172 | (dependent-namespaces ns-sym)))) 173 | ([ns-sym] 174 | (reload-all ns-sym {}))) 175 | 176 | (defn reload-dependents 177 | "Reload all dependent namespaces, filtering those that filter-ns? 178 | returns true for." 179 | ([ns-sym {:keys [filter-ns? unload verbose] :as options}] 180 | (reload-namespaces (dependent-namespaces ns-sym) options)) 181 | ([ns-sym] 182 | (reload-dependents ns-sym {}))) 183 | 184 | (defn reload 185 | "Reload a namespace and all its dependent namespaces, filtering 186 | those that filter-ns? returns true for." 187 | ([ns-sym {:keys [filter-ns? unload verbose] :as options}] 188 | (reload (concat [ns-sym] (dependent-namespaces ns-sym) options))) 189 | ([ns-sym] 190 | (reload ns-sym {}))) 191 | 192 | 193 | ;;; Injection of requires by macros 194 | (def ^:private ^:dynamic *ns-names*) 195 | 196 | (defn- possibly-require 197 | [x] 198 | (when (symbol? x) 199 | (let [n (namespace x)] 200 | (when (and n 201 | (not= (ns-name *ns*) n) 202 | (.contains n ".") 203 | (not (depends-on? (ns-name *ns*) (symbol n)))) 204 | (set! *ns-names* (conj *ns-names* n))))) 205 | x) 206 | 207 | (defn with-requires 208 | "A function for use in macros that adds requires to *ns* for the 209 | namespace of any namespace qualified symbol in body. Returns body. 210 | 211 | This ensures that there is a discoverable dependency on the 212 | namespaces of code injected by body." 213 | [body] 214 | (binding [*ns-names* []] 215 | (walk/postwalk possibly-require body) 216 | (doseq [x (distinct *ns-names*) 217 | :when (not ; this is rather slow 218 | (try (Class/forName x) 219 | (catch Exception e)))] 220 | (require (symbol x)))) 221 | body) 222 | -------------------------------------------------------------------------------- /src/com/palletops/ns_reload/hooks.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.ns-reload.hooks 2 | "Hooks for augmented namespace tracking" 3 | (:require 4 | [com.palletops.ns-reload :refer [depends-on? with-requires]] 5 | [robert.hooke :refer [add-hook]])) 6 | 7 | (defn- -defmacro 8 | [f &form &env & args] 9 | (let [[nameargs & arities] (partition-by sequential? args) 10 | arities (apply concat arities)] 11 | (if (vector? (first arities)) 12 | (apply f &form &env 13 | (concat nameargs [(first arities) 14 | `(with-requires (do ~@(rest arities)))])) 15 | (apply f &form &env 16 | (concat 17 | nameargs 18 | (map 19 | (fn [[argv & r]] 20 | (list argv `(with-requires (do ~@r)))) 21 | arities)))))) 22 | 23 | (defn- -load-lib 24 | "Augment load-lib to add aliases for all required namespaces that 25 | have no other discoverable dependency information." 26 | [f prefix lib & options] 27 | (let [v (apply f prefix lib options) 28 | lib (if prefix (symbol (str prefix \. lib)) lib)] 29 | (when-not (depends-on? (ns-name *ns*) lib) 30 | (alias (symbol (str (name lib) (hash (name lib)))) lib)) 31 | v)) 32 | 33 | (defn hooks 34 | [] 35 | (add-hook #'clojure.core/load-lib -load-lib) 36 | (add-hook #'clojure.core/defmacro -defmacro)) 37 | 38 | (comment 39 | (hooks) 40 | (robert.hooke/clear-hooks #'clojure.core/load-lib) 41 | (robert.hooke/clear-hooks #'clojure.core/defmacro)) 42 | -------------------------------------------------------------------------------- /src/com/palletops/ns_reload/repl.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.ns-reload.repl 2 | "Wrappers for use at the repl, with persistent configuration, so it 3 | can be set in profiles." 4 | (:require 5 | [com.palletops.ns-reload :as ns-reload])) 6 | 7 | (defonce ^:private -config (atom {})) 8 | 9 | (defn pred-fn 10 | [k v] 11 | (case k 12 | :constantly (fn [f] (fn [_] v)) 13 | :excludes (fn [f] (fn [n] (if ((set v) n) nil (f n)))) 14 | :includes (fn [f] (fn [n] (if ((set v) n) true (f n)))) 15 | :exclude-regex (fn [f] (fn [n] (if (re-find v (name n)) nil (f n)))) 16 | :include-regex (fn [f] (fn [n] (if (re-find v (name n)) true (f n)))))) 17 | 18 | (defn filter-pred 19 | "Combine clauses in a filter predicate." 20 | [clauses default] 21 | (reduce 22 | (fn [f [k v]] 23 | ((pred-fn k v) f)) 24 | (fn [_] default) 25 | clauses)) 26 | 27 | (defn set-config! 28 | "Set the configuration for using ns-reload from the repl." 29 | ([{:keys [options ns-filters reload-filters pre-reload-hook post-reload-hook] 30 | :as config}] 31 | (reset! -config 32 | (merge 33 | (select-keys config [:pre-reload-hook :post-reload-hook]) 34 | {:options (assoc options 35 | :filter-ns? (filter-pred 36 | (conj ns-filters [:excludes ['user]]) 37 | true)) 38 | :should-reload-dependents? (filter-pred reload-filters nil)})))) 39 | 40 | (defn reload 41 | "Reload a namespace and it's dependents. `options' are merged with any 42 | configuration that has been set with `set-config!'." 43 | ([ns-sym {:keys [unload verbose filter-ns?] :as options}] 44 | (ns-reload/reload ns-sym (merge @-config options))) 45 | ([ns-sym] 46 | (reload ns-sym {}))) 47 | 48 | (defn reload-dependents 49 | "Reload the dependents of a namespace. `options' are merged with any 50 | configuration that has been set with `set-config!'." 51 | ([ns-sym {:keys [unload verbose filter-ns?] :as options}] 52 | (ns-reload/reload-dependents 53 | ns-sym (merge (:options @-config) options))) 54 | ([ns-sym] 55 | (reload-dependents ns-sym {}))) 56 | 57 | (defn ns-reload-hook 58 | "Function that can be used to add a hook on namespace reload and 59 | trigger a reload of dependents." 60 | [ns-sym options] 61 | (let [{:keys [should-reload-dependents? pre-reload-hook post-reload-hook]} 62 | @-config] 63 | (when (and should-reload-dependents? (should-reload-dependents? ns-sym)) 64 | (when-let [f (and pre-reload-hook (resolve pre-reload-hook))] 65 | (f)) 66 | (ns-reload/reload-dependents 67 | ns-sym (merge (:options @-config) options)) 68 | (when-let [f (and post-reload-hook (resolve post-reload-hook))] 69 | (f))))) 70 | -------------------------------------------------------------------------------- /src/ns-reload/profiles.clj: -------------------------------------------------------------------------------- 1 | {:shorthand 2 | {. [com.palletops.ns-reload.repl/reload 3 | com.palletops.ns-reload.repl/reload-dependents]}} 4 | -------------------------------------------------------------------------------- /src/ns_reload/plugin.clj: -------------------------------------------------------------------------------- 1 | (ns ns-reload.plugin 2 | "Plugin for using ns-reload" 3 | (:require 4 | [clojure.java.io :as io] 5 | [leiningen.core.main :as main] 6 | [leiningen.core.project :as project] 7 | [robert.hooke :refer [add-hook]])) 8 | 9 | ;; Keep in sync with VERSION-FORM in project.clj 10 | (def ^:private properties-file 11 | "META-INF/maven/com.palletops/ns-reload/pom.properties") 12 | 13 | (defn- version 14 | [] 15 | (let [v (-> (doto (java.util.Properties.) 16 | (.load (io/reader (io/resource properties-file)))) 17 | (.getProperty "version"))] 18 | (assert v (str "Unexpected error, plugin version is not availaible")) 19 | v)) 20 | 21 | (defn profiles 22 | [project] 23 | {:plugin.ns-reload/injections 24 | {:dependencies [['com.palletops/ns-reload (version)]] 25 | :injections [`(require 'com.palletops.ns-reload.hooks 26 | 'com.palletops.ns-reload.repl) 27 | `(com.palletops.ns-reload.hooks/hooks) 28 | `(com.palletops.ns-reload.repl/set-config! 29 | ~(:ns-reload project))]}}) 30 | 31 | (defn middleware 32 | "Middleware to add a profile defining :injections." 33 | [project] 34 | (project/add-profiles project (profiles project))) 35 | 36 | ;; We would like to be able to hook a function after the :repl profile 37 | ;; is merged, but that is not very feasible at the moment. 38 | 39 | ;; We also want to avoid require'ing leiningen.repl just to hook it,as 40 | ;; it can add considerably to lein startup time when not using the repl. 41 | 42 | (defn repl-hook 43 | [task & [project & args]] 44 | (apply task 45 | (project/merge-profiles project [:plugin.ns-reload/injections]) 46 | args)) 47 | 48 | (defn add-repl-hook [] 49 | (when-let [repl (resolve 'leiningen.repl/repl)] 50 | (add-hook repl repl-hook))) 51 | 52 | (defn resolve-task-hook 53 | [f & args] 54 | (let [r (apply f args)] 55 | (add-repl-hook) 56 | r)) 57 | 58 | (defn hooks 59 | [] 60 | (add-hook #'main/resolve-task resolve-task-hook)) 61 | -------------------------------------------------------------------------------- /test/com/palletops/ns_reload/hooks_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.ns-reload.hooks-test 2 | (:require [com.palletops.ns-reload.hooks :refer :all :as hooks] 3 | [clojure.test :refer :all :as test])) 4 | 5 | (comment 6 | (robert.hooke/clear-hooks #'clojure.core/load-lib) 7 | (robert.hooke/clear-hooks #'clojure.core/defmacro)) 8 | 9 | (hooks) 10 | 11 | (defonce aliases 12 | (set (vals (ns-aliases 'com.palletops.ns-reload.hooks-test)))) 13 | 14 | (defmacro m [] :m) 15 | (defmacro p [] `(clojure.set/difference #{} #{})) 16 | (defmacro q 17 | ([] `(clojure.walk/postwalk #(do %) nil)) 18 | ([x] `(clojure.walk/postwalk #(do %) nil))) 19 | 20 | (defonce aliases-after-defmacro 21 | (set (vals (ns-aliases 'com.palletops.ns-reload.hooks-test)))) 22 | 23 | (deftest defmacro-hook-declare-test 24 | (is (= aliases aliases-after-defmacro))) 25 | 26 | (m) 27 | (defonce aliases-after-m 28 | (set (vals (ns-aliases 'com.palletops.ns-reload.hooks-test)))) 29 | 30 | (p) 31 | (defonce aliases-after-p 32 | (set (vals (ns-aliases 'com.palletops.ns-reload.hooks-test)))) 33 | 34 | (q) 35 | (defonce aliases-after-q 36 | (set (vals (ns-aliases 'com.palletops.ns-reload.hooks-test)))) 37 | 38 | (deftest defmacro-hook-macro-call-test 39 | (is (= aliases aliases-after-m)) 40 | (is (= (conj aliases (the-ns 'clojure.set)) aliases-after-p)) 41 | (is (= (conj aliases-after-p (the-ns 'clojure.walk)) aliases-after-q))) 42 | -------------------------------------------------------------------------------- /test/com/palletops/ns_reload_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.ns-reload-test 2 | (:require [com.palletops.ns-reload :refer :all] 3 | [com.palletops.ns-reload.hooks :as hooks] 4 | [clojure.test :refer :all] 5 | [robert.hooke :refer [add-hook]])) 6 | 7 | ;; add hook so require of clojure.string gets recorded 8 | (add-hook #'clojure.core/load-lib @#'hooks/-load-lib) 9 | 10 | (defmacro x [body] 11 | (with-requires 12 | `(clojure.string/upper-case ~body))) 13 | 14 | (def y (x "a")) 15 | 16 | (deftest with-requires-test 17 | (is (= y "A")) 18 | (println (required-namespaces 'com.palletops.ns-reload-test)) 19 | (is ((set (required-namespaces 'com.palletops.ns-reload-test)) 20 | 'clojure.string))) 21 | --------------------------------------------------------------------------------