Skip to content

Commit

Permalink
remove ruby as a build dependency
Browse files Browse the repository at this point in the history
convert str2go from ruby to go
  • Loading branch information
zimbatm committed Oct 16, 2017
1 parent 79aa1d0 commit c5d59f2
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 26 deletions.
28 changes: 3 additions & 25 deletions script/str2go
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
#!/usr/bin/env ruby
#!/bin/sh
#
# str2go <package_name> <constant_name>
# Usage: str2go <package_name> <constant_name>
#

package_name = ARGV[0]
constant_name = ARGV[1]

input = $stdin
output = $stdout

def line_to_go(line)
'"' + line.gsub('\\', '\\\\\\').gsub("\n", '\n').gsub('"', '\"').gsub(/[^[:ascii:]]/) do |char|
"\\#{char.ord}"
end + '"'
end

def lines_to_go(lines)
lines.map do |line|
"\t#{line_to_go(line)}"
end.join(" +\n").sub("\t", '')
end

output.puts "package #{package_name}"
output.puts

output.puts "const #{constant_name} = #{lines_to_go(input.each_line)}"
exec go run "$0.go" -- "$@"
61 changes: 61 additions & 0 deletions script/str2go.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"bufio"
"flag"
"fmt"
"io"
"os"
"unicode"
)

const (
BackSlash = '\\'
NewLine = '\n'
DoubleQuote = '"'
)

func printRune(w *bufio.Writer, r rune) {
switch r {
case BackSlash:
w.WriteRune(BackSlash)
w.WriteRune(BackSlash)
case NewLine:
w.WriteString("\\n\" +\n\t\"")
case DoubleQuote:
w.WriteRune(BackSlash)
w.WriteRune(DoubleQuote)
default:
if !IsASCII(r) {
panic("only ASCII is supported")
}
w.WriteRune(r)
}
}

func IsASCII(r rune) bool {
return r < unicode.MaxASCII
}

func main() {
flag.Parse()
packageName := flag.Arg(0)
constantName := flag.Arg(1)
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()

fmt.Fprintf(out, "package %s\n\nconst %s = \"", packageName, constantName)

for {
r, _, err := in.ReadRune()
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
printRune(out, r)
}
fmt.Fprint(out, "\"\n")
}
3 changes: 2 additions & 1 deletion stdlib.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,4 +613,5 @@ const STDLIB = "#!bash\n" +
" source \"${XDG_CONFIG_HOME:-$HOME/.config}/direnv/direnvrc\" >&2\n" +
"elif [[ -f $HOME/.direnvrc ]]; then\n" +
" source \"$HOME/.direnvrc\" >&2\n" +
"fi\n"
"fi\n" +
""

0 comments on commit c5d59f2

Please sign in to comment.