Skip to content

Commit

Permalink
feat: initial library
Browse files Browse the repository at this point in the history
  • Loading branch information
spence committed Feb 12, 2017
0 parents commit 0f6bc0b
Show file tree
Hide file tree
Showing 10 changed files with 310 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# The directory Mix will write compiled artifacts to.
/_build

# If you run "mix test --cover", coverage assets end up here.
/cover

# The directory Mix downloads your dependencies sources to.
/deps

# Where 3rd-party dependencies like ExDoc output generated docs.
/doc

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Hex docs
doc
13 changes: 13 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
language: elixir
matrix:
include:
- otp_release: 18.3
elixir: 1.3.2
- otp_release: 19.0
elixir: 1.3.2
sudo: false
before_script:
- mix local.hex --force # Update Mix
- mix deps.get --only test
script:
- mix test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2016 Spencer Creasey <[email protected]>

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.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# ValidUrl [![Build Status](https://travis-ci.org/spence/valid_url.svg?branch=master)](https://travis-ci.org/spence/valid_url)

Validate a URL.

## Installation

The package can be installed as:

1. Add `valid_url` to your list of dependencies in `mix.exs`:

```elixir
def deps do
[{:valid_url, "~> 0.1.0"}]
end
```

2. Ensure `valid_url` is started before your application:

```elixir
def application do
[applications: [:valid_url]]
end
```

## Usage

```elixir
ValidUrl.validate("https://www.spencercreasey.com") # => true
ValidUrl.validate("ftp://www.example.com") # => true
ValidUrl.validate("www.google.com") # => false
```

## Development

```
mix test
```

## License

MIT

## Contributing

1. Fork it
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 new Pull Request
1 change: 1 addition & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use Mix.Config
63 changes: 63 additions & 0 deletions lib/valid_url.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
defmodule ValidUrl do
@moduledoc """
The base module of ValidUrl.
It exposes a single function, `validate`.
"""

@docp """
Regex to validate URLs.
Adapted from https://gist.github.com/dperini/729294.
"""
@link_regex Regex.compile!(
"^" <>
# protocol identifier
"(?:(?:https?|ftp)://)" <>
# user:pass authentication
"(?:\\S+(?::\\S*)?@)?" <>
"(?:" <>
# IP address exclusion
# private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" <>
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" <>
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" <>
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 224.0.0.0
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" <>
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" <>
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" <>
"|" <>
# host name
"(?:(?:[a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-9]+)" <>
# domain name
"(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*" <>
# TLD identifier
"(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,}))" <>
# TLD may end with dot
"\\.?" <>
")" <>
# port number
"(?::\\d{2,5})?" <>
# resource path
"(?:[/?#]\\S*)?" <>
"$", "iu"
)

@doc """
Test whether a string is a valid URL.
Regular expression-based. Adapted from [https://gist.github.com/dperini/729294](https://gist.github.com/dperini/729294).
Args:
* `url` - The URL to validate, string
Returns a boolean.
"""
def validate(url) do
Regex.match?(@link_regex, url)
end
end
37 changes: 37 additions & 0 deletions mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
defmodule ValidUrl.Mixfile do
use Mix.Project

def project do
[app: :valid_url,
version: "0.1.0",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps,
description: "Validate URL",
files: ["lib", "src", "mix.exs", "README.md", "LICENSE"],
package: package,

# Docs
name: "ValidUrl",
source_url: "https://github.com/spence/valid_url",
docs: [main: "ValidUrl",
extras: ["README.md"]]]
end

def package do
[maintainers: ["Spencer Creasey <[email protected]>"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/spence/valid_url",
"Docs" => "https://hexdocs.pm/valid_url"}]
end

def application do
[applications: [:logger]]
end

defp deps do
[{:earmark, "~> 1.1", only: :dev},
{:ex_doc, "~> 0.14", only: :dev}]
end
end
2 changes: 2 additions & 0 deletions mix.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
%{"earmark": {:hex, :earmark, "1.1.1", "433136b7f2e99cde88b745b3a0cfc3fbc81fe58b918a09b40fce7f00db4d8187", [:mix], []},
"ex_doc": {:hex, :ex_doc, "0.14.5", "c0433c8117e948404d93ca69411dd575ec6be39b47802e81ca8d91017a0cf83c", [:mix], [{:earmark, "~> 1.0", [hex: :earmark, optional: false]}]}}
1 change: 1 addition & 0 deletions test/test_helper.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ExUnit.start()
103 changes: 103 additions & 0 deletions test/valid_url_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
defmodule ValidUrlTest do
use ExUnit.Case
doctest ValidUrl

# Tests taken from https://mathiasbynens.be/demo/url-regex

test "returns true for valid URLs" do
urls = [
"http://foo.com/blah_blah",
"http://foo.com/blah_blah/",
"http://foo.com/blah_blah_(wikipedia)",
"http://foo.com/blah_blah_(wikipedia)_(again)",
"http://www.example.com/wpstyle/?p=364",
"https://www.example.com/foo/?bar=baz&inga=42&quux",
"http://✪df.ws/123",
"http://userid:[email protected]:8080",
"http://userid:[email protected]:8080/",
"http://[email protected]",
"http://[email protected]/",
"http://[email protected]:8080",
"http://[email protected]:8080/",
"http://userid:[email protected]",
"http://userid:[email protected]/",
"http://142.42.1.1/",
"http://142.42.1.1:8080/",
"http://➡.ws/䨹",
"http://⌘.ws",
"http://⌘.ws/",
"http://foo.com/blah_(wikipedia)#cite-1",
"http://foo.com/blah_(wikipedia)_blah#cite-1",
"http://foo.com/unicode_(✪)_in_parens",
"http://foo.com/(something)?after=parens",
"http://☺.damowmow.com/",
"http://code.google.com/events/#&product=browser",
"http://j.mp",
"ftp://foo.bar/baz",
"http://foo.bar/?q=Test%20URL-encoded%20stuff",
"http://مثال.إختبار",
"http://例子.测试",
"http://उदाहरण.परीक्षा",
"http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com",
"http://1337.net",
"http://a.b-c.de",
"http://a.b--c.de/",
"http://www.foo.bar./",
"http://223.255.255.254",
"http://www.example.com.",
"http://www.example.com/",
"http://www.example.com?",
"http://www.example.com#",
"http://www.example.com./?#"
]

for url <- urls do
assert(ValidUrl.validate(url), "Expected \"#{url}\" to be a valid URL.")
end
end

test "returns false for invalid URLs" do
invalidUrls = [
"http://",
"http://.",
"http://..",
"http://../",
"http://?",
"http://??",
"http://??/",
"http://#",
"http://##",
"http://##/",
"http://foo.bar?q=Spaces should be encoded",
"//",
"//a",
"///a",
"///",
"http:///a",
"foo.com",
"rdar://1234",
"h://test",
"http:// shouldfail.com",
":// should fail",
"http://foo.bar/foo(bar)baz quux",
"ftps://foo.bar/",
"http://-error-.invalid/",
"http://-a.b.co",
"http://a.b-.co",
"http://0.0.0.0",
"http://10.1.1.0",
"http://10.1.1.255",
"http://224.1.1.1",
"http://1.1.1.1.1",
"http://123.123.123",
"http://3628126748",
"http://.www.foo.bar/",
"http://.www.foo.bar./",
"http://10.1.1.1"
]

for invalidUrl <- invalidUrls do
assert(!ValidUrl.validate(invalidUrl), "Expected \"#{invalidUrl}\" to be an invalid URL.")
end
end
end

0 comments on commit 0f6bc0b

Please sign in to comment.