dug 0.1.0.alpha1

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
+ SHA1:
3
+ metadata.gz: 4455906bdb42a42d8fbdce98f6b73debdd0b5f1b
4
+ data.tar.gz: 63f162259f8dc882857627df00b17fb4ae23e28b
5
+ SHA512:
6
+ metadata.gz: df82930ee5ea1e54545cf0a34f62f9ddf0c53f640771e36819636c8f88e2f7cc1a755846153e8bceedaa749a92f149b87be2613342218ecc56830593b8153359
7
+ data.tar.gz: 0e5565de67ebf529278a01f4ec52d31cd2197a6528b22d58fed0fc7fecc5b2196a739d1783386fac853d7b552b204f55a196fae8de089302c2a1288dbdb405db
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.gem
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.0
4
+ before_install: gem install bundler -v 1.11.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in dug.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Chris Arcand
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,41 @@
1
+ # Dug
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/dug`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'dug'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install dug
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/dug. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "dug"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
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
data/dug.gemspec ADDED
@@ -0,0 +1,28 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'dug/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "dug"
8
+ spec.version = Dug::VERSION
9
+ spec.authors = ["Chris Arcand"]
10
+ spec.email = ["chris@chrisarcand.com"]
11
+
12
+ spec.summary = %q{[D]amn yo[u], [G]mail. A gem to organize your GitHub notification emails in ways Gmail filters can't.}
13
+ spec.description = %q{[D]amn yo[u], [G]mail. A gemified script to organize your GitHub notification emails using a simple configuration file in ways Gmail filters can't, such as X-GitHub-Reason headers.}
14
+ spec.homepage = "https://github.com/chrisarcand/dug"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_dependency "google-api-client", "~> 0.9"
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.11"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "minitest", "~> 5.0"
27
+ spec.add_development_dependency "simplecov"
28
+ end
@@ -0,0 +1,125 @@
1
+ require 'yaml'
2
+
3
+ module Dug
4
+ class Configurator
5
+ LABEL_RULE_TYPES = %i(organization repository reason)
6
+ GITHUB_REASONS = %w(author comment mention team_mention state_change assign)
7
+
8
+ attr_accessor :client_id
9
+ attr_accessor :client_secret
10
+ attr_accessor :token_store
11
+ attr_accessor :application_credentials_file
12
+
13
+ def initialize
14
+ self.label_rules = { "organizations" => {}, "reasons" => {} }
15
+ end
16
+
17
+ def set_organization_rule(name, label: nil)
18
+ organizations[name] ||= { "repositories" => {} }
19
+ organizations[name]["label"] = label || name
20
+ end
21
+
22
+ def set_repository_rule(name, organization:, label: nil)
23
+ organizations[organization] ||= { "repositories" => {} }
24
+ organizations[organization]["repositories"][name] ||= {}
25
+ organizations[organization]["repositories"][name]["label"] = label || name
26
+ end
27
+
28
+ def set_reason_rule(name, label: nil)
29
+ validate_reason(name)
30
+ reasons[name] ||= {}
31
+ reasons[name]["label"] = label || name
32
+ end
33
+
34
+ def label_for(type, name, organization: nil)
35
+ validate_label_type(type)
36
+ case type
37
+ when :organization
38
+ organizations.fetch(name, {})["label"]
39
+ when :repository
40
+ raise ArgumentError, "Repository label rules require an organization to be specified" unless organization
41
+ organizations.fetch(organization, {})
42
+ .fetch("repositories", {})
43
+ .fetch(name, {})["label"]
44
+ when :reason
45
+ validate_reason(name)
46
+ reasons.fetch(name, {})["label"]
47
+ end
48
+ end
49
+
50
+ def application_credentials_file
51
+ ENV['GOOGLE_APPLICATION_CREDENTIALS'] || @application_credentials_file
52
+ end
53
+
54
+ def client_id
55
+ ENV['GOOGLE_CLIENT_ID'] || @client_id
56
+ end
57
+
58
+ def client_secret
59
+ ENV['GOOGLE_CLIENT_SECRET'] || @client_secret
60
+ end
61
+
62
+ def token_store
63
+ ENV['TOKEN_STORE_PATH'] || @token_store || File.join(Dir.home, ".dug", "authorization.yaml")
64
+ end
65
+
66
+ def rule_file
67
+ @rule_file
68
+ end
69
+
70
+ def rule_file=(file_path)
71
+ @rule_file = file_path
72
+ load_rules
73
+ @rule_file
74
+ end
75
+
76
+ private
77
+
78
+ attr_accessor :label_rules
79
+
80
+ def load_rules
81
+ file = YAML.load_file(rule_file)
82
+
83
+ file["organizations"].each do |org|
84
+ case org
85
+ when String
86
+ set_organization_rule(org)
87
+ when Hash
88
+ set_organization_rule(org["name"], label: org["label"])
89
+ if repos = org["repositories"]
90
+ repos.each do |repo|
91
+ set_repository_rule(repo["name"], organization: org["name"], label: repo["label"])
92
+ end
93
+ end
94
+ end
95
+ end
96
+
97
+ file["reasons"].keys.each do |reason|
98
+ validate_reason(reason)
99
+ set_reason_rule(reason, label: file["reasons"][reason]["label"])
100
+ end
101
+ end
102
+
103
+ def validate_label_type(type)
104
+ unless LABEL_RULE_TYPES.include?(type)
105
+ raise ConfigurationError, "'#{type}' is not a valid label rule type. Valid types: #{}"
106
+ end
107
+ end
108
+
109
+ def validate_reason(reason)
110
+ unless GITHUB_REASONS.include?(reason)
111
+ raise ConfigurationError, "'#{reason}' is not a valid GitHub notification reason. Valid reasons include: #{GITHUB_REASONS.map { |x| "'#{x}'" }.join(', ')}"
112
+ end
113
+ end
114
+
115
+ def organizations
116
+ label_rules["organizations"]
117
+ end
118
+
119
+ def reasons
120
+ label_rules["reasons"]
121
+ end
122
+ end
123
+
124
+ ConfigurationError = Class.new(StandardError)
125
+ end
@@ -0,0 +1,91 @@
1
+ require 'google/apis/gmail_v1'
2
+ require 'googleauth'
3
+ require 'googleauth/stores/file_token_store'
4
+ require 'fileutils'
5
+ require 'forwardable'
6
+
7
+ module Dug
8
+ class GmailServicer
9
+ extend Forwardable
10
+
11
+ OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
12
+ APPLICATION_NAME = 'Dug'
13
+ SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_MODIFY
14
+
15
+ def_delegators :@gmail, :get_user_message,
16
+ :list_user_messages,
17
+ :modify_message
18
+
19
+ def initialize
20
+ @gmail = Google::Apis::GmailV1::GmailService.new
21
+ @gmail.client_options.application_name = APPLICATION_NAME
22
+ end
23
+
24
+ def labels(use_cache: true)
25
+ @labels = nil unless use_cache
26
+ @labels ||= @gmail.list_user_labels('me').labels.reduce({}) do |hash, label|
27
+ hash.tap { |h| h[label.name] = label }
28
+ end
29
+ end
30
+
31
+ def add_labels_by_name(*args)
32
+ modify_message_request(*args) do |request, ids|
33
+ request.add_label_ids = ids
34
+ end
35
+ end
36
+
37
+ def remove_labels_by_name(*args)
38
+ modify_message_request(*args) do |request, ids|
39
+ request.remove_label_ids = ids
40
+ end
41
+ end
42
+
43
+ # TODO: break some of this code down, prolly into a separate Authorizer class or something
44
+ def authorize!
45
+ token_store_path = Dug.configuration.token_store
46
+ FileUtils.mkdir_p(File.dirname(token_store_path))
47
+
48
+ client_id = begin
49
+ if Dug.configuration.client_id
50
+ Google::Auth::ClientId.new(Dug.configuration.client_id,
51
+ Dug.configuration.client_secret)
52
+ else
53
+ Google::Auth::ClientId.from_file(Dug.configuration.application_credentials_file)
54
+ end
55
+ end
56
+ token_store = Google::Auth::Stores::FileTokenStore.new(file: token_store_path)
57
+ authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
58
+ user_id = 'default'
59
+
60
+ credentials = authorizer.get_credentials(user_id)
61
+ if credentials.nil?
62
+ url = authorizer.get_authorization_url(
63
+ base_url: OOB_URI)
64
+ puts "Open the following URL in the browser and enter the " +
65
+ "resulting code after authorization"
66
+ puts url
67
+ code = gets
68
+ credentials = authorizer.get_and_store_credentials_from_code(
69
+ user_id: user_id, code: code, base_url: OOB_URI)
70
+ end
71
+ @gmail.authorization = credentials
72
+ end
73
+
74
+ private
75
+
76
+ def modify_message_request(message, label_names)
77
+ ids = []
78
+ label_names.each do |name|
79
+ unless labels[name] && id = labels[name].id
80
+ raise MissingLabel, "The label '#{name}' does not exist. Please add the label in Gmail first."
81
+ end
82
+ ids << id
83
+ end
84
+ request = Google::Apis::GmailV1::ModifyMessageRequest.new
85
+ yield request, ids
86
+ modify_message('me', message.id, request)
87
+ end
88
+ end
89
+
90
+ MissingLabel = Class.new(StandardError)
91
+ end
data/lib/dug/logger.rb ADDED
@@ -0,0 +1,7 @@
1
+ module Dug
2
+ module Logger
3
+ def log(message, level: :info)
4
+ puts "[#{level.to_s.upcase}] #{Time.now} - #{message}"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,33 @@
1
+ module Dug
2
+ class NotificationDecorator < SimpleDelegator
3
+ %w(Date From To Subject).each do |header|
4
+ define_method(header.downcase) do
5
+ headers[header]
6
+ end
7
+ end
8
+
9
+ def organization
10
+ list_match[1]
11
+ end
12
+
13
+ def repository
14
+ list_match[2]
15
+ end
16
+
17
+ def reason
18
+ headers["X-GitHub-Reason"]
19
+ end
20
+
21
+ def headers
22
+ @headers ||= payload.headers.each_with_object({}) do |header, hash|
23
+ hash[header.name] = header.value
24
+ end
25
+ end
26
+
27
+ private
28
+
29
+ def list_match
30
+ headers["List-ID"].match(/^([\w\-_]+)\/([\w\-_]+)/)
31
+ end
32
+ end
33
+ end
data/lib/dug/runner.rb ADDED
@@ -0,0 +1,72 @@
1
+ module Dug
2
+ class Runner
3
+ include Dug::Logger
4
+
5
+ attr_reader :servicer
6
+
7
+ def self.run(*args)
8
+ new.run(*args)
9
+ end
10
+
11
+ def initialize
12
+ @servicer = Dug::GmailServicer.new
13
+ servicer.authorize!
14
+ end
15
+
16
+ def run
17
+ if unprocessed_notifications?
18
+ log("Processing #{unprocessed_notifications.size} GitHub notifications...")
19
+ unprocessed_notifications.each do |message|
20
+ process_message(message.id)
21
+ end
22
+ log("Finished processing #{unprocessed_notifications.size} GitHub notifications.")
23
+ else
24
+ log("No new GitHub notifications.")
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def process_message(id)
31
+ message = NotificationDecorator.new(servicer.get_user_message('me', id))
32
+
33
+ labels_to_add = ["GitHub"]
34
+ labels_to_remove = ["GitHub/Unprocessed"]
35
+ if message.reason
36
+ labels_to_add << Dug.configuration.label_for(:reason, message.reason)
37
+ end
38
+ labels_to_add << Dug.configuration.label_for(:organization, message.organization)
39
+ labels_to_add << Dug.configuration.label_for(:repository,
40
+ message.repository,
41
+ organization: message.organization)
42
+ labels_to_add.flatten! and labels_to_remove.flatten!
43
+ labels_to_add.compact! and labels_to_remove.compact!
44
+
45
+ info = "Processing message:"
46
+ info << "\n ID: #{message.id}"
47
+ %w(Date From Subject).each do |header|
48
+ info << "\n #{header}: #{message.headers[header]}"
49
+ end
50
+ info << "\n * Applying labels: #{labels_to_add.join(' | ')} *"
51
+ log(info)
52
+
53
+ servicer.add_labels_by_name(message, labels_to_add)
54
+ servicer.remove_labels_by_name(message, labels_to_remove)
55
+ end
56
+
57
+ def unprocessed_notifications(use_cache: true)
58
+ unless use_cache
59
+ log("Requesting latest emails from Gmail...")
60
+ @unprocessed_notifications = nil
61
+ end
62
+ unprocessed_label = servicer.labels(use_cache: use_cache)["GitHub/Unprocessed"]
63
+ @unprocessed_notifications ||= servicer
64
+ .list_user_messages('me', label_ids: [unprocessed_label.id])
65
+ .messages
66
+ end
67
+
68
+ def unprocessed_notifications?
69
+ !!unprocessed_notifications(use_cache: false)
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,3 @@
1
+ module Dug
2
+ VERSION = "0.1.0.alpha1"
3
+ end
data/lib/dug.rb ADDED
@@ -0,0 +1,20 @@
1
+ require "dug/version"
2
+ require "dug/configurator"
3
+ require "dug/gmail_servicer"
4
+ require "dug/logger"
5
+ require "dug/notification_decorator"
6
+ require "dug/runner"
7
+
8
+ module Dug
9
+ def self.authorize!
10
+ Dug::GmailServicer.new.authorize!
11
+ end
12
+
13
+ def self.configure(&block)
14
+ yield configuration
15
+ end
16
+
17
+ def self.configuration
18
+ @config ||= Dug::Configurator.new
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,133 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dug
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.alpha1
5
+ platform: ruby
6
+ authors:
7
+ - Chris Arcand
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-02-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: google-api-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.9'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.11'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.11'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: simplecov
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: "[D]amn yo[u], [G]mail. A gemified script to organize your GitHub notification
84
+ emails using a simple configuration file in ways Gmail filters can't, such as X-GitHub-Reason
85
+ headers."
86
+ email:
87
+ - chris@chrisarcand.com
88
+ executables: []
89
+ extensions: []
90
+ extra_rdoc_files: []
91
+ files:
92
+ - ".gitignore"
93
+ - ".travis.yml"
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - bin/console
99
+ - bin/setup
100
+ - dug.gemspec
101
+ - lib/dug.rb
102
+ - lib/dug/configurator.rb
103
+ - lib/dug/gmail_servicer.rb
104
+ - lib/dug/logger.rb
105
+ - lib/dug/notification_decorator.rb
106
+ - lib/dug/runner.rb
107
+ - lib/dug/version.rb
108
+ homepage: https://github.com/chrisarcand/dug
109
+ licenses:
110
+ - MIT
111
+ metadata: {}
112
+ post_install_message:
113
+ rdoc_options: []
114
+ require_paths:
115
+ - lib
116
+ required_ruby_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - ">="
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ required_rubygems_version: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - ">"
124
+ - !ruby/object:Gem::Version
125
+ version: 1.3.1
126
+ requirements: []
127
+ rubyforge_project:
128
+ rubygems_version: 2.5.1
129
+ signing_key:
130
+ specification_version: 4
131
+ summary: "[D]amn yo[u], [G]mail. A gem to organize your GitHub notification emails
132
+ in ways Gmail filters can't."
133
+ test_files: []