diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index b5eecc3..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,11 +0,0 @@ -version: 2 -jobs: - build: - docker: - - image: 'circleci/golang:1.10.3' - working_directory: /go/src/github.com/kamontat/gitgo - steps: - - checkout - - run: go get -v -t -d ./... - - run: go test ./... -cover -coverprofile=coverage.txt -covermode=atomic - - run: 'bash <(curl -s https://codecov.io/bash)' diff --git a/.gitgo/config.yaml b/.gitgo/config.yaml deleted file mode 100755 index f7344a3..0000000 --- a/.gitgo/config.yaml +++ /dev/null @@ -1,4 +0,0 @@ -version: 3 -log: true -commit: - message: true diff --git a/.gitgo/list.yaml b/.gitgo/list.yaml deleted file mode 100755 index b58dfa9..0000000 --- a/.gitgo/list.yaml +++ /dev/null @@ -1,4 +0,0 @@ -version: 3 -list: - - type: empty - value: Update this commit header diff --git a/.gitignore b/.gitignore deleted file mode 100644 index efcc37d..0000000 --- a/.gitignore +++ /dev/null @@ -1,157 +0,0 @@ - -# Created by https://www.gitignore.io/api/emacs,go,godot,linux,macos,vim,visualstudiocode - -### Emacs ### -# -*- mode: gitignore; -*- -*~ -\#*\# -/.emacs.desktop -/.emacs.desktop.lock -*.elc -auto-save-list -tramp -.\#* - -# Org-mode -.org-id-locations -*_archive - -# flymake-mode -*_flymake.* - -# eshell files -/eshell/history -/eshell/lastdir - -# elpa packages -/elpa/ - -# reftex files -*.rel - -# AUCTeX auto folder -/auto/ - -# cask packages -.cask/ -dist/ - -# Flycheck -flycheck_*.el - -# server auth directory -/server/ - -# projectiles files -.projectile -projectile-bookmarks.eld - -# directory configuration -.dir-locals.el - -# saveplace -places - -# url cache -url/cache/ - -# cedet -ede-projects.el - -# smex -smex-items - -# company-statistics -company-statistics-cache.el - -# anaconda-mode -anaconda-mode/ - -### Go ### -# Binaries for programs and plugins -bin -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -test -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -### Godot ### -.import/ -.mono/ -export_presets.cfg - -### Linux ### - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -### macOS ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -### Vim ### -# swap -.sw[a-p] -.*.sw[a-p] -# session -Session.vim -# temporary -.netrwhist -# auto-generated tag files -tags - -### VisualStudioCode ### -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -.history - -### Go compiled ### -gitgo -build - -# End of https://www.gitignore.io/api/emacs,go,godot,linux,macos,vim,visualstudiocode - -coverage.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..259de67 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Gitgo - agile process management + +## What is this ? + +Basically, this is a `git commit` with `interactive prompt` that help you to create formatting commit message that able to use to generate `CHANGELOG` file and easy to read the same commit format. + +## Version + +I seperate each individual version into each branch (current 6 Feb 2019 is version 3.0.0) + +1. version 1 on [version/1.x.x](https://github.com/kamontat/gitgo/tree/version/1.x.x) +2. version 2 on [version/2.x.x](https://github.com/kamontat/gitgo/tree/version/2.x.x) +3. version 3 on [version/3.x.x](https://github.com/kamontat/gitgo/tree/version/3.x.x) diff --git a/build.sh b/build.sh deleted file mode 100755 index 409571e..0000000 --- a/build.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC1000 - -# generate by v3.0.2 -# link (https://github.com/Template-generator/script-genrating/tree/v3.0.2) - -# set -x #DEBUG - Display commands and their arguments as they are executed. -# set -v #VERBOSE - Display shell input lines as they are read. -# set -n #EVALUATE - Check syntax of the script but don't execute. - -#/ ----------------------------------- -#/ Description: generate build of gitgo command to several OS -#/ ----------------------------------- -#/ Create by: Kamontat Chantrachirathunrong -#/ Since: 16/08/2018 -#/ ----------------------------------- - -export APPNAME="gitgo" - -mkdir ./build/ &>/dev/null - -process() { - local cmd="$1" - local title="$2" - shift 2 - IFS=" " read -r -a array <<<"$@" - duration=$# - - curr_bar=0 - for ((elapsed = 1; elapsed <= duration; elapsed++)); do - barsize=$(($(tput cols) - 17)) - unity=$((barsize / duration)) - increment=$((barsize % duration)) - skip=$((duration / (duration - increment))) - # Elapsed - ((curr_bar += unity)) - - if [[ $increment -ne 0 ]]; then - if [[ $skip -eq 1 ]]; then - [[ $((elapsed % (duration / increment))) -eq 0 ]] && ((curr_bar++)) - else - [[ $((elapsed % skip)) -ne 0 ]] && ((curr_bar++)) - fi - fi - - [[ $elapsed -eq 1 && $increment -eq 1 && $skip -ne 1 ]] && ((curr_bar++)) - [[ $((barsize - curr_bar)) -eq 1 ]] && ((curr_bar++)) - [[ $curr_bar -lt $barsize ]] || curr_bar=$barsize - - printf "%-7s |" "$title" - - # Exection - "$cmd" "${array[elapsed - 1]}" - - # Progress - for ((filled = 0; filled <= curr_bar; filled++)); do - printf "#" - done - - # Remaining - for ((remain = curr_bar; remain < barsize; remain++)); do - printf " " - done - - # Percentage - printf "| %s%%" $(((elapsed * 100) / duration)) - - # Return - printf '\r' - done - echo -} - -build() { - local input="${1}" - local os="${input%%,*}" - local arch="${input##*,}" - local ext=".sh" - - [[ "$os" == "windows" ]] && ext=".exe" - [[ "$os" == "darwin" ]] && ext=".sh" - - local filename="./build/${APPNAME}.${os}.${arch}${ext}" - env GOOS="$os" GOARCH="$arch" go build -o "$filename" &>/dev/null -} - -process go "Go Run" "build" "install" - -process build "MacOS" "darwin,386" "darwin,amd64" - -process build "Window" "windows,386" "windows,amd64" - -process build "Linux" "linux,386" "linux,amd64" "linux,arm" "linux,arm64" "solaris,amd64" - -process build "bsd" "openbsd,386" "openbsd,amd64" "openbsd,arm" "freebsd,386" "freebsd,amd64" "freebsd,arm" "netbsd,386" "netbsd,amd64" "netbsd,arm" diff --git a/cmd/commit.go b/cmd/commit.go deleted file mode 100644 index 5818e48..0000000 --- a/cmd/commit.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -// Package cmd is the default package of commands provide by cobra cli. -package cmd - -import ( - "strings" - - "github.com/spf13/viper" - - "github.com/kamontat/go-log-manager" - "github.com/spf13/cobra" -) - -// commitCmd represents the commit command -var commitCmd = &cobra.Command{ - Use: "commit", - Aliases: []string{"c"}, - Short: "Git commit with format string", - Long: ``, - Run: func(cmd *cobra.Command, args []string) { - om.Log.ToLog("commit", "start...") - - if all { - throw := repo.AddAll() - throw.ShowMessage() - } else { - if len(add) > 0 { - om.Log.ToDebug("commit", "add files ["+strings.Join(add, ", ")+"]") - repo.Add(add).ShowMessage() - } - } - - hasMessage := viper.GetBool("commit.message") - if hasMessage { - om.Log.ToVerbose("commit", "with message") - } else { - om.Log.ToVerbose("commit", "without message") - } - repo.GetCommit(dry).LoadList(globalList).MergeList(localList).Commit(hasMessage) - }, -} - -var add []string -var all bool -var dry bool - -func init() { - rootCmd.AddCommand(commitCmd) - - commitCmd.PersistentFlags().StringArrayVarP(&add, "add", "a", []string{}, "Commit with add [multiple use]") - commitCmd.PersistentFlags().BoolVarP(&all, "all", "A", false, "Commit with add all") - - commitCmd.PersistentFlags().BoolVarP(&dry, "dry", "d", false, "dry run will show only the commit message, but not commit anything") -} diff --git a/cmd/config.go b/cmd/config.go deleted file mode 100644 index 6467367..0000000 --- a/cmd/config.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -package cmd - -import ( - "github.com/skratchdot/open-golang/open" - - "github.com/kamontat/go-log-manager" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - inGlobal bool - inLocal bool -) - -// configCmd represents the config command -var configCmd = &cobra.Command{ - Use: "config", - Aliases: []string{"C", "configuration"}, - Short: "Gitgo configuration", - Long: ``, - Run: func(cmd *cobra.Command, args []string) { - om.Log.ToLog("config", "start...") - - open.Run(viper.ConfigFileUsed()) - }, -} - -func init() { - rootCmd.AddCommand(configCmd) - - configCmd.PersistentFlags().BoolVarP(&inLocal, "local", "l", false, "initial configuration file in local") - configCmd.PersistentFlags().BoolVarP(&inGlobal, "global", "g", false, "initial configuration file in global") -} diff --git a/cmd/configInitial.go b/cmd/configInitial.go deleted file mode 100644 index a53f947..0000000 --- a/cmd/configInitial.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -package cmd - -import ( - "errors" - "os" - "path/filepath" - - "github.com/kamontat/gitgo/model" - - manager "github.com/kamontat/go-error-manager" - "github.com/kamontat/go-log-manager" - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" -) - -var initialForce bool - -// configInitialCmd represents the configInitial command -var configInitialCmd = &cobra.Command{ - Use: "init", - Aliases: []string{"i", "initial"}, - Short: "Create and initial gitgo configuration files", - Long: ``, - Run: func(cmd *cobra.Command, args []string) { - om.Log.ToLog("config", "initial start...") - yaml := model.GeneratorYAML() - - if initialForce { - om.Log.ToVerbose("config", "initial with force") - } - - init := false - var file *manager.ResultWrapper - - if inLocal { - file = getFile(getLPath("config.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.GDefaultConfig()) - }).Catch(func() error { - return errors.New("Cannot save config.yaml in local") - }, throw) - - file = getFile(getLPath("list.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.LEmptyList()) - }).Catch(func() error { - return errors.New("Cannot save list.yaml in local") - }, throw) - - init = true - } - - if inGlobal { - file = getFile(getGPath("config.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.GDefaultConfig()) - }).Catch(func() error { - return errors.New("Cannot save config.yaml in global") - }, throw) - - file = getFile(getGPath("list.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.GDefaultList()) - }).Catch(func() error { - return errors.New("Cannot save list.yaml in global") - }, throw) - - init = true - } - - if !init { - file = getFile(getGPath("config.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.GDefaultConfig()) - }).Catch(func() error { - return errors.New("Cannot save config.yaml in global") - }, throw) - - file = getFile(getGPath("list.yaml")) - file.Unwrap(func(i interface{}) { - writeTo(i.(*os.File), yaml.GDefaultList()) - }).Catch(func() error { - return errors.New("Cannot save list.yaml in global") - }, throw) - } - }, -} - -func getGPath(filename string) *manager.ResultWrapper { - return manager.StartResultManager().Exec02(homedir.Dir).IfResultThen(func(home string) interface{} { - path := filepath.Join(home, ".gitgo", filename) - os.MkdirAll(filepath.Dir(path), os.ModePerm) - return path - }) -} - -func getLPath(filename string) *manager.ResultWrapper { - return manager.StartResultManager().Exec12(filepath.Abs, ".").IfResultThen(func(home string) interface{} { - path := filepath.Join(home, ".gitgo", filename) - os.MkdirAll(filepath.Dir(path), os.ModePerm) - return path - }) -} - -func getFile(path *manager.ResultWrapper) *manager.ResultWrapper { - return path.UnwrapNext(func(i interface{}) interface{} { - om.Log.ToDebug("config", "start initial path ") - - f, _ := os.OpenFile(i.(string), os.O_CREATE|os.O_WRONLY, os.ModePerm) - return f - }) -} - -func isFileExist(file *os.File) *manager.ErrManager { - i, e := file.Stat() - m := manager.NewE().Add(e) - if i.Size() <= 0 { - m.AddMessage("File size is 0 (file empty)") - } - return m -} - -func writeTo(file *os.File, str string) { - e := isFileExist(file) - if initialForce || !e.HaveError() { - _, err := file.WriteString(str) - - e.Add(err) - e.Throw().ShowMessage().ExitWithCode(11) - - om.Log.ToInfo("config", "Done @"+file.Name()) - } else { - om.Log.ToWarn("config", "Exist @"+file.Name()) - } -} - -func throw(throw *manager.Throwable) { - throw.ShowMessage().ExitWithCode(len(throw.ListErrors())) -} - -func init() { - configCmd.AddCommand(configInitialCmd) - - configInitialCmd.Flags().BoolVarP(&initialForce, "force", "f", false, "force initial even file exist") -} diff --git a/cmd/configOpen.go b/cmd/configOpen.go deleted file mode 100644 index ccc6c4c..0000000 --- a/cmd/configOpen.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -package cmd - -import ( - "path" - - "github.com/kamontat/go-log-manager" - "github.com/skratchdot/open-golang/open" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var parent bool - -// configOpenCmd represents the configOpen command -var configOpenCmd = &cobra.Command{ - Use: "open", - Aliases: []string{"o"}, - Short: "open config in your default editor", - Long: ``, - Run: func(cmd *cobra.Command, args []string) { - om.Log.ToLog("config", "open start...") - - if inLocal { - if parent { - om.Log.ToVerbose("config", "On local parent") - open.Run(path.Dir(localList.ConfigFileUsed())) - } else { - om.Log.ToVerbose("config", "On local list") - open.Run(localList.ConfigFileUsed()) - } - } else if inGlobal { - if parent { - om.Log.ToVerbose("config", "on global parent") - open.Run(path.Dir(globalList.ConfigFileUsed())) - } else { - om.Log.ToVerbose("config", "on global list") - open.Run(globalList.ConfigFileUsed()) - } - } else { - om.Log.ToVerbose("config", "on using config") - open.Run(viper.ConfigFileUsed()) - } - }, -} - -func init() { - configCmd.AddCommand(configOpenCmd) - - configOpenCmd.Flags().BoolVarP(&parent, "parent", "p", false, "open folder instead of config file") -} diff --git a/cmd/root.go b/cmd/root.go deleted file mode 100644 index 5d7628d..0000000 --- a/cmd/root.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -package cmd - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "regexp" - - "github.com/kamontat/gitgo/model" - - "github.com/kamontat/go-error-manager" - "github.com/kamontat/go-log-manager" - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var globalList *viper.Viper -var localList *viper.Viper - -var repo *model.Repo -var debug bool -var verbose bool - -// rootCmd represents the base command when called without any subcommands. -var rootCmd = &cobra.Command{ - Use: "gitgo", - Short: "gitgo command by Kamontat Chantrachurathumrong", - Version: "3.0.0", -} - -// Execute is execute method that call by cobra cli. -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } -} - -func init() { - cobra.OnInitialize(initLogger, initConfig, setOutput, initGlobalList, initLocalList, initRepository) - - rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, "add debug output") - rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "V", false, "add verbose output") -} - -func initLogger() { - om.ConstrantExitOnError = false - om.ConstrantAppName = "gitgo" - - om.SetupNewLogger(&om.Setting{ - Color: true, - Level: om.LLevelInfo, - }) -} - -func setOutput() { - if debug { - om.Log.Setting().SetMaximumLevel(om.LLevelDebug) - om.Log.ToDebug("set", "debug mode") - } - - if verbose { - om.Log.Setting().SetMaximumLevel(om.LLevelVerbose) - om.Log.ToVerbose("set", "verbose mode") - } -} - -func initGlobalList() { - om.Log.ToVerbose("init", "global list") - - manager.StartResultManager().Exec02(homedir.Dir).IfError(func(t *manager.Throwable) { - t.ShowMessage().ExitWithCode(3) - }).IfResult(func(home string) { - globalList = viper.New() - globalList.SetConfigFile(home + "/.gitgo/list.yaml") - - if !manager.NewE().Add(globalList.ReadInConfig()).HaveError() { - om.Log.ToDebug("Global list", globalList.ConfigFileUsed()) - - configVersionChecker(globalList) - } - }) -} - -func initLocalList() { - om.Log.ToVerbose("init", "local list") - - manager.StartResultManager().Exec12(filepath.Abs, ".").IfError(func(t *manager.Throwable) { - t.ShowMessage().ExitWithCode(4) - }).IfResult(func(home string) { - localList = viper.New() - localList.SetConfigFile(home + "/.gitgo/list.yaml") - - if !manager.NewE().Add(localList.ReadInConfig()).HaveError() { - om.Log.ToDebug("Local list", localList.ConfigFileUsed()) - - configVersionChecker(localList) - } - }) -} - -// initConfig reads in config file and ENV variables if set. -func initConfig() { - om.Log.ToVerbose("init", "config") - - manager.StartResultManager().Exec02(homedir.Dir).IfError(func(t *manager.Throwable) { - t.ShowMessage().ExitWithCode(2) - }).IfResult(func(home string) { - // Search config in home directory with name ".xyz" (without extension). - viper.SetConfigType("yaml") - viper.SetConfigName("config") - viper.AddConfigPath("./.gitgo") - viper.AddConfigPath(home + "/.gitgo") - - viper.SetEnvPrefix("GG") - viper.AutomaticEnv() // read in environment variables that match - - if !manager.NewE().Add(viper.ReadInConfig()).HaveError() { - om.Log.ToDebug("Config file", viper.ConfigFileUsed()) - - manager.Wrap(viper.Get("log")).UnwrapNext(func(i interface{}) interface{} { - return viper.GetBool("log") - }).Unwrap(func(log interface{}) { - if !log.(bool) { - om.Log.ToVerbose("log setting", "none of output will be print") - om.Log.Setting().SetMaximumLevel(om.LLevelNone) - } - }) - - configVersionChecker(nil) - } - }) -} - -func initRepository() { - om.Log.ToVerbose("init", "repository") - repo = model.NewRepo() - repo.Setup() -} - -func configVersionChecker(vp *viper.Viper) bool { - var v string - var cv string - - v = rootCmd.Version - if vp == nil { - cv = viper.GetString("version") - } else { - cv = vp.GetString("version") - } - m, e := regexp.MatchString(cv, v) - var ee error - if !m { - ee = errors.New(`config version not matches ( ` + v + ` !== ` + cv + ` )`) - } - - manager.NewE().AddNewError(e).AddNewError(ee).Throw(). - ShowMessage().ExitWithCode(10) - - return true -} diff --git a/deploy.sh b/deploy.sh deleted file mode 100755 index 174584e..0000000 --- a/deploy.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC1000 - -# generate by v3.0.2 -# link (https://github.com/Template-generator/script-genrating/tree/v3.0.2) - -# set -x #DEBUG - Display commands and their arguments as they are executed. -# set -v #VERBOSE - Display shell input lines as they are read. -# set -n #EVALUATE - Check syntax of the script but don't execute. - -#/ ----------------------------------- -#/ Description: ... -#/ How to: ... -#/ ... -#/ Option: --help | -h | -? | help | h | ? -#/ > show this message -#/ --version | -v | version | v -#/ > show command version -#/ ----------------------------------- -#/ Create by: Kamontat Chantrachirathunrong -#/ Since: 16/08/2018 -#/ ----------------------------------- -#/ Error code 1 -- error -#/ ----------------------------------- -#/ Known bug: ... -#/ ----------------------------------- -#// Version: 0.0.1 -- description -#// 0.0.2b1 -- beta-format -#// 0.0.2a1 -- alpha-format - -go install - -gitgo --version - -printf "press to next" -# shellcheck disable=SC2034 -read -r ans - -git status -printf "Git status; press to next" -read -r ans - -tag="v$(gitgo --version | sed -e 's/gitgo version //g')" -git add -A -git commit -m "[release] Version $tag" - -printf "create tag %s; press to next" "$tag" -# shellcheck disable=SC2034 -read -r ans - -git tag "$tag" - -./build.sh -./docs.sh - -git add -A -git commit -m "[doc] Update documents (docs)" - -git push && - git push --tag - -printf "create pull-request; press to next" -# shellcheck disable=SC2034 -read -r ans - -command -v "hub" &>/dev/null && - hub pull-request -m "create pull request to release latest version $tag" -b master diff --git a/docs.sh b/docs.sh deleted file mode 100755 index a5591a3..0000000 --- a/docs.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC1000 - -# generate by v3.0.2 -# link (https://github.com/Template-generator/script-genrating/tree/v3.0.2) - -# set -x #DEBUG - Display commands and their arguments as they are executed. -# set -v #VERBOSE - Display shell input lines as they are read. -# set -n #EVALUATE - Check syntax of the script but don't execute. - -#/ ----------------------------------- -#/ Description: generate docs of gitgo command to several OS -#/ ----------------------------------- -#/ Create by: Kamontat Chantrachirathunrong -#/ Since: 16/08/2018 -#/ ----------------------------------- - -printf "Generate godoc | " -godoc -html . >docs/godoc.html && echo "Completed" || echo "Failure" - -printf "Generate changelog | " -git changelog --all --prune-old --stdout >docs/changelog.md && echo "Completed" || echo "Failure" - -printf "Generate summary | " -echo "# Summary" >docs/summary.txt && - git summary >>docs/summary.txt && - echo "## Lines report" >>docs/summary.txt && - echo >>docs/summary.txt && - git summary --line | grep -A 100 "lines" >>docs/summary.txt && - echo "Completed" || - echo "Failure" diff --git a/docs/changelog.md b/docs/changelog.md deleted file mode 100644 index 5abb8c9..0000000 --- a/docs/changelog.md +++ /dev/null @@ -1,161 +0,0 @@ - -n.n.n / 2018-08-23 -================== - - * [merge] GH version to local version - * [fix] Fix wrong path - * [config] Update go version - * [config] Update circle ci error - * [fix] Fix during to lib changes - * [improve] Add 2 more list init, release - * [improve] Add go build to build script - * [lib] Update library changes - * [doc] Update documents (docs) - -v2.0.2 / 2018-08-21 -=================== - - * [improve] Update version variable - * [refactor] Clean code and Add test, Setup CI - * [feature] Update to support error and log library - * [doc] Update documents - * [script] Update deploy script - * [doc] Update error message and godoc - * [fix] Fix condition - * [] Fix header is too long - * [fix] Fix list error by wrong config format - * [algo] Change logic of deploy - -v2.0.1 / 2018-08-16 -=================== - - * [release] Version v2.0.1 - * [release] Version 2.0.1 - * [fix] Fix list config in local file should be empty - * [fix] Fix config initial error when no local files - * [doc : Documenting source code / user manual.] Update document - * [config] Update default config files - * [config] Update default config files - * [doc] Update documents - * [config] Update default config - -v2.0.0 / 2018-08-16 -=================== - - * [release] Version 2.0.0 - * [refactor] Clean code - * [feature] Add config open and initial - * [log] Update log file output - * [model] Enable commit code - * [refactor] Update root code - * [model] Update commit and completed - * [config] Update gitgo config file - * [feature] Add commit subcommand, but not key list yet. - * [init] Start project - -v1.4.1 / 2018-06-25 -=================== - - * [release]: Release version 1.4.1 - * [config] Change default configuration - * [release]: Release version 1.4.0, - * [bug] Fix config file error while creating - * [release]: Release new version 1.4.0-beta.3 - * [improve]: Add and Improve testing code, - * [release]: Release new version 1.4.0-beta.2 - * [fix] Fix git message not found! - * []: - -1.4.0-alpha.1 / 2018-05-05 -========================== - - * [release]: Release 1.4.0-alpha.1, Add new emoji APIs - * [improve]: Improve git commit logic - * [improve]: Update prompt library, use survey instead - * [doc]: Update documents - -1.3.0-beta.1 / 2018-04-11 -========================= - - * [release]: Release new version 1.3.0-beta.1 - * [feature]: Implemented git commit release, Not test yet! - * [doc]: Remove unused USAGE file - * [improve]: Add script for build binary code - * [doc] CREATE LICENSE - * [doc] Update LICENSE in README file - * Merge branch 'master' of https://github.com/kamontat/gitgo - * [doc] Add README.md - * [fix]: Fix pull errors, Fix pull error when specify branch and add missing options - -1.3.0-alpha.1 / 2018-04-11 -========================== - - * [feature]: Add commit release and push deploy subcommands, Not implement yet!!! - * [improve]: Improve commit, push algorithm, Improve code, Add documents, Add validator to init commit - -1.1.6 / 2018-04-10 -================== - - * [doc]: Release v1.1.6, Fix errors - * [fix]: Fix push with branch, This push command ignore first input - * [fix]: Update commit initial commands, fix a bug - * [fix]: Fix wrong path in prod env, when import we should add prefix (github) - -1.1.4 / 2018-04-10 -================== - - * [fix]: Fix initial commit nothing appear - -1.1.3 / 2018-04-07 -================== - - * [doc]: Update version in docs, To version 1.1.3 - * [fix]: Fix commit got wrong format, and update documentation - * [docs]: Update documents of cli, - * [improve]: improve code and clean them~, - * [improve]: Clean and update code, - * [doc]: Update version number, 1.1.2, - * [improve]: Update commit format, - * [improve]: add helper docs in yaml user config, - * [improve]: colorize output of git status, - * [feature]: Add auto install config, and update documents, - * [fix]: Fix config error, get config not throw, if key not found - * [feature]: Add management about config file, set is NOT implement yet! - * [fix]: Fix title not prompt, Title don't prompt even user set non-auto title settings - * [improve]: improve default config file - * [improve]: Improvement, Update code - * [feature]: Add new features, Add open config by editor - * [feature]: Add new features, Add config location command - * [feature]: Add new features, Add auto initial commit - * [init]: Initial commit, commit! - -1.0.0-beta.2 / 2018-04-04 -========================= - - * [config]: Update config update version in config and fix type in commit - * [feature]: GitAdd new features add git status feature - * [📈]: Improvement update code on commit design - * [📈]: Improvement - * "[emoji-icon]: Update config Updated" - * "[log]: Log Remove logging" - * "[feature]: GitAdd new features Add commit by text command!" - * [database] setup database - * [docs] Update commands documents - * [feature] Add pull feature - -0.0.1-alpha.6 / 2018-04-03 -========================== - - * [feature] completed push feature, and improve usability code - -0.0.1-alpha.5 / 2018-04-03 -========================== - - * [feature] Add set-push and improvement code - -0.0.1-alpha.3 / 2018-04-02 -========================== - - * [config] Update version 0.0.1-alpha.3 - * [config] Update gitignore - * [config] Start project diff --git a/docs/godoc.html b/docs/godoc.html deleted file mode 100644 index 556b7a5..0000000 --- a/docs/godoc.html +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - -

