jtag 0.1.25 → 0.2.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.
@@ -1,319 +0,0 @@
1
- # encoding: utf-8
2
- #
3
- ## Stupid small pure Ruby JSON parser & generator.
4
- #
5
- # Copyright © 2013 Mislav Marohnić
6
- #
7
- # Permission is hereby granted, free of charge, to any person obtaining a copy of this
8
- # software and associated documentation files (the “Software”), to deal in the Software
9
- # without restriction, including without limitation the rights to use, copy, modify,
10
- # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
11
- # permit persons to whom the Software is furnished to do so, subject to the following
12
- # conditions:
13
- #
14
- # The above copyright notice and this permission notice shall be included in all copies or
15
- # substantial portions of the Software.
16
- #
17
- # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
- # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
- # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
- # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21
- # OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- # OTHER DEALINGS IN THE SOFTWARE.
23
-
24
- require 'strscan'
25
- require 'forwardable'
26
-
27
- # Usage:
28
- #
29
- # JSON.parse(json_string) => Array/Hash
30
- # JSON.generate(object) => json string
31
- #
32
- # Run tests by executing this file directly. Pipe standard input to the script to have it
33
- # parsed as JSON and to display the result in Ruby.
34
- #
35
- class JSON
36
- def self.parse(data) new(data).parse end
37
-
38
- WSP = /\s+/
39
- OBJ = /[{\[]/; HEN = /\}/; AEN = /\]/
40
- COL = /\s*:\s*/; KEY = /\s*,\s*/
41
- NUM = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/
42
- BOL = /true|false/; NUL = /null/
43
-
44
- extend Forwardable
45
-
46
- attr_reader :scanner
47
- alias_method :s, :scanner
48
- def_delegators :scanner, :scan, :matched
49
- private :s, :scan, :matched
50
-
51
- def initialize data
52
- @scanner = StringScanner.new data.to_s
53
- end
54
-
55
- def parse
56
- space
57
- object
58
- end
59
-
60
- private
61
-
62
- def space() scan WSP end
63
-
64
- def endkey() scan(KEY) or space end
65
-
66
- def object
67
- matched == '{' ? hash : array if scan(OBJ)
68
- end
69
-
70
- def value
71
- object or string or
72
- scan(NUL) ? nil :
73
- scan(BOL) ? matched.size == 4:
74
- scan(NUM) ? eval(matched) :
75
- error
76
- end
77
-
78
- def hash
79
- obj = {}
80
- space
81
- repeat_until(HEN) { k = string; scan(COL); obj[k] = value; endkey }
82
- obj
83
- end
84
-
85
- def array
86
- ary = []
87
- space
88
- repeat_until(AEN) { ary << value; endkey }
89
- ary
90
- end
91
-
92
- SPEC = {'b' => "\b", 'f' => "\f", 'n' => "\n", 'r' => "\r", 't' => "\t"}
93
- UNI = 'u'; CODE = /[a-fA-F0-9]{4}/
94
- STR = /"/; STE = '"'
95
- ESC = '\\'
96
-
97
- def string
98
- if scan(STR)
99
- str, esc = '', false
100
- while c = s.getch
101
- if esc
102
- str << (c == UNI ? (s.scan(CODE) || error).to_i(16).chr : SPEC[c] || c)
103
- esc = false
104
- else
105
- case c
106
- when ESC then esc = true
107
- when STE then break
108
- else str << c
109
- end
110
- end
111
- end
112
- str
113
- end
114
- end
115
-
116
- def error
117
- raise "parse error at: #{scan(/.{1,10}/m).inspect}"
118
- end
119
-
120
- def repeat_until reg
121
- until scan(reg)
122
- pos = s.pos
123
- yield
124
- error unless s.pos > pos
125
- end
126
- end
127
-
128
- module Generator
129
- def generate(obj)
130
- raise ArgumentError unless obj.is_a? Array or obj.is_a? Hash
131
- generate_type(obj)
132
- end
133
- alias dump generate
134
-
135
- private
136
-
137
- def generate_type(obj)
138
- type = obj.is_a?(Numeric) ? :Numeric : obj.class.name
139
- begin send(:"generate_#{type}", obj)
140
- rescue NoMethodError; raise ArgumentError, "can't serialize #{type}"
141
- end
142
- end
143
-
144
- ESC_MAP = Hash.new {|h,k| k }.update \
145
- "\r" => 'r',
146
- "\n" => 'n',
147
- "\f" => 'f',
148
- "\t" => 't',
149
- "\b" => 'b'
150
-
151
- def quote(str) %("#{str}") end
152
-
153
- def generate_String(str)
154
- quote str.gsub(/[\r\n\f\t\b"\\]/) { "\\#{ESC_MAP[$&]}"}
155
- end
156
-
157
- def generate_simple(obj) obj.inspect end
158
- alias generate_Numeric generate_simple
159
- alias generate_TrueClass generate_simple
160
- alias generate_FalseClass generate_simple
161
-
162
- def generate_Symbol(sym) generate_String(sym.to_s) end
163
-
164
- def generate_Time(time)
165
- quote time.strftime(time.utc? ? "%F %T UTC" : "%F %T %z")
166
- end
167
- def generate_Date(date) quote date.to_s end
168
-
169
- def generate_NilClass(*) 'null' end
170
-
171
- def generate_Array(ary) '[%s]' % ary.map {|o| generate_type(o) }.join(', ') end
172
-
173
- def generate_Hash(hash)
174
- '{%s}' % hash.map { |key, value|
175
- "#{generate_String(key.to_s)}: #{generate_type(value)}"
176
- }.join(', ')
177
- end
178
- end
179
-
180
- extend Generator
181
- end
182
-
183
- if __FILE__ == $0
184
- if !$stdin.tty?
185
- data = JSON.parse $stdin.read
186
- require 'pp'
187
- pp data
188
- else
189
- require 'test/unit'
190
- require 'date'
191
- class ParserTest < Test::Unit::TestCase
192
- PARSED = JSON.parse DATA.read
193
- def parsed() PARSED end
194
- def parse_string(str) JSON.parse(%(["#{str}"]).gsub('\\\\', '\\')).first end
195
- def test_string
196
- assert_equal "Pagination library for \"Rails 3\", Sinatra, Merb, DataMapper, and more",
197
- parsed['head']['repository']['description']
198
- end
199
- def test_string_specials
200
- assert_equal "\r\n\t\f\b", parse_string('\r\n\t\f\b')
201
- assert_equal "aA", parse_string('\u0061\u0041')
202
- assert_equal "\e", parse_string('\u001B')
203
- assert_equal "xyz", parse_string('\x\y\z')
204
- assert_equal '"\\/', parse_string('\"\\\\\\/')
205
- assert_equal 'no #{interpolation}', parse_string('no #{interpolation}')
206
- end
207
- def test_hash
208
- assert_equal %w[label ref repository sha user], parsed['head'].keys.sort
209
- end
210
- def test_number
211
- assert_equal 124.3e2, parsed['head']['repository']['size']
212
- end
213
- def test_bool
214
- assert_equal true, parsed['head']['repository']['fork']
215
- assert_equal false, parsed['head']['repository']['private']
216
- end
217
- def test_nil
218
- assert_nil parsed['head']['user']['company']
219
- end
220
- def test_array
221
- assert_equal ["4438f", {"a" => "b"}], parsed['head']['sha']
222
- end
223
- def test_invalid
224
- assert_raises(RuntimeError) { JSON.parse %({) }
225
- assert_raises(RuntimeError) { JSON.parse %({ "foo": }) }
226
- assert_raises(RuntimeError) { JSON.parse %([ "foo": "bar" ]) }
227
- assert_raises(RuntimeError) { JSON.parse %([ ~"foo" ]) }
228
- assert_raises(RuntimeError) { JSON.parse %([ "foo ]) }
229
- assert_raises(RuntimeError) { JSON.parse %([ "foo\\" ]) }
230
- assert_raises(RuntimeError) { JSON.parse %([ "foo\\uabGd" ]) }
231
- end
232
- end
233
-
234
- class GeneratorTest < Test::Unit::TestCase
235
- def generate(obj) JSON.generate(obj) end
236
- def test_array
237
- assert_equal %([1, 2, 3]), generate([1, 2, 3])
238
- end
239
- def test_bool
240
- assert_equal %([true, false]), generate([true, false])
241
- end
242
- def test_null
243
- assert_equal %([null]), generate([nil])
244
- end
245
- def test_string
246
- assert_equal %(["abc\\n123"]), generate(["abc\n123"])
247
- end
248
- def test_string_unicode
249
- assert_equal %(["ć\\"č\\nž\\tš\\\\đ"]), generate(["ć\"č\nž\tš\\đ"])
250
- end
251
- def test_time
252
- time = Time.utc(2012, 04, 19, 1, 2, 3)
253
- assert_equal %(["2012-04-19 01:02:03 UTC"]), generate([time])
254
- end
255
- def test_date
256
- time = Date.new(2012, 04, 19)
257
- assert_equal %(["2012-04-19"]), generate([time])
258
- end
259
- def test_symbol
260
- assert_equal %(["abc"]), generate([:abc])
261
- end
262
- def test_hash
263
- json = generate(:abc => 123, 123 => 'abc')
264
- assert_match /^\{/, json
265
- assert_match /\}$/, json
266
- assert_equal [%("123": "abc"), %("abc": 123)], json[1...-1].split(', ').sort
267
- end
268
- def test_nested_structure
269
- json = generate(:hash => {1=>2}, :array => [1,2])
270
- assert json.include?(%("hash": {"1": 2}))
271
- assert json.include?(%("array": [1, 2]))
272
- end
273
- def test_invalid_json
274
- assert_raises(ArgumentError) { generate("abc") }
275
- end
276
- def test_invalid_object
277
- err = assert_raises(ArgumentError) { generate("a" => Object.new) }
278
- assert_equal "can't serialize Object", err.message
279
- end
280
- end
281
- end
282
- end
283
-
284
- __END__
285
- {
286
- "head": {
287
- "ref": "master",
288
- "repository": {
289
- "forks": 0,
290
- "integrate_branch": "rails3",
291
- "watchers": 1,
292
- "language": "Ruby",
293
- "description": "Pagination library for \"Rails 3\", Sinatra, Merb, DataMapper, and more",
294
- "has_downloads": true,
295
- "fork": true,
296
- "created_at": "2011/10/24 03:20:48 -0700",
297
- "homepage": "http://github.com/mislav/will_paginate/wikis",
298
- "size": 124.3e2,
299
- "private": false,
300
- "has_wiki": true,
301
- "name": "will_paginate",
302
- "owner": "dbackeus",
303
- "url": "https://github.com/dbackeus/will_paginate",
304
- "has_issues": false,
305
- "open_issues": 0,
306
- "pushed_at": "2011/10/25 05:44:05 -0700"
307
- },
308
- "label": "dbackeus:master",
309
- "sha": ["4438f", { "a" : "b" }],
310
- "user": {
311
- "name": "David Backeus",
312
- "company": null,
313
- "gravatar_id": "ebe96524f5db9e92188f0542dc9d1d1a",
314
- "location": "Stockholm (Sweden)",
315
- "type": "User",
316
- "login": "dbackeus"
317
- }
318
- }
319
- }
data/lib/jtag/util.rb DELETED
@@ -1,244 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module JekyllTag
4
- # JTag utilities
5
- class Util
6
- attr_writer :debug_level
7
- attr_writer :silent
8
- attr_accessor :log
9
- attr_accessor :config_target
10
-
11
- DEBUG_LEVELS = {
12
- :error => 0,
13
- :warn => 1,
14
- :info => 2,
15
- :debug => 3,
16
- }
17
-
18
- CONFIG_FILES = %w{blacklist.txt config.yml stopwords.txt synonyms.yml}
19
-
20
- def initialize
21
- @debug_level = 3
22
- @silent = false
23
- end
24
-
25
- ##
26
- ## Output tags in the specified format
27
- ##
28
- ## @param tags [Array] array of tags
29
- ## @param options [Hash] hash of options
30
- ##
31
- ## @option options :format [String] format to output tags in
32
- ## @option options :print0 [Boolean] print tags with null delimiter
33
- ## @option options :filename [String] filename to output
34
- ## @option options :content [String] content to output for complete format
35
- ## @option options :grouping [String] grouping key for YAML tags
36
- ##
37
- ## @return [void]
38
- ##
39
- def output_tags(tags, options)
40
- # Determine the format for output, defaulting to "yaml" if not specified
41
- format = options[:format].respond_to?(:to_format) ? options[:format].to_format : (options[:format] || :yaml)
42
- format = format.to_sym
43
- # Determine if tags should be printed with a null delimiter
44
- print0 = options[:print0] || false
45
- # Determine the filename for output, if specified
46
- filename = options[:filename] || false
47
- # Content that was piped in
48
- content = options[:content] || false
49
-
50
- tags.sort!
51
- tags.uniq!
52
-
53
- case format
54
- when :complete
55
- if filename || content
56
- content = filename ? IO.read(File.expand_path(filename)) : content
57
- parts = content.split(/---\s*\n/)
58
- if parts.count < 2
59
- console_log "No front matter found in #{filename}", level: :error, err: true
60
- yaml = {}
61
- body = content
62
- else
63
- yaml = YAML.load(parts[1])
64
- body = parts[2..-1].join("\n")
65
- end
66
- options[:grouping] ||= "tags"
67
- yaml[options[:grouping]] = tags
68
- console_log "#{filename}", level: :info, err: true if filename
69
- console_log yaml.to_yaml + "---\n" + body, level: :error, err: false
70
- else
71
- console_log tags.join("\n"), level: :error, err: false
72
- end
73
- when :list
74
- # Join tags with a null character delimiter
75
- console_log tags.map(&:strip).join(print0 ? "\x00" : "\n"), level: :error, err: false, file: filename
76
- when :csv
77
- # Log the tags in CSV format
78
- console_log tags.to_csv
79
- when :json
80
- # Create a hash with tags and optional filename, then log as JSON
81
- out = {}
82
- out["tags"] = tags
83
- out["path"] = filename if filename
84
- console_log out.to_json
85
- when :plist
86
- # Create a hash with optional filename, then log as plist
87
- out = {}
88
- out["path"] = filename if filename
89
- out["tags"] = tags
90
- console_log out.to_plist
91
- else
92
- # Default to YAML format, create a hash with grouping and tags, then log as YAML
93
- out = {}
94
- options[:grouping] ||= "tags"
95
- out[options[:grouping]] = tags
96
- console_log out.to_yaml
97
- end
98
- end
99
-
100
- ##
101
- ## Logging
102
- ##
103
- ### Log levels
104
- ## 0 = error
105
- ## 1 = warn
106
- ## 2 = info
107
- ## 3 = debug
108
- ##
109
- ### Debug levels
110
- ## 1 = errors only
111
- ## 2 = errors and warnings
112
- ## 3 = errors, warnings and info
113
- ## 4 = errors, warnings, info and debug
114
- ##
115
- ### Test level < debug level (true = return, false = continue)
116
- ## true = continue
117
- ## false = return
118
- ##
119
- ### Examples
120
- ## send info (2) and debug is errors and warnings (2) (2 < 2 = return)
121
- ## send error (0) and debug is errors and warnings (2) (0 < 2 = continue)
122
- ## send warning (1) and debug is errors only (1) (1 < 1 = return)
123
- ## send error (0) and debug level is silent (0) (0 < 0 = return)
124
- ## send debug (3) and debug level is info (3) (3 < 4 = return)
125
- ## send debug (3) and debug level is debug (4) (3 < 4 = continue)
126
- ##
127
- ## @example Log an info message
128
- ## console_log("This is an info message", level: :info)
129
- ##
130
- ## @example Log a warning message and output to STDERR
131
- ## console_log("This is a warning message", level: :warn, err: true)
132
- ##
133
- ## @param msg [String] message to log
134
- ## @param options [Hash] hash of options
135
- ##
136
- ## @option options :level [Symbol] level of message (info, warn, error, debug)
137
- ## @option options :err [Boolean] print to STDERR
138
- ## @option options :log [Boolean] write to log file
139
- ## @option options :filename [String] write to file
140
- ##
141
- ## @return [void]
142
- ##
143
- def console_log(msg = "", options = {})
144
- level = options[:level] || :info
145
- err = options[:err] || false
146
- options[:log] ||= false
147
-
148
- threshold = @debug_level || 0
149
- return unless DEBUG_LEVELS.fetch(level.to_sym, 0) < threshold
150
-
151
- if options[:log]
152
- if err
153
- @log.warn(msg)
154
- else
155
- @log.info(msg)
156
- end
157
- end
158
-
159
- if options[:filename]
160
- File.open(options[:filename], "w") do |f|
161
- f.puts msg
162
- end
163
- end
164
-
165
- return if @silent
166
-
167
- unless err
168
- $stdout.puts msg
169
- else
170
- $stderr.puts msg
171
- end
172
- end
173
-
174
- #
175
- ## Write configuration files
176
- ##
177
- ## @param atomic [Boolean] force write of config files
178
- ##
179
- ## @example Write configuration files
180
- ## write_config
181
- ##
182
- ## @return [void]
183
- ##
184
- def write_config(atomic = false)
185
- # Get the root path of the gem
186
- jtag_gem = Gem.loaded_specs["jtag"]
187
- gem_root = jtag_gem.full_gem_path || File.expand_path("../../", __dir__)
188
- # Get the lib directory within the gem
189
- gem_lib = File.join(gem_root, "lib")
190
- # Define the source directory for the configuration files
191
- config_source = File.join(gem_lib, "/jtag/config_files/")
192
-
193
- FileUtils.rm_rf(@config_target) if File.directory?(@config_target) && atomic
194
-
195
- # If the config target directory does not exist or atomic is true, copy the config files
196
- if !File.directory?(@config_target)
197
- # Ensure the target directory exists
198
- FileUtils.mkdir_p(@config_target)
199
- CONFIG_FILES.each do |file|
200
- FileUtils.cp(File.join(config_source, file), @config_target)
201
- end
202
- # console_log "Configuration files written to #{@config_target}", level: :warn
203
- end
204
-
205
- # Iterate over each config file
206
- CONFIG_FILES.each do |file|
207
- # If the config file does not exist in the target directory, copy it from the source
208
- unless File.exist?(File.join(@config_target, file))
209
- # Define the source and target file paths
210
- source_file = File.join(config_source, file)
211
- target_file = File.join(@config_target, file)
212
- # Copy the source file to the target location
213
- FileUtils.cp(source_file, target_file)
214
- # Log that the config file has been added
215
- console_log "Config file #{file} added."
216
- end
217
- end
218
-
219
- # Output the final location of the configuration files
220
- console_log
221
- console_log "Configuration files are located in the folder: " + @config_target
222
- # Output a reminder to set the tags_location in the config.yml file
223
- console_log %Q{Make sure that "tags_location" in the config.yml file is set to your tags json file.}
224
- end
225
-
226
- ## Check if all config files are present
227
- ##
228
- ## @example Check if all config files are present
229
- ## config_files_complete?
230
- ## # => true
231
- ##
232
- ## @return [Boolean]
233
- def config_files_complete?
234
- # Move ~/.jtag if needed
235
- update_deprecated_config
236
-
237
- # Check if all config files are present
238
- CONFIG_FILES.each do |file|
239
- return false unless File.exist?(File.join(@config_target, file))
240
- end
241
- true
242
- end
243
- end
244
- end
data/mise.toml DELETED
@@ -1,2 +0,0 @@
1
- [tools]
2
- ruby = "3.3.0"