metapath 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: 4091eaf52c7e621333e586ec6e584b1a44e11a83aec5b4dee3d983435e14289b
4
+ data.tar.gz: c97f90285b9e7677e9842fd64ae3b9798fc47c87178e4cdb27d39e8e10a0eeea
5
+ SHA512:
6
+ metadata.gz: 9c21bc7669bb48e4c338344c93390898412767470d6a7705db004b0bfb8598bd89690bb3ca3c20dabdcc712a0c9108a709b3350ebc2b5fabaae2287266b31029
7
+ data.tar.gz: f1bef6a89a2aa460088fc54589c0dcb3122c01614bd7e8a923ceab84b3583d48b327032808c9f7c8e9a18f771558b19b4898fec3382b1ebe312394bdc48a61d1
checksums.yaml.gz.sig ADDED
Binary file
data/LICENSE.adoc ADDED
@@ -0,0 +1,134 @@
1
+ = Hippocratic License
2
+
3
+ Version: 2.1.0.
4
+
5
+ Purpose. The purpose of this License is for the Licensor named above to
6
+ permit the Licensee (as defined below) broad permission, if consistent
7
+ with Human Rights Laws and Human Rights Principles (as each is defined
8
+ below), to use and work with the Software (as defined below) within the
9
+ full scope of Licensor’s copyright and patent rights, if any, in the
10
+ Software, while ensuring attribution and protecting the Licensor from
11
+ liability.
12
+
13
+ Permission and Conditions. The Licensor grants permission by this
14
+ license ("License"), free of charge, to the extent of Licensor’s
15
+ rights under applicable copyright and patent law, to any person or
16
+ entity (the "Licensee") obtaining a copy of this software and
17
+ associated documentation files (the "Software"), to do everything with
18
+ the Software that would otherwise infringe (i) the Licensor’s copyright
19
+ in the Software or (ii) any patent claims to the Software that the
20
+ Licensor can license or becomes able to license, subject to all of the
21
+ following terms and conditions:
22
+
23
+ * Acceptance. This License is automatically offered to every person and
24
+ entity subject to its terms and conditions. Licensee accepts this
25
+ License and agrees to its terms and conditions by taking any action with
26
+ the Software that, absent this License, would infringe any intellectual
27
+ property right held by Licensor.
28
+ * Notice. Licensee must ensure that everyone who gets a copy of any part
29
+ of this Software from Licensee, with or without changes, also receives
30
+ the License and the above copyright notice (and if included by the
31
+ Licensor, patent, trademark and attribution notice). Licensee must cause
32
+ any modified versions of the Software to carry prominent notices stating
33
+ that Licensee changed the Software. For clarity, although Licensee is
34
+ free to create modifications of the Software and distribute only the
35
+ modified portion created by Licensee with additional or different terms,
36
+ the portion of the Software not modified must be distributed pursuant to
37
+ this License. If anyone notifies Licensee in writing that Licensee has
38
+ not complied with this Notice section, Licensee can keep this License by
39
+ taking all practical steps to comply within 30 days after the notice. If
40
+ Licensee does not do so, Licensee’s License (and all rights licensed
41
+ hereunder) shall end immediately.
42
+ * Compliance with Human Rights Principles and Human Rights Laws.
43
+ [arabic]
44
+ . Human Rights Principles.
45
+ [loweralpha]
46
+ .. Licensee is advised to consult the articles of the United Nations
47
+ Universal Declaration of Human Rights and the United Nations Global
48
+ Compact that define recognized principles of international human rights
49
+ (the "Human Rights Principles"). Licensee shall use the Software in a
50
+ manner consistent with Human Rights Principles.
51
+ .. Unless the Licensor and Licensee agree otherwise, any dispute,
52
+ controversy, or claim arising out of or relating to (i) Section 1(a)
53
+ regarding Human Rights Principles, including the breach of Section 1(a),
54
+ termination of this License for breach of the Human Rights Principles,
55
+ or invalidity of Section 1(a) or (ii) a determination of whether any Law
56
+ is consistent or in conflict with Human Rights Principles pursuant to
57
+ Section 2, below, shall be settled by arbitration in accordance with the
58
+ Hague Rules on Business and Human Rights Arbitration (the "Rules");
59
+ provided, however, that Licensee may elect not to participate in such
60
+ arbitration, in which event this License (and all rights licensed
61
+ hereunder) shall end immediately. The number of arbitrators shall be one
62
+ unless the Rules require otherwise.
63
+ +
64
+ Unless both the Licensor and Licensee agree to the contrary: (1) All
65
+ documents and information concerning the arbitration shall be public and
66
+ may be disclosed by any party; (2) The repository referred to under
67
+ Article 43 of the Rules shall make available to the public in a timely
68
+ manner all documents concerning the arbitration which are communicated
69
+ to it, including all submissions of the parties, all evidence admitted
70
+ into the record of the proceedings, all transcripts or other recordings
71
+ of hearings and all orders, decisions and awards of the arbitral
72
+ tribunal, subject only to the arbitral tribunal’s powers to take such
73
+ measures as may be necessary to safeguard the integrity of the arbitral
74
+ process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3)
75
+ Article 26(6) of the Rules shall not apply.
76
+ . Human Rights Laws. The Software shall not be used by any person or
77
+ entity for any systems, activities, or other uses that violate any Human
78
+ Rights Laws. "Human Rights Laws" means any applicable laws,
79
+ regulations, or rules (collectively, "Laws") that protect human,
80
+ civil, labor, privacy, political, environmental, security, economic, due
81
+ process, or similar rights; provided, however, that such Laws are
82
+ consistent and not in conflict with Human Rights Principles (a dispute
83
+ over the consistency or a conflict between Laws and Human Rights
84
+ Principles shall be determined by arbitration as stated above). Where
85
+ the Human Rights Laws of more than one jurisdiction are applicable or in
86
+ conflict with respect to the use of the Software, the Human Rights Laws
87
+ that are most protective of the individuals or groups harmed shall
88
+ apply.
89
+ . Indemnity. Licensee shall hold harmless and indemnify Licensor (and
90
+ any other contributor) against all losses, damages, liabilities,
91
+ deficiencies, claims, actions, judgments, settlements, interest, awards,
92
+ penalties, fines, costs, or expenses of whatever kind, including
93
+ Licensor’s reasonable attorneys’ fees, arising out of or relating to
94
+ Licensee’s use of the Software in violation of Human Rights Laws or
95
+ Human Rights Principles.
96
+ * Failure to Comply. Any failure of Licensee to act according to the
97
+ terms and conditions of this License is both a breach of the License and
98
+ an infringement of the intellectual property rights of the Licensor
99
+ (subject to exceptions under Laws, e.g., fair use). In the event of a
100
+ breach or infringement, the terms and conditions of this License may be
101
+ enforced by Licensor under the Laws of any jurisdiction to which
102
+ Licensee is subject. Licensee also agrees that the Licensor may enforce
103
+ the terms and conditions of this License against Licensee through
104
+ specific performance (or similar remedy under Laws) to the extent
105
+ permitted by Laws. For clarity, except in the event of a breach of this
106
+ License, infringement, or as otherwise stated in this License, Licensor
107
+ may not terminate this License with Licensee.
108
+ * Enforceability and Interpretation. If any term or provision of this
109
+ License is determined to be invalid, illegal, or unenforceable by a
110
+ court of competent jurisdiction, then such invalidity, illegality, or
111
+ unenforceability shall not affect any other term or provision of this
112
+ License or invalidate or render unenforceable such term or provision in
113
+ any other jurisdiction; provided, however, subject to a court
114
+ modification pursuant to the immediately following sentence, if any term
115
+ or provision of this License pertaining to Human Rights Laws or Human
116
+ Rights Principles is deemed invalid, illegal, or unenforceable against
117
+ Licensee by a court of competent jurisdiction, all rights in the
118
+ Software granted to Licensee shall be deemed null and void as between
119
+ Licensor and Licensee. Upon a determination that any term or provision
120
+ is invalid, illegal, or unenforceable, to the extent permitted by Laws,
121
+ the court may modify this License to affect the original purpose that
122
+ the Software be used in compliance with Human Rights Principles and
123
+ Human Rights Laws as closely as possible. The language in this License
124
+ shall be interpreted as to its fair meaning and not strictly for or
125
+ against any party.
126
+ * Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES
127
+ "AS IS," WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND
128
+ ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR
129
+ OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
130
+ OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM.
131
+
132
+ This Hippocratic License is an link:https://ethicalsource.dev[Ethical Source license] and is offered
133
+ for use by licensors and licensees at their own risk, on an "AS IS" basis, and with no warranties
134
+ express or implied, to the maximum extent permitted by Laws.
data/README.adoc ADDED
@@ -0,0 +1,356 @@
1
+ :toc: macro
2
+ :toclevels: 5
3
+ :figure-caption!:
4
+
5
+ :data_link: link:https://alchemists.io/articles/ruby_data[Data]
6
+ :dry_monads_link: link:https://dry-rb.org/gems/dry-monads[Dry Monads]
7
+ :railway_pattern_link: link:https://alchemists.io/articles/railway_pattern[Railway Pattern]
8
+ :rubysmith_link: link:https://alchemists.io/projects/rubysmith[Rubysmith]
9
+
10
+ = Metapath
11
+
12
+ Dynamically parses and enriches paths metadata so you can obtain information from directories and files with minimal effort. Having metadata for each directory and/or file -- no matter how nested your directory structure is -- allows you to perform additional processing on your file structure for analysis, transformation, import, and so much more.
13
+
14
+ toc::[]
15
+
16
+ == Features
17
+
18
+ * Dynamically obtains metadata about a directory or a file.
19
+ * Supports an optional, per directory, configuration.
20
+ * Supports nested directory structures.
21
+ * Answers an array of paths with associated metadata.
22
+
23
+ == Requirements
24
+
25
+ . link:https://www.ruby-lang.org[Ruby].
26
+
27
+ == Setup
28
+
29
+ To install _with_ security, run:
30
+
31
+ [source,bash]
32
+ ----
33
+ # 💡 Skip this line if you already have the public certificate installed.
34
+ gem cert --add <(curl --compressed --location https://alchemists.io/gems.pem)
35
+ gem install metapath --trust-policy HighSecurity
36
+ ----
37
+
38
+ To install _without_ security, run:
39
+
40
+ [source,bash]
41
+ ----
42
+ gem install metapath
43
+ ----
44
+
45
+ You can also add the gem directly to your project:
46
+
47
+ [source,bash]
48
+ ----
49
+ bundle add metapath
50
+ ----
51
+
52
+ Once the gem is installed, you only need to require it:
53
+
54
+ [source,ruby]
55
+ ----
56
+ require "metapath"
57
+ ----
58
+
59
+ == Usage
60
+
61
+ Getting started is as quick as creating an instance and then pointing it at a directory structure:
62
+
63
+ [source,ruby]
64
+ ----
65
+ metapath = Metapath.new
66
+ metapath.call Pathname.pwd
67
+
68
+ Success(
69
+ [
70
+ #<data Metapath::Model:0x00002710
71
+ attributes = {},
72
+ errors = {},
73
+ label = "Crested Butte",
74
+ name = "crested_butte",
75
+ path = #<Pathname:/Users/demo/Scratch/photos/Crested_Butte.jpeg>,
76
+ position = 0,
77
+ tags = []
78
+ >,
79
+ #<data Metapath::Model:0x00002780
80
+ attributes = {},
81
+ errors = {},
82
+ label = "Flaming Gorge",
83
+ name = "flaming_gorge",
84
+ path = #<Pathname:/Users/demo/Scratch/photos/Flaming_Gorge.jpeg>,
85
+ position = 0,
86
+ tags = []
87
+ >,
88
+ #<data Metapath::Model:0x000027f0
89
+ attributes = {},
90
+ errors = {},
91
+ label = "Grand Canyon",
92
+ name = "grand_canyon",
93
+ path = #<Pathname:/Users/demo/Scratch/photos/Grand_Canyon.jpeg>,
94
+ position = 0,
95
+ tags = []
96
+ >
97
+ ]
98
+ )
99
+ ----
100
+
101
+ === Roots
102
+
103
+ When calling a metapath, you must always supply a root path for processing. In the earlier example, this was `Pathname.pwd` (current path):
104
+
105
+ [source,ruby]
106
+ ----
107
+ metapath.call Pathname.pwd
108
+ ----
109
+
110
+ Strings, if supplied, will be automatically converted into pathnames and auto-expanding into absolute paths. Examples:
111
+
112
+ [source,ruby]
113
+ ----
114
+ metapath.call "~/photos"
115
+ # Expands to: #<Pathname:/Users/<your user>/photos>
116
+
117
+ metapath.call "photos"
118
+ # Expands to: #<Pathname:<current working directory>/photos>
119
+
120
+ metapath.call "/Users/demo/photos"
121
+ # Identical: "#<Pathname:/Users/demo/photos>"
122
+ ----
123
+
124
+ All directories and files will be processed within the root path supplied (no matter how deeply nested).
125
+
126
+ === Directories and Files
127
+
128
+ Each directory and file can have it's own metadata using any of the following characters:
129
+
130
+ * `0-9`: Any number is valid.
131
+ * `a-z`: Any lowercase letter is valid. This includes Unicode.
132
+ * `A-Z`: Any uppercase letter is valid. This includes Unicode.
133
+ * `-` (hyphen): Translates to `" - "` when building the label. Example:
134
+ ** Before: `A-Demo`.
135
+ ** After: `A - Demo`.
136
+ * `_` (underscore): Translates to `" "` when building the label. Example:
137
+ ** Before: `A_Demo`.
138
+ ** After: `A Demo`.
139
+ * `+` (plus): Marks the start of tag or attribute information. See examples below for details.
140
+ * `,` (comma): Specifies an array of tag or attribute metdata. See examples below for details.
141
+ * `=` (equals): Delimits the key and value of an attribute. For example `kind=demo`, where `kind` is the key and `demo` is the value.
142
+ * `%` (percent): Reserved for token replacement as commonly found in {rubysmith_link} for processing of templates where you want to dynamically replace each placeholder (example: `%demo%`) with a dynamic value that matches the `demo` key (in this example). Currently meant for post-processing.
143
+ * `.` (dot): Reserved for file extensions or multiple formats. Example: `demo.html`, `demo.html.erb`, etc.
144
+ * `~` (tilde): Reserved but currently not used.
145
+ * `@` (at): Reserved but currently not used.
146
+ * `^` (carrot): Reserved but currently not used.
147
+
148
+ All of the characters shown above allow you to have files and directories that don't require special quoting which works well across multiple operating systems.
149
+
150
+ ==== Positions
151
+
152
+ Prefix your directories or files with a number immediately followed by a dash to keep them organized but also for sequential processing order.
153
+
154
+ * *Format*: `<position>-<name>`
155
+ * *Example* `01-demo`
156
+
157
+ The position is always `0` when none is given.
158
+
159
+ ==== Tags
160
+
161
+ Use tags to provide additional metadata about your directories and files (use a comma to separate multiple values).
162
+
163
+ * *Format* (single): `<name>+<tag>`
164
+ * *Example* (single): `demo+blue`
165
+ * *Format* (multiple): `<name>+<tag>,<tag>,<tag>`
166
+ * *Example* (multiple): `demo+blue,red,green`
167
+
168
+ 💡 Use a directory configuration (`meta.yml`) to extract common metadata if your metadata gets too long and unwieldy.
169
+
170
+ ==== Attributes
171
+
172
+ Use attributes to provide additional metadata about your directories and files (use a comma to separate multiple values).
173
+
174
+ * *Format* (single): `<name>+<key>=<value>`
175
+ * *Example* (single): `demo+album=panoramas`
176
+ * *Format* (multiple): `<name>+<key>=<value>,<key>=<value>,<key>=<value>`
177
+ * *Example* (multiple): `demo+album=panoramas,kind=landscapes,location=snow_peak`
178
+
179
+ 💡 Use a directory configuration (`meta.yml`) to extract common metadata if your metadata gets too long and unwieldy.
180
+
181
+ === Configurations
182
+
183
+ You can configure common metadata per directory by placing a `meta.yml` in the root of any directory. The following is an example of what this file might contain:
184
+
185
+ [source,yaml]
186
+ ----
187
+ tags:
188
+ - demo
189
+ - photos
190
+ attributes:
191
+ album: panoramas
192
+ kind: landscapes
193
+ ----
194
+
195
+ With the above, you can supply as many tags and attributes as necessary which will then be inherited as common metadata when processing files within the directory. This includes inheriting configurations from parent directories. Keep in mind that any file with it's own metdata will take precedence.
196
+
197
+ Only the `tag` and `attributes` keys are honored, all other top level keys are ignored.
198
+
199
+ === Priority
200
+
201
+ Metadata is resolved by merging each of the following in order listed (lowest to highest):
202
+
203
+ 3. Directory
204
+ 2. `meta.yml`
205
+ 1. File
206
+
207
+ Resolution of the above happens by merging metadata from the lowest level into the next level until all levels are merged as one. This means you can set defaults at the lowest level which will be inherited, or overwritten, at the highest level. In pseudo code, it looks like this:
208
+
209
+ [source,ruby]
210
+ ----
211
+ directory.deep_merge(meta).deep_merge file
212
+ ----
213
+
214
+ === Monads
215
+
216
+ Every time you call your metapath instance, you'll get either a `Success` or `Failure` as provided by {dry_monads_link}. This allows you to use the {railway_pattern_link} pattern to build fault tolerant functional pipelines for robust error processing.
217
+
218
+ When results are a success, you'll get an array of models. Example:
219
+
220
+ [source,ruby]
221
+ ----
222
+ Success(
223
+ [
224
+ #<data Metapath::Model:0x00002710
225
+ attributes = {},
226
+ label = "Crested Butte",
227
+ name = "crested_butte",
228
+ path = #<Pathname:/Users/demo/Scratch/photos/Crested_Butte.jpeg>,
229
+ position = 0,
230
+ tags = []
231
+ >
232
+ ]
233
+ )
234
+ ----
235
+
236
+ You can get a success when errors are detected with metadata associated with your directories or files. For example, let's say your `meta.yml` has the following content:
237
+
238
+ [source,]
239
+ ----
240
+ attributes:
241
+ ----
242
+
243
+ [source,ruby]
244
+ ----
245
+ Success(
246
+ [
247
+ #<data Metapath::Model:0x00002710
248
+ attributes = {},
249
+ errors = {attributes: ["must be filled"]},
250
+ label = "Crested Butte",
251
+ name = "crested_butte",
252
+ path = #<Pathname:/Users/demo/Scratch/photos/Crested_Butte.jpeg>,
253
+ position = 0,
254
+ tags = []
255
+ >
256
+ ]
257
+ )
258
+ ----
259
+
260
+ If a failure does occur, this usually means errors with your configuration. For example, let's say your `meta.yml` has the following content:
261
+
262
+ [source,yaml]
263
+ ----
264
+ Danger!
265
+ ----
266
+
267
+ This means you'll get the following result:
268
+
269
+ [source,ruby]
270
+ ----
271
+ Failure "Invalid content: Danger."
272
+ ----
273
+
274
+ === Models
275
+
276
+ Each model is a {data_link} object. Additionally, the following methods are also provided for you:
277
+
278
+ [source,ruby]
279
+ ----
280
+ model = Metapath::Model[
281
+ name: "demo",
282
+ label: "Demo",
283
+ tags: %w[demo photos],
284
+ attributes: {
285
+ "album" => "panoramas",
286
+ "kind" => "landscapes"
287
+ }
288
+ ]
289
+
290
+ model.fetch "album" # "panoramas"
291
+ model.fetch "bogus", "fallback" # "fallback"
292
+ model.fetch("bogus") { "fallback" } # "fallback"
293
+ model.fetch "bogus" # KeyError
294
+
295
+ model.key? "album" # true
296
+ model.key? "bogus" # false
297
+
298
+ model.tag? "photos" # true
299
+ model.tag? "bogus" # false
300
+
301
+ other = Metapath::Model[name: "other", path: Pathname("_demo.html")]
302
+
303
+ other.partial? # true
304
+ model.partial? # false
305
+
306
+ other = Metapath::Model[name: "other", path: Pathname("demo.html"), errors: {message: "Danger!"}]
307
+
308
+ other.errors? # true
309
+ model.errors? # false
310
+ ----
311
+
312
+ == Development
313
+
314
+ To contribute, run:
315
+
316
+ [source,bash]
317
+ ----
318
+ git clone https://github.com/bkuhlmann/metapath
319
+ cd metapath
320
+ bin/setup
321
+ ----
322
+
323
+ You can also use the IRB console for direct access to all objects:
324
+
325
+ [source,bash]
326
+ ----
327
+ bin/console
328
+ ----
329
+
330
+ == Tests
331
+
332
+ To test, run:
333
+
334
+ [source,bash]
335
+ ----
336
+ bin/rake
337
+ ----
338
+
339
+ == link:https://alchemists.io/policies/license[License]
340
+
341
+ == link:https://alchemists.io/policies/security[Security]
342
+
343
+ == link:https://alchemists.io/policies/code_of_conduct[Code of Conduct]
344
+
345
+ == link:https://alchemists.io/policies/contributions[Contributions]
346
+
347
+ == link:https://alchemists.io/policies/developer_certificate_of_origin[Developer Certificate of Origin]
348
+
349
+ == link:https://alchemists.io/projects/metapath/versions[Versions]
350
+
351
+ == link:https://alchemists.io/community[Community]
352
+
353
+ == Credits
354
+
355
+ * Built with link:https://alchemists.io/projects/gemsmith[Gemsmith].
356
+ * Engineered by link:https://alchemists.io/team/brooke_kuhlmann[Brooke Kuhlmann].
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+ require "refinements/hash"
5
+ require "refinements/pathname"
6
+
7
+ module Metapath
8
+ # Enriches paths with metadata.
9
+ class Enricher
10
+ include Dry::Monads[:result]
11
+
12
+ using Refinements::Hash
13
+ using Refinements::Pathname
14
+
15
+ def initialize parser: Parser.new, loader: Loader.new, meta_file: "meta.yml"
16
+ @parser = parser
17
+ @loader = loader
18
+ @meta_file = meta_file
19
+ @metadata = {}
20
+ end
21
+
22
+ def call root
23
+ metadata.clear
24
+ visit(Pathname(root).expand_path).fmap { it.sort_by! { it[:path] } }
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :parser, :loader, :meta_file, :metadata
30
+
31
+ def visit directory, collection: []
32
+ merge_metadata_for(directory).fmap do
33
+ directory.children.each.with_object collection do |path, enrichments|
34
+ next if path.fnmatch? "*#{meta_file}"
35
+
36
+ if path.directory?
37
+ visit path, collection: enrichments
38
+ else
39
+ enrichments.append enrich(path)
40
+ end
41
+ end
42
+ end
43
+ end
44
+
45
+ def merge_metadata_for directory
46
+ metadata.deep_merge! parser.call(directory.name)
47
+
48
+ configuration_path = directory.files(meta_file).first
49
+
50
+ return Success() unless configuration_path
51
+
52
+ loader.call(configuration_path).fmap { metadata.deep_merge! it }
53
+ end
54
+
55
+ def enrich path
56
+ parser.call(path.name).then do |data|
57
+ merged = metadata.deep_merge data.to_h
58
+ name = merged.delete(:name).downcase
59
+
60
+ {name:, path:, **merged}
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+ require "refinements/hash"
5
+ require "yaml"
6
+
7
+ module Metapath
8
+ # Load directory metadata.
9
+ class Loader
10
+ include Dry::Monads[:result]
11
+
12
+ using Refinements::Hash
13
+
14
+ def initialize yaml: YAML
15
+ @yaml = yaml
16
+ end
17
+
18
+ def call path
19
+ load path
20
+ rescue Errno::ENOENT,
21
+ NoMethodError,
22
+ Psych::AliasesNotEnabled,
23
+ Psych::DisallowedClass,
24
+ Psych::SyntaxError => error
25
+
26
+ Failure error.message
27
+ end
28
+
29
+ private
30
+
31
+ attr_reader :yaml
32
+
33
+ def load path
34
+ yaml.safe_load_file(path).then do |content|
35
+ case content
36
+ in Hash then Success content.symbolize_keys
37
+ in String then Failure "Invalid content: #{content}."
38
+ else Success Hash.new
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Metapath
4
+ # Stores path metadata.
5
+ Model = Data.define :name, :path, :label, :position, :tags, :attributes, :errors do
6
+ def initialize name:, path:, label: nil, position: 0, tags: [], attributes: {}, errors: {}
7
+ super
8
+ end
9
+
10
+ def fetch(key, *default, &) = attributes.fetch(key.to_s, *default, &)
11
+
12
+ def tag?(item) = tags.include? item
13
+
14
+ def key?(value) = attributes.key? value
15
+
16
+ def partial? = path.basename.fnmatch? "_*"
17
+
18
+ def errors? = !errors.empty?
19
+ end
20
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+
5
+ module Metapath
6
+ # Validates and models metadata.
7
+ class Modeler
8
+ include Dry::Monads[:result]
9
+
10
+ def initialize enricher: Enricher.new, schema: Schema, model: Model
11
+ @enricher = enricher
12
+ @schema = schema
13
+ @model = model
14
+ end
15
+
16
+ def call(root, **) = enricher.call(root, **).fmap { build_models it }
17
+
18
+ private
19
+
20
+ attr_reader :enricher, :schema, :model
21
+
22
+ def instance_variables_to_inspect = %i[@enricher @model]
23
+
24
+ def build_models(data) = data.map { build_model it }
25
+
26
+ def build_model data
27
+ case schema.call(data).to_monad
28
+ in Success(result)
29
+ model[**result.to_h]
30
+ in Failure(result)
31
+ model[**data.slice(:name, :label, :path), errors: result.errors.to_h]
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "refinements/hash"
4
+
5
+ module Metapath
6
+ # Parses path metadata.
7
+ class Parser
8
+ using Refinements::Hash
9
+
10
+ PATTERN = /
11
+ (?: # Start non-capture group.
12
+ (?<position>[0-9]+) # Position capture group, numbers only.
13
+ - # Dash.
14
+ )? # End non-capture group and make it optional.
15
+ (?<name>[[:word:]-]+) # Name capture group, required.
16
+ (?: # Non-capture group start.
17
+ \+ # Plus.
18
+ (?<meta>[[:word:]\-,=]+) # Meta capture group, required.
19
+ )? # End non-capture group and make it optional.
20
+ /x
21
+
22
+ SPACERS = {dash: ["-", " - "], underscore: ["_", " "]}.freeze
23
+ DELIMITERS = {array: ",", hash: "="}.freeze
24
+
25
+ def initialize pattern: PATTERN, spacers: SPACERS, delimiters: DELIMITERS
26
+ @pattern = pattern
27
+ @spacers = spacers
28
+ @delimiters = delimiters
29
+ end
30
+
31
+ def call path
32
+ captures = path.to_s.match(pattern).named_captures
33
+ meta = parse_metadata captures["meta"]
34
+ name = captures["name"]
35
+
36
+ {name:, label: parse_label(name), position: captures["position"], **meta}.compress
37
+ end
38
+
39
+ private
40
+
41
+ attr_reader :pattern, :spacers, :delimiters
42
+
43
+ def instance_variables_to_inspect = []
44
+
45
+ def parse_label(value) = value.gsub(*spacers.fetch(:dash)).tr(*spacers.fetch(:underscore))
46
+
47
+ def parse_metadata value
48
+ return {} unless value
49
+
50
+ value.split(delimiters.fetch(:array))
51
+ .each
52
+ .with_object({tags: [], attributes: {}}) { |item, all| add_metadata item, all }
53
+ end
54
+
55
+ def add_metadata item, bag
56
+ if item.include? hash_delimiter
57
+ key, value = item.split hash_delimiter
58
+ bag[:attributes][key] = value
59
+ else
60
+ bag[:tags].append item
61
+ end
62
+ end
63
+
64
+ def hash_delimiter
65
+ @hash_delimiter ||= delimiters.fetch :hash
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/schema"
4
+
5
+ module Metapath
6
+ # Validates metadata information.
7
+ Schema = Dry::Schema.Params do
8
+ required(:name).filled :string
9
+ required(:label).filled :string
10
+ required(:path).filled
11
+ optional(:position).filled :integer
12
+ optional(:tags).filled(:array).each(:string)
13
+ optional(:attributes).filled :hash
14
+ end
15
+ end
data/lib/metapath.rb ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/schema"
4
+ require "zeitwerk"
5
+
6
+ Dry::Schema.load_extensions :monads
7
+
8
+ Zeitwerk::Loader.new.then do |loader|
9
+ loader.inflector.inflect "cli" => "CLI"
10
+ loader.tag = File.basename __FILE__, ".rb"
11
+ loader.push_dir __dir__
12
+ loader.setup
13
+ end
14
+
15
+ # Main namespace.
16
+ module Metapath
17
+ def self.loader registry = Zeitwerk::Registry
18
+ @loader ||= registry.loaders.each.find do |loader|
19
+ loader.tag == File.basename(__FILE__, ".rb")
20
+ end
21
+ end
22
+
23
+ def self.new = Modeler.new
24
+ end
data/metapath.gemspec ADDED
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "metapath"
5
+ spec.version = "0.0.0"
6
+ spec.authors = ["Brooke Kuhlmann"]
7
+ spec.email = ["brooke@alchemists.io"]
8
+ spec.homepage = "https://alchemists.io/projects/metapath"
9
+ spec.summary = "A parser of enriched file path metadata."
10
+ spec.license = "Hippocratic-2.1"
11
+
12
+ spec.metadata = {
13
+ "bug_tracker_uri" => "https://github.com/bkuhlmann/metapath/issues",
14
+ "changelog_uri" => "https://alchemists.io/projects/metapath/versions",
15
+ "homepage_uri" => "https://alchemists.io/projects/metapath",
16
+ "funding_uri" => "https://github.com/sponsors/bkuhlmann",
17
+ "label" => "Metapath",
18
+ "rubygems_mfa_required" => "true",
19
+ "source_code_uri" => "https://github.com/bkuhlmann/metapath"
20
+ }
21
+
22
+ spec.signing_key = Gem.default_key_path
23
+ spec.cert_chain = [Gem.default_cert_path]
24
+
25
+ spec.required_ruby_version = ">= 4.0"
26
+
27
+ spec.add_dependency "dry-monads", "~> 1.11"
28
+ spec.add_dependency "dry-schema", "~> 1.16"
29
+ spec.add_dependency "refinements", "~> 14.0"
30
+ spec.add_dependency "zeitwerk", "~> 2.8"
31
+
32
+ spec.extra_rdoc_files = Dir["README*", "LICENSE*"]
33
+ spec.files = Dir["*.gemspec", "lib/**/*"]
34
+ end
data.tar.gz.sig ADDED
Binary file
metadata ADDED
@@ -0,0 +1,140 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: metapath
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Brooke Kuhlmann
8
+ bindir: bin
9
+ cert_chain:
10
+ - |
11
+ -----BEGIN CERTIFICATE-----
12
+ MIIENjCCAp6gAwIBAgIBAzANBgkqhkiG9w0BAQsFADBBMQ8wDQYDVQQDDAZicm9v
13
+ a2UxGjAYBgoJkiaJk/IsZAEZFgphbGNoZW1pc3RzMRIwEAYKCZImiZPyLGQBGRYC
14
+ aW8wHhcNMjYwMzI1MTI0OTEyWhcNMjcwMzI1MTI0OTEyWjBBMQ8wDQYDVQQDDAZi
15
+ cm9va2UxGjAYBgoJkiaJk/IsZAEZFgphbGNoZW1pc3RzMRIwEAYKCZImiZPyLGQB
16
+ GRYCaW8wggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCro8tj5/E1Hg88
17
+ f4qfiwPVd2zJQHvdYt4GHVvuHRRgx4HGhJuNp+4BId08RBn7V6V1MW6MY3kezRBs
18
+ M+7QOQ4b1xNLTvY7FYQB1wGK5a4x7TTokDrPYQxDB2jmsdDYCzVbIMrAvUfcecRi
19
+ khyGZCdByiiCl4fKv77P12tTT+NfsvXkLt/AYCGwjOUyGKTQ01Z6eC09T27GayPH
20
+ QQvIkakyFgcJtzSyGzs8bzK5q9u7wQ12MNTjJoXzW69lqp0oNvDylu81EiSUb5S6
21
+ QzzPxZBiRB1sgtbt1gUbVI262ZDq1gR+HxPFmp+Cgt7ZLIJZAtesQvtcMzseXpfn
22
+ hpmm0Sw22KGhRAy/mqHBRhDl5HqS1SJp2Ko3lcnpXeFResp0HNlt8NSu13vhC08j
23
+ GUHU9MyIXbFOsnp3K3ADrAVjPWop8EZkmUR3MV/CUm00w2cZHCSGiXl1KMpiVKvk
24
+ Ywr1gd2ZME4QLSo+EXUtLxDUa/W3xnBS8dBOuMMz02FPWYr3PN8CAwEAAaM5MDcw
25
+ CQYDVR0TBAIwADALBgNVHQ8EBAMCBLAwHQYDVR0OBBYEFAFgmv0tYMZnItuPycSM
26
+ F5wykJEVMA0GCSqGSIb3DQEBCwUAA4IBgQAG+ykjp+DIXSybGEtX+/ve974mYfN6
27
+ 8U7qcVfRM+qDSOZ+97iu30qUTbVAKIHlHCDKRn3SgOffDUB5VU2MsJBh/3TPKWBZ
28
+ anB/uzMcwOfru+qyA3b7ZFqZzRLWmR5FtPObFxc0gYMT3YvLNHk2Nb9Vjq/PoiGG
29
+ e75PXweDOokwDA5m1gMOz1rdp/dlGMXkSFQg94PPVyUKXgO4VzWTgePSDxOIL+v6
30
+ +OWV6AaEH9BaqxnmdA5ubi0L7bhl0gbN92FxpNO3kpTjww8kme856a+wCK3qyM5w
31
+ 7ZLbUexynDN0Au8eSpT2Bf6ztGmB1S9ffzDJsGX1/lkpMIB51e48Xe2+gzzOgemk
32
+ CdZaGupj6WkarnT8kh/cPtyA5ax4rGX6GOS8meGxzkv8Uy0JSEOYAp6wLfIisYZp
33
+ IJBIXIOkwKKJ0eB5YHrUSJxzpP4LlcIg/eTftaXmJdYjy+2VRrCZYDjfguyLmMjR
34
+ KR9w4/Fjvqy87kCHmxMWa6IL2Vzt1Clm2cA=
35
+ -----END CERTIFICATE-----
36
+ date: 1980-01-02 00:00:00.000000000 Z
37
+ dependencies:
38
+ - !ruby/object:Gem::Dependency
39
+ name: dry-monads
40
+ requirement: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - "~>"
43
+ - !ruby/object:Gem::Version
44
+ version: '1.11'
45
+ type: :runtime
46
+ prerelease: false
47
+ version_requirements: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - "~>"
50
+ - !ruby/object:Gem::Version
51
+ version: '1.11'
52
+ - !ruby/object:Gem::Dependency
53
+ name: dry-schema
54
+ requirement: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - "~>"
57
+ - !ruby/object:Gem::Version
58
+ version: '1.16'
59
+ type: :runtime
60
+ prerelease: false
61
+ version_requirements: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - "~>"
64
+ - !ruby/object:Gem::Version
65
+ version: '1.16'
66
+ - !ruby/object:Gem::Dependency
67
+ name: refinements
68
+ requirement: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - "~>"
71
+ - !ruby/object:Gem::Version
72
+ version: '14.0'
73
+ type: :runtime
74
+ prerelease: false
75
+ version_requirements: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - "~>"
78
+ - !ruby/object:Gem::Version
79
+ version: '14.0'
80
+ - !ruby/object:Gem::Dependency
81
+ name: zeitwerk
82
+ requirement: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - "~>"
85
+ - !ruby/object:Gem::Version
86
+ version: '2.8'
87
+ type: :runtime
88
+ prerelease: false
89
+ version_requirements: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - "~>"
92
+ - !ruby/object:Gem::Version
93
+ version: '2.8'
94
+ email:
95
+ - brooke@alchemists.io
96
+ executables: []
97
+ extensions: []
98
+ extra_rdoc_files:
99
+ - LICENSE.adoc
100
+ - README.adoc
101
+ files:
102
+ - LICENSE.adoc
103
+ - README.adoc
104
+ - lib/metapath.rb
105
+ - lib/metapath/enricher.rb
106
+ - lib/metapath/loader.rb
107
+ - lib/metapath/model.rb
108
+ - lib/metapath/modeler.rb
109
+ - lib/metapath/parser.rb
110
+ - lib/metapath/schema.rb
111
+ - metapath.gemspec
112
+ homepage: https://alchemists.io/projects/metapath
113
+ licenses:
114
+ - Hippocratic-2.1
115
+ metadata:
116
+ bug_tracker_uri: https://github.com/bkuhlmann/metapath/issues
117
+ changelog_uri: https://alchemists.io/projects/metapath/versions
118
+ homepage_uri: https://alchemists.io/projects/metapath
119
+ funding_uri: https://github.com/sponsors/bkuhlmann
120
+ label: Metapath
121
+ rubygems_mfa_required: 'true'
122
+ source_code_uri: https://github.com/bkuhlmann/metapath
123
+ rdoc_options: []
124
+ require_paths:
125
+ - lib
126
+ required_ruby_version: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '4.0'
131
+ required_rubygems_version: !ruby/object:Gem::Requirement
132
+ requirements:
133
+ - - ">="
134
+ - !ruby/object:Gem::Version
135
+ version: '0'
136
+ requirements: []
137
+ rubygems_version: 4.0.22
138
+ specification_version: 4
139
+ summary: A parser of enriched file path metadata.
140
+ test_files: []
metadata.gz.sig ADDED
Binary file