Subdirectories

- - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameSynopsis
..
- build - - -
- cmd - - -
- docs - - -
- model - - -
-
- - - - diff --git a/docs/summary.txt b/docs/summary.txt deleted file mode 100644 index 2c5cc6f..0000000 --- a/docs/summary.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Summary - - project : gitgo - repo age : 9 days - active : 6 days - commits : 38 - files : 26 - authors : - 38 Kamontat Chantrachirathumrong 100.0% - -## Lines report - - lines : 1951 - authors : - 1937 Kamontat Chantrachirathumrong 99.3% - 14 Not Committed Yet 0.7% - - diff --git a/main.go b/main.go deleted file mode 100644 index 39335d2..0000000 --- a/main.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2018 Kamontat Chantrachirathumrong -// -// 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. - -package main - -import "github.com/kamontat/gitgo/cmd" - -func main() { - cmd.Execute() -} diff --git a/model/commit.go b/model/commit.go deleted file mode 100644 index 867921d..0000000 --- a/model/commit.go +++ /dev/null @@ -1,189 +0,0 @@ -// Package model provides the model of repository and commit. -// As long as another model that will be use in gitgo command. -package model - -import ( - "fmt" - "strconv" - - "github.com/kamontat/go-error-manager" - - "github.com/spf13/viper" - - "github.com/kamontat/go-log-manager" - survey "gopkg.in/AlecAivazis/survey.v1" -) - -// Commit is Commit object of deal with commit things. -type Commit struct { - throwable *manager.Throwable - list []CommitHeader - options struct { - dry bool - } -} - -// CanCommit mean this commit contain no errors -func (c *Commit) CanCommit() bool { - return !c.throwable.CanBeThrow() -} - -// ListHeaderOptions return the list of string of commit that create by Format() method in CommitHeader. -func (c *Commit) ListHeaderOptions() *manager.ResultWrapper { - var list []string - for _, commits := range c.list { - list = append(list, commits.Format()) - } - om.Log.ToVerbose("commit list", list) - wrap := manager.WrapNil() - if len(list) > 0 { - wrap = manager.Wrap(list) - } - - return wrap -} - -func (c *Commit) getQuestion() *manager.ResultWrapper { - return c.ListHeaderOptions().UnwrapNext(func(i interface{}) interface{} { - return []*survey.Question{ - { - Name: "type", - Prompt: &survey.Select{ - Message: "Select commit header", - Options: i.([]string), - Help: "Header will represent 'one word' type of the commit", - PageSize: 5, - VimMode: true, - }, - Validate: survey.Required, - }, { - Name: "scope", - Prompt: &survey.Input{ - Message: "Enter commit scope", - Help: "Message should represent the scope of commit type", - }, - }, { - Name: "title", - Prompt: &survey.Input{ - Message: "Enter commit title", - Help: "Title will represent one short sentence of the commit", - }, - Validate: func(val interface{}) error { - err := survey.Required(val) - if err == nil { - err = survey.MaxLength(50)(val) - } - return err - }, - }, { - Name: "hasMessage", - Prompt: &survey.Confirm{ - Message: "Do you have commit message?", - }, - }, - } - }) -} - -// LoadList will initial new list of Header. -func (c *Commit) LoadList(vp *viper.Viper) *Commit { - if vp == nil { - om.Log.ToDebug("commit list", "viper is nil, cannot load list") - return c - } - - // reset list - c.list = []CommitHeader{} - - om.Log.ToDebug("commit list", "load commit list from "+vp.ConfigFileUsed()) - return c.MergeList(vp) -} - -// MergeList will merge current list to the new ones. -func (c *Commit) MergeList(vp *viper.Viper) *Commit { - if vp == nil { - om.Log.ToVerbose("commit list", "viper is nil, cannot merge list") - return c - } - if c.list == nil { - c.list = []CommitHeader{} - } - - if vp.Get("list") == nil { - return c - } - - om.Log.ToVerbose("commit list", "merge commit list from "+vp.ConfigFileUsed()) - for i, element := range vp.Get("list").([]interface{}) { - cm := element.(map[interface{}]interface{}) - - commitHeader := CommitHeader{ - Type: cm["type"].(string), - Value: cm["value"].(string), - } - - om.Log.ToVerbose("header "+strconv.Itoa(i), commitHeader.String()) - c.list = append(c.list, commitHeader) - } - - return c -} - -// Commit is action for ask the message from user and call CustomCommit. -func (c *Commit) Commit(hasMessage bool) { - // the questions to ask - var result = c.getQuestion() - - result.Unwrap(func(i interface{}) { - qs := i.([]*survey.Question) - - if !hasMessage { - qs = qs[:len(qs)-1] - } - - om.Log.ToDebug("question list", strconv.Itoa(len(qs))) - - answers := CommitMessage{Message: "", HasMessage: false} - manager.StartResultManager().Save("", survey.Ask(qs, &answers)).IfNoError(func() { - if answers.HasMessage { - messageQuestion := &survey.Multiline{ - Message: "Enter commit message", - Help: "Message will represent everything that commit have done", - } - survey.AskOne(messageQuestion, &answers.Message, nil) - } - - om.Log.ToDebug("commit type", answers.GetType()) - om.Log.ToDebug("commit scope", answers.Scope) - om.Log.ToDebug("commit title", answers.Title) - om.Log.ToDebug("has commit message", answers.HasMessage) - om.Log.ToDebug("commit message", answers.Message) - - c.CustomCommit(answers) - - }).IfError(func(t *manager.Throwable) { - t.GetCustomMessage(func(errs []error) string { - for i, e := range errs { - om.Log.ToError(strconv.Itoa(i)+")", e.Error()) - } - return "" - }) - }) - }) -} - -// CustomCommit will run git commit -m "" with the default format. -func (c *Commit) CustomCommit(answers CommitMessage) { - var commitMessage string - - if answers.Scope != "" { - answers.Scope = "(" + answers.Scope + ")" - } - - commitMessage = fmt.Sprintf("%s%s: %s\n%s", answers.GetType(), answers.Scope, answers.Title, answers.Message) - om.Log.ToInfo("Commit", commitMessage) - - if !c.options.dry { - Git().Exec("commit", "-m", commitMessage) - } -} diff --git a/model/commit_header.go b/model/commit_header.go deleted file mode 100644 index 0dc1b15..0000000 --- a/model/commit_header.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import "fmt" - -// CommitHeader is struct of Key and Value, using in list.yaml. -type CommitHeader struct { - Type string - Value string -} - -// Format will return format of string. -func (c *CommitHeader) Format() string { - return fmt.Sprintf("%-10s: %s", c.Type, c.Value) -} - -// String will return string that show what is it. -func (c *CommitHeader) String() string { - return fmt.Sprintf("commit type=%s, value=%s", c.Type, c.Value) -} diff --git a/model/commit_message.go b/model/commit_message.go deleted file mode 100644 index dab5f7c..0000000 --- a/model/commit_message.go +++ /dev/null @@ -1,23 +0,0 @@ -package model - -import "strings" - -// CommitMessage is the commit message for save in commit. -type CommitMessage struct { - Type string - Scope string - Title string - HasMessage bool - Message string -} - -// GetType will try to format the type to right way. -// Otherwise, return normal Type -func (c *CommitMessage) GetType() string { - arr := strings.Split(c.Type, ":") - if len(arr) > 0 { - s := arr[0] - return strings.TrimSpace(s) - } - return c.Type -} diff --git a/model/config.go b/model/config.go deleted file mode 100644 index c7933e0..0000000 --- a/model/config.go +++ /dev/null @@ -1,50 +0,0 @@ -package model - -// YAML is object of config yaml -type YAML struct{} - -// GeneratorYAML will return YAML Object -func GeneratorYAML() *YAML { - return &YAML{} -} - -// GDefaultConfig is global default config.yaml -func (y *YAML) GDefaultConfig() string { - return `version: 3 -log: true -commit: - message: true -` -} - -// GDefaultList is global default list.yaml -func (y *YAML) GDefaultList() string { - return `version: 3 -list: - - type: feature - value: Introducing new features. - - type: improve - value: Improving user experience / usability / performance. - - type: fix - value: Fixing a bug. - - type: refactor - value: Refactoring code. - - type: file - value: Updating file(s) or folder(s). - - type: doc - value: Documenting source code / user manual. - - type: init - value: Start project or Initial commit. - - type: release - value: Release stable version or tags. -` -} - -// LEmptyList is empty list.yaml -func (y *YAML) LEmptyList() string { - return `version: 3 -list: - - type: empty - value: Update this commit header -` -} diff --git a/model/config_test.go b/model/config_test.go deleted file mode 100644 index 858cac2..0000000 --- a/model/config_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package model_test - -import ( - "testing" - - "github.com/kamontat/gitgo/model" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestConfig(t *testing.T) { - Convey("Given config yaml object", t, func() { - yaml := model.GeneratorYAML() - - Convey("When check", func() { - Convey("Then shouldn't be empty or nil", func() { - So(yaml, ShouldNotBeNil) - }) - }) - - Convey("When check global default config", func() { - g := yaml.GDefaultConfig() - - Convey("Then it should contain version", func() { - So(g, ShouldContainSubstring, "version: ") - }) - - Convey("Then it should contain log setting", func() { - So(g, ShouldContainSubstring, "log: true") - }) - - Convey("Then it should contain commit.message setting", func() { - So(g, ShouldContainSubstring, "message: false") - }) - }) - - Convey("When check global default list", func() { - g := yaml.GDefaultList() - - Convey("Then it should contain version", func() { - So(g, ShouldContainSubstring, "version: ") - }) - - Convey("Then it should contain list array", func() { - So(g, ShouldContainSubstring, "list:") - So(g, ShouldContainSubstring, "- type: ") - So(g, ShouldContainSubstring, "value: ") - }) - - Convey("Then it should contain some default list", func() { - So(g, ShouldContainSubstring, "feature") - So(g, ShouldContainSubstring, "improve") - So(g, ShouldContainSubstring, "fix") - }) - }) - - Convey("When check local empty list", func() { - g := yaml.LEmptyList() - - Convey("Then it should contain version", func() { - So(g, ShouldContainSubstring, "version: ") - }) - - Convey("Then it should contain list array", func() { - So(g, ShouldContainSubstring, "list:") - So(g, ShouldContainSubstring, "- type: ") - So(g, ShouldContainSubstring, "value: ") - }) - }) - }) -} diff --git a/model/git.go b/model/git.go deleted file mode 100644 index c4fb91c..0000000 --- a/model/git.go +++ /dev/null @@ -1,71 +0,0 @@ -package model - -import ( - "io" - "os" - "os/exec" - - "github.com/kamontat/go-error-manager" - "github.com/kamontat/go-log-manager" -) - -// GitCommand is git-cli command with custom stdout and custom stderr -type GitCommand struct { - in io.Reader - out io.Writer - err io.Writer -} - -var gc = &GitCommand{} - -// Git will return singleton GitCommand -func Git() *GitCommand { - return gc -} - -// SetErrWriter will set err writer -func (g *GitCommand) SetErrWriter(err io.Writer) *GitCommand { - g.err = err - return g -} - -// SetOutWriter will set out writer -func (g *GitCommand) SetOutWriter(out io.Writer) *GitCommand { - g.out = out - return g -} - -// SetReader will set reader -func (g *GitCommand) SetReader(in io.Reader) *GitCommand { - g.in = in - return g -} - -// Exec will run git cli in command line -func (g *GitCommand) Exec(args ...string) *manager.ErrManager { - cmd := exec.Command("git", args...) - - if g.out != nil { - om.Log.ToVerbose("setting", "custom command output") - cmd.Stdout = g.out - } else { - cmd.Stdout = os.Stdout - } - - if g.err != nil { - om.Log.ToVerbose("setting", "custom command error") - cmd.Stderr = g.err - } else { - cmd.Stderr = os.Stderr - } - - if g.in != nil { - om.Log.ToVerbose("setting", "custom command input") - cmd.Stdin = g.in - } else { - cmd.Stdin = os.Stdin - } - - e := cmd.Run() - return manager.NewE().Add(e) -} diff --git a/model/git_test.go b/model/git_test.go deleted file mode 100644 index 3a41f58..0000000 --- a/model/git_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package model_test - -import ( - "bytes" - "testing" - - "github.com/kamontat/go-log-manager" - - "github.com/kamontat/gitgo/model" - . "github.com/smartystreets/goconvey/convey" -) - -func TestGitCommand(t *testing.T) { - om.SetupNewLogger(&om.Setting{Color: false, Level: om.LLevelVerbose, To: &om.OutputTo{Stdout: true, File: false}}) - om.Log.Setting().SetMaximumLevel(om.LLevelNone) - - Convey("Given GitCommand", t, func() { - g := model.Git() - - Convey("When get the command", func() { - Convey("Then shouldn't be nil", func() { - So(g, ShouldNotBeNil) - }) - - Convey("the result should be singleton", func() { - So(model.Git(), ShouldEqual, g) - }) - }) - - Convey("When setup output", func() { - var buf bytes.Buffer - g.SetOutWriter(&buf).Exec("status") - - Convey("Then the output should write to custom Writer", func() { - So(buf.String(), ShouldNotBeEmpty) - So(buf.String(), ShouldNotBeNil) - So(buf.String(), ShouldContainSubstring, "commit") - }) - }) - - Convey("When reset both out and err", func() { - model.Git().SetErrWriter(nil) - model.Git().SetOutWriter(nil) - }) - - Convey("When setup error output", func() { - var buf bytes.Buffer - g.SetErrWriter(&buf).Exec("abc") - - Convey("Then the output should write to custom Writer", func() { - So(buf.String(), ShouldNotBeEmpty) - So(buf.String(), ShouldNotBeNil) - So(buf.String(), ShouldContainSubstring, "abc") - }) - }) - - Convey("When setup input", func() { - var buf bytes.Buffer - var err bytes.Buffer - buf.WriteString("Hello world") - g.SetReader(&buf).SetErrWriter(&err).Exec("xyz") - - Convey("Then the output should write to custom Writer", func() { - So(err.String(), ShouldNotBeEmpty) - So(err.String(), ShouldNotBeNil) - So(err.String(), ShouldContainSubstring, "xyz") - }) - }) - }) -} diff --git a/model/repo.go b/model/repo.go deleted file mode 100644 index 64b1da6..0000000 --- a/model/repo.go +++ /dev/null @@ -1,132 +0,0 @@ -package model - -import ( - "path/filepath" - - "github.com/kamontat/go-error-manager" - "github.com/kamontat/go-log-manager" - - git "gopkg.in/src-d/go-git.v4" -) - -// Repo is git repository object for gitgo. -type Repo struct { - isSetup bool - path string - repo *git.Repository - gitCommand *GitCommand - Manager *manager.ResultManager -} - -// NewRepo will return new repository with current path. -// you must call setup for load git repository to memory. -func NewRepo() *Repo { - return CustomRepo(".") -} - -// CustomRepo will return repo of custom path -func CustomRepo(path string) *Repo { - management := manager.StartResultManager() - - return &Repo{ - isSetup: false, - path: management.Execute1ParametersB(filepath.Abs, path).GetResult(), - gitCommand: Git(), - Manager: management, - repo: nil, - } -} - -// Setup will load git repository to memory. -// If any error occurred, exit with code 5. -func (r *Repo) Setup() { - if r.isSetup { - return - } - - om.Log.ToVerbose("Repository", "initial path "+r.path) - result, err := git.PlainOpen(r.path) - r.Manager.Save("", err) - - r.Manager.IfNoError(func() { - r.isSetup = true - r.repo = result - }) -} - -// GetGitRepository will return git.Repository of this Repo -func (r *Repo) GetGitRepository() *manager.ResultWrapper { - r.Setup() - - return r.Manager.IfNoErrorThen(func() interface{} { - if r.isSetup { - return r.repo - } - return nil - }) -} - -// GetWorktree is getter method, which get git.Worktree from git.Repository. -// It's will Exit with code 5 if any error occurred. -func (r *Repo) GetWorktree() *manager.ResultWrapper { - resultWrapper := r.GetGitRepository() - return resultWrapper.UnwrapNext(func(i interface{}) interface{} { - worktree, err := i.(*git.Repository).Worktree() - r.Manager.Save("", err) - if r.Manager.NoError() { - return worktree - } - return nil - }) -} - -// Status will return *git.Status. -func (r *Repo) Status() *manager.ResultWrapper { - resultWrapper := r.GetWorktree() - return resultWrapper.UnwrapNext(func(i interface{}) interface{} { - status, err := i.(*git.Worktree).Status() - r.Manager.Save("", err) - if r.Manager.NoError() { - return status - } - return nil - }) -} - -// Add get array of filepath, and return ErrManager. -// anyway, It's will run os.Exit with code 10 if any error occurred. -func (r *Repo) Add(filepath []string) *manager.Throwable { - worktree := r.GetWorktree() - - worktree.Unwrap(func(i interface{}) { - work := i.(*git.Worktree) - for _, f := range filepath { - work.Add(f) - } - }) - - return r.Manager.Throw() -} - -// AddAll will run git add -A command in cli. -func (r *Repo) AddAll() *manager.Throwable { - r.Setup() - t := r.gitCommand.Exec("add", "-A").Throw() - for _, e := range t.ListErrors() { - r.Manager.Save("", e) - } - - return r.Manager.Throw() -} - -// GetCommit will return Commit object. -func (r *Repo) GetCommit(dry bool) *Commit { - r.Setup() - - commit := &Commit{ - throwable: r.Manager.Throw(), - } - - commit.options.dry = dry - return commit -} diff --git a/model/repo_test.go b/model/repo_test.go deleted file mode 100644 index 74592ce..0000000 --- a/model/repo_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package model_test - -import ( - "errors" - "testing" - - "github.com/kamontat/go-error-manager" - - "github.com/kamontat/gitgo/model" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestRepoObject(t *testing.T) { - Convey("Given Repository", t, func() { - Convey("When try to create new repo", func() { - // start path is /model - r := model.CustomRepo("..") - - Convey("And Setup the git repository", func() { - r.Setup() - - Convey("Then can get git repository", func() { - repo := r.GetGitRepository() - - t := repo.Unwrap(func(i interface{}) { - So(i, ShouldNotBeNil) - }).Catch(func() error { - return nil - }, nil) - - So(repo.Exist(), ShouldBeTrue) - So(t.CanBeThrow(), ShouldBeFalse) - }) - - Convey("Then can get git worktree", func() { - worktree := r.GetWorktree() - - So(r.Manager.HaveError(), ShouldBeFalse) - - t := worktree.Unwrap(func(i interface{}) { - So(i, ShouldNotBeNil) - }).Catch(func() error { - return errors.New("throw error") - }, func(t *manager.Throwable) { - // This should be run - So(t.CanBeThrow(), ShouldBeTrue) - }) - - So(worktree.Exist(), ShouldBeTrue) - So(t.CanBeThrow(), ShouldBeFalse) - }) - - Convey("Then can add file", nil) - - Convey("Then can get every files/folders", nil) - - Convey("Then can show git status", func() { - status := r.Status() - - So(status.Exist(), ShouldBeTrue) - - status.Catch(func() error { - return errors.New("status not exist") - }, func(t *manager.Throwable) { - So(t.GetMessage(), ShouldBeEmpty) - }) - }) - - Convey("Then commit will return Commit object", nil) - - }) - }) - - Convey("When create new not exist repo", func() { - // new repo will setup repo on this folder (/model) - r := model.NewRepo() - - Convey("Then cannot get any git repository", func() { - repo := r.GetGitRepository() - So(repo.NotExist(), ShouldBeTrue) - }) - - Convey("Then cannot get any git worktree", func() { - worktree := r.GetWorktree() - So(worktree.NotExist(), ShouldBeTrue) - }) - - Convey("Then cannot add", func() { - t := r.Add([]string{"/abc/def"}) - - So(t.CanBeThrow(), ShouldBeTrue) - }) - - Convey("Then cannot add all", func() { - t := r.AddAll() - - So(t.CanBeThrow(), ShouldBeTrue) - }) - - Convey("Then cannot show git status", func() { - status := r.Status() - - So(status.NotExist(), ShouldBeTrue) - - status.Catch(func() error { - return errors.New("status not exist") - }, func(t *manager.Throwable) { - So(t.GetMessage(), ShouldContainSubstring, "status not exist") - }) - }) - - Convey("Then commit shouldn't exist", func() { - commit := r.GetCommit() - So(commit.CanCommit(), ShouldBeFalse) - }) - }) - }) -}