convert_json_to_csv 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5eac1b26f6fc3f0c694818e3539b8b4cea2e9e0708ccb9d8a1e6a97c1be2f6e7
4
+ data.tar.gz: 87d7c9ec09de59add865f06b42e65dd3944b68e05e79c96ffef6732e2271888d
5
+ SHA512:
6
+ metadata.gz: 22eb61d7d952926d7b49883f6af1192f7a457cd2f3ec8170ff2e73e54e1325d7ad85b328f1d455070aa1ffe80865222161da4ef930f774d25105bdd3104ecd7d
7
+ data.tar.gz: f489e1af0902e6edfaf3ee9aa3a4e3dd61d6666777948c0ae68211b7d7c360b68afe93d71d2b96691fad83eacfee323ad739d379a10d633d6ca54033dd7ebcbc
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.0
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.3
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,17 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: single_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+
15
+ Metrics/BlockLength:
16
+ Exclude:
17
+ - 'spec/*'
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # 0.1.0
2
+
3
+ * First release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at suddani@googlemail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in convert_json_to_csv.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+
10
+ gem 'rspec', '~> 3.0'
11
+
12
+ gem 'rubocop', '~> 0.80'
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ convert_json_to_csv (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.4.4)
11
+ parallel (1.20.1)
12
+ parser (3.0.1.0)
13
+ ast (~> 2.4.1)
14
+ rainbow (3.0.0)
15
+ rake (13.0.3)
16
+ regexp_parser (2.1.1)
17
+ rexml (3.2.5)
18
+ rspec (3.10.0)
19
+ rspec-core (~> 3.10.0)
20
+ rspec-expectations (~> 3.10.0)
21
+ rspec-mocks (~> 3.10.0)
22
+ rspec-core (3.10.1)
23
+ rspec-support (~> 3.10.0)
24
+ rspec-expectations (3.10.1)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.10.0)
27
+ rspec-mocks (3.10.2)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.10.0)
30
+ rspec-support (3.10.2)
31
+ rubocop (0.93.1)
32
+ parallel (~> 1.10)
33
+ parser (>= 2.7.1.5)
34
+ rainbow (>= 2.2.2, < 4.0)
35
+ regexp_parser (>= 1.8)
36
+ rexml
37
+ rubocop-ast (>= 0.6.0)
38
+ ruby-progressbar (~> 1.7)
39
+ unicode-display_width (>= 1.4.0, < 2.0)
40
+ rubocop-ast (1.4.1)
41
+ parser (>= 2.7.1.5)
42
+ ruby-progressbar (1.11.0)
43
+ unicode-display_width (1.7.0)
44
+
45
+ PLATFORMS
46
+ x86_64-linux
47
+
48
+ DEPENDENCIES
49
+ convert_json_to_csv!
50
+ rake (~> 13.0)
51
+ rspec (~> 3.0)
52
+ rubocop (~> 0.80)
53
+
54
+ BUNDLED WITH
55
+ 2.2.3
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Daniel Sudmann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Suddani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # ConvertJsonToCsv
2
+
3
+ This programm is ment as a small shel programm that converts json stream files to csv files.
4
+
5
+ It works with the standard input if no input file is given.
6
+ ## Installation
7
+
8
+ ```
9
+ gem install convert_json_to_csv
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```
15
+ Usage: convert_to_csv [options] FILE
16
+ --[no-]stdout Print to stdout as well
17
+ -o, --output=OUTPUT Output file or print to std out
18
+ --[no-]header Output header line
19
+ -k, --keys=KEYS Keys to use for csv. Comma seperated
20
+ --key-file FILE File containing keys one per line
21
+ --only-keys Only print keys
22
+ --filter-file FILE File containing filter
23
+ -f, --filter FILTER Filter by key,value0,value1,value2
24
+ -l, --limit LIMIT Limit output to LIMIT entries(equal or greater than 0)
25
+ -h, --help Prints this help
26
+ ```
27
+
28
+ ## Installation as dependency
29
+
30
+ Add this line to your application's Gemfile:
31
+
32
+ ```ruby
33
+ gem 'convert_json_to_csv'
34
+ ```
35
+
36
+ And then execute:
37
+
38
+ $ bundle install
39
+
40
+ Or install it yourself as:
41
+
42
+ $ gem install convert_json_to_csv
43
+ ## Development
44
+
45
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
46
+
47
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
48
+
49
+ ## Contributing
50
+
51
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/convert_json_to_csv. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/convert_json_to_csv/blob/master/CODE_OF_CONDUCT.md).
52
+
53
+ ## License
54
+
55
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
56
+
57
+ ## Code of Conduct
58
+
59
+ Everyone interacting in the ConvertJsonToCsv project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/convert_json_to_csv/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'convert_json_to_csv'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/convert_json_to_csv/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'convert_json_to_csv'
7
+ spec.version = ConvertJsonToCsv::VERSION
8
+ spec.authors = ['Suddani']
9
+ spec.email = ['suddani@googlemail.com']
10
+
11
+ spec.summary = 'Convert a stream of json objects to csv'
12
+ spec.description = 'Convert a stream of json objects to csv'
13
+ spec.homepage = 'https://github.com/suddani/convert_json_to_csv'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.6.0')
16
+
17
+ # spec.metadata['allowed_push_host'] = 'https://rubygems.com'
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/suddani/convert_json_to_csv'
21
+ spec.metadata['changelog_uri'] = 'https://github.com/suddani/convert_json_to_csv/CHANGELOG.md'
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = ['convert_json_to_csv']
30
+ spec.require_paths = ['lib']
31
+
32
+ # Uncomment to register a new dependency of your gem
33
+ # spec.add_dependency "example-gem", "~> 1.0"
34
+
35
+ # For more information and examples about making a new gem, checkout our
36
+ # guide at: https://bundler.io/guides/creating_gem.html
37
+ end
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'convert_json_to_csv'
6
+
7
+ ConvertJsonToCsv::Parser.run
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'csv'
4
+ require 'time'
5
+ require 'json'
6
+ require 'optparse'
7
+
8
+ require_relative 'convert_json_to_csv/convert_to_csv'
9
+ require_relative 'convert_json_to_csv/find_all_keys'
10
+ require_relative 'convert_json_to_csv/limit_wrapper'
11
+ require_relative 'convert_json_to_csv/multi_wrapper'
12
+ require_relative 'convert_json_to_csv/no_close_wrapper'
13
+ require_relative 'convert_json_to_csv/parser'
14
+
15
+ # Wraps all json to csv related classes and functions
16
+ module ConvertJsonToCsv
17
+ class Error < StandardError; end
18
+ # Your code goes here...
19
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Converting json stream to csv stream
4
+ module ConvertJsonToCsv
5
+ def self.enity_to_array(entity, keys)
6
+ keys.map do |key|
7
+ if key.end_with?('_at')
8
+ Date.parse(entity[key]).to_s
9
+ else
10
+ entity[key]
11
+ end
12
+ end
13
+ end
14
+
15
+ def self.should_output?(filter, data)
16
+ return true unless filter
17
+
18
+ filter[1].include?(data[filter[0].to_s].to_s)
19
+ end
20
+
21
+ def self.get_keys(data, output:)
22
+ keys = data.keys
23
+ output&.puts CSV.generate_line(keys)
24
+ keys
25
+ end
26
+
27
+ def self.convert_to_csv(input, output, keys: nil, filter: nil, header: true)
28
+ output.puts CSV.generate_line(keys) if keys && header
29
+ input.each_line do |line|
30
+ data = JSON.parse(line)
31
+ keys ||= get_keys(data, output: header ? output : nil)
32
+ entry = enity_to_array(data, keys)
33
+ output.puts CSV.generate_line(entry) if should_output?(filter, data)
34
+ end
35
+ nil
36
+ end
37
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Extract all keys from a stream of json objects
4
+ module ConvertJsonToCsv
5
+ def self.find_all_keys(input, output)
6
+ all_keys = []
7
+ input.each_line do |line|
8
+ all_keys = (all_keys + JSON.parse(line).keys).uniq
9
+ end
10
+ all_keys.each do |key|
11
+ output.puts key
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConvertJsonToCsv
4
+ # Wraps an output stream and only allows limited number of puts
5
+ class LimitWrapper
6
+ def initialize(io, limit, header)
7
+ @io = io
8
+ @limit = limit + (header ? 1 : 0)
9
+ @count = 0
10
+ end
11
+
12
+ def puts(data)
13
+ return should_exit! if @count >= @limit
14
+
15
+ out = @io.puts data
16
+ @count += 1
17
+ return should_exit! if @count >= @limit
18
+
19
+ out
20
+ end
21
+
22
+ def close
23
+ @io.close
24
+ end
25
+
26
+ def should_exit!
27
+ exit
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConvertJsonToCsv
4
+ # Wraps multiple output streams and fans out the puts command
5
+ class MultiWrapper
6
+ def initialize(*outputs)
7
+ @outputs = outputs.flatten
8
+ end
9
+
10
+ def puts(data)
11
+ @outputs.each do |output|
12
+ output.puts data
13
+ end
14
+ end
15
+
16
+ def close
17
+ @outputs.each(&:close)
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConvertJsonToCsv
4
+ # Wraps an output streams and prevents the user from closing it
5
+ class NoCloseWrapper
6
+ def initialize(io)
7
+ @io = io
8
+ end
9
+
10
+ def puts(data)
11
+ @io.puts data
12
+ end
13
+
14
+ def close; end
15
+ end
16
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConvertJsonToCsv
4
+ # The parser used in the executeable to load terminal arguments
5
+ class Parser
6
+ attr_accessor :file, :keys, :only_keys, :filter, :limit, :header, :std
7
+
8
+ def initialize
9
+ self.file = nil
10
+ self.keys = nil
11
+ self.only_keys = false
12
+ self.filter = nil
13
+ self.limit = nil
14
+ self.header = true
15
+ self.std = false
16
+ end
17
+
18
+ def file_output
19
+ @file_output ||= if std && file
20
+ MultiWrapper.new(NoCloseWrapper.new($stdout), file)
21
+ else
22
+ file
23
+ end
24
+ end
25
+
26
+ def output
27
+ @output ||= if limit
28
+ LimitWrapper.new(file_output || NoCloseWrapper.new($stdout), limit, header)
29
+ else
30
+ file_output || NoCloseWrapper.new($stdout)
31
+ end
32
+ end
33
+
34
+ def parse_filter_file(filter_file)
35
+ content = CSV.parse(
36
+ File.read(filter_file), headers: true, header_converters: :symbol
37
+ )
38
+ filters = content.reduce({}) do |r, row|
39
+ {
40
+ row.first[0] => (r[row.first[0]] || []) + [row.first[1]].compact
41
+ }
42
+ end
43
+ filters.to_a.first
44
+ end
45
+
46
+ # rubocop:disable Metrics/MethodLength
47
+ # rubocop:disable Metrics/AbcSize
48
+ def opt_parser
49
+ # rubocop:disable Metrics/BlockLength
50
+ @opt_parser ||= OptionParser.new do |opts|
51
+ opts.banner = 'Usage: convert_to_csv [options] FILE'
52
+
53
+ opts.on('--[no-]stdout', 'Print to stdout as well') do |std|
54
+ self.std = std
55
+ end
56
+
57
+ opts.on('-o', '--output=OUTPUT', 'Output file or print to std out') do |n|
58
+ self.file = File.open(n, 'w+')
59
+ end
60
+
61
+ opts.on('--[no-]header', 'Output header line') do |header|
62
+ self.header = header
63
+ end
64
+
65
+ opts.on('-k', '--keys=KEYS', Array, 'Keys to use for csv. Comma seperated') do |keys|
66
+ self.keys = keys
67
+ end
68
+
69
+ opts.on('--key-file FILE', 'File containing keys one per line') do |key_file|
70
+ self.keys = File.read(key_file).split("\n")
71
+ end
72
+
73
+ opts.on('--only-keys', 'Only print keys') do |_keys|
74
+ self.header = false
75
+ self.only_keys = true
76
+ end
77
+
78
+ opts.on('--filter-file FILE', 'File containing filter') do |filter_file|
79
+ self.filter = parse_filter_file(filter_file)
80
+ end
81
+
82
+ opts.on('-f', '--filter FILTER', Array, 'Filter by key,value0,value1,value2') do |filter|
83
+ self.filter = [filter[0], filter[1..]]
84
+ end
85
+
86
+ opts.on('-l', '--limit LIMIT', Integer, 'Limit output to LIMIT entries(equal or greater than 0)') do |limit|
87
+ raise if limit.negative?
88
+
89
+ self.limit = limit
90
+ end
91
+
92
+ opts.on('-h', '--help', 'Prints this help') do
93
+ puts opts
94
+ exit
95
+ end
96
+ end
97
+ # rubocop:enable Metrics/BlockLength
98
+ end
99
+ # rubocop:enable Metrics/AbcSize
100
+ # rubocop:enable Metrics/MethodLength
101
+
102
+ def parse(options)
103
+ opt_parser.parse!(options)
104
+ self
105
+ rescue StandardError
106
+ puts opt_parser
107
+ nil
108
+ end
109
+
110
+ # rubocop:disable Metrics/MethodLength
111
+ def self.run
112
+ parser = new
113
+ options = parser.parse ARGV
114
+
115
+ if options&.only_keys
116
+ ConvertJsonToCsv.find_all_keys(ARGF, options.output)
117
+ elsif options
118
+ ConvertJsonToCsv.convert_to_csv(
119
+ ARGF, options.output,
120
+ keys: options.keys,
121
+ filter: options.filter,
122
+ header: options.header
123
+ )
124
+ end
125
+ ensure
126
+ options&.output&.close
127
+ end
128
+ # rubocop:enable Metrics/MethodLength
129
+ end
130
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConvertJsonToCsv
4
+ VERSION = '0.1.0'
5
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: convert_json_to_csv
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Suddani
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-04-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Convert a stream of json objects to csv
14
+ email:
15
+ - suddani@googlemail.com
16
+ executables:
17
+ - convert_json_to_csv
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".github/workflows/main.yml"
22
+ - ".gitignore"
23
+ - ".rspec"
24
+ - ".rubocop.yml"
25
+ - CHANGELOG.md
26
+ - CODE_OF_CONDUCT.md
27
+ - Gemfile
28
+ - Gemfile.lock
29
+ - LICENSE
30
+ - LICENSE.txt
31
+ - README.md
32
+ - Rakefile
33
+ - bin/console
34
+ - bin/setup
35
+ - convert_json_to_csv.gemspec
36
+ - exe/convert_json_to_csv
37
+ - lib/convert_json_to_csv.rb
38
+ - lib/convert_json_to_csv/convert_to_csv.rb
39
+ - lib/convert_json_to_csv/find_all_keys.rb
40
+ - lib/convert_json_to_csv/limit_wrapper.rb
41
+ - lib/convert_json_to_csv/multi_wrapper.rb
42
+ - lib/convert_json_to_csv/no_close_wrapper.rb
43
+ - lib/convert_json_to_csv/parser.rb
44
+ - lib/convert_json_to_csv/version.rb
45
+ homepage: https://github.com/suddani/convert_json_to_csv
46
+ licenses:
47
+ - MIT
48
+ metadata:
49
+ homepage_uri: https://github.com/suddani/convert_json_to_csv
50
+ source_code_uri: https://github.com/suddani/convert_json_to_csv
51
+ changelog_uri: https://github.com/suddani/convert_json_to_csv/CHANGELOG.md
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 2.6.0
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubygems_version: 3.2.16
68
+ signing_key:
69
+ specification_version: 4
70
+ summary: Convert a stream of json objects to csv
71
+ test_files: []