Skip to content
This repository has been archived by the owner on Dec 7, 2020. It is now read-only.

Commit

Permalink
Merge pull request #3 from 030/gh2-first-version
Browse files Browse the repository at this point in the history
Gh2 first version
  • Loading branch information
030 authored Oct 28, 2018
2 parents f43a2a2 + c70a1d7 commit 8b86f73
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
73 changes: 73 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"bufio"
"flag"
"fmt"
"log"
"os"
"regexp"
"strings"

"github.com/sirupsen/logrus"
)

func scanFile(file string, key string) string {
f, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()

scanner := bufio.NewScanner(f)

var val string

for scanner.Scan() {
logrus.Debug("Check whether file: ", file, " and line: ", scanner.Text(), " contains key: ", key)
if strings.Contains(scanner.Text(), key+":") {
val = value(scanner.Text())
}
}

if err := scanner.Err(); err != nil {
log.Fatal(err)
}

return val
}

func value(keyValue string) string {
re := regexp.MustCompile("^[a-z-_]+: (.*)$")
match := re.FindStringSubmatch(keyValue)

if len(match) == 0 {
log.Fatal("Cannot extract value for key, but was: '", keyValue,
"' please check whether the regex matches the key")
}

logrus.Debug("MATCH: ", match)

return match[1]
}

func main() {
key := flag.String("key", "key", "Specify the key")
yamlFile := flag.String("yamlFile", "file.yaml", "Path to a yaml file")
debug := flag.Bool("debug", false, "Whether debugging should be enabled")

flag.Parse()

if *debug {
logrus.SetLevel(logrus.DebugLevel)
}

logrus.Debug("key: ", *key)
logrus.Debug("yamlFile: ", *yamlFile)

value := scanFile(*yamlFile, *key)
if value == "" {
log.Fatal("File: ", *yamlFile, " does not contain key: ", *key)
}
fmt.Println(value)
}
20 changes: 20 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import "testing"

func TestScanFile(t *testing.T) {
keyValue := map[string]string{
"a": "abc",
"b": "def",
"c": "ghi",
"under_scores": "ensure that keys may contain an underscore",
}

for key, value := range keyValue {
expected := value
actual := scanFile("test.yaml", key)
if expected != actual {
t.Errorf("Value was incorrect, got: %s, want: %s.", actual, expected)
}
}
}
4 changes: 4 additions & 0 deletions test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
a: abc
b: def
c: ghi
under_scores: ensure that keys may contain an underscore

0 comments on commit 8b86f73

Please sign in to comment.