core-watch 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 742d61f2473ddb32defdf6b2379cf4bcb2c678ce889af2e2c8ae29b63548269b
4
+ data.tar.gz: 72bfc097768d5abf52db5e4db2ca7828d2bb7d7013872bac622197e205529573
5
+ SHA512:
6
+ metadata.gz: 737bbeea342ae421335afc835826f515a60f441f0beb5e370c2e1c1f1389def2c466c1b895650806acb9bd3e4b87869f6046f02805c7d74a7bc3ab9eaf85641b
7
+ data.tar.gz: e1725cf0a045c22d734b4819dfc9ccb0372864383e6adea88c0c2188d37ee39020087f8d8145f2ad2b6a1342779b21fe57c92dd7959c9f0ecb243f16c09e091a
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## [v0.0.0](https://github.com/metabahn/corerb/releases/tag/2021-04-03)
2
+
3
+ *released on 2021-04-03*
4
+
5
+ * `add` [#26](https://github.com/metabahn/corerb/pull/26) Initial implementation of core-watch ([bryanp](https://github.com/bryanp))
6
+
7
+
data/LICENSE ADDED
@@ -0,0 +1,353 @@
1
+ Mozilla Public License, version 2.0
2
+
3
+ 1. Definitions
4
+
5
+ 1.1. “Contributor”
6
+
7
+ means each individual or legal entity that creates, contributes to the
8
+ creation of, or owns Covered Software.
9
+
10
+ 1.2. “Contributor Version”
11
+
12
+ means the combination of the Contributions of others (if any) used by a
13
+ Contributor and that particular Contributor’s Contribution.
14
+
15
+ 1.3. “Contribution”
16
+
17
+ means Covered Software of a particular Contributor.
18
+
19
+ 1.4. “Covered Software”
20
+
21
+ means Source Code Form to which the initial Contributor has attached the
22
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
23
+ Modifications of such Source Code Form, in each case including portions
24
+ thereof.
25
+
26
+ 1.5. “Incompatible With Secondary Licenses”
27
+ means
28
+
29
+ a. that the initial Contributor has attached the notice described in
30
+ Exhibit B to the Covered Software; or
31
+
32
+ b. that the Covered Software was made available under the terms of version
33
+ 1.1 or earlier of the License, but not also under the terms of a
34
+ Secondary License.
35
+
36
+ 1.6. “Executable Form”
37
+
38
+ means any form of the work other than Source Code Form.
39
+
40
+ 1.7. “Larger Work”
41
+
42
+ means a work that combines Covered Software with other material, in a separate
43
+ file or files, that is not Covered Software.
44
+
45
+ 1.8. “License”
46
+
47
+ means this document.
48
+
49
+ 1.9. “Licensable”
50
+
51
+ means having the right to grant, to the maximum extent possible, whether at the
52
+ time of the initial grant or subsequently, any and all of the rights conveyed by
53
+ this License.
54
+
55
+ 1.10. “Modifications”
56
+
57
+ means any of the following:
58
+
59
+ a. any file in Source Code Form that results from an addition to, deletion
60
+ from, or modification of the contents of Covered Software; or
61
+
62
+ b. any new file in Source Code Form that contains any Covered Software.
63
+
64
+ 1.11. “Patent Claims” of a Contributor
65
+
66
+ means any patent claim(s), including without limitation, method, process,
67
+ and apparatus claims, in any patent Licensable by such Contributor that
68
+ would be infringed, but for the grant of the License, by the making,
69
+ using, selling, offering for sale, having made, import, or transfer of
70
+ either its Contributions or its Contributor Version.
71
+
72
+ 1.12. “Secondary License”
73
+
74
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
75
+ General Public License, Version 2.1, the GNU Affero General Public
76
+ License, Version 3.0, or any later versions of those licenses.
77
+
78
+ 1.13. “Source Code Form”
79
+
80
+ means the form of the work preferred for making modifications.
81
+
82
+ 1.14. “You” (or “Your”)
83
+
84
+ means an individual or a legal entity exercising rights under this
85
+ License. For legal entities, “You” includes any entity that controls, is
86
+ controlled by, or is under common control with You. For purposes of this
87
+ definition, “control” means (a) the power, direct or indirect, to cause
88
+ the direction or management of such entity, whether by contract or
89
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
90
+ outstanding shares or beneficial ownership of such entity.
91
+
92
+
93
+ 2. License Grants and Conditions
94
+
95
+ 2.1. Grants
96
+
97
+ Each Contributor hereby grants You a world-wide, royalty-free,
98
+ non-exclusive license:
99
+
100
+ a. under intellectual property rights (other than patent or trademark)
101
+ Licensable by such Contributor to use, reproduce, make available,
102
+ modify, display, perform, distribute, and otherwise exploit its
103
+ Contributions, either on an unmodified basis, with Modifications, or as
104
+ part of a Larger Work; and
105
+
106
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
107
+ sale, have made, import, and otherwise transfer either its Contributions
108
+ or its Contributor Version.
109
+
110
+ 2.2. Effective Date
111
+
112
+ The licenses granted in Section 2.1 with respect to any Contribution become
113
+ effective for each Contribution on the date the Contributor first distributes
114
+ such Contribution.
115
+
116
+ 2.3. Limitations on Grant Scope
117
+
118
+ The licenses granted in this Section 2 are the only rights granted under this
119
+ License. No additional rights or licenses will be implied from the distribution
120
+ or licensing of Covered Software under this License. Notwithstanding Section
121
+ 2.1(b) above, no patent license is granted by a Contributor:
122
+
123
+ a. for any code that a Contributor has removed from Covered Software; or
124
+
125
+ b. for infringements caused by: (i) Your and any other third party’s
126
+ modifications of Covered Software, or (ii) the combination of its
127
+ Contributions with other software (except as part of its Contributor
128
+ Version); or
129
+
130
+ c. under Patent Claims infringed by Covered Software in the absence of its
131
+ Contributions.
132
+
133
+ This License does not grant any rights in the trademarks, service marks, or
134
+ logos of any Contributor (except as may be necessary to comply with the
135
+ notice requirements in Section 3.4).
136
+
137
+ 2.4. Subsequent Licenses
138
+
139
+ No Contributor makes additional grants as a result of Your choice to
140
+ distribute the Covered Software under a subsequent version of this License
141
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
142
+ under the terms of Section 3.3).
143
+
144
+ 2.5. Representation
145
+
146
+ Each Contributor represents that the Contributor believes its Contributions
147
+ are its original creation(s) or it has sufficient rights to grant the
148
+ rights to its Contributions conveyed by this License.
149
+
150
+ 2.6. Fair Use
151
+
152
+ This License is not intended to limit any rights You have under applicable
153
+ copyright doctrines of fair use, fair dealing, or other equivalents.
154
+
155
+ 2.7. Conditions
156
+
157
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
158
+ Section 2.1.
159
+
160
+
161
+ 3. Responsibilities
162
+
163
+ 3.1. Distribution of Source Form
164
+
165
+ All distribution of Covered Software in Source Code Form, including any
166
+ Modifications that You create or to which You contribute, must be under the
167
+ terms of this License. You must inform recipients that the Source Code Form
168
+ of the Covered Software is governed by the terms of this License, and how
169
+ they can obtain a copy of this License. You may not attempt to alter or
170
+ restrict the recipients’ rights in the Source Code Form.
171
+
172
+ 3.2. Distribution of Executable Form
173
+
174
+ If You distribute Covered Software in Executable Form then:
175
+
176
+ a. such Covered Software must also be made available in Source Code Form,
177
+ as described in Section 3.1, and You must inform recipients of the
178
+ Executable Form how they can obtain a copy of such Source Code Form by
179
+ reasonable means in a timely manner, at a charge no more than the cost
180
+ of distribution to the recipient; and
181
+
182
+ b. You may distribute such Executable Form under the terms of this License,
183
+ or sublicense it under different terms, provided that the license for
184
+ the Executable Form does not attempt to limit or alter the recipients’
185
+ rights in the Source Code Form under this License.
186
+
187
+ 3.3. Distribution of a Larger Work
188
+
189
+ You may create and distribute a Larger Work under terms of Your choice,
190
+ provided that You also comply with the requirements of this License for the
191
+ Covered Software. If the Larger Work is a combination of Covered Software
192
+ with a work governed by one or more Secondary Licenses, and the Covered
193
+ Software is not Incompatible With Secondary Licenses, this License permits
194
+ You to additionally distribute such Covered Software under the terms of
195
+ such Secondary License(s), so that the recipient of the Larger Work may, at
196
+ their option, further distribute the Covered Software under the terms of
197
+ either this License or such Secondary License(s).
198
+
199
+ 3.4. Notices
200
+
201
+ You may not remove or alter the substance of any license notices (including
202
+ copyright notices, patent notices, disclaimers of warranty, or limitations
203
+ of liability) contained within the Source Code Form of the Covered
204
+ Software, except that You may alter any license notices to the extent
205
+ required to remedy known factual inaccuracies.
206
+
207
+ 3.5. Application of Additional Terms
208
+
209
+ You may choose to offer, and to charge a fee for, warranty, support,
210
+ indemnity or liability obligations to one or more recipients of Covered
211
+ Software. However, You may do so only on Your own behalf, and not on behalf
212
+ of any Contributor. You must make it absolutely clear that any such
213
+ warranty, support, indemnity, or liability obligation is offered by You
214
+ alone, and You hereby agree to indemnify every Contributor for any
215
+ liability incurred by such Contributor as a result of warranty, support,
216
+ indemnity or liability terms You offer. You may include additional
217
+ disclaimers of warranty and limitations of liability specific to any
218
+ jurisdiction.
219
+
220
+ 4. Inability to Comply Due to Statute or Regulation
221
+
222
+ If it is impossible for You to comply with any of the terms of this License
223
+ with respect to some or all of the Covered Software due to statute, judicial
224
+ order, or regulation then You must: (a) comply with the terms of this License
225
+ to the maximum extent possible; and (b) describe the limitations and the code
226
+ they affect. Such description must be placed in a text file included with all
227
+ distributions of the Covered Software under this License. Except to the
228
+ extent prohibited by statute or regulation, such description must be
229
+ sufficiently detailed for a recipient of ordinary skill to be able to
230
+ understand it.
231
+
232
+ 5. Termination
233
+
234
+ 5.1. The rights granted under this License will terminate automatically if You
235
+ fail to comply with any of its terms. However, if You become compliant,
236
+ then the rights granted under this License from a particular Contributor
237
+ are reinstated (a) provisionally, unless and until such Contributor
238
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
239
+ if such Contributor fails to notify You of the non-compliance by some
240
+ reasonable means prior to 60 days after You have come back into compliance.
241
+ Moreover, Your grants from a particular Contributor are reinstated on an
242
+ ongoing basis if such Contributor notifies You of the non-compliance by
243
+ some reasonable means, this is the first time You have received notice of
244
+ non-compliance with this License from such Contributor, and You become
245
+ compliant prior to 30 days after Your receipt of the notice.
246
+
247
+ 5.2. If You initiate litigation against any entity by asserting a patent
248
+ infringement claim (excluding declaratory judgment actions, counter-claims,
249
+ and cross-claims) alleging that a Contributor Version directly or
250
+ indirectly infringes any patent, then the rights granted to You by any and
251
+ all Contributors for the Covered Software under Section 2.1 of this License
252
+ shall terminate.
253
+
254
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
255
+ license agreements (excluding distributors and resellers) which have been
256
+ validly granted by You or Your distributors under this License prior to
257
+ termination shall survive termination.
258
+
259
+ 6. Disclaimer of Warranty
260
+
261
+ Covered Software is provided under this License on an “as is” basis, without
262
+ warranty of any kind, either expressed, implied, or statutory, including,
263
+ without limitation, warranties that the Covered Software is free of defects,
264
+ merchantable, fit for a particular purpose or non-infringing. The entire
265
+ risk as to the quality and performance of the Covered Software is with You.
266
+ Should any Covered Software prove defective in any respect, You (not any
267
+ Contributor) assume the cost of any necessary servicing, repair, or
268
+ correction. This disclaimer of warranty constitutes an essential part of this
269
+ License. No use of any Covered Software is authorized under this License
270
+ except under this disclaimer.
271
+
272
+ 7. Limitation of Liability
273
+
274
+ Under no circumstances and under no legal theory, whether tort (including
275
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
276
+ distributes Covered Software as permitted above, be liable to You for any
277
+ direct, indirect, special, incidental, or consequential damages of any
278
+ character including, without limitation, damages for lost profits, loss of
279
+ goodwill, work stoppage, computer failure or malfunction, or any and all
280
+ other commercial damages or losses, even if such party shall have been
281
+ informed of the possibility of such damages. This limitation of liability
282
+ shall not apply to liability for death or personal injury resulting from such
283
+ party’s negligence to the extent applicable law prohibits such limitation.
284
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
285
+ consequential damages, so this exclusion and limitation may not apply to You.
286
+
287
+ 8. Litigation
288
+
289
+ Any litigation relating to this License may be brought only in the courts of
290
+ a jurisdiction where the defendant maintains its principal place of business
291
+ and such litigation shall be governed by laws of that jurisdiction, without
292
+ reference to its conflict-of-law provisions. Nothing in this Section shall
293
+ prevent a party’s ability to bring cross-claims or counter-claims.
294
+
295
+ 9. Miscellaneous
296
+
297
+ This License represents the complete agreement concerning the subject matter
298
+ hereof. If any provision of this License is held to be unenforceable, such
299
+ provision shall be reformed only to the extent necessary to make it
300
+ enforceable. Any law or regulation which provides that the language of a
301
+ contract shall be construed against the drafter shall not be used to construe
302
+ this License against a Contributor.
303
+
304
+
305
+ 10. Versions of the License
306
+
307
+ 10.1. New Versions
308
+
309
+ Mozilla Foundation is the license steward. Except as provided in Section
310
+ 10.3, no one other than the license steward has the right to modify or
311
+ publish new versions of this License. Each version will be given a
312
+ distinguishing version number.
313
+
314
+ 10.2. Effect of New Versions
315
+
316
+ You may distribute the Covered Software under the terms of the version of
317
+ the License under which You originally received the Covered Software, or
318
+ under the terms of any subsequent version published by the license
319
+ steward.
320
+
321
+ 10.3. Modified Versions
322
+
323
+ If you create software not governed by this License, and you want to
324
+ create a new license for such software, you may create and use a modified
325
+ version of this License if you rename the license and remove any
326
+ references to the name of the license steward (except to note that such
327
+ modified license differs from this License).
328
+
329
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
330
+ If You choose to distribute Source Code Form that is Incompatible With
331
+ Secondary Licenses under the terms of this version of the License, the
332
+ notice described in Exhibit B of this License must be attached.
333
+
334
+ Exhibit A - Source Code Form License Notice
335
+
336
+ This Source Code Form is subject to the
337
+ terms of the Mozilla Public License, v.
338
+ 2.0. If a copy of the MPL was not
339
+ distributed with this file, You can
340
+ obtain one at
341
+ http://mozilla.org/MPL/2.0/.
342
+
343
+ If it is not possible or desirable to put the notice in a particular file, then
344
+ You may include the notice in a location (such as a LICENSE file in a relevant
345
+ directory) where a recipient would be likely to look for such a notice.
346
+
347
+ You may add additional accurate notices of copyright ownership.
348
+
349
+ Exhibit B - “Incompatible With Secondary Licenses” Notice
350
+
351
+ This Source Code Form is “Incompatible
352
+ With Secondary Licenses”, as defined by
353
+ the Mozilla Public License, v. 2.0.
data/lib/core/watch.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ require_relative "watch/callback"
6
+ require_relative "watch/diff"
7
+ require_relative "watch/snapshot"
8
+ require_relative "watch/status"
9
+ require_relative "watch/strategy"
10
+ require_relative "watch/system"
11
+ require_relative "watch/version"
12
+ end
13
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ # [public] Callback for a watched system.
6
+ #
7
+ class Callback
8
+ class << self
9
+ # [public] Build a callback instance for a given value and block.
10
+ #
11
+ def build(value, &block)
12
+ case value
13
+ when Callback
14
+ value
15
+ when ::NilClass
16
+ Callback.new(&block)
17
+ when ::Regexp
18
+ Callbacks::Regexp.new(value, &block)
19
+ else
20
+ Callbacks::Path.new(value, &block)
21
+ end
22
+ end
23
+ end
24
+
25
+ def initialize(&block)
26
+ @block = block
27
+ end
28
+
29
+ # [public] Invoke the callback.
30
+ #
31
+ def call(*args, **kwargs)
32
+ @block.call(*args, **kwargs)
33
+ end
34
+
35
+ # [public]
36
+ #
37
+ def match?(_)
38
+ true
39
+ end
40
+ end
41
+
42
+ require_relative "callbacks/path"
43
+ require_relative "callbacks/regexp"
44
+ end
45
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ module Core
6
+ module Watch
7
+ module Callbacks
8
+ # [public] Callback that wraps a path.
9
+ #
10
+ class Path < Callback
11
+ def initialize(value, **kwargs, &block)
12
+ super(**kwargs, &block)
13
+
14
+ @path = Pathname(value.to_s)
15
+ end
16
+
17
+ # [public] Return `true` if this callback matches the path.
18
+ #
19
+ def match?(path)
20
+ @path == path
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ module Callbacks
6
+ # [public] Callback that wraps a regular expression.
7
+ #
8
+ class Regexp < Callback
9
+ def initialize(regexp, **kwargs, &block)
10
+ super(**kwargs, &block)
11
+
12
+ @regexp = regexp
13
+ end
14
+
15
+ # [public] Return `true` if this callback matches the path.
16
+ #
17
+ def match?(path)
18
+ @regexp.match?(path.to_s)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ module Core
6
+ module Watch
7
+ # [public] Contains changes to a watched system, organized by operation.
8
+ #
9
+ class Diff
10
+ OPERATIONS = %i[added changed removed].freeze
11
+
12
+ def initialize
13
+ @changes = {}
14
+ end
15
+
16
+ OPERATIONS.each do |operation|
17
+ # [public]
18
+ #
19
+ class_eval <<~CODE, __FILE__, __LINE__ + 1
20
+ def #{operation}(path)
21
+ @changes[path] = #{operation.inspect}
22
+ end
23
+ CODE
24
+ end
25
+
26
+ # [public] Call the given block once with each changed path and operation.
27
+ #
28
+ def each_change(&block)
29
+ return to_enum(:each_change) unless block
30
+
31
+ @changes.each_pair(&block)
32
+ end
33
+
34
+ # [public] Call the given block once with each changed path.
35
+ #
36
+ def each_changed_path(&block)
37
+ return to_enum(:each_changed_path) unless block
38
+
39
+ @changes.each_key(&block)
40
+ end
41
+
42
+ # [public] Return `true` if the diff contains changes.
43
+ #
44
+ def changed?
45
+ @changes.any?
46
+ end
47
+
48
+ # [public] Return `true` if `path` is included in the changes.
49
+ #
50
+ def include?(path)
51
+ @changes.include?(Pathname(path))
52
+ end
53
+
54
+ # [public] Return the operation for the given path.
55
+ #
56
+ def operation(path)
57
+ @changes[path]
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "diff"
4
+
5
+ module Core
6
+ module Watch
7
+ # [public] Snapshot of a watched system that can generate diffs.
8
+ #
9
+ class Snapshot
10
+ class << self
11
+ def default_strategy
12
+ require_relative "strategies/digest"
13
+
14
+ Strategies::Digest
15
+ end
16
+ end
17
+
18
+ def initialize(*paths, ignore: [], strategy: self.class.default_strategy)
19
+ @ignore = ignore
20
+ @directories = {}
21
+ @files = {}
22
+ @strategy = strategy.new
23
+
24
+ track(*paths)
25
+ end
26
+
27
+ # [public] Return `true` if `path` is ignored.
28
+ #
29
+ def ignore?(path)
30
+ @ignore.any? do |ignore|
31
+ path.fnmatch?(ignore)
32
+ end
33
+ end
34
+
35
+ # [public] Detect changes, update the snapshot, and return a diff.
36
+ #
37
+ def diff
38
+ trackable = []
39
+ untrackable = []
40
+ diff = Diff.new
41
+
42
+ # The mtime of the parent directory changes when its contents have changed (e.g. a file is added or removed).
43
+ # So, do the minimum amount of work necessary to detect added/removed files, then detect file changes below.
44
+ #
45
+ @directories.each do |path, current|
46
+ if !path.exist?
47
+ diff.removed(path)
48
+ untrackable << path
49
+ elsif @strategy.identify(path) != current
50
+ path.glob("*") do |each_path|
51
+ unless @directories.include?(each_path) || @files.include?(each_path)
52
+ next if ignore?(each_path)
53
+
54
+ diff.added(each_path)
55
+ trackable << each_path
56
+ end
57
+ end
58
+
59
+ trackable << path
60
+ end
61
+ end
62
+
63
+ @files.each do |path, current|
64
+ if !path.exist?
65
+ diff.removed(path)
66
+ untrackable << path
67
+ elsif @strategy.identify(path) != current
68
+ diff.changed(path)
69
+ trackable << path
70
+ end
71
+ end
72
+
73
+ track(*trackable)
74
+ untrack(*untrackable)
75
+
76
+ diff
77
+ end
78
+
79
+ # [public]
80
+ #
81
+ private def track(*paths)
82
+ paths.each do |path|
83
+ next if ignore?(path)
84
+
85
+ if path.file?
86
+ @files[path] = @strategy.identify(path)
87
+ elsif path.directory?
88
+ existed = @directories.include?(path)
89
+ @directories[path] = @strategy.identify(path)
90
+
91
+ unless existed
92
+ track(*path.glob("*"))
93
+ end
94
+ else
95
+ track(*Dir.glob(path).map { |string| Pathname(string) })
96
+ end
97
+ end
98
+ end
99
+
100
+ # [public]
101
+ #
102
+ private def untrack(*paths)
103
+ paths.each do |path|
104
+ @files.delete(path)
105
+ @directories.delete(path)
106
+ end
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ # [public] The status of a system watch.
6
+ #
7
+ class Status
8
+ STATES = %i[running paused stopped].freeze
9
+
10
+ def initialize
11
+ @state = :stopped
12
+ @mutex = Mutex.new
13
+ end
14
+
15
+ STATES.each do |state|
16
+ # [public]
17
+ #
18
+ class_eval <<~CODE, __FILE__, __LINE__ + 1
19
+ def #{state}!
20
+ @mutex.synchronize {
21
+ if @state == #{state.inspect}
22
+ false
23
+ else
24
+ @state = #{state.inspect}
25
+ true
26
+ end
27
+ }
28
+ end
29
+ CODE
30
+
31
+ # [public]
32
+ #
33
+ class_eval <<~CODE, __FILE__, __LINE__ + 1
34
+ def #{state}?
35
+ @state == #{state.inspect} || (#{state.inspect} == :running && @state == :paused)
36
+ end
37
+ CODE
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ require_relative "../strategy"
6
+
7
+ module Core
8
+ module Watch
9
+ module Strategies
10
+ # [public] Identifies a path by digest or modified time (for directories).
11
+ #
12
+ class Digest
13
+ BUFFER_LENGTH = 16_384
14
+
15
+ # [public]
16
+ #
17
+ def identify(path)
18
+ if path.file?
19
+ md5 = OpenSSL::Digest.new("MD5")
20
+
21
+ path.open("rb") do |file|
22
+ buffer = +""
23
+ while file.read(BUFFER_LENGTH, buffer)
24
+ md5 << buffer
25
+ end
26
+ end
27
+
28
+ md5.digest
29
+ else
30
+ path.mtime
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../strategy"
4
+
5
+ module Core
6
+ module Watch
7
+ module Strategies
8
+ # [public] Identifies a path by modified time.
9
+ #
10
+ class Timestamp
11
+ # [public]
12
+ #
13
+ def identify(path)
14
+ path.mtime
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ # [public] Abstract strategy for uniquely identifying a path.
6
+ #
7
+ class Strategy
8
+ # [public]
9
+ #
10
+ def identify(path)
11
+ raise "unimplemented"
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ require "core/async"
6
+
7
+ require_relative "callback"
8
+ require_relative "snapshot"
9
+ require_relative "status"
10
+
11
+ module Core
12
+ module Watch
13
+ # [public] The system watcher.
14
+ #
15
+ class System
16
+ include Is::Async
17
+
18
+ # [public] The configured polling interval.
19
+ #
20
+ attr_accessor :interval
21
+
22
+ # [public] The status object.
23
+ #
24
+ attr_reader :status
25
+
26
+ # [public] The current latency.
27
+ #
28
+ attr_reader :latency
29
+
30
+ def initialize(interval: 0.1, strategy: :digest)
31
+ @interval = interval
32
+ @status = Status.new
33
+ @mutex = Mutex.new
34
+ @watched = []
35
+ @ignored = []
36
+ @callbacks = []
37
+ @working = false
38
+ @latency = nil
39
+
40
+ @strategy = case strategy.to_sym
41
+ when :digest
42
+ require_relative "strategies/digest"
43
+ Strategies::Digest
44
+ when :timestamp
45
+ require_relative "strategies/timestamp"
46
+ Strategies::Timestamp
47
+ else
48
+ raise ArgumentError, "unknown watch strategy `#{strategy.inspect}'"
49
+ end
50
+ end
51
+
52
+ # [public] Watch `path` for changes.
53
+ #
54
+ def watch(path)
55
+ path = Pathname(path).expand_path
56
+
57
+ @mutex.synchronize do
58
+ unless @watched.include?(path)
59
+ mutate do
60
+ @watched << path
61
+ end
62
+ end
63
+ end
64
+ end
65
+
66
+ # [public] Ignore changes at `path`.
67
+ #
68
+ def ignore(path)
69
+ path = path.to_s
70
+
71
+ @mutex.synchronize do
72
+ unless @ignored.include?(path)
73
+ mutate do
74
+ @ignored << path
75
+ end
76
+ end
77
+ end
78
+ end
79
+
80
+ # [public] Register a callback to be called when a change is detected. The callback will only be called once per
81
+ # tick and will be given a `Core::Watch::Diff` instance. If `matcher` is passed, the callback will only be called
82
+ # for matching changes. The matcher can be a string or any object that responds to `match?`.
83
+ #
84
+ def callback(matcher = nil, &block)
85
+ raise ArgumentError, "expected a block" if block.nil?
86
+
87
+ @mutex.synchronize do
88
+ @callbacks << Callback.build(matcher, &block)
89
+ end
90
+ end
91
+
92
+ # [public] Start the watcher.
93
+ #
94
+ def start
95
+ await do
96
+ unless @status.running?
97
+ @future = run
98
+ end
99
+ end
100
+ end
101
+
102
+ # [public] Stop the watcher.
103
+ #
104
+ def stop(force: false)
105
+ if !@working || force
106
+ @future&.cancel
107
+ end
108
+
109
+ @status.stopped!
110
+ end
111
+
112
+ # [public] Pause the watcher, causing it to continue running but not invoke callbacks.
113
+ #
114
+ def pause
115
+ @status.paused!
116
+ end
117
+
118
+ # [public] Resume a paused watcher.
119
+ #
120
+ def resume
121
+ @status.running!
122
+ end
123
+
124
+ private def run
125
+ async {
126
+ @status.running!
127
+
128
+ rebuild_snapshot
129
+
130
+ until @status.stopped?
131
+ sleep(@interval)
132
+
133
+ started = current_time
134
+
135
+ # Don't process this tick if the watch was paused or stopped while sleeping.
136
+ #
137
+ next if @status.paused? || @status.stopped?
138
+
139
+ # Do the work, updating the snapshot in the process.
140
+ #
141
+ invoke_callbacks(@snapshot.diff)
142
+
143
+ # Measure the latency for this tick.
144
+ #
145
+ @latency = [0, current_time - started - @interval].max
146
+ end
147
+ }
148
+ end
149
+
150
+ private def mutate
151
+ yield
152
+
153
+ if @status.running?
154
+ rebuild_snapshot
155
+ end
156
+ end
157
+
158
+ private def rebuild_snapshot
159
+ @snapshot = Snapshot.new(*@watched, ignore: @ignored, strategy: @strategy)
160
+ end
161
+
162
+ private def invoke_callbacks(diff)
163
+ return unless diff.changed?
164
+
165
+ await do
166
+ @working = true
167
+ @callbacks.each do |callback|
168
+ maybe_invoke_callback(callback, diff)
169
+ end
170
+ end
171
+ ensure
172
+ @working = false
173
+ end
174
+
175
+ private def maybe_invoke_callback(callback, diff)
176
+ diff.each_change do |path, event|
177
+ if callback.match?(path)
178
+ return async { callback.call(diff) }
179
+ end
180
+ end
181
+ end
182
+
183
+ private def current_time
184
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
185
+ end
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Core
4
+ module Watch
5
+ VERSION = "0.0.0"
6
+
7
+ def self.version
8
+ VERSION
9
+ end
10
+ end
11
+ end
metadata ADDED
@@ -0,0 +1,70 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: core-watch
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Bryan Powell
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-04-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: core-async
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.5.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.5.0
27
+ description: Watches the filesystem for changes.
28
+ email: bryan@metabahn.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - CHANGELOG.md
34
+ - LICENSE
35
+ - lib/core/watch.rb
36
+ - lib/core/watch/callback.rb
37
+ - lib/core/watch/callbacks/path.rb
38
+ - lib/core/watch/callbacks/regexp.rb
39
+ - lib/core/watch/diff.rb
40
+ - lib/core/watch/snapshot.rb
41
+ - lib/core/watch/status.rb
42
+ - lib/core/watch/strategies/digest.rb
43
+ - lib/core/watch/strategies/timestamp.rb
44
+ - lib/core/watch/strategy.rb
45
+ - lib/core/watch/system.rb
46
+ - lib/core/watch/version.rb
47
+ homepage: https://github.com/metabahn/corerb/
48
+ licenses:
49
+ - MPL-2.0
50
+ metadata: {}
51
+ post_install_message:
52
+ rdoc_options: []
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: 2.5.0
60
+ required_rubygems_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ requirements: []
66
+ rubygems_version: 3.2.4
67
+ signing_key:
68
+ specification_version: 4
69
+ summary: Watches the filesystem for changes.
70
+ test_files: []