Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jakewarren committed Apr 26, 2018
0 parents commit ea16377
Show file tree
Hide file tree
Showing 16 changed files with 762 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bin/
38 changes: 38 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
language: go

go:
- "1.9.x"
- "1.10.x"
- "master"

matrix:
allow_failures:
- go: "master"

fast_finish: true

before_script:
- GO_FILES=$(find . -iname '*.go' -type f | grep -v /vendor/) # All the .go files, excluding vendor/
- go get github.com/golang/lint/golint # Linter
- go get honnef.co/go/tools/cmd/megacheck # Badass static analyzer/linter
- go get github.com/fzipp/gocyclo
- go get github.com/mitchellh/gox

script:
- test -z $(gofmt -s -l $GO_FILES) # Fail if a .go file hasn't been formatted with gofmt
- go test -v -race ./... # Run all the tests with the race detector enabled
- go vet ./... # go vet is the official Go static analyzer
- megacheck ./... # "go vet on steroids" + linter
- gocyclo -over 19 $GO_FILES # forbid code with huge functions
- golint -set_exit_status $(go list ./...) # one last linter
- make release # build release binaries

deploy:
provider: releases
api_key:
secure: msaX8Nhd/xtjf/55LLFnf1dHBX6JBtHjR0hkg6w+lqTbq2Tj1wc92i99sP2XHTKd83K7remQbsMj0G7vi4Zkno6CuPVdKInmLP1OmyfIyHESkwGi4in/EKuZfZs25+TVOyOK0l2CKiaf9Duuo7DsxswxJc31yKKzH2E1Di3A+O/vRojXvNsDQGuMUKqheVP3lKT988HysHs81SF3m0z4C8qKToIJszqMGp+nUDKURPNd2w4sYa0tTKXCuU/ye0dm2FgO4rETCn7AOIUTVj9NzzcMrVd8tzCGd65JMJoj8ZSB/AccLtREvy1yPey1MoFUwwJd3/EFvDgYD4Anb5U31V6s+so+X64BxkW+pBMPeyQLbv6OEBl4vN8xi0V3Enq7zunWgz8lQxsnTQYqGWMl1DQW/9f4f2s5SEPBSbyy9SUBGGYniW+CeZ2MtYxxFLQoYZafOdYpMp/5zC13xkyEolXsF1F0JWRNrItcNVfVV9WMEmttBvPbr/D4pKbnOjTBc2VL0lWSsMeMYlCbZWBEs3MLKqZyEdRFhohFwBbZMUIpWSuCqmglJ3HXSwmA/76OQaiZ33ZJO/NY/xXEFhIA66McKTxY5LekI8YtKnYvjM+Q/3stvoAo0+pKubnh009/MczQhEoTEExDxL3eWszGACA1vHaua/nvww3mJvAjEuM=
file_glob: true
file: 'bin/*'
on:
repo: jakewarren/defang
tags: true
26 changes: 26 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
BINARY := defang

VERSION := $(shell git describe --tags --abbrev=0 2>/dev/null || (git describe --always --long --dirty|tr '\n' '-';date +%Y.%m.%d))
LDFLAGS = -ldflags "-w -s -X main.version=${VERSION}"
LDFLAGS_DEV = -ldflags "-X main.version=${VERSION}"

#Build release builds
release:
@CGO_ENABLED=0 gox -osarch="darwin/386 darwin/amd64 linux/386 linux/amd64 windows/386 windows/amd64" ${LDFLAGS} -output="bin/{{.Dir}}_{{.OS}}_{{.Arch}}" cmd/defang/main.go

#Build a development build
dev:
@CGO_ENABLED=0 go build --installsuffix cgo ${LDFLAGS_DEV} -o bin/${BINARY} cmd/defang/main.go

#Install a release build on your local system
install: clean
@go install ${LDFLAGS} cmd/defang/main.go

build:
@go build ${LDFLAGS_DEV} -o bin/${BINARY} cmd/defang/main.go

clean:
@go clean -i

test:
@go test -v ./...
136 changes: 136 additions & 0 deletions cmd/defang/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package main

import (
"bufio"
"fmt"
"io"
"os"
"strings"

"github.com/atotto/clipboard"
"github.com/jakewarren/defang"
"github.com/mingrammer/commonregex"
"github.com/spf13/pflag"
)

var version string

type config struct {
}

type app struct {
Config config
input io.Reader
}

func main() {

d := app{}

displayVersion := pflag.BoolP("version", "V", false, "display version")
displayHelp := pflag.BoolP("help", "h", false, "display help")

pflag.Parse()

// override the default usage display
if *displayHelp {
displayUsage()
os.Exit(0)
}

if *displayVersion {
fmt.Println(version)
os.Exit(0)
}

d.input = getInput()

d.processInput()

}

