magic_parser 0.0.1.pre

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: e9d21d03735ffbd01e28a9874bc023341feff0e43ab69ec7f2189b186a88f2fe
4
+ data.tar.gz: 70d0b3b839fa244618a252d97225fe8badbf16d82f36b17ec47ad59182872126
5
+ SHA512:
6
+ metadata.gz: 4531eaabb7f3b066f0038c3a2b6779a531f244bf028a9cb04128ebbbf09ab9b5a15c5901eacd500e6cde9bfe8e2d1213db611953055df129f475c9d61c222746
7
+ data.tar.gz: ee3b60402f7d64c9daaaf9437f8c1985db6c574dcd6412f114156cc3edc6ff3bfc89e4943e1a8ef0cc2e118e6d2d9e5ddeca83fcf3823e263c3504b8225a41d3
@@ -0,0 +1,224 @@
1
+ require 'date'
2
+ require 'bigdecimal'
3
+ require 'bigdecimal/util'
4
+
5
+ def assert cond, msg = 'Error!'
6
+ if !cond then raise msg end
7
+ end
8
+
9
+ def error msg = 'Error!'
10
+ assert false, msg
11
+ end
12
+
13
+ def check_args var, type
14
+ if var.class != Array then var = [var] end
15
+ if type.class != Array then type = [type] end
16
+
17
+ assert (var.length == type.length), 'array lengths must match'
18
+
19
+ ctr = 0
20
+ while ctr < var.length
21
+ var[ctr].assert_type type[ctr]
22
+ ctr += 1
23
+ end
24
+ end
25
+
26
+ class Integer
27
+ def factorial_recursive
28
+ self <= 1 ? 1 : self * (self - 1).factorial
29
+ end
30
+
31
+ def factorial_iterative
32
+ f = 1; for i in 1..self; f *= i; end; f
33
+ end
34
+
35
+ alias :factorial :factorial_iterative
36
+ alias :fact :factorial
37
+ end
38
+
39
+ class Object
40
+ def assert_type clas, msg = nil
41
+ msg ||= "Bad type: expected #{clas}, got #{self.class}"
42
+ if !clas.kind_of? Array then clas = [clas] end
43
+ clas.each { |c|
44
+ if self.kind_of?( c ) then return; end
45
+ }
46
+ assert false, "Bad type: expected #{clas}, got #{self.class}"
47
+ end
48
+
49
+ def stringable?
50
+ respond_to? 'to_s'
51
+ end
52
+ end
53
+
54
+ class String
55
+ def pad size, char
56
+ size -= length
57
+ if size > 0 then replace self+(char*size) end
58
+ end
59
+
60
+ def addslashes
61
+ gsub(/['"\\\x0]/,'\\\\\0')
62
+ end
63
+
64
+ def addslashes!
65
+ replace addslashes
66
+ end
67
+
68
+ def write filename = nil
69
+ write_file( filename ){ self }
70
+ end
71
+ end
72
+
73
+ def write_file filename = nil
74
+ file = filename ? File.open( filename, 'w' ) : Tempfile.new( filename )
75
+
76
+ file.print yield
77
+ file.close
78
+ end
79
+
80
+ class Array
81
+ def find
82
+ ctr = 0
83
+ each { |e|
84
+ if yield( e )
85
+ return ctr
86
+ end
87
+ }
88
+
89
+ nil
90
+ end
91
+
92
+ def prep_insert table
93
+ set = []
94
+
95
+ each { |line|
96
+ set = "( #{line.join ','} )"
97
+ }
98
+
99
+ set = "insert into #{table} values ( #{set.join ','} ),"
100
+ end
101
+
102
+ def assert_all_types clas, msg = nil
103
+ each { |x|
104
+ x.assert_type clas, msg
105
+ }
106
+ end
107
+
108
+ def contains? *elements
109
+ elements.each { |element|
110
+ if !include?( element ) then return false end
111
+ }
112
+ true
113
+ end
114
+
115
+ # buggy Ruby is supposed to do this already...
116
+ def to_s
117
+ collect { |x|
118
+ x.to_s
119
+ }.join
120
+ end
121
+ end
122
+
123
+ class Stack < Array
124
+ def push x
125
+ end
126
+
127
+ def pop
128
+ end
129
+ end
130
+
131
+ #class Queue < Array
132
+ # def nxt
133
+ # end
134
+
135
+ # def add x
136
+ # end
137
+ #end
138
+
139
+ class Hash
140
+ def defaults defs
141
+ defs.assert_type Hash
142
+
143
+ keyset = keys
144
+ defs.each { |k, v|
145
+ if !keyset.include? k then self[k] = v end
146
+ }
147
+ end
148
+
149
+ def prep_insert table
150
+ set = []
151
+
152
+ each { |k, v|
153
+ set = "( #{k}, #{v} )"
154
+ }
155
+
156
+ set = "insert into #{table} values ( #{set.join ','} ),"
157
+ end
158
+
159
+ def select *items
160
+ r = {}
161
+
162
+ items.each { |item|
163
+ r[item] = self[item]
164
+ }
165
+
166
+ r
167
+ end
168
+
169
+ def create_path *path
170
+ entry = self
171
+ endcap = path.pop
172
+ final = path.pop
173
+
174
+ path.each { |e|
175
+ if !entry[e] then entry[e] = {} end
176
+ entry = entry[e]
177
+ }
178
+
179
+ if !entry[final] then entry[final] = endcap end
180
+ end
181
+
182
+ def required *elements
183
+ elements.each { |element|
184
+ assert has_key?( element ), "required key missing: #{element}"
185
+ }
186
+ end
187
+ end
188
+
189
+ class Value
190
+ attr_accessor :value
191
+
192
+ def initialize v = 0
193
+ set v
194
+ end
195
+
196
+ def set x
197
+ x.assert_type Numeric
198
+ @value = Float.new x
199
+ end
200
+
201
+ def to_i
202
+ @value.to_i
203
+ end
204
+
205
+ def to_f
206
+ @value
207
+ end
208
+ end
209
+
210
+ class Date
211
+ def american sep = '/'
212
+ "%02d#{sep}%02d#{sep}%02d" % [month, day, year]
213
+ end
214
+ end
215
+
216
+ class Time
217
+ def Time.stamp
218
+ n = Time.now
219
+ "%d%02d%02d-%02d%02d%02d" % [n.year, n.month, n.day, n.hour, n.min, n.sec]
220
+ end
221
+ end
222
+
223
+ class FileName < String
224
+ end
@@ -0,0 +1,218 @@
1
+ =begin
2
+ parser = {
3
+ 'name' => [/pattern/, {subparser}
4
+ ...
5
+ ]
6
+ }
7
+
8
+ # token
9
+ parsed
10
+ text, name, [breakdown]
11
+ =end
12
+
13
+ require 'basic/basic'
14
+
15
+ class Token < Array
16
+ attr_accessor :text, :name
17
+
18
+ def initialize n = nil, t = nil
19
+ check_args [n, t], [[String, NilClass], [String, NilClass]]
20
+
21
+ @name, @text, @@tab = n, t, 0
22
+
23
+ update
24
+ end
25
+
26
+ def print_verbose
27
+ print true
28
+ end
29
+
30
+ def print verbose = false
31
+ out = ''
32
+
33
+ if name || verbose
34
+ val = @@tab
35
+ if !verbose then val -= 1 end
36
+ out += "\t" * val
37
+ out += "#{name} |#{text}|\n"
38
+ end
39
+
40
+ @@tab += 1
41
+ each { |s|
42
+ out += s.print verbose
43
+ }
44
+ @@tab -= 1
45
+
46
+ out
47
+ end
48
+
49
+ def to_s
50
+ update
51
+ end
52
+
53
+ def update
54
+ if length == 0
55
+ return text
56
+ end
57
+
58
+ text = ''
59
+
60
+ each { |t|
61
+ text += t.update
62
+ }
63
+
64
+ text
65
+ end
66
+
67
+ def write filename = nil
68
+ write_file( filename ){ to_s }
69
+ end
70
+ end
71
+
72
+ class Rule
73
+ attr_reader :name, :subrule, :pattern
74
+
75
+ def initialize n, pa = /.*/, s = {}
76
+ check_args [n, pa], [String, Regexp]
77
+
78
+ @pattern = pa
79
+ @name = n
80
+
81
+ if block_given?
82
+ s = yield
83
+ end
84
+ s.assert_type Hash
85
+
86
+ @subrule = RuleSet.new( s )
87
+ end
88
+
89
+ def to_s
90
+ out = "Rule: #{name}, pattern: #{pattern}, subrules: #{subrule.length}\n"
91
+ subrule.each { |name, s|
92
+ out += s.to_s
93
+ }
94
+ out
95
+ end
96
+
97
+ def apply token
98
+ token.assert_type Token
99
+
100
+ result = token.dup.clear
101
+
102
+ if token.length == 0
103
+ token << Token.new( nil, token.text )
104
+ end
105
+
106
+ token.each { |subtoken|
107
+ if subtoken.name
108
+ result << subtoken
109
+ else
110
+ cursor = 0
111
+ subtoken.text.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
112
+ r = subtoken.text.scan pattern
113
+
114
+ r.each { |match|
115
+ if match.kind_of? Array
116
+ match = match[0]
117
+ end
118
+
119
+ offset = subtoken.text.index match, cursor
120
+ if offset != cursor
121
+ text = subtoken.text.slice(cursor .. offset-1)
122
+ result << Token.new( nil, text )
123
+ cursor = offset
124
+ end
125
+
126
+ offset = cursor + match.length
127
+ text = subtoken.text.slice(cursor .. offset-1)
128
+ new_subtoken = Token.new( name, text )
129
+
130
+ if subrule
131
+ new_subtoken = subrule.apply( new_subtoken )
132
+ end
133
+
134
+ result << new_subtoken
135
+ cursor = offset
136
+ }
137
+
138
+ if cursor < subtoken.text.length
139
+ text = subtoken.text.slice(cursor .. -1)
140
+ result << Token.new( nil, text )
141
+ end
142
+ end
143
+ }
144
+
145
+ result
146
+ end
147
+ end
148
+
149
+ class RuleSet < Hash
150
+ def initialize rules = {}
151
+ if block_given?
152
+ rules = yield
153
+ end
154
+
155
+ rules.assert_type Hash
156
+
157
+ rules.each { |name, rule|
158
+ pattern, subrule = rule
159
+ if !subrule
160
+ subrule = {}
161
+ end
162
+ self[name] = Rule.new( name, pattern, subrule )
163
+ }
164
+ end
165
+
166
+ def to_s
167
+ out = ''
168
+ each { |name, rule|
169
+ out += "#{rule}\n"
170
+ }
171
+ out
172
+ end
173
+
174
+ def apply token
175
+ if token.kind_of? String
176
+ token = Token.new( token )
177
+ end
178
+
179
+ token.assert_type Token
180
+
181
+ each { |name, rule|
182
+ token = rule.apply token
183
+ }
184
+
185
+ token
186
+ end
187
+
188
+ def parse text: '', file: nil
189
+ Parser.parse text, file
190
+ end
191
+
192
+ def RuleSet.parse text: '', file: nil
193
+ check_args [text, file], [String, [String, NilClass]]
194
+
195
+ if file
196
+ text = File.read( file )
197
+ end
198
+
199
+ apply Token.new( nil, text.force_encoding('UTF-8') )
200
+ end
201
+ end
202
+
203
+ class Parser < RuleSet
204
+ end
205
+
206
+ class Document < Token
207
+ @@parser = nil
208
+
209
+ def initialize text: '', file: nil
210
+ check_args [text, file], [String, [String, NilClass]]
211
+
212
+ assert @@parser, 'Parser must be assigned'
213
+
214
+ result = @@parser.parse( text: text, file: file )
215
+ concat result
216
+ super result.name, result.text
217
+ end
218
+ end
data/readme.md ADDED
@@ -0,0 +1,175 @@
1
+ parser
2
+ ======
3
+
4
+ The parser gem provides an easy way to do most simple parsing of text files. The grammar for a file format is written as a hierarchy of regular expression/tag pairs. Here is an example taken from the definition of xml:
5
+
6
+ xml.rb
7
+
8
+ require 'magic_parser'
9
+
10
+ class XMLParser < Parser
11
+ def initialize
12
+ # XML definition
13
+ attr_value_w_space = "([\\'\"]?\\s*[\\w\\-\\.\/: ]+\\s*[\\'\"]?)"
14
+ attr_value_no_space = "(\\s*[\\w\\-\\.\/:]+\\s*)"
15
+ attr_name = "([\\w:-]+)"
16
+ tag_name = attr_name
17
+ attr_value = "(#{attr_value_w_space}|#{attr_value_no_space})"
18
+ attribute = "#{attr_name}\\s*\\=\\s*#{attr_value}"
19
+
20
+ super() { {
21
+ 'tag' => [ /\s*(\<\??\s*#{tag_name}(\s*#{attribute}\s*)*\/?\s*\??\>)\s*/, {
22
+ 'name' => /\<\??\s*#{tag_name}/,
23
+ 'attribute' => [ /\s*(#{attribute})\s*/, {
24
+ 'name' => /(#{attr_name})\s*\=/,
25
+ 'value' => /\=\s*#{attr_value}/
26
+ }]
27
+ }],
28
+ 'close_tag' => [ /\s*(\<\s*\/#{tag_name}\s*\>)\s*/, {
29
+ 'name' => /\<\s*\/#{tag_name}/
30
+ }],
31
+ 'content' => /\s*(\w.*)/
32
+ } }
33
+ end
34
+ end
35
+
36
+ class XML < Document
37
+ @@parser = XMLParser.new
38
+ end
39
+
40
+ With this you can parse a simple bit of text:
41
+
42
+ text = '<?xml version="1.0" encoding="UTF-8"?>'
43
+
44
+ xml = XML.new( text: text )
45
+
46
+ or an entire file. For a file called data.xml:
47
+
48
+ <?xml version="1.0" encoding="UTF-8"?>
49
+ <catalog>
50
+ <cd>
51
+ <title>Empire Burlesque</title>
52
+ <artist>Bob Dylan</artist>
53
+ <country>USA</country>
54
+ <company>Columbia</company>
55
+ <price>10.90</price>
56
+ <year>1985</year>
57
+ </cd>
58
+ </catalog>
59
+
60
+ your code can look like:
61
+
62
+ require 'xml'
63
+
64
+ catalog = XML.new 'data.xml'
65
+ catalog.print
66
+
67
+ which will output:
68
+
69
+ tag, |<?xml version="1.0" encoding="UTF-8"?>|
70
+ name, |xml|
71
+ attribute, |version="1.0"|
72
+ name, |version|
73
+ value, |"1.0"|
74
+ attribute, |encoding="UTF-8"|
75
+ name, |encoding|
76
+ value, |"UTF-8"|
77
+ tag, |<catalog>|
78
+ name, |catalog|
79
+ tag, |<cd>|
80
+ name, |cd|
81
+ tag, |<title>|
82
+ name, |title|
83
+ content, |Empire Burlesque|
84
+ close_tag, |</title>|
85
+ name, |title|
86
+ tag, |<artist>|
87
+ name, |artist|
88
+ content, |Bob Dylan|
89
+ close_tag, |</artist>|
90
+ name, |artist|
91
+ tag, |<country>|
92
+ name, |country|
93
+ content, |USA|
94
+ close_tag, |</country>|
95
+ name, |country|
96
+ tag, |<company>|
97
+ name, |company|
98
+ content, |Columbia|
99
+ close_tag, |</company>|
100
+ name, |company|
101
+ tag, |<price>|
102
+ name, |price|
103
+ content, |10.90|
104
+ close_tag, |</price>|
105
+ name, |price|
106
+ tag, |<year>|
107
+ name, |year|
108
+ content, |1985|
109
+ close_tag, |</year>|
110
+ name, |year|
111
+ close_tag, |</cd>|
112
+ name, |cd|
113
+ close_tag, |</catalog>|
114
+ name, |catalog|
115
+
116
+ The Token class is an Array of Tokens and has 'name' and 'text' attributes. A Document is a kind of Token. You can iterate through the parsed file examining and editing tags and content. Given the prior code:
117
+
118
+ # print a list of titles and artists
119
+ catalog.each {|title|
120
+ puts title.name
121
+ puts title.text
122
+
123
+ index = 0
124
+ title.each {|field|
125
+ if field.name == 'tag' && field[0].name == 'artist'
126
+ # this should be the artist name
127
+ puts title[index+1].text
128
+ end
129
+ index += 1
130
+ }
131
+ }
132
+
133
+ It is important to note that in definitions order matters! The most specific cases must be matched before the more general ones.
134
+
135
+ Features
136
+ --------
137
+ - definitions are entirely based on regular expressions
138
+ - definitions are stored as hash trees, so they can build on each other (e.g. HTML can be defined as an extension of XML)
139
+
140
+ Future Expansion
141
+ ----------------
142
+
143
+ This will be the basis for further projects such as an xslt processor. A logical next step will be to add XPath features.
144
+
145
+ Installation
146
+ ------------
147
+
148
+ Install parser by running:
149
+
150
+ sudo gem install magic_parser
151
+
152
+ Contribute
153
+ ----------
154
+
155
+ - Issue Tracker: github.com/$project/$project/issues
156
+ - Source Code: github.com/$project/$project
157
+
158
+ Support
159
+ -------
160
+
161
+ If you are having issues, please let us know.
162
+ We have a mailing list located at: project@google-groups.com
163
+
164
+ License
165
+ -------
166
+
167
+ (The MIT License)
168
+
169
+ Copyright � Paul Amirian
170
+
171
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
172
+
173
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
174
+
175
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/test/xml/xml.rb ADDED
@@ -0,0 +1,31 @@
1
+ require 'magic_parser'
2
+
3
+ class XMLParser < Parser
4
+ def initialize
5
+ # XML definition
6
+ attr_value_w_space = "([\\'\"]?\\s*[\\w\\-\\.\/: ]+\\s*[\\'\"]?)"
7
+ attr_value_no_space = "(\\s*[\\w\\-\\.\/:]+\\s*)"
8
+ attr_name = "([\\w:-]+)"
9
+ tag_name = attr_name
10
+ attr_value = "(#{attr_value_w_space}|#{attr_value_no_space})"
11
+ attribute = "#{attr_name}\\s*\\=\\s*#{attr_value}"
12
+
13
+ super() { {
14
+ 'tag' => [ /\s*(\<\??\s*#{tag_name}(\s*#{attribute}\s*)*\/?\s*\??\>)\s*/, {
15
+ 'name' => /\<\??\s*#{tag_name}/,
16
+ 'attribute' => [ /\s*(#{attribute})\s*/, {
17
+ 'name' => /(#{attr_name})\s*\=/,
18
+ 'value' => /\=\s*#{attr_value}/
19
+ }]
20
+ }],
21
+ 'close_tag' => [ /\s*(\<\s*\/#{tag_name}\s*\>)\s*/, {
22
+ 'name' => /\<\s*\/#{tag_name}/
23
+ }],
24
+ 'content' => /\s*(\w.*)/
25
+ } }
26
+ end
27
+ end
28
+
29
+ class XML < Document
30
+ @@parser = XMLParser.new
31
+ end
@@ -0,0 +1,14 @@
1
+ #! /usr/bin/ruby
2
+
3
+ $: << '.'
4
+
5
+ require 'xml'
6
+
7
+ text = '<?xml version="1.0" encoding="UTF-8"?>'
8
+
9
+ #xml = XML.new( text: text )
10
+ #xml = XML.new( file: 'form.xsl' )
11
+ xml = XML.new( file: 'data.xml' )
12
+
13
+ puts xml.print
14
+ # puts xml.to_s
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: magic_parser
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1.pre
5
+ platform: ruby
6
+ authors:
7
+ - Digital Magic
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-04-11 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - lib/basic/basic.rb
20
+ - lib/magic_parser.rb
21
+ - readme.md
22
+ - test/xml/xml.rb
23
+ - test/xml/xml_test.rb
24
+ homepage:
25
+ licenses:
26
+ - MIT
27
+ metadata: {}
28
+ post_install_message:
29
+ rdoc_options: []
30
+ require_paths:
31
+ - lib
32
+ required_ruby_version: !ruby/object:Gem::Requirement
33
+ requirements:
34
+ - - ">="
35
+ - !ruby/object:Gem::Version
36
+ version: '0'
37
+ required_rubygems_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">"
40
+ - !ruby/object:Gem::Version
41
+ version: 1.3.1
42
+ requirements: []
43
+ rubygems_version: 3.0.1
44
+ signing_key:
45
+ specification_version: 4
46
+ summary: regex-based parser
47
+ test_files: []