hrx 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 113be96953fad121bc702b9218c683c567fab09f
4
+ data.tar.gz: 57dd4863e7b7e74e59d652cccc033f7dec8b7356
5
+ SHA512:
6
+ metadata.gz: 503935bd42061aca65943fca313eeefe893ff8f744753ca547200bde88d73760d2c7a24c49bc67c534b9b30a89868f0dd167d740b9bf7e9fa05e0603f94147b9
7
+ data.tar.gz: 0ecbd595c273f93e457d6c89ce417f9f8bf6e66df068f8e6e9e6a25e1a56779dde994c4fd2958cb991d980cfde99c21b44345ec8704e851eb60e67a6483467fd
@@ -0,0 +1,31 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ ## Documentation cache and generated files:
14
+ /.yardoc/
15
+ /_yardoc/
16
+ /doc/
17
+ /rdoc/
18
+
19
+ ## Environment normalization:
20
+ /.bundle/
21
+ /vendor/bundle
22
+ /lib/bundler/man/
23
+
24
+ # for a library or gem, you might want to ignore these files since the code is
25
+ # intended to run in multiple environments; otherwise, check them in:
26
+ Gemfile.lock
27
+ .ruby-version
28
+ .ruby-gemset
29
+
30
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
31
+ .rvmrc
@@ -0,0 +1,23 @@
1
+ --- !ruby/object:RDoc::Options
2
+ encoding: UTF-8
3
+ static_path: []
4
+ rdoc_include:
5
+ - "."
6
+ - "/home/nweiz/goog/hrx-ruby"
7
+ charset: UTF-8
8
+ exclude:
9
+ hyperlink_all: false
10
+ line_numbers: false
11
+ locale:
12
+ locale_dir: locale
13
+ locale_name:
14
+ main_page:
15
+ markup: markdown
16
+ output_decoration: true
17
+ page_dir:
18
+ show_hash: false
19
+ tab_width: 8
20
+ template_stylesheets: []
21
+ title:
22
+ visibility: :protected
23
+ webcvs:
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,28 @@
1
+ # How to Contribute
2
+
3
+ We'd love to accept your patches and contributions to this project. There are
4
+ just a few small guidelines you need to follow.
5
+
6
+ ## Contributor License Agreement
7
+
8
+ Contributions to this project must be accompanied by a Contributor License
9
+ Agreement. You (or your employer) retain the copyright to your contribution;
10
+ this simply gives us permission to use and redistribute your contributions as
11
+ part of the project. Head over to <https://cla.developers.google.com/> to see
12
+ your current agreements on file or to sign a new one.
13
+
14
+ You generally only need to submit a CLA once, so if you've already submitted one
15
+ (even if it was for a different project), you probably don't need to do it
16
+ again.
17
+
18
+ ## Code reviews
19
+
20
+ All submissions, including submissions by project members, require review. We
21
+ use GitHub pull requests for this purpose. Consult
22
+ [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23
+ information on using pull requests.
24
+
25
+ ## Community Guidelines
26
+
27
+ This project follows [Google's Open Source Community
28
+ Guidelines](https://opensource.google.com/conduct/).
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ gem "rspec", "~> 3.0", group: :test
6
+ gem "rspec-temp_dir", "~> 1.0", group: :test
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,35 @@
1
+ # HRX (Human Readable Archive)
2
+
3
+ This gem is a parser and serializer for the [HRX format][].
4
+
5
+ [HRX format]: https://github.com/google/hrx
6
+
7
+ ```ruby
8
+ # Load an archive from a path on disk. You can also parse it directly from a
9
+ # string using HRX::Archive.parse, or create an empty archive using
10
+ # HRX::Archive.new.
11
+ archive = HRX::Archive.load("path/to/archive.hrx")
12
+
13
+ # You can read files directly from an archive as though it were a filesystem.
14
+ puts archive.read("dir/file.txt")
15
+
16
+ # You can also write to files. Writing to a file implicitly creates any
17
+ # directories above it. You can also overwrite an existing file.
18
+ archive.write("dir/new.txt", "New file contents!\n")
19
+
20
+ # You can access HRX::File or HRX::Directory objects directly using
21
+ # HRX::Archive#[]. Unlike HRX::Archive#read(), this will just return nil if the
22
+ # entry isn't found.
23
+ archive["dir/file.txt"] # => HRX::File
24
+
25
+ # You can add files to the end of the archive using HRX::Archive#<< or
26
+ # HRX::Archive#add. If you pass `before:` or `after:`, you can control where in
27
+ # the archive they're added.
28
+ archive << HRX::File.new("dir/newer.txt", "Newer file contents!\n")
29
+
30
+ # Write the file back to disk. You can also use HRX::Archive#to_hrx to serialize
31
+ # the archive to a string.
32
+ archive.write!("path/to/archive.hrx")
33
+ ```
34
+
35
+ This is not an officially supported Google product.
@@ -0,0 +1,30 @@
1
+ # Copyright 2018 Google Inc
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ Gem::Specification.new do |s|
16
+ s.name = "hrx"
17
+ s.version = "1.0.0"
18
+ s.license = "Apache-2.0"
19
+
20
+ s.homepage = "https://github.com/google/hrx-ruby"
21
+ s.summary = "An HRX parser and serializer"
22
+ s.description = "A parser and serializer for the HRX human-readable archive format."
23
+ s.authors = ["Natalie Weizenbaum"]
24
+ s.email = "nweiz@google.com"
25
+
26
+ s.files = `git ls-files -z`.split("\x0")
27
+
28
+ s.add_runtime_dependency "linked-list", "~> 0.0.13"
29
+ s.required_ruby_version = ">= 2.3.0"
30
+ end
@@ -0,0 +1,22 @@
1
+ # Copyright 2018 Google Inc
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # The parent module for all HRX classes. See the README for more information and
16
+ # usage examples.
17
+ #
18
+ # Parse an archive from a string with HRX::Archive.parse, load it from disk with
19
+ # HRX::Archive.load, or create an empty archive with HRX::Archive.new.
20
+ module HRX; end
21
+
22
+ require_relative 'hrx/archive'
@@ -0,0 +1,461 @@
1
+ # Copyright 2018 Google Inc
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'linked-list'
16
+ require 'set'
17
+ require 'strscan'
18
+
19
+ require_relative 'directory'
20
+ require_relative 'error'
21
+ require_relative 'file'
22
+ require_relative 'ordered_node'
23
+ require_relative 'parse_error'
24
+
25
+ # An HRX archive.
26
+ #
27
+ # Parse an archive from a string with ::parse, load it from disk with ::load, or
28
+ # create an empty archive with ::new.
29
+ class HRX::Archive
30
+ class << self
31
+ # Parses an HRX file's text.
32
+ #
33
+ # If `file` is passed, it's used as the file name for error reporting.
34
+ #
35
+ # Throws an HRX::ParseError if `text` isn't valid HRX. Throws an
36
+ # EncodingError if `text` can't be converted to UTF-8.
37
+ def parse(text, file: nil)
38
+ text = text.encode("UTF-8")
39
+ return new if text.empty?
40
+
41
+ scanner = StringScanner.new(text)
42
+ unless boundary = scanner.scan(/<=+>/)
43
+ HRX::Util.parse_error(scanner, "Expected boundary", file: file)
44
+ end
45
+ boundary_length = boundary.length - 2
46
+ hrx = HRX::Archive.new(boundary_length: boundary_length)
47
+ boundary_regexp = /^<={#{boundary_length}}>/m
48
+
49
+ loop do
50
+ if scanner.scan(/\n/)
51
+ if comment_plus_boundary = scanner.scan_until(boundary_regexp)
52
+ comment = comment_plus_boundary[0...-boundary_length - 3]
53
+ else
54
+ hrx.last_comment = scanner.rest
55
+ return hrx
56
+ end
57
+ end
58
+
59
+ unless scanner.scan(/ /)
60
+ HRX::Util.parse_error(scanner, "Expected space", file: file)
61
+ end
62
+
63
+ before_path = scanner.pos
64
+ path = HRX::Util.scan_path(scanner, assert_done: false, file: file)
65
+ unless scanner.scan(/\n/)
66
+ HRX::Util.parse_error(scanner, "Expected newline", file: file)
67
+ end
68
+
69
+ begin
70
+ if path.end_with?("/")
71
+ hrx << HRX::Directory._new_without_checks(path, comment)
72
+ return hrx if scanner.eos?
73
+ next if scanner.scan(boundary_regexp)
74
+ HRX::Util.parse_error(scanner, "Expected boundary", file: file)
75
+ end
76
+
77
+ if content_plus_boundary = scanner.scan_until(boundary_regexp)
78
+ content = content_plus_boundary[0...-boundary_length - 3]
79
+ hrx << HRX::File._new_without_checks(path, content, comment)
80
+ else
81
+ hrx << HRX::File._new_without_checks(path, scanner.rest, comment)
82
+ return hrx
83
+ end
84
+ rescue HRX::ParseError => e
85
+ raise e
86
+ rescue HRX::Error => e
87
+ scanner.pos = before_path
88
+ HRX::Util.parse_error(scanner, e.message, file: file)
89
+ end
90
+ end
91
+ end
92
+
93
+ # Loads an HRX::Archive from the given `file`.
94
+ #
95
+ # Throws an HRX::ParseError if the file isn't valid HRX. Throws an
96
+ # EncodingError if the file isn't valid UTF-8.
97
+ def load(file)
98
+ text = File.read(file, mode: "rb", encoding: "UTF-8")
99
+
100
+ # If the encoding is invalid, force an InvalidByteSequenceError.
101
+ text.encode("UTF-16") unless text.valid_encoding?
102
+
103
+ parse(text, file: file)
104
+ end
105
+
106
+ # Creates an archive as a child of an existing archive.
107
+ #
108
+ # The `root` is the path to the root of this archive, relative to its
109
+ # outermost ancestor. The `entries` is the outermost ancestor's entries
110
+ # list. The `entries_by_path` is the subtree of the outermost ancestor's
111
+ # entries tree that corresponds to this child.
112
+ def _new_child(root, boundary_length, entries, entries_by_path) # :nodoc:
113
+ allocate.tap do |archive|
114
+ archive._initialize_child(root, boundary_length, entries, entries_by_path)
115
+ end
116
+ end
117
+ end
118
+
119
+ # The last comment in the document, or `nil` if it has no final comment.
120
+ #
121
+ # HRX comments are always encoded as UTF-8.
122
+ attr_reader :last_comment
123
+
124
+ # Creates a new, empty archive.
125
+ #
126
+ # The `boundary_length` is the number of `=` signs to include in the boundary
127
+ # when #to_hrx is called, unless a file already contains that boundary.
128
+ def initialize(boundary_length: 3)
129
+ if boundary_length && boundary_length < 1
130
+ raise ArgumentError.new("boundary_length must be 1 or greater")
131
+ end
132
+
133
+ @root = nil
134
+ @boundary_length = boundary_length
135
+ @entries = LinkedList::List.new
136
+ @entries_by_path = {}
137
+ end
138
+
139
+ # See _new_child.
140
+ def _initialize_child(root, boundary_length, entries, entries_by_path) # :nodoc:
141
+ @root = root.end_with?("/") ? root : root + "/"
142
+ @boundary_length = boundary_length
143
+ @entries = entries
144
+ @entries_by_path = entries_by_path
145
+ end
146
+
147
+ # A frozen array of the HRX::File and/or HRX::Directory objects that this
148
+ # archive contains.
149
+ #
150
+ # Note that a new array is created every time this method is called, so try to
151
+ # avoid calling this many times in a tight loop.
152
+ def entries
153
+ return @entries.to_a.freeze unless @root
154
+ @entries.
155
+ each.
156
+ select {|e| e.path.start_with?(@root) && e.path != @root}.
157
+ map {|e| e._relative(@root)}.
158
+ freeze
159
+ end
160
+
161
+ # Returns the HRX::File or HRX::Directory at the given `path` in this archive,
162
+ # or `nil` if there's no entry at that path.
163
+ #
164
+ # This doesn't verify that `path` is well-formed, but instead just returns
165
+ # `nil`.
166
+ #
167
+ # If `path` ends with `"/"`, returns `nil` if the entry at the given path is a
168
+ # file rather than a directory.
169
+ def [](path)
170
+ _find_node(path)&.data&._relative(@root)
171
+ end
172
+
173
+ # Returns all HRX::File or HRX::Directory objects in this archive that match
174
+ # `pattern`. See also Dir::glob. This always uses the option File::FNM_PATHNAME.
175
+ #
176
+ # This only returns HRX::Directory objects if `pattern` ends in `/` or
177
+ # includes `**`.
178
+ def glob(pattern, flags = 0)
179
+ entries.select {|e| File.fnmatch?(pattern, e.path, flags | File::FNM_PATHNAME)}
180
+ end
181
+
182
+ # Returns the contents of the file at `path` in the archive as a frozen
183
+ # string.
184
+ #
185
+ # Throws an HRX::Error if there is no file at `path`, or if `path` is invalid
186
+ # (including if it ends with `/`).
187
+ def read(path)
188
+ raise HRX::Error.new("There is no file at \"#{path}\"") unless node = _find_node(path)
189
+ unless node.data.is_a?(HRX::File)
190
+ raise HRX::Error.new("\"#{node.data._relative(@root).path}\" is a directory")
191
+ end
192
+ node.data.content
193
+ end
194
+
195
+ # Returns an HRX::Archive that provides access to the entries in `path` as
196
+ # though they were at the root of the archive.
197
+ #
198
+ # Any modifications to the child archive will be reflected in the parent as
199
+ # well. The HRX::File and HRX::Directory objects returned by the child archive
200
+ # will have their paths adjusted to be relative to the child's root.
201
+ def child_archive(path)
202
+ components = path.split("/")
203
+ raise HRX::Error.new('There is no directory at ""') if components.empty?
204
+ child_entries_by_path = @entries_by_path.dig(*components)
205
+ raise HRX::Error.new("There is no directory at \"#{path}\"") unless child_entries_by_path
206
+ if child_entries_by_path.is_a?(LinkedList::Node)
207
+ raise HRX::Error.new("\"#{child_entries_by_path.data._relative(@root).path}\" is a file")
208
+ end
209
+
210
+ HRX::Archive._new_child(_absolute(path), @boundary_length, @entries, child_entries_by_path)
211
+ end
212
+
213
+ # Writes `content` to the file at `path`.
214
+ #
215
+ # If there's already a file at `path`, overwrites it. Otherwise, creates a new
216
+ # file after the nearest file in the archive.
217
+ #
218
+ # If `comment` is passed, it's used as the comment for the new file. The
219
+ # special value `:copy` copies the existing comment for the file, if there is
220
+ # one.
221
+ #
222
+ # Throws an HRX::ParseError if `path` is invalid.
223
+ #
224
+ # Throws an HRX::Error if there's a directory at `path`.
225
+ def write(path, content, comment: nil)
226
+ components = path.split("/")
227
+ nearest_dir = nil
228
+ parent = components[0...-1].inject(@entries_by_path) do |hash, component|
229
+ entry = hash[component]
230
+ if entry.is_a?(LinkedList::Node)
231
+ raise HRX::Error.new("\"#{entry.data._relative(@root).path}\" is a file")
232
+ end
233
+
234
+ # Even though both branches of this if are assignments, their return
235
+ # values are used by #inject.
236
+ if entry
237
+ nearest_dir = entry
238
+ else
239
+ hash[component] = {}
240
+ end
241
+ end
242
+ nearest_dir = parent unless parent.empty?
243
+
244
+ previous = parent[components.last]
245
+ if previous.is_a?(Hash)
246
+ raise HRX::Error.new("\"#{path}/\" is a directory")
247
+ end
248
+
249
+ if previous.is_a?(LinkedList::Node)
250
+ comment = previous.data.comment if comment == :copy
251
+ previous.data = HRX::File.new(_absolute(path), content, comment: comment)
252
+ return
253
+ end
254
+
255
+ comment = nil if comment == :copy
256
+ node = HRX::OrderedNode.new(HRX::File.new(_absolute(path), content, comment: comment))
257
+ if nearest_dir.nil?
258
+ @entries << node
259
+ else
260
+ # Add the new file after its closest pre-existing cousin. Start looking
261
+ # for siblings in `nearest_dir`, and then work down through its children.
262
+ if last_cousin = _each_entry(nearest_dir).max_by {|n| n.order}
263
+ @entries.insert_after_node(node, last_cousin)
264
+ else
265
+ @entries << node
266
+ end
267
+ end
268
+
269
+ parent[components.last] = node
270
+ nil
271
+ end
272
+
273
+ # Deletes the file or directory at `path`.
274
+ #
275
+ # Throws an HRX::Error if there's no entry at `path`.
276
+ def delete(path, recursive: false)
277
+ # The outermost parent directory hash that contains only the entry at
278
+ # `path`, from which key_to_delete should be deleted
279
+ parent_to_delete_from = nil
280
+ key_to_delete = nil
281
+
282
+ components = path.split("/")
283
+ parent = components[0...-1].inject(@entries_by_path) do |hash, component|
284
+ entry = hash[component]
285
+ if entry.is_a?(LinkedList::Node)
286
+ raise HRX::Error.new("\"#{entry.data._relative(@root).path}\" is a file")
287
+ end
288
+
289
+ if entry.nil?
290
+ raise HRX::Error.new("\"#{path}\" doesn't exist")
291
+ elsif entry.size == 1
292
+ parent_to_delete_from ||= hash
293
+ key_to_delete ||= component
294
+ else
295
+ parent_to_delete_from = nil
296
+ key_to_delete = nil
297
+ end
298
+
299
+ hash[component] ||= {}
300
+ end
301
+ parent_to_delete_from ||= parent
302
+ key_to_delete ||= components.last
303
+
304
+ node = parent[components.last]
305
+ if node.nil?
306
+ raise HRX::Error.new("\"#{path}\" doesn't exist")
307
+ elsif node.is_a?(Hash)
308
+ if recursive
309
+ _each_entry(node) {|n| @entries.delete(n)}
310
+ else
311
+ unless node = node[:dir]
312
+ raise HRX::Error.new("\"#{path}\" is not an explicit directory and recursive isn't set")
313
+ end
314
+ @entries.delete(node)
315
+ end
316
+ elsif path.end_with?("/")
317
+ raise HRX::Error.new("\"#{path}\" is a file")
318
+ else
319
+ @entries.delete(node)
320
+ end
321
+
322
+ parent_to_delete_from.delete(key_to_delete)
323
+ end
324
+
325
+ # Sets the text of the last comment in the document.
326
+ #
327
+ # Throws an EncodingError if `comment` can't be converted to UTF-8.
328
+ def last_comment=(comment)
329
+ @last_comment = comment.encode("UTF-8")
330
+ end
331
+
332
+ # Adds an HRX::File or HRX::Directory to this archive.
333
+ #
334
+ # If `before` or `after` is passed, this adds `entry` before or after the
335
+ # entry with the given path in the archive. If the archive has no entry with
336
+ # the given path, this throws an HRX::Error. If `before` and `after` are
337
+ # *both* passed, this throws an ArgumentError.
338
+ #
339
+ # Throws an HRX::Error if the entry conflicts with an existing entry.
340
+ def add(entry, before: nil, after: nil)
341
+ raise ArgumentError.new("before and after may not both be passed") if before && after
342
+
343
+ node = HRX::OrderedNode.new(entry._absolute(@root))
344
+
345
+ path = entry.path.split("/")
346
+ parent = path[0...-1].inject(@entries_by_path) do |hash, component|
347
+ if hash[component].is_a?(LinkedList::Node)
348
+ raise HRX::Error.new("\"#{hash[component].data._relative(@root).path}\" defined twice")
349
+ end
350
+ hash[component] ||= {}
351
+ end
352
+
353
+ if parent[path.last].is_a?(LinkedList::Node)
354
+ raise HRX::Error.new("\"#{entry.path}\" defined twice")
355
+ end
356
+
357
+ if entry.is_a?(HRX::Directory)
358
+ dir = (parent[path.last] ||= {})
359
+ if dir.is_a?(LinkedList::Node) || dir[:dir]
360
+ raise HRX::Error.new("\"#{entry.path}\" defined twice")
361
+ end
362
+ dir[:dir] = node
363
+ else
364
+ raise HRX::Error.new("\"#{entry.path}\" defined twice") if parent.has_key?(path.last)
365
+ parent[path.last] = node
366
+ end
367
+
368
+ if before || after
369
+ reference = _find_node(before || after)
370
+ raise HRX::Error.new("There is no entry named \"#{before || after}\"") if reference.nil?
371
+
372
+ if before
373
+ @entries.insert_before_node(node, reference)
374
+ else
375
+ @entries.insert_after_node(node, reference)
376
+ end
377
+ else
378
+ @entries << node
379
+ end
380
+
381
+ nil
382
+ end
383
+ alias_method :<<, :add
384
+
385
+ # Returns this archive, serialized to text in HRX format.
386
+ def to_hrx
387
+ buffer = String.new.encode("UTF-8")
388
+ boundary = "<#{"=" * _choose_boundary_length}>"
389
+
390
+ entries.each_with_index do |e, i|
391
+ buffer << boundary << "\n" << e.comment << "\n" if e.comment
392
+ buffer << boundary << " " << e.path << "\n"
393
+ if e.respond_to?(:content) && !e.content.empty?
394
+ buffer << e.content
395
+ buffer << "\n" unless i == entries.length - 1
396
+ end
397
+ end
398
+ buffer << boundary << "\n" << last_comment if last_comment
399
+
400
+ buffer.freeze
401
+ end
402
+
403
+ # Writes this archive to disk at `file`.
404
+ def write!(file)
405
+ File.write(file, to_hrx, mode: "wb")
406
+ end
407
+
408
+ private
409
+
410
+ # Adds `@root` to the beginning of `path` if `@root` isn't `nil`.
411
+ def _absolute(path)
412
+ @root ? @root + path : path
413
+ end
414
+
415
+ # Returns the LinkedList::Node at the given `path`, or `nil` if there is no
416
+ # node at that path.
417
+ def _find_node(path)
418
+ components = path.split("/")
419
+ return if components.empty?
420
+ result = @entries_by_path.dig(*components)
421
+ return result[:dir] if result.is_a?(Hash)
422
+ return result unless path.end_with?("/")
423
+ end
424
+
425
+ # Returns each entry in or beneath the directory hash `dir`, in no particular
426
+ # order.
427
+ def _each_entry(dir)
428
+ return to_enum(__method__, dir) unless block_given?
429
+
430
+ dir.values.each do |entry|
431
+ if entry.is_a?(Hash)
432
+ _each_entry(entry) {|e| yield e}
433
+ else
434
+ yield entry
435
+ end
436
+ end
437
+ end
438
+
439
+ # Returns a boundary length for a serialized archive that doesn't conflict
440
+ # with any of the files that archive contains.
441
+ def _choose_boundary_length
442
+ forbidden_boundary_lengths = Set.new
443
+ entries.each do |e|
444
+ [
445
+ (e.content if e.respond_to?(:content)),
446
+ e.comment
447
+ ].each do |text|
448
+ next unless text
449
+ text.scan(/^<(=+)>/m).each do |(equals)|
450
+ forbidden_boundary_lengths << equals.length
451
+ end
452
+ end
453
+ end
454
+
455
+ boundary_length = @boundary_length
456
+ while forbidden_boundary_lengths.include?(boundary_length)
457
+ boundary_length += 1
458
+ end
459
+ boundary_length
460
+ end
461
+ end