func (d app) processInput() {

var output string

scanner := bufio.NewScanner(d.input)

for scanner.Scan() {
text := scanner.Text()

// process email addresses
emails := commonregex.Emails(text)

for _, e := range emails {

address := strings.Split(e, "@")

u, _ := defang.URL(address[1])

defangedEmail := address[0] + "@" + u

//remove the email to prevent it from being processed again as a URL
text = strings.Replace(text, e, "", -1)

output += defangedEmail + "\n"
}

// process links
links := commonregex.Links(text)

for _, l := range links {
u, _ := defang.URL(l)

output += u + "\n"
}

}

fmt.Print(output)
clipboard.WriteAll(output)

}

// getInput determines the input source between STDIN, String param or file name
func getInput() io.Reader {

var f io.Reader
fi, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
if fi.Mode()&os.ModeNamedPipe != 0 { // check if STDIN is attached
f = os.Stdin
} else if len(pflag.Args()) > 0 {
// check the first argument to see if it's a file
if fileExists(pflag.Arg(0)) {
f, err = os.Open(pflag.Arg(0))
if err != nil {
panic(err)
}
} else { // if the user did not pass a file then process the arguments
f = strings.NewReader(strings.Join(pflag.Args(), "\n"))
}

} else {
displayUsage()
os.Exit(0)
}
return f
}

// fileExists checks if a file or path fileExists
func fileExists(filepath string) bool {
if _, err := os.Stat(filepath); err != nil {
return os.IsExist(err)
}
return true
}

// print custom usage instead of the default provided by pflag
func displayUsage() {

fmt.Printf("Usage: defang [<flags>] [FILE]\n\n")
fmt.Printf("Optional flags:\n\n")
pflag.PrintDefaults()
}
112 changes: 112 additions & 0 deletions cmd/defang/main.go.201804261453.backup
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package main

import (
"fmt"
"io"
"io/ioutil"
"os"
"strings"

"github.com/apex/log"
"github.com/jakewarren/defang"
"github.com/mingrammer/commonregex"
"github.com/spf13/pflag"
)

var version string

type config struct {
}

type app struct {
Config config
input io.Reader
}

func main() {

d := app{}

displayVersion := pflag.BoolP("version", "V", false, "display version")
displayHelp := pflag.BoolP("help", "h", false, "display help")

pflag.Parse()

// override the default usage display
if *displayHelp {
displayUsage()
os.Exit(0)
}

if *displayVersion {
fmt.Println(version)
os.Exit(0)
}

d.input = getInput()

d.processInput()

}

func (d app) processInput() {

var output string

buf, err := ioutil.ReadAll(d.input)
if err != nil {
log.WithError(err).Fatal("error reading from input")
}

links := commonregex.Links(string(buf))

for _, l := range links {
u, _ := defang.URL(l)

output += u + "\n"
}

fmt.Print(output)

}

// getInput determines the input source between STDIN, String param or file name
func getInput() io.Reader {

var f io.Reader
fi, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
if fi.Mode()&os.ModeNamedPipe != 0 { // check if STDIN is attached
f = os.Stdin
} else if len(pflag.Args()) > 0 {
// check the first argument to see if it's a file
if fileExists(pflag.Arg(0)) {
f, err = os.Open(pflag.Arg(0))
if err != nil {
panic(err)
}
} else { // if the user did not pass a file then process the arguments
f = strings.NewReader(strings.Join(pflag.Args(), "\n"))
}

}
return f
}

// fileExists checks if a file or path fileExists
func fileExists(filepath string) bool {
if _, err := os.Stat(filepath); err != nil {
return os.IsExist(err)
}
return true
}

// print custom usage instead of the default provided by pflag
func displayUsage() {

fmt.Printf("Usage: defang [<flags>] [FILE]\n\n")
fmt.Printf("Optional flags:\n\n")
pflag.PrintDefaults()
}
28 changes: 28 additions & 0 deletions defang_ip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package defang

import (
"net"
"regexp"

"github.com/pkg/errors"
)

// IPv4 defangs an IPv4 address
func IPv4(ip interface{}) (string, error) {

var ipAddress string

switch ip := ip.(type) {
case string:
ipAddress = ip
case net.IP:
ipAddress = ip.String()
default:
return "", errors.New("unknown type")
}

re := regexp.MustCompile(`(\d{1,3}\.\d{1,3}\.\d{1,3})(\.)(\d{1,3})`)

return re.ReplaceAllString(ipAddress, `$1[.]$3`), nil

}
41 changes: 41 additions & 0 deletions defang_ip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package defang

import (
"fmt"
"net"
"testing"
)

func ExampleDefangIPv4() {
defangedIP, _ := IPv4("8.8.8.8")
fmt.Println(defangedIP)
// Output: 8.8.8[.]8
}

func TestDefangIPv4(t *testing.T) {
type args struct {
ip interface{}
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{"test string input", args{"4.4.4.4"}, "4.4.4[.]4", false},
{"test net.IP input", args{net.ParseIP("4.4.4.4")}, "4.4.4[.]4", false},
{"test unsupported type", args{false}, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := IPv4(tt.args.ip)
if (err != nil) != tt.wantErr {
t.Errorf("IPv4() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("IPv4() = %v, want %v", got, tt.want)
}
})
}
}
Loading

0 comments on commit ea16377

Please sign in to comment.