port_map 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
+ SHA1:
3
+ metadata.gz: a9144c963820f3ad67ddaa22b88da961e2089a5d
4
+ data.tar.gz: 580bdec31873ecad6109a1c005dc510c8e6e14f6
5
+ SHA512:
6
+ metadata.gz: b96382df0a479e97c2bbcf4a3fbd8ff082d205432dc5d6717ff1aeb9ddd83d2d5496fed1c1801c94b593c3f210ad21d7945b1bf98bf3c01b62e1decaa329de07
7
+ data.tar.gz: cd928903c386ee429b1ce128201891a5368af59c37e2548ba0f1910d9a8cebfec30216957dc20eca5dd35e2a56e92baa4f9edc77257f42e485137d014db9d0b0
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers 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. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in port_map.gemspec
4
+ gemspec
5
+
6
+ gem 'codeclimate-test-reporter', group: :test, require: nil
data/Gemfile.lock ADDED
@@ -0,0 +1,53 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ port_map (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ codeclimate-test-reporter (0.4.8)
10
+ simplecov (>= 0.7.1, < 1.0.0)
11
+ coderay (1.1.0)
12
+ diff-lcs (1.2.5)
13
+ docile (1.1.5)
14
+ json (1.8.3)
15
+ method_source (0.8.2)
16
+ pry (0.10.3)
17
+ coderay (~> 1.1.0)
18
+ method_source (~> 0.8.1)
19
+ slop (~> 3.4)
20
+ rake (10.5.0)
21
+ rspec (3.4.0)
22
+ rspec-core (~> 3.4.0)
23
+ rspec-expectations (~> 3.4.0)
24
+ rspec-mocks (~> 3.4.0)
25
+ rspec-core (3.4.2)
26
+ rspec-support (~> 3.4.0)
27
+ rspec-expectations (3.4.0)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.4.0)
30
+ rspec-mocks (3.4.1)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.4.0)
33
+ rspec-support (3.4.1)
34
+ simplecov (0.11.2)
35
+ docile (~> 1.1.0)
36
+ json (~> 1.8)
37
+ simplecov-html (~> 0.10.0)
38
+ simplecov-html (0.10.0)
39
+ slop (3.6.0)
40
+
41
+ PLATFORMS
42
+ ruby
43
+
44
+ DEPENDENCIES
45
+ bundler (~> 1.0)
46
+ codeclimate-test-reporter
47
+ port_map!
48
+ pry (~> 0.10.0)
49
+ rake (~> 10.0)
50
+ rspec (~> 3.4.0)
51
+
52
+ BUNDLED WITH
53
+ 1.10.6
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Kevin Jalbert
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,113 @@
1
+ # PortMap
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/port_map.svg)](https://badge.fury.io/rb/port_map)
4
+ [![Build Status](https://travis-ci.org/kevinjalbert/port_map.svg?branch=master)](https://travis-ci.org/kevinjalbert/port_map)
5
+ [![Code Climate](https://codeclimate.com/github/kevinjalbert/port_map/badges/gpa.svg)](https://codeclimate.com/github/kevinjalbert/port_map)
6
+ [![Test Coverage](https://codeclimate.com/github/kevinjalbert/port_map/badges/coverage.svg)](https://codeclimate.com/github/kevinjalbert/port_map/coverage)
7
+
8
+
9
+ During web development you are constantly running/starting/stoping local web servers. This isn't a huge problem when dealing with a single web server. As you run more web servers at the same time (i.e., microservices) the complexity jumps as you have to manually account for the ports each will be running on. This gem aims at simplifying the managment of web servers as well as exposing named domains for each web server. In addition, it takes advantage of nginx as the underlying web server.
10
+
11
+ ## Example Scenario
12
+
13
+ ### The Setup
14
+ You are developing a service that uses multiple web servers. You have two rails applications and one ember application.
15
+
16
+ | Application | Directory | Command | Local URL |
17
+ |-------------|-----------|---------|-----------|
18
+ Rails API | `/api/` | `rails server` | http://localhost:3000
19
+ Rails Background Jobs | ``/jobs/`` | `rails server --port 3001` | http://localhost:3001
20
+ Ember Application | `/ember/` | `ember server` | http://localhost:4200
21
+
22
+ ### The Problem
23
+ In each of these applications there is some configuration work required to ensure that they communicate on the correct ports. There are two issues here:
24
+
25
+ - As we add more web servers we have to avoid clashing on existing ports.
26
+ - You have to make sure that you correctly start each server with the right port number.
27
+
28
+ ### `port_map` to the Rescue!
29
+ We're going to transform this unwieldly scenario into an organized and easy to manage one using `port_map`.
30
+
31
+ | Application | Directory | Command | Local URL |
32
+ |-------------|-----------|---------|-----------|
33
+ Rails API | `/api/` | `port_map rails server` | http://api.dev
34
+ Rails Background Jobs | ``/jobs/`` | `port_map rails server` | http://jobs.dev
35
+ Ember Application | `/ember/` | `port_map ember server` | http://ember.dev
36
+
37
+ The domain names can be configured with environment variables, but by default they are based on the directory's name.
38
+
39
+ You can close and restart each web server multiple times and they will continue to use the same domain names. `port_map` provides an easy way to logically name each web server, as well as remove the need of specifying ports.
40
+
41
+ ## Assumptions and Dependencies
42
+
43
+ 1. You have the nginx web server installed
44
+ 2. You are able to run nginx with sudo (this is required as we're listening on the protected port 80)
45
+ 3. You have `include servers/*;` within your `nginx.conf` within the `http` block
46
+ 4. (optional) Allow nginx command to be ran without password prompt (add command to sudoers via `visudo`)
47
+
48
+ ## Installation
49
+
50
+ ```
51
+ gem install port_map
52
+ ```
53
+
54
+ ## Commands
55
+ Installing this gem provides four executable commands:
56
+
57
+ ### `create_port_map`
58
+ - `create_port_map 3000`
59
+ - _Add proxy mapping http://127.0.0.1:3000/ to http://directory_name.dev_
60
+ 1. A generated nginx configuration is created under nginx's servers directory (`/usr/local/etc/nginx/servers/directory_name.port_map.conf`).
61
+ 2. Update `/etc/hosts` with new entry `127.0.0.1 directory_name.dev #port_map`.
62
+ 3. Reloads nginx -- `sudo nginx -s reload`.
63
+ - `create_port_map 3000 <specified_name>`
64
+ - _Add proxy mapping http://127.0.0.1:3000/ to http://specified_name.dev_
65
+ 1. A generated nginx configuration is created under nginx's servers directory (`/usr/local/etc/nginx/servers/specified_name.port_map.conf`).
66
+ 2. Update `/etc/hosts` with new entry `127.0.0.1 specified_name.dev #port_map`.
67
+ 3. Reloads nginx -- `sudo nginx -s reload`.
68
+
69
+ ### `list_port_maps`
70
+ - `list_port_maps`
71
+ - List a parsable JSON payload of the current port maps that are managed.
72
+ ```
73
+ [
74
+ {
75
+ "name": "api",
76
+ "nginx_conf": "/usr/local/etc/nginx/servers/api.port_map.conf",
77
+ "server_name": "api.dev",
78
+ "locations": [
79
+ {
80
+ "name": "/",
81
+ "proxy_pass": "http://127.0.0.1:3000"
82
+ }
83
+ ]
84
+ }
85
+ ]
86
+ ```
87
+
88
+ ### `remove_port_map`
89
+ - `remove_port_map <specified_name>`
90
+ - _Removed proxy mapping of specified_name.dev/ to http://127.0.0.1:3000_
91
+ 1. Removes the nginx config generated from `create_port_map`.
92
+ 2. Removes the hosts entry generated from `create_port_map`.
93
+ 3. Reloads nginx -- `sudo nginx -s reload`.
94
+
95
+ ### `port_map`
96
+ - `port_map <command>`
97
+ 1. Adjusts/Adds a dynamic port number on command (assuming command takes `-p <number>` or `--port <number>`).
98
+ 2. Executes `create_port_map <dynamic_port_number>`
99
+ 1. Uses a `.port_map.conf` nginx server configuration (with a `$PORT` placeholder present), for generated nginx configuration.
100
+ 2. Using a name specified in the `PORT_MAP_NAME` environment variable.
101
+ 1. Using a name specified from the current directory.
102
+ 3. Updates `/etc/hosts` with new entry `127.0.0.1 determined_name.dev #port_map`.
103
+ 4. Reloads nginx -- `sudo nginx -s reload`.
104
+ 5. Executes `<command>`.
105
+ 6. Executes `remove_port_map <determined_name>`.
106
+
107
+ ## Contributing
108
+
109
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kevinjalbert/port_map. 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.
110
+
111
+ ## License
112
+
113
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port_map'
3
+
4
+ port = ARGV[0]
5
+
6
+ unless (1..65535).cover?(port.to_i)
7
+ raise 'a valid port number must be provided as the first argument'
8
+ end
9
+
10
+ server_conf = nil
11
+ if File.exist?(PortMap::NginxConf::PORT_MAP_CONF_FILENAME)
12
+ server_conf = PortMap::NginxConf.from_file(port, File.new(PortMap::NginxConf::PORT_MAP_CONF_FILENAME))
13
+ else
14
+ name = ARGV[1] || Dir.pwd.split('/').last
15
+ server_conf = PortMap::NginxConf.new(port, name)
16
+ end
17
+ server_conf.save
18
+
19
+ PortMap::Hosts.update
20
+
21
+ puts "Add proxy mapping http://127.0.0.1:#{server_conf.port}/ to http://#{server_conf.server_name}"
22
+
23
+ PortMap::Nginx.reload
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port_map'
3
+
4
+ puts JSON.pretty_generate(PortMap::Mappings.all)
data/bin/port_map ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port_map'
3
+
4
+ port = PortMap::Utilities.next_empty_port
5
+ name = ENV['PORT_MAP_NAME']
6
+
7
+ success = system("create_port_map #{port} #{name}")
8
+ raise 'exception occurred during `create_port_map`' unless success
9
+
10
+ port_removed = false
11
+
12
+ Signal.trap('INT') do
13
+ system("remove_port_map #{name}")
14
+ port_removed = true
15
+ end
16
+
17
+ Signal.trap('TERM') do
18
+ system("remove_port_map #{name}")
19
+ port_removed = true
20
+ end
21
+
22
+ cmd = PortMap::Utilities.apply_open_port_option(port, ARGV.join(' '))
23
+ system(PortMap::Utilities.shell_cmd_wrapper(cmd))
24
+
25
+ at_exit do
26
+ system("remove_port_map #{name}") unless port_removed
27
+ end
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port_map'
3
+
4
+ name = ARGV[0] || Dir.pwd.split('/').last
5
+
6
+ port_map = PortMap::Mappings.all.detect do |element|
7
+ element[:name] == name
8
+ end
9
+
10
+ raise "There are no port-maps matching #{name}" if port_map.nil?
11
+ raise "#{port_map[:nginx_conf]} does not exist" unless File.exist?(port_map[:nginx_conf])
12
+
13
+ File.delete(port_map[:nginx_conf])
14
+
15
+ PortMap::Hosts.update
16
+
17
+ port_map[:locations].each do |location|
18
+ puts "Removed proxy mapping of #{port_map[:server_name]}#{location[:name]} to #{location[:proxy_pass]}"
19
+ end
20
+
21
+ PortMap::Nginx.reload
@@ -0,0 +1,27 @@
1
+ module PortMap
2
+ module Hosts
3
+ PORT_MAP_TRACK_COMMENT = '#port_map'.freeze
4
+ HOSTS_FILENAME = '/etc/hosts'.freeze
5
+
6
+ def self.update
7
+ new_contents = contents
8
+ port_maps = JSON.parse(`list_port_maps`)
9
+
10
+ unless port_maps.empty?
11
+ new_contents += "\n127.0.0.1 #{port_maps.map { |port_map| port_map['server_name'] }.join(' ')} #{PORT_MAP_TRACK_COMMENT}"
12
+ end
13
+
14
+ save(new_contents)
15
+ end
16
+
17
+ def self.save(new_contents)
18
+ File.open(HOSTS_FILENAME, 'w+') { |f| f.write(new_contents) }
19
+ end
20
+
21
+ def self.contents
22
+ File.readlines(HOSTS_FILENAME).reject do |line|
23
+ line.strip.match(/#{PORT_MAP_TRACK_COMMENT}$/)
24
+ end.join
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,25 @@
1
+ module PortMap
2
+ module Mappings
3
+ def self.parse_conf(filename)
4
+ contents = File.new(filename).read
5
+ server_name = contents.match(/server_name\s+(.+?);/)
6
+ location_mappings = contents.scan(/location\s+(.+?)\s+{\s+proxy_pass\s+(.+?);\s+}/m)
7
+
8
+ data = {}
9
+ data[:name] = File.basename(filename, '.port_map.conf')
10
+ data[:nginx_conf] = PortMap::Nginx.servers_directory + File::Separator + data[:name] + '.port_map.conf'
11
+ data[:server_name] = server_name.captures.first
12
+ data[:locations] = location_mappings.map do |location_mapping|
13
+ { name: location_mapping.first, proxy_pass: location_mapping.last }
14
+ end
15
+
16
+ data
17
+ end
18
+
19
+ def self.all
20
+ Dir.glob(PortMap::Nginx.servers_directory + File::Separator + '/*.port_map.conf').map do |filename|
21
+ parse_conf(filename)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,24 @@
1
+ module PortMap
2
+ module Nginx
3
+ def self.conf_directory
4
+ return ENV.fetch('NGINX_DIR') if ENV.key?('NGINX_DIR')
5
+
6
+ _, stdout, stderr = Open3.popen3('nginx -t')
7
+ location_match = [stdout.read, stderr.read].join.match(/nginx: the configuration file (.+?) syntax/)
8
+
9
+ if location_match && !location_match.captures.empty?
10
+ Pathname.new(location_match.captures.first).dirname.to_s
11
+ else
12
+ raise '`nginx -t` command did not reveal nginx conf. You can set NGINX_DIR environment variable to indicate nginx conf directory'
13
+ end
14
+ end
15
+
16
+ def self.servers_directory
17
+ conf_directory + File::Separator + 'servers'
18
+ end
19
+
20
+ def self.reload
21
+ `sudo nginx -s reload`
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,59 @@
1
+ module PortMap
2
+ class NginxConf
3
+ DOMAIN = 'dev'.freeze
4
+ PORT_PLACEHOLDER = '$PORT'.freeze
5
+ PORT_MAP_CONF_FILENAME = '.port_map.conf'.freeze
6
+
7
+ attr_reader :name,
8
+ :port,
9
+ :domain,
10
+ :output
11
+
12
+ def self.from_file(port, file)
13
+ file_content = file.read
14
+
15
+ raise "File #{file} does not contain special $PORT placeholder" unless file_content.include?(PORT_PLACEHOLDER)
16
+ file_content = file_content.sub(PORT_PLACEHOLDER, port)
17
+
18
+ name, domain = file_content.match(/server_name\s+(.+)\.(.+?);/).captures
19
+ new(port, name, domain, file_content)
20
+ end
21
+
22
+ def initialize(port, name, domain = DOMAIN, existing_conf_content = '')
23
+ @name = name
24
+ @port = port
25
+ @domain = domain
26
+
27
+ if existing_conf_content.empty?
28
+ @output = default_conf_content
29
+ else
30
+ @output = existing_conf_content
31
+ end
32
+ end
33
+
34
+ def default_conf_content
35
+ %(
36
+ server {
37
+ listen 80;
38
+ server_name #{@name}.#{DOMAIN};
39
+
40
+ location / {
41
+ proxy_pass http://127.0.0.1:#{@port};
42
+ }
43
+ }
44
+ )
45
+ end
46
+
47
+ def server_name
48
+ "#{@name}.#{@domain}"
49
+ end
50
+
51
+ def filename
52
+ Nginx.servers_directory + File::Separator + @name + '.port_map.conf'
53
+ end
54
+
55
+ def save
56
+ File.open(filename, 'w+') { |f| f.write(@output) }
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,43 @@
1
+ module PortMap
2
+ module Utilities
3
+ BASH_SHELL = '/bin/bash'.freeze
4
+ ZSH_SHELL = '/bin/zsh'.freeze
5
+
6
+ BASH_CMD_STRING = "bash -c 'source ~/.bashrc > /dev/null; PATH=%{path}; shopt -s expand_aliases; %{cmd}"
7
+ ZSH_CMD_STRING = "zsh -c 'source ~/.zshrc > /dev/null; PATH=%{path}; setopt aliases; eval %{cmd}'"
8
+
9
+ STARTING_PORT_NUMBER = 20000
10
+ PORT_NUMBER_INCREMENT = 100
11
+
12
+ def self.shell_cmd_wrapper(cmd)
13
+ case ENV.fetch('SHELL')
14
+ when ZSH_SHELL
15
+ ZSH_CMD_STRING % { path: ENV.fetch('PATH'), cmd: cmd }
16
+ when BASH_SHELL
17
+ BASH_CMD_STRING % { path: ENV.fetch('PATH'), cmd: cmd }
18
+ else
19
+ cmd
20
+ end
21
+ end
22
+
23
+ def self.apply_open_port_option(port, cmd)
24
+ port_option_flag = '--port'
25
+
26
+ if cmd.sub!(/-p\s+(\d+)/, '')
27
+ port_option_flag = '-p'
28
+ elsif cmd.sub!(/--port\s+(\d+)/, '')
29
+ port_option_flag = '--port'
30
+ end
31
+
32
+ [cmd.strip, port_option_flag, port].join(' ')
33
+ end
34
+
35
+ def self.next_empty_port
36
+ highest_port = PortMap::Mappings.all.map do |port_map|
37
+ port_map[:locations].detect { |location| location[:name] == '/' }[:proxy_pass].split(':').last.to_i
38
+ end.sort.reverse.first
39
+
40
+ highest_port.nil? ? STARTING_PORT_NUMBER : highest_port + PORT_NUMBER_INCREMENT
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,3 @@
1
+ module PortMap
2
+ VERSION = '0.1.0'
3
+ end
data/lib/port_map.rb ADDED
@@ -0,0 +1,8 @@
1
+ require 'pathname'
2
+ require 'open3'
3
+ require 'json'
4
+
5
+ Dir.glob(File.dirname(__FILE__) + '/**/*.rb') { |file| require file }
6
+
7
+ module PortMap
8
+ end
Binary file
data/port_map.gemspec ADDED
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'port_map/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'port_map'
8
+ spec.version = PortMap::VERSION
9
+ spec.authors = ['Kevin Jalbert']
10
+ spec.email = ['kevin.j.jalbert@gmail.com']
11
+
12
+ spec.summary = 'Provides an easy and mostly automatic way of mapping ports to local domains'
13
+ spec.description = 'Provides an easy and mostly automatic way of mapping ports to local domains'
14
+ spec.homepage = 'https://github.com/kevinjalbert/port_map/'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = Dir['**/*']
18
+ spec.test_files = Dir['{test,spec,features}/**/*']
19
+ spec.executables = Dir['bin/*'].map { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_development_dependency 'bundler', '~> 1.0'
23
+ spec.add_development_dependency 'rake', '~> 10.0'
24
+ spec.add_development_dependency 'rspec', '~> 3.4.0'
25
+ spec.add_development_dependency 'pry', '~> 0.10.0'
26
+ end
@@ -0,0 +1,76 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe PortMap::Hosts do
4
+ describe '.update' do
5
+ let(:contents) { 'line' }
6
+ let(:expected_contents) { [contents, "127.0.0.1 #{servers.join(' ')} #{described_class::PORT_MAP_TRACK_COMMENT}"].join("\n") }
7
+ let(:port_maps) { servers.map { |server| { 'server_name' => server } } }
8
+
9
+ before do
10
+ allow(described_class).to receive(:contents) { contents }
11
+ allow(JSON).to receive(:parse) { port_maps }
12
+ end
13
+
14
+ context 'with no port_maps' do
15
+ let(:servers) { [] }
16
+ let(:expected_contents) { contents }
17
+
18
+ it 'does not change the contents' do
19
+ expect(described_class).to receive(:save).with(expected_contents)
20
+ described_class.update
21
+ end
22
+ end
23
+
24
+ context 'with one port_map' do
25
+ let(:servers) { ['server_a'] }
26
+
27
+ it 'adds server and port map track comment' do
28
+ expect(described_class).to receive(:save).with(expected_contents)
29
+ described_class.update
30
+ end
31
+ end
32
+
33
+ context 'with multiple port_maps' do
34
+ let(:servers) { ['server_a', 'server_b'] }
35
+
36
+ it 'adds servers and port map track comment' do
37
+ expect(described_class).to receive(:save).with(expected_contents)
38
+ described_class.update
39
+ end
40
+ end
41
+ end
42
+
43
+ describe '#save' do
44
+ let(:temp_dir) { Dir.mktmpdir }
45
+ let(:temp_file) { File.new(temp_dir + File::Separator + 'hosts', 'w+') }
46
+ let(:content) { 'example_content' }
47
+
48
+ before { stub_const('PortMap::Hosts::HOSTS_FILENAME', temp_file.path) }
49
+ after { FileUtils.rm_rf(temp_dir) }
50
+
51
+ it 'saves output(default conf) to filename' do
52
+ described_class.save(content)
53
+ expect(temp_file.read).to eq(content)
54
+ end
55
+ end
56
+
57
+ describe '.contents' do
58
+ before { allow(File).to receive(:readlines).with(PortMap::Hosts::HOSTS_FILENAME) { content } }
59
+
60
+ context 'content has no port map track comment' do
61
+ let(:content) { ['normal line', 'line with no comment'] }
62
+
63
+ it 'returns all lines of content' do
64
+ expect(described_class.contents).to eq(content.join)
65
+ end
66
+ end
67
+
68
+ context 'content has port map track comment' do
69
+ let(:content) { ['normal line', "line with port map track comment #{described_class::PORT_MAP_TRACK_COMMENT}"] }
70
+
71
+ it 'returns all lines of content' do
72
+ expect(described_class.contents).to eq(content.first)
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,41 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe PortMap::Mappings do
4
+ describe '.parse_conf' do
5
+ let(:port) { '3000' }
6
+ let(:name) { 'admin' }
7
+ let(:domain) { 'dev' }
8
+
9
+ let(:nginx_conf) { PortMap::NginxConf.new(port, name, domain).tap(&:save) }
10
+ let(:temp_dir) { Dir.mktmpdir }
11
+
12
+ before { allow(PortMap::Nginx).to receive(:servers_directory) { temp_dir } }
13
+ after { FileUtils.rm_rf(temp_dir) }
14
+
15
+ it 'parses correctly' do
16
+ data = described_class.parse_conf(nginx_conf.filename)
17
+ expect(data[:name]).to eq(name)
18
+ expect(data[:nginx_conf]).to eq(nginx_conf.filename)
19
+ expect(data[:server_name]).to eq(nginx_conf.server_name)
20
+ expect(data[:locations].first[:name]).to eq('/')
21
+ expect(data[:locations].first[:proxy_pass]).to eq("http://127.0.0.1:#{port}")
22
+ end
23
+ end
24
+
25
+ describe '.all' do
26
+ let(:temp_dir) { Dir.mktmpdir }
27
+
28
+ before do
29
+ allow(PortMap::Nginx).to receive(:servers_directory) { temp_dir }
30
+ File.open(temp_dir + File::Separator + 'admin.port_map.conf', 'w')
31
+ File.open(temp_dir + File::Separator + 'api.port_map.conf', 'w')
32
+ end
33
+
34
+ after { FileUtils.rm_rf(temp_dir) }
35
+
36
+ it 'calls parse_conf for each port_map.conf' do
37
+ expect(described_class).to receive(:parse_conf).twice
38
+ described_class.all
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,135 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe PortMap::NginxConf do
4
+ describe '.from_file' do
5
+ let(:port_placeholder) { '$PORT' }
6
+ let(:port) { '3000' }
7
+ let(:name) { 'admin' }
8
+ let(:domain) { 'dev' }
9
+
10
+ let(:temp_dir) { Dir.mktmpdir }
11
+ let(:temp_file) do
12
+ File.new(temp_dir + File::Separator + 'temp.conf', 'w+').tap do |file|
13
+ file.write(content)
14
+ file.rewind
15
+ end
16
+ end
17
+ let(:content) do
18
+ %(
19
+ server {
20
+ listen 80;
21
+ server_name #{name}.#{domain};
22
+
23
+ location / {
24
+ proxy_pass http://127.0.0.1:#{port_placeholder};
25
+ }
26
+ }
27
+ )
28
+ end
29
+
30
+ after { FileUtils.rm_rf(temp_dir) }
31
+
32
+ context 'file has no $PORT placeholder' do
33
+ let(:port_placeholder) { '$NOT_PORT' }
34
+ it { expect { described_class.from_file(port, temp_file) }.to raise_error(StandardError) }
35
+ end
36
+
37
+ context 'file has $PORT placeholder' do
38
+ let(:port_placeholder) { '$PORT' }
39
+ it { expect { described_class.from_file(port, temp_file) }.not_to raise_error }
40
+ end
41
+
42
+ it 'creates conf from file' do
43
+ conf = described_class.from_file(port, temp_file)
44
+ expect(conf.port).to eq(port)
45
+ expect(conf.name).to eq(name)
46
+ expect(conf.domain).to eq(domain)
47
+ expect(conf.output).to eq(content.gsub(port_placeholder, port))
48
+ end
49
+ end
50
+
51
+ describe '#initialize' do
52
+ let(:port) { 3000 }
53
+ let(:name) { 'admin' }
54
+ let(:domain) { 'dev' }
55
+
56
+ context 'without existing_conf_content' do
57
+ it 'sets output to default_conf_content' do
58
+ conf = described_class.new(port, name)
59
+ expect(conf.output).to eq(conf.default_conf_content)
60
+ end
61
+ end
62
+
63
+ context 'with existing_conf_content' do
64
+ let(:existing_conf_content) { 'example conf config' }
65
+
66
+ it 'sets output to existing_conf_content' do
67
+ conf = described_class.new(port, name, domain, existing_conf_content)
68
+ expect(conf.output).to eq(existing_conf_content)
69
+ end
70
+ end
71
+ end
72
+
73
+ describe '#default_conf_content' do
74
+ let(:name) { 'admin' }
75
+ let(:port) { '3000' }
76
+ let(:domain) { 'dev' }
77
+ let(:default_config) do
78
+ %(
79
+ server {
80
+ listen 80;
81
+ server_name #{name}.#{domain};
82
+
83
+ location / {
84
+ proxy_pass http://127.0.0.1:#{port};
85
+ }
86
+ }
87
+ )
88
+ end
89
+
90
+ it 'should return a default conf' do
91
+ conf = described_class.new(port, name, domain)
92
+ expect(conf.output).to eq(default_config)
93
+ end
94
+ end
95
+
96
+ describe '#server_name' do
97
+ let(:name) { 'admin' }
98
+ let(:port) { '3000' }
99
+ let(:domain) { 'dev' }
100
+
101
+ it 'returns server_name' do
102
+ conf = described_class.new(port, name, domain)
103
+ expect(conf.server_name).to eq("#{name}.#{domain}")
104
+ end
105
+ end
106
+
107
+ describe '#filename' do
108
+ let(:name) { 'admin' }
109
+ let(:port) { '3000' }
110
+ let(:temp_dir) { '/temp' }
111
+
112
+ before { allow(PortMap::Nginx).to receive(:servers_directory) { temp_dir } }
113
+
114
+ it 'returns filename' do
115
+ conf = described_class.new(port, name)
116
+ expect(conf.filename).to eq(temp_dir + File::Separator + name + '.port_map.conf')
117
+ end
118
+ end
119
+
120
+ describe '#save' do
121
+ let(:name) { 'admin' }
122
+ let(:port) { '3000' }
123
+ let(:temp_dir) { Dir.mktmpdir }
124
+
125
+ before { allow(PortMap::Nginx).to receive(:servers_directory) { temp_dir } }
126
+ after { FileUtils.rm_rf(temp_dir) }
127
+
128
+ it 'saves output(default conf) to filename' do
129
+ conf = described_class.new(port, name)
130
+ conf.save
131
+ expect(File.exist?(conf.filename)).to be true
132
+ expect(File.new(conf.filename).read).to eq(conf.default_conf_content)
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,53 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe PortMap::Nginx do
4
+ describe '.conf_directory' do
5
+ context 'env var NGINX_DIR is not set' do
6
+ context 'nginx is not installed' do
7
+ let(:cmd_output) { 'zsh: command not found: nginx' }
8
+
9
+ before { allow(Open3).to receive(:popen3).with('nginx -t') { [nil, double(read: ''), double(read: cmd_output)] } }
10
+
11
+ it 'raises exception' do
12
+ expect { described_class.conf_directory }.to raise_error(StandardError)
13
+ end
14
+ end
15
+
16
+ context 'nginx is installed' do
17
+ let(:nginx_dir) { '/usr/local/etc/nginx' }
18
+ let(:cmd_output) do
19
+ [
20
+ "nginx: the configuration file #{nginx_dir}/nginx.conf syntax is ok",
21
+ "nginx: configuration file #{nginx_dir}/nginx.conf test is successful"
22
+ ].join("\n")
23
+ end
24
+
25
+ before { allow(Open3).to receive(:popen3).with('nginx -t') { [nil, double(read: ''), double(read: cmd_output)] } }
26
+
27
+ it 'returns nginx_dir' do
28
+ expect(described_class.conf_directory).to eq(nginx_dir)
29
+ end
30
+ end
31
+ end
32
+
33
+ context 'env var NGINX_DIR is set' do
34
+ let(:nginx_dir) { '/temp' }
35
+ before do
36
+ allow(ENV).to receive(:key?).with('NGINX_DIR') { true }
37
+ allow(ENV).to receive(:fetch).with('NGINX_DIR') { nginx_dir }
38
+ end
39
+
40
+ it 'returns nginx_dir' do
41
+ expect(described_class.conf_directory).to eq(nginx_dir)
42
+ end
43
+ end
44
+ end
45
+
46
+ describe '.servers_directory!' do
47
+ before { allow(described_class).to receive(:conf_directory) { '/temp/' } }
48
+
49
+ it 'returns servers directory' do
50
+ expect(described_class.servers_directory).to eq(described_class.conf_directory + File::Separator + 'servers')
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,161 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe PortMap::Utilities do
4
+ describe '.shell_cmd_wrapper' do
5
+ let(:cmd) { 'rails server' }
6
+ let(:example_path) { 'example_path' }
7
+
8
+ before { allow(ENV).to receive(:fetch).with('PATH') { example_path } }
9
+
10
+ context 'zsh shell' do
11
+ before { allow(ENV).to receive(:fetch).with('SHELL') { described_class::ZSH_SHELL } }
12
+
13
+ it 'returns zsh cmd' do
14
+ zsh_cmd = described_class.shell_cmd_wrapper(cmd)
15
+ expected_zsh_cmd = described_class::ZSH_CMD_STRING % { path: example_path, cmd: cmd }
16
+ expect(zsh_cmd).to eq(expected_zsh_cmd)
17
+ end
18
+ end
19
+
20
+ context 'bash shell' do
21
+ before { allow(ENV).to receive(:fetch).with('SHELL') { described_class::BASH_SHELL } }
22
+
23
+ it 'returns bash cmd' do
24
+ bash_cmd = described_class.shell_cmd_wrapper(cmd)
25
+ expected_bash_cmd = described_class::BASH_CMD_STRING % { path: example_path, cmd: cmd }
26
+ expect(bash_cmd).to eq(expected_bash_cmd)
27
+ end
28
+ end
29
+ end
30
+
31
+ describe '.apply_open_port_option' do
32
+ let(:cmd) { "example_cmd -t 30 --num 60 #{port_flag} #{port_number}" }
33
+
34
+ let(:port_flag) { '--port' }
35
+ let(:port_number) { 3000 }
36
+
37
+ let(:expected_cmd) { "example_cmd -t 30 --num 60 #{expected_port_flag} #{expected_port_number}" }
38
+ let(:expected_port_number) { 10000 }
39
+
40
+ before { allow(described_class).to receive(:next_empty_port) { expected_port_number } }
41
+
42
+ context 'with --port in cmd' do
43
+ let(:expected_port_flag) { '--port' }
44
+
45
+ it { expect(described_class.apply_open_port_option(expected_port_number, cmd)).to eq(expected_cmd) }
46
+ end
47
+
48
+ context 'with -p in cmd' do
49
+ let(:port_flag) { '-p' }
50
+ let(:expected_port_flag) { '-p' }
51
+
52
+ it { expect(described_class.apply_open_port_option(expected_port_number, cmd)).to eq(expected_cmd) }
53
+ end
54
+
55
+ context 'with no port option in cmd' do
56
+ let(:port_flag) { nil }
57
+ let(:port_number) { nil }
58
+ let(:expected_port_flag) { '--port' }
59
+
60
+ it { expect(described_class.apply_open_port_option(expected_port_number, cmd)).to eq(expected_cmd) }
61
+ end
62
+ end
63
+
64
+ describe '.next_empty_port' do
65
+ let(:port_mappings) { [] }
66
+
67
+ before { allow(PortMap::Mappings).to receive(:all) { port_mappings } }
68
+
69
+ context 'no port mappings exist' do
70
+ it 'returns STARTING_PORT_NUMBER' do
71
+ expect(described_class.next_empty_port).to eq(described_class::STARTING_PORT_NUMBER)
72
+ end
73
+ end
74
+
75
+ context 'one port mapping exist' do
76
+ context 'with one location' do
77
+ let(:previous_highest_port_number) { 30000 }
78
+ let(:port_mappings) do
79
+ [
80
+ {
81
+ name: 'admin',
82
+ nginx_conf: '/usr/local/etc/nginx/servers/admin.port_map.conf',
83
+ server_name: 'admin.dev',
84
+ locations: [
85
+ {
86
+ name: '/',
87
+ proxy_pass: "http://127.0.0.1:#{previous_highest_port_number}"
88
+ }
89
+ ]
90
+ }
91
+ ]
92
+ end
93
+
94
+ it 'returns STARTING_PORT_NUMBER' do
95
+ expect(described_class.next_empty_port).to eq(previous_highest_port_number + described_class::PORT_NUMBER_INCREMENT)
96
+ end
97
+ end
98
+
99
+ context 'with multiple locations' do
100
+ let(:previous_highest_port_number) { 30000 }
101
+ let(:port_mappings) do
102
+ [
103
+ {
104
+ name: 'admin',
105
+ nginx_conf: '/usr/local/etc/nginx/servers/admin.port_map.conf',
106
+ server_name: 'admin.dev',
107
+ locations: [
108
+ {
109
+ name: '/',
110
+ proxy_pass: "http://127.0.0.1:#{previous_highest_port_number}"
111
+ },
112
+ {
113
+ name: '/test',
114
+ proxy_pass: 'http://test.dev'
115
+ }
116
+ ]
117
+ }
118
+ ]
119
+ end
120
+
121
+ it 'returns STARTING_PORT_NUMBER' do
122
+ expect(described_class.next_empty_port).to eq(previous_highest_port_number + described_class::PORT_NUMBER_INCREMENT)
123
+ end
124
+ end
125
+ end
126
+
127
+ context 'multiple port mappings exist' do
128
+ let(:previous_highest_port_number) { 30000 }
129
+ let(:port_mappings) do
130
+ [
131
+ {
132
+ name: 'admin',
133
+ nginx_conf: '/usr/local/etc/nginx/servers/admin.port_map.conf',
134
+ server_name: 'admin.dev',
135
+ locations: [
136
+ {
137
+ name: '/',
138
+ proxy_pass: 'http://127.0.0.1:20720'
139
+ }
140
+ ]
141
+ },
142
+ {
143
+ name: 'api',
144
+ nginx_conf: '/usr/local/etc/nginx/servers/api.port_map.conf',
145
+ server_name: 'api.dev',
146
+ locations: [
147
+ {
148
+ name: '/',
149
+ proxy_pass: "http://127.0.0.1:#{previous_highest_port_number}"
150
+ }
151
+ ]
152
+ }
153
+ ]
154
+ end
155
+
156
+ it 'returns STARTING_PORT_NUMBER' do
157
+ expect(described_class.next_empty_port).to eq(previous_highest_port_number + described_class::PORT_NUMBER_INCREMENT)
158
+ end
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,6 @@
1
+ require 'codeclimate-test-reporter'
2
+ CodeClimate::TestReporter.start
3
+
4
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
5
+
6
+ require 'port_map'
metadata ADDED
@@ -0,0 +1,135 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: port_map
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Kevin Jalbert
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-02-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 3.4.0
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 3.4.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.10.0
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.10.0
69
+ description: Provides an easy and mostly automatic way of mapping ports to local domains
70
+ email:
71
+ - kevin.j.jalbert@gmail.com
72
+ executables:
73
+ - create_port_map
74
+ - list_port_maps
75
+ - port_map
76
+ - remove_port_map
77
+ extensions: []
78
+ extra_rdoc_files: []
79
+ files:
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - Gemfile.lock
83
+ - LICENSE
84
+ - README.md
85
+ - Rakefile
86
+ - bin/create_port_map
87
+ - bin/list_port_maps
88
+ - bin/port_map
89
+ - bin/remove_port_map
90
+ - lib/port_map.rb
91
+ - lib/port_map/hosts.rb
92
+ - lib/port_map/mappings.rb
93
+ - lib/port_map/nginx.rb
94
+ - lib/port_map/nginx_conf.rb
95
+ - lib/port_map/utilities.rb
96
+ - lib/port_map/version.rb
97
+ - pkg/port_map-0.1.0.gem
98
+ - port_map.gemspec
99
+ - spec/port_map/hosts_spec.rb
100
+ - spec/port_map/mappings_spec.rb
101
+ - spec/port_map/nginx_conf_spec.rb
102
+ - spec/port_map/nginx_spec.rb
103
+ - spec/port_map/utilities_spec.rb
104
+ - spec/spec_helper.rb
105
+ homepage: https://github.com/kevinjalbert/port_map/
106
+ licenses:
107
+ - MIT
108
+ metadata: {}
109
+ post_install_message:
110
+ rdoc_options: []
111
+ require_paths:
112
+ - lib
113
+ required_ruby_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ required_rubygems_version: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: '0'
123
+ requirements: []
124
+ rubyforge_project:
125
+ rubygems_version: 2.4.5.1
126
+ signing_key:
127
+ specification_version: 4
128
+ summary: Provides an easy and mostly automatic way of mapping ports to local domains
129
+ test_files:
130
+ - spec/port_map/hosts_spec.rb
131
+ - spec/port_map/mappings_spec.rb
132
+ - spec/port_map/nginx_conf_spec.rb
133
+ - spec/port_map/nginx_spec.rb
134
+ - spec/port_map/utilities_spec.rb
135
+ - spec/spec_helper.rb