Skip to content
This repository has been archived by the owner on Oct 17, 2018. It is now read-only.

Commit

Permalink
[Init] Extracts Client Reload Form Amber CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
eliasjpr committed Sep 23, 2018
0 parents commit 4d76a97
Show file tree
Hide file tree
Showing 11 changed files with 282 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*.cr]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf

# Libraries don't need dependency lock
# Dependencies will be locked in application that uses them
/shard.lock
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
language: crystal
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Elias J. Perez

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# live_reload

TODO: Write a description here

## Installation

Add this to your application's `shard.yml`:

```yaml
dependencies:
live_reload:
github: your-github-user/live_reload
```
## Usage
```crystal
require "live_reload"
```

TODO: Write usage instructions here

## Development

TODO: Write development instructions here

## Contributing

1. Fork it (<https://github.com/your-github-user/live_reload/fork>)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## Contributors

- [your-github-user](https://github.com/your-github-user) Elias J. Perez - creator, maintainer
9 changes: 9 additions & 0 deletions shard.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: live_reload
version: 0.1.0

authors:
- Elias J. Perez <eliasjpr@gmail.com>

crystal: 0.26.1

license: MIT
9 changes: 9 additions & 0 deletions spec/live_reload_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
require "./spec_helper"

describe LiveReload do
# TODO: Write tests

it "works" do
false.should eq(true)
end
end
2 changes: 2 additions & 0 deletions spec/spec_helper.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require "spec"
require "../src/live_reload"
127 changes: 127 additions & 0 deletions src/client_reload.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
require "logger"
require "./file_watcher"

module LiveReload
struct Client
CLI_IO = ::Process::Redirect::Inherit
SESSIONS = [] of HTTP::WebSocket
PROCESSES = [] of Process

@file_watcher = FileWatcher.new
@app_running = false

getter commands : Array(String),
files : Array(String),
logger : Environment::Logger

def self.run(watch_config : Hash(String, Array(String)), logger : Environment::Logger)
new(watch_config, logger).run
end

def initialize(watch_config : Hash(String, Array(String)), @logger)
@commands = watch_config["commands"]
@files = watch_config["files"]

at_exit do
kill_client_processes
end
end

def run
run_watcher
rescue ex
error "Error in watch configuration. #{ex.message}"
exit 1
end

private def run_watcher
if files.empty?
run_commands
else
spawn watcher
end
create_reload_server
rescue ex
error "Error in watch configuration. #{ex.message}"
exit 1
end

private def watcher
loop do
scan_files
@app_running = true
sleep 1
end
end

# Todo : Extract websocket dependency
private def create_reload_server
Amber::WebSockets::Server::Handler.new "/client-reload" do |session|
SESSIONS << session
session.on_close do
SESSIONS.delete session
end
end
end

def scan_files
file_counter = 0
@file_watcher.scan_files(files) do |file|
if @app_running
debug "File changed: #{file}"
end
file_counter += 1
check_file(file)
end
if file_counter > 0
debug "Watching #{file_counter} client files..."
kill_client_processes
run_commands
end
end

private def check_file(file)
case file
when .ends_with? ".css"
reload_clients(msg: "refreshcss")
else
reload_clients(msg: "reload")
end
end

private def reload_clients(msg)
SESSIONS.each do |session|
session.@ws.send msg
end
end

private def run_commands
commands.each do |command|
PROCESSES << run_process(command)
end
end

private def kill_client_processes
PROCESSES.each do |process|
process.kill unless process.terminated?
PROCESSES.delete(process)
end
end

private def debug(msg)
logger.debug msg, "Watcher", :light_gray
end

private def error(msg)
logger.error msg, "Watcher", :red
end

private def warn(msg)
logger.warn msg, "Watcher", :yellow
end

private def run_process(command, shell = true, input = CLI_IO, output = CLI_IO, error = CLI_IO)
::Process.new(command, shell: shell, input: input, output: output, error: error)
end
end
end
19 changes: 19 additions & 0 deletions src/file_watcher.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module LiveReload
class FileWatcher
@file_timestamps = {} of String => String

private def get_timestamp(file : String)
File.info(file).modification_time.to_s("%Y%m%d%H%M%S")
end

def scan_files(files)
Dir.glob(files) do |file|
timestamp = get_timestamp(file)
if @file_timestamps[file]? != timestamp
@file_timestamps[file] = timestamp
yield file
end
end
end
end
end
39 changes: 39 additions & 0 deletions src/live_reload.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require "./client_reload"
require "http"

module LiveReload
VERSION = "0.1.0"

class Handler
include HTTP::Handler
CONTENT_TYPE_HEADER = "Content-Type"

def initialize(
logger : Environment::Logger = Amber.settings.logger,
@env : Environment::Env = Amber.env
)
LiveReload::Client.run(
watch_config = {
"commands" => [""],
"files" => ["public/**/*"],
},
logger
)
end

def initialize(
config : Hash(String, Array(String)),
logger : Environment::Logger = Amber.settings.logger,
@env : Environment::Env = Amber.env
)
LiveReload::Client.run(config, logger)
end

def call(context : HTTP::Server::Context)
if @env.development? && context.request.headers[CONTENT_TYPE_HEADER]?.to_s.downcase == "text/html"
context.response.headers["Client-Reload"] = %(true)
end
call_next(context)
end
end
end

0 comments on commit 4d76a97

Please sign in to comment.