aboutsummaryrefslogtreecommitdiff
path: root/lib.clj
blob: ab15779f85f05caf56411736c96b7d4e1e676441 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
;;  Copyright (c) Stephen C. Gilardi. All rights reserved.
;;  The use and distribution terms for this software are covered by the
;;  Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
;;  which can be found in the file CPL.TXT at the root of this distribution.
;;  By using this software in any fashion, you are agreeing to be bound by
;;  the terms of this license.
;;  You must not remove this notice, or any other, from this software.
;;
;;  File: lib.clj
;;
;;  lib.clj provides facilities for loading and managing libs. A lib is
;;  is a unit of Clojure code contained in a file or other resource within
;;  classpath. The name of the lib's container is the lib's name followed
;;  by ".clj". A lib's name must be a valid Clojure symbol name.
;;
;;  A lib will typically contain useful functions, macros, and other vars.
;;
;;  Core
;;
;;  Function: load-libs
;;
;;  load-libs is the core function provided by lib.clj. Its arguments are
;;  libspecs and flags. It uses libspecs to find lib containers and flags
;;  to control how the libs are loaded. In an explicit call to load-libs
;;  libspecs must be quoted. This requirement is relaxed by the 'require'
;;  and 'use' macros described below.
;;
;;  Libspecs
;;
;;  A libspec is either a lib name or a list beginning with the lib name
;;  and followed by zero or more options.
;;
;;  Options
;;
;;  Options in a libspec are keywords followed by values. These are the
;;  options supported by load-libs and the kind of value each expects:
;;
;;    :in          a string specifying the path to the parent directory
;;                 of the lib's container relative to one of the
;;                 directories in classpath
;;    :ns          a symbol specifying a namespace for the lib. If :ns
;;                 is not present, its value defaults to the lib's name.
;;                 See the :use flag below.
;;    :exclude     a list as documented for clojure/refer
;;    :only        a list as documented for clojure/refer
;;    :rename      a map as documented for clojure/refer
;;
;;  Flags
;;
;;  Flags apply to all the libs specified in a single call to load-libs.
;;  These are the flags supported by load-libs:
;;
;;  :require       indicates that already loaded libs need not be reloaded
;;  :use           triggers a call to clojure/refer for each lib's namespace
;;                 after ensuring the lib is loaded. The call to refer
;;                 includes any filter options in the libspec.
;;  :reload        forces reloading of libs that are already loaded
;;  :reload-all    implies :reload and also forces reloading of all libs
;;                 on which each lib directly or indirectly depends
;;  :verbose       triggers printing a message each time a lib is loaded
;;
;;  (The :reload and :reload-all flags supersede :require.)
;;
;;  Function: libs
;;
;;  The libs function returns a sorted seq of symbols naming the currently
;;  loaded libs.
;;
;;  Convenience
;;
;;  lib.clj provides two convenience macros to make calls to load-libs
;;  easier to write and read. Libspecs in calls to these macros do not
;;  need to be quoted.
;;
;;  Macro: require
;;
;;  The require macro accepts libspecs and flags and ensures that the
;;  specified libs are loaded. By default, require will not reload a lib
;;  that is already loaded.
;;
;;  Macro: use
;;
;;  The use macro accepts libspecs and flags and first requires the libs
;;  and then refers to each lib's namespace using any filter options present
;;  in its libspec.
;;
;;  Examples
;;
;;  (load-libs :require 'sql '(test :in "private/resources"))
;;  (require sql (test :in "private/resources"))
;;
;;  (load-libs :require :use 'sql 'ns-utils :verbose)
;;  (use sql ns-utils :verbose)
;;
;;  (use :reload-all :verbose
;;    (sql :exclude (get-connection) :rename {execute-commands do-commands})
;;    ns-utils)
;;  (use (sql))
;;
;;  (use (genclass :ns clojure))
;;
;;  scgilardi (gmail)
;;  06 May 2008
;;
;;  Thanks to Stuart Sierra for providing many useful ideas, discussions
;;  and code contributions for lib.clj.

(clojure/in-ns 'lib)
(clojure/refer 'clojure)

(import '(java.io BufferedReader InputStreamReader))
(import '(clojure.lang RT))

;; Private

(defmacro init-once
  "Initializes a var exactly once. The var must already exist."
  {:private true}
  [var init]
  `(let [v# (resolve '~var)]
     (when-not (.isBound v#)
       (.bindRoot v# ~init))))

(def
 #^{:private true :doc
    "A ref to a set of symbols representing loaded libs"}
 *libs*)
(init-once *libs* (ref #{}))

(def
 #^{:private true :doc
    "True while a verbose require is pending"}
 *verbose*)
(init-once *verbose* false)

(defn- load-lib
  "Loads a lib from <classpath>/in/ and ensures that namespace
  ns (if specified) exists"
  [sym in ns]
  (let [res (str sym ".clj")]
    (.loadResourceScript RT (if in (str in \/ res) res))
    (when (and ns (not (find-ns ns)))
      (throw (Exception.
              (str "namespace '" ns "' not found after "
                   "loading resource '" res "'")))))
  (dosync
   (commute *libs* conj sym))
  (when *verbose*
    (println "loaded" sym)))

(defn- load-all
  "Loads a lib from <classpath>/in/ and forces a load of any
  libs on which it directly or indirectly depends"
  [sym in ns]
  (dosync
   (commute *libs* set/union
            (binding [*libs* (ref #{})]
              (load-lib sym in ns)
              @*libs*))))

(defn- load-with-options
  "Load a lib with options expressed as sequential keywords and
  values"
  [sym & options]
  (let [opts (apply hash-map options)
        in (:in opts)
        ns (:ns opts)
        reload (:reload opts)
        reload-all (:reload-all opts)
        require (:require opts)
        use (:use opts)
        verbose (:verbose opts)
        loaded (contains? @*libs* sym)
        namespace (and use (or ns sym))]
    (binding [*verbose* (or *verbose* verbose)]
      (cond reload-all
            (load-all sym in namespace)
            (or reload (not require) (not loaded))
            (load-lib sym in namespace)))
    (when namespace
      (apply refer namespace options))))

(defn- remove-quote
  "If form is a 'quote' special form, return the unquoted value
  else return form"
  [form]
  (if (and (seq? form)
           (= 'quote (first form))
           (= 2 (count form)))
    (second form) form))

;; Core

(defn load-libs
  "Searches classpath for libs and loads them based on libspecs
  and flags. In addition to the flags documented for 'require'
  load-libs supports :require which indicates that already loaded
  libs need not be reloaded and :use which triggers a call to
  'clojure/refer' for the lib's namespace after ensuring the lib
  is loaded. The :reload and :reload-all flags supersede
  :require."
  [& args]
  (let [libspecs (filter (complement keyword?) args)
        flags (filter keyword? args)
        options (interleave flags (repeat true))]
    (doseq libspec libspecs
      (let [libspec (remove-quote libspec)
            combine (if (symbol? libspec) cons concat)]
        (apply load-with-options (combine libspec options))))))

(defn libs
  "Returns a sorted sequence of symbols naming loaded libs"
  []
  (sort @*libs*))

;; Convenience

(defmacro require
  "Searches classpath for libs and loads them if they are not
  already loaded. Each argument is either a libspec or a flag.
  A libspec is a name or a seq of the form (name [options*]).
  Each option is a sequential keyword-value pair. 'require'
  supports the :in option whose value is the path of the lib's
  parent directory relative to a location in classpath.

  Flags may include:

    :reload
    :reload-all
    :verbose

  The :reload flag forces reloading of libs that are already
  loaded. The :reload-all flag implies :reload and also forces
  reloading of all libs on which the libs directly or indirectly
  depend. The :verbose flag triggers printing a message each time
  a lib is loaded."
  [& args]
  `(apply load-libs :require '~args))

(defmacro use
  "Requires and refers to the named libs (see clojure/refer).
  Arguments are like those of 'lib/require', except that libspecs
  can contain an :ns option specifying a namespace to refer to
  (ns defaults to the lib's name) and additional options which
  are filters for clojure/refer."
  [& args]
  `(apply load-libs :require :use '~args))