Skip to content

Commit

Permalink
🔨 Auto mode for TEMPest (#28)
Browse files Browse the repository at this point in the history
* 🚧 Moved configs files for TEMpest into a directory
	[+] Added .sh for auto-mode
	--> Issues related: #24, #15
* Handler for shutup mode made, need merge
* Stash pop
* 🏁 Added tests for shutup mode handler (start.go)
	-> Issues related: #15, #16
* ✔️🏁 Added logs flag for get command
	[+] Added the corresponding test
	--> Issues related: #15, #16
* ✔️ Added handler for relative paths with ``add``
* 🏁 Added tests for treatRelativePath()
* 🏁 Test for getAllLogs() (--logs)
	--> Issues related: #15, #16
	[*] Should be the end of the Linux part for this one
* 💻 Windows autostart kinda done for theoric part
	[#] Issues related: #15, #9
	[T] Unit tests for set.go:setAutoStart()
	[T] Runtime testing for Windows
* 📛 Hot fix for codecov chmod
* 🏁 Test only for error checks
	[I] #15, #16
	[T] More elaborated tests for setAutoStart()
	[#] Fixes #15
  • Loading branch information
ChacaS0 committed Apr 8, 2018
1 parent 30c9649 commit deec00c
Show file tree
Hide file tree
Showing 19 changed files with 663 additions and 99 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ before_install:
- go get -u github.com/golang/dep

script:
- chmod +x coverage.sh
- go install -v ./... && ./coverage.sh
- chmod +x scripts/coverage.sh
- go install -v ./... && ./scripts/coverage.sh
- go test -v -race ./...

after_success:
Expand Down
46 changes: 41 additions & 5 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"io/ioutil"
"log"
"os"
"regexp"
"strings"

"github.com/spf13/viper"
Expand Down Expand Up @@ -107,13 +108,14 @@ func addLine(args []string) error {
}
defer tmpcf.Close()

// Fetch current directory
this, errDir := os.Getwd()
if errDir != nil {
log.Fatal(errDir)
}

// if no args
if len(args) == 0 {
// Fetch current directory
this, errDir := os.Getwd()
if errDir != nil {
log.Fatal(errDir)
}
// Check if already exists
sliceThis := make([]string, 1)
sliceThis[0] = this
Expand Down Expand Up @@ -143,6 +145,9 @@ func addLine(args []string) error {
fmt.Println(redB("::"), color.RedString("Can't add this target, check it does exist >>"), path)
return errors.New("")
}
// In case it is a relative path
treatRelativePath(&path, this)

// Add all the paths passed in the file
nbBytes, errWS := tmpcf.WriteString(path + "\n")
if errWS != nil {
Expand All @@ -156,6 +161,37 @@ func addLine(args []string) error {
return nil
}

// treatRelativePath treats a string in case it is a relative path.
// The func does check if it should act and does the action.
// if the first character is not a pathSeparator or the first two chars are ``./``
// It shall be replaced by the full path of the working directory followed by a path separator.
func treatRelativePath(path *string, workingDir string) {
// setup
var matchSimpleRel string
var matchDotRel string
workingDir += string(os.PathSeparator)

// regexes
// for match
regSimpleRel := regexp.MustCompile(`^([[:alpha:]]|[\d])`)
regDotRel := regexp.MustCompile(`^(\.(\/|\\))`)

// Matching
// Simple Relative path (with the form ``Documents/temp``)
matchSimpleRel = regSimpleRel.FindString(*path)
// Dot Relative path (with the form ``./Documents/temp``)
matchDotRel = regDotRel.FindString(*path)

switch {
case matchSimpleRel != "":
// replace
*path = regSimpleRel.ReplaceAllString(*path, workingDir+matchSimpleRel)
case matchDotRel != "":
// replace
*path = regDotRel.ReplaceAllString(*path, workingDir)
}
}

// checkRedondance returns true if a string is contained in both slices
// Eventually it is used to check if the path has already been set in ~/.tempestcf
// It also checks ``sliceArgs`` with ``sliceArgs`` to see if there were multiple same paths
Expand Down
38 changes: 38 additions & 0 deletions cmd/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,44 @@ func TestTreatLastChar(t *testing.T) {
}
}

// TestTreatRelativePath is the test for treatRelativePath(path *string, workDir string) {}.
// Should check if it uses full path to the working dir when adding relative paths.
// It should do nothing for full paths.
func TestTreatRelativePath(t *testing.T) {
// working directory
workDir, errDir := os.Getwd()
if errDir != nil {
t.Log("[ERROR]:: Can't retrieve the current directory", errDir)
t.FailNow()
}
// params
p1 := "./Downloads/temp"
p2 := "Documents/temp"
p3 := conf.Gopath
// wants
w1 := workDir + "/Downloads/temp"
w2 := workDir + "/" + p2

var tests = []struct {
path string
wkdir string
want string
errT error
}{
{p1, workDir, w1, errors.New("[FAIL]:: Can't process './' types")},
{p2, workDir, w2, errors.New("[FAIL]:: Can't process 'Doc/temp... types")},
{p3, workDir, p3, errors.New("[FAIL]:: Should have done nothing, yet did much")},
}

for _, tst := range tests {
treatRelativePath(&tst.path, tst.wkdir)
if tst.path != tst.want {
t.Log(tst.errT, "\n\t[GOT]-> ", tst.path, "\n\t[WANT]->", tst.want)
t.Fail()
}
}
}

// TestAddLine is the test for addLine(args []string) error {}
// Check if it does add the proper line to a .tempestcf file.
func TestAddLine(t *testing.T) {
Expand Down
33 changes: 33 additions & 0 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,19 @@ package cmd

import (
"fmt"
"io/ioutil"

"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// gAge is true if the user wants to know the age set in config
var gAge bool

// allLogs tells if the user wants to see logs
var allLogs bool

// getCmd represents the get command
var getCmd = &cobra.Command{
Use: "get",
Expand Down Expand Up @@ -60,6 +65,32 @@ func init() {
// getCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

getCmd.Flags().BoolVarP(&gAge, "age", "a", false, "Use this if you want to know the age set in .tempest.yaml")
getCmd.Flags().BoolVarP(&allLogs, "logs", "l", false, "Use this flag to view all logs")
}

// getAllLogs handle the use of ``logs`` flag.
// We assume that ``allLogs`` is sets to true when calling this func.
func getAllLogs(args []string) error {
// var declare
var showShutup bool

//* Setup rights for shutup
if len(args) == 0 {
showShutup = true
}

//* Display Log Shutup
if is, err := IsDirectory(LogShutup); !is && err == nil && showShutup {
// Fetch the content of LogShutup
fileCtnt, errRF := ioutil.ReadFile(LogShutup)
if errRF != nil {
fmt.Println(redB(":: [ERROR]"), color.HiRedString("Could not read the file -_-\n\t->", LogShutup, "\n\t->", errRF))
}
fmt.Println(magB("=========================================== - [ShutupLogs] - ==================================================="))
fmt.Println(string(fileCtnt))
fmt.Println(magB("======================================== - [EOF - ShutupLogs] - ================================================"))
}
return nil
}

// printAnyIfSet displays the config set for the ones asked.
Expand All @@ -69,6 +100,8 @@ func printAnyIfSet(args []string) {
case gAge:
// Age A.K.A. the duration
fmt.Println(blueB("::"), whiteB("Age:"), getAge())
case allLogs:
getAllLogs(args)
default:
// help ?
getHelp()
Expand Down
38 changes: 38 additions & 0 deletions cmd/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package cmd

import (
"fmt"
"io/ioutil"
"testing"

"github.com/fatih/color"
"github.com/spf13/viper"
)

Expand All @@ -28,3 +30,39 @@ func TestGetAge(t *testing.T) {
}

}

// TestGetAllLogs is the test for getAllLogs(args []string){}.
// It should display all the logs available
func TestGetAllLogs(t *testing.T) {
//setup
testAll = true
logshutupbup, _ := setTestLogShutup(t)

var want string

// styling
headerShutup := magB("=========================================== - [ShutupLogs] - ===================================================")
footerShutup := magB("======================================== - [EOF - ShutupLogs] - ================================================")

fileCtnt, errRF := ioutil.ReadFile(LogShutup)
if errRF != nil {
fmt.Println(redB(":: [ERROR]"), color.HiRedString("Could not read the file -_-\n\t->", LogShutup, "\n\t->", errRF))
}

// what we want
want += fmt.Sprintf("%v\n", headerShutup)
want += fmt.Sprintln(string(fileCtnt))
want += fmt.Sprintf("%v\n", footerShutup)

got := captureStdout(func() {
getAllLogs([]string{})
})

if got != want {
t.Log("[FAIL]:: Result is different than expected:\n\t[GOT] \n", got, "\n\t[WANT]\n", want)
t.Fail()
}

// fall back to previous conf
fbTestLogShutup(t, logshutupbup)
}
30 changes: 28 additions & 2 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,16 @@ This file will contain the list of all the directories you wish tempest to handl
`,
Run: func(cmd *cobra.Command, args []string) {
// ~/.tempest DIR
if err := initTempestDir(); err != nil {
fmt.Println(redB("::"), color.HiRedString("Sorry could not create the .tempest dir in "), conf.Home, "\n\t[ERROR]::", err)
return
}

// .tempest.yaml
if err := initializeCfFile(); err != nil {
fmt.Println(redB("::"), color.HiRedString("Could not initialize .tempest.yaml"))
fmt.Println(redB("::"), color.HiRedString("If the error persists, try to create the file manually : touch $HOME/.tempest.yaml"))
fmt.Println(redB("::"), color.HiRedString("If the error persists, try to create the file manually : touch $HOME/.tempest/.tempest.yaml"))
// fmt.Println(err) //DEBUG
return
}
Expand Down Expand Up @@ -82,6 +88,26 @@ func init() {
// initCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// initTempestDir init func for .tempest directory
func initTempestDir() error {
// remove if already exists
if is, err := IsDirectory(TempestConfigDir); is && err == nil {
if errRm := os.RemoveAll(TempestConfigDir); errRm != nil {
return errRm
}
}
// fmt.Println("conf dir deleted")
// Create the conf dir
if err := os.Mkdir(TempestConfigDir, 0755); err != nil {
return err
}
// fmt.Println("conf dir created")
// create the log dir
err := os.Mkdir(TempestConfigDir+string(os.PathSeparator)+".log", 0755)
// fmt.Println("log dir created if nil =>", err)
return err
}

// initializeTP creates the ~/.tempestcf file or
// empty it if already exists
func initializeTP() error {
Expand Down Expand Up @@ -119,7 +145,7 @@ auto-mode: false
if errDir == nil {
// if already exists, we delete

errDel := os.Remove(Tempestyml)
errDel := os.RemoveAll(Tempestyml)
if errDel != nil {
fmt.Println(redB("::"), color.RedString("Error while replacing existing file ("+Tempestyml+")"))
return errDel
Expand Down
Loading

0 comments on commit deec00c

Please sign in to comment.