From 05c49d1bbf5278652e75e24b1f77bf4fe3f29480 Mon Sep 17 00:00:00 2001 From: Haruaki Tamada Date: Thu, 23 Apr 2020 16:54:23 +0900 Subject: [PATCH 1/9] ref #85 reorganized directory layouts. rrh.go -> cmd/rrh/main.go, and lib directory to the top directory. --- Makefile | 11 +- cmd/rrh-new/main.go | 34 ++--- rrh.go => cmd/rrh/main.go | 6 +- ...colorable_output.go => colorable_output.go | 2 +- ...output_test.go => colorable_output_test.go | 4 +- lib/config.go => config.go | 2 +- lib/config_test.go => config_test.go | 14 +- lib/database.go => database.go | 2 +- lib/database_test.go => database_test.go | 24 ++-- lib/git.go => git.go | 2 +- lib/git_test.go => git_test.go | 8 +- internal/add_cmd.go | 32 ++--- internal/add_test.go | 28 ++-- internal/clone_cmd.go | 38 +++--- internal/clone_test.go | 26 ++-- internal/common.go | 14 +- internal/config_cmd.go | 14 +- internal/config_test.go | 126 +++++++++--------- internal/export_cmd.go | 8 +- internal/export_test.go | 24 ++-- internal/fetch_all_cmd.go | 16 +-- internal/fetch_cmd.go | 22 +-- internal/fetch_test.go | 4 +- internal/group_cmd.go | 60 ++++----- internal/group_test.go | 48 +++---- internal/import_cmd.go | 46 +++---- internal/import_test.go | 10 +- internal/list_cmd.go | 28 ++-- internal/list_test.go | 28 ++-- internal/messages_cmd.go | 4 +- internal/messages_test.go | 4 +- internal/move_cmd.go | 34 ++--- internal/move_test.go | 28 ++-- internal/open.go | 12 +- internal/prune_cmd.go | 20 +-- internal/prune_test.go | 14 +- internal/remove_cmd.go | 22 +-- internal/remove_test.go | 34 ++--- internal/repository_cmd.go | 74 +++++----- internal/repository_test.go | 34 ++--- internal/status_cmd.go | 40 +++--- internal/status_test.go | 8 +- lib/message_test.go => message_test.go | 2 +- lib/messages.go => messages.go | 2 +- lib/rrhtime.go => rrhtime.go | 2 +- lib/testutils.go => testutils.go | 4 +- lib/util.go => util.go | 2 +- lib/util_test.go => util_test.go | 14 +- 48 files changed, 518 insertions(+), 517 deletions(-) rename rrh.go => cmd/rrh/main.go (96%) rename lib/colorable_output.go => colorable_output.go (99%) rename lib/colorable_output_test.go => colorable_output_test.go (97%) rename lib/config.go => config.go (99%) rename lib/config_test.go => config_test.go (91%) rename lib/database.go => database.go (99%) rename lib/database_test.go => database_test.go (92%) rename lib/git.go => git.go (99%) rename lib/git_test.go => git_test.go (90%) rename lib/message_test.go => message_test.go (98%) rename lib/messages.go => messages.go (99%) rename lib/rrhtime.go => rrhtime.go (98%) rename lib/testutils.go => testutils.go (96%) rename lib/util.go => util.go (99%) rename lib/util_test.go => util_test.go (90%) diff --git a/Makefile b/Makefile index e21343c..5afc667 100644 --- a/Makefile +++ b/Makefile @@ -12,8 +12,8 @@ update_version: sed -e 's!Version-[0-9.]*-yellowgreen!Version-${VERSION}-yellowgreen!g' -e 's!tag/v[0-9.]*!tag/v${VERSION}!g' $$i > a ; mv a $$i; \ done - @sed 's/const VERSION = .*/const VERSION = "${VERSION}"/g' lib/config.go > a - @mv a lib/config.go + @sed 's/const VERSION = .*/const VERSION = "${VERSION}"/g' config.go > a + @mv a config.go @sed 's/ \/\/ rrh version .*/ \/\/ rrh version ${VERSION}/g' internal/messages_test.go > a @mv a internal/messages_test.go @echo "Replace version to \"${VERSION}\"" @@ -25,13 +25,14 @@ test: setup $(GO) test -covermode=count -coverprofile=coverage.out $$(go list ./...) define _buildSubcommand - $(GO) build -o rrh-$(1) cmd/rrh-$(1)/*.go + $(GO) build -o $(1) cmd/$(1)/*.go endef build: setup $(GO) build - @$(call _buildSubcommand,helloworld) - @$(call _buildSubcommand,new) + @$(call _buildSubcommand,rrh) + @$(call _buildSubcommand,rrh-helloworld) + @$(call _buildSubcommand,rrh-new) lint: setup format $(GO) vet $$(go list ./...) diff --git a/cmd/rrh-new/main.go b/cmd/rrh-new/main.go index 92458cc..d71eac5 100644 --- a/cmd/rrh-new/main.go +++ b/cmd/rrh-new/main.go @@ -8,7 +8,7 @@ import ( "strings" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" "gopkg.in/src-d/go-billy.v4/osfs" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing/cache" @@ -44,9 +44,9 @@ ARGUMENTS REPOSITORY specifies repository name, and it is directory name.` } -func buildFlagSet(config *lib.Config) (*flag.FlagSet, *newOptions) { +func buildFlagSet(config *rrh.Config) (*flag.FlagSet, *newOptions) { var opt = newOptions{info: new(repositoryInfo)} - var defaultGroup = config.GetValue(lib.RrhDefaultGroupName) + var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) flags := flag.NewFlagSet("new", flag.ContinueOnError) flags.Usage = func() { fmt.Println(getHelpMessage()) } flags.StringVarP(&opt.info.description, "description", "d", "", "specifys description of the project") @@ -100,7 +100,7 @@ func createReadme(dest, projectName string) { } } -func makeGitDirectory(config *lib.Config, repo *repo, opts *newOptions) error { +func makeGitDirectory(config *rrh.Config, repo *repo, opts *newOptions) error { if opts.dryrunMode { return nil } @@ -158,7 +158,7 @@ func findRepoName(arg string) string { return terms[1] } -func createRepo(config *lib.Config, arg string, opts *newOptions) (*repo, error) { +func createRepo(config *rrh.Config, arg string, opts *newOptions) (*repo, error) { var dest, err = findDirectoryName(arg, opts) if err != nil { return nil, err @@ -167,11 +167,11 @@ func createRepo(config *lib.Config, arg string, opts *newOptions) (*repo, error) return &repo{givenString: arg, dest: dest, repoName: repoName}, nil } -func registerToGroup(db *lib.Database, repo *repo, opts *newOptions) error { +func registerToGroup(db *rrh.Database, repo *repo, opts *newOptions) error { if opts.dryrunMode { return nil } - var remotes, _ = lib.FindRemotes(repo.dest) + var remotes, _ = rrh.FindRemotes(repo.dest) var _, err1 = db.CreateRepository(repo.repoName, repo.dest, opts.info.description, remotes) if err1 != nil { return err1 @@ -183,7 +183,7 @@ func registerToGroup(db *lib.Database, repo *repo, opts *newOptions) error { return nil } -func createRepository(db *lib.Database, arg string, opts *newOptions) error { +func createRepository(db *rrh.Database, arg string, opts *newOptions) error { var repo, err = createRepo(db.Config, arg, opts) if err == nil { err = makeGitDirectory(db.Config, repo, opts) @@ -201,28 +201,28 @@ func createRepository(db *lib.Database, arg string, opts *newOptions) error { return err } -func isOnError(config *lib.Config, handler string) bool { - var onError = config.GetValue(lib.RrhOnError) +func isOnError(config *rrh.Config, handler string) bool { + var onError = config.GetValue(rrh.RrhOnError) return onError == handler } -func storeDbWhenSucceeded(db *lib.Database, errors []error) { +func storeDbWhenSucceeded(db *rrh.Database, errors []error) { var config = db.Config - if len(errors) == 0 || isOnError(config, lib.Ignore) { + if len(errors) == 0 || isOnError(config, rrh.Ignore) { db.StoreAndClose() } } -func createRepositories(config *lib.Config, args []string, opts *newOptions) []error { +func createRepositories(config *rrh.Config, args []string, opts *newOptions) []error { var errors = []error{} - var db, err = lib.Open(config) + var db, err = rrh.Open(config) defer storeDbWhenSucceeded(db, errors) if err != nil { return []error{err} } for _, arg := range args[1:] { if err := createRepository(db, arg, opts); err != nil { - if isOnError(config, lib.FailImmediately) { + if isOnError(config, rrh.FailImmediately) { return []error{err} } errors = append(errors, err) @@ -231,7 +231,7 @@ func createRepositories(config *lib.Config, args []string, opts *newOptions) []e return errors } -func perform(config *lib.Config, args []string, opts *newOptions) int { +func perform(config *rrh.Config, args []string, opts *newOptions) int { if opts.helpFlag { fmt.Println(getHelpMessage()) return 0 @@ -241,7 +241,7 @@ func perform(config *lib.Config, args []string, opts *newOptions) int { } func goMain(args []string) int { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var flag, opts = buildFlagSet(config) if err := flag.Parse(args); err != nil { fmt.Println(err.Error()) diff --git a/rrh.go b/cmd/rrh/main.go similarity index 96% rename from rrh.go rename to cmd/rrh/main.go index 101eec4..ad7c903 100644 --- a/rrh.go +++ b/cmd/rrh/main.go @@ -8,12 +8,12 @@ import ( "strings" "github.com/mitchellh/cli" + "github.com/tamada/rrh" "github.com/tamada/rrh/internal" - "github.com/tamada/rrh/lib" ) func executeInternalCommand(commands map[string]cli.CommandFactory, args []string) (int, error) { - var c = cli.NewCLI("rrh", lib.VERSION) + var c = cli.NewCLI("rrh", rrh.VERSION) c.Name = "rrh" c.Args = args c.Autocomplete = true @@ -104,7 +104,7 @@ func executeExternalCommand(args []string) (int, error) { func (opts *rrhOptions) updateConfigPath() { if opts.configPath != "" { - os.Setenv(lib.RrhConfigPath, opts.configPath) + os.Setenv(rrh.RrhConfigPath, opts.configPath) } } diff --git a/lib/colorable_output.go b/colorable_output.go similarity index 99% rename from lib/colorable_output.go rename to colorable_output.go index 8bf9ce0..fba93c4 100644 --- a/lib/colorable_output.go +++ b/colorable_output.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "strings" diff --git a/lib/colorable_output_test.go b/colorable_output_test.go similarity index 97% rename from lib/colorable_output_test.go rename to colorable_output_test.go index 1e69852..8599861 100644 --- a/lib/colorable_output_test.go +++ b/colorable_output_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "os" @@ -8,7 +8,7 @@ import ( ) func TestEnableColorize(t *testing.T) { - os.Setenv(RrhConfigPath, "../testdata/config.json") + os.Setenv(RrhConfigPath, "testdata/config.json") var config = OpenConfig() config.Update(RrhEnableColorized, "true") var cs = InitializeColor(config) diff --git a/lib/config.go b/config.go similarity index 99% rename from lib/config.go rename to config.go index bec8e80..8ae4ad1 100644 --- a/lib/config.go +++ b/config.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "encoding/json" diff --git a/lib/config_test.go b/config_test.go similarity index 91% rename from lib/config_test.go rename to config_test.go index 4088fec..76d7044 100644 --- a/lib/config_test.go +++ b/config_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "errors" @@ -103,7 +103,7 @@ func TestUpdateTrueFalseValue(t *testing.T) { } for _, data := range testdata { - var dbfile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, oldDB *Database) { + var dbfile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, oldDB *Database) { if err := config.Update(data.key, data.value); (err == nil) == data.wantError { t.Errorf("%s: set to \"%s\", error: %s", data.key, data.value, err.Error()) } @@ -128,7 +128,7 @@ func TestUpdateOnError(t *testing.T) { } for _, data := range testdata { - var dbfile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, oldDB *Database) { + var dbfile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, oldDB *Database) { if err := config.Update(RrhOnError, data.key); (err == nil) != data.success { t.Errorf("%s: set to \"%s\", success: %v", RrhOnError, data.key, data.success) } @@ -152,7 +152,7 @@ func TestUpdateValue(t *testing.T) { {"unknown", "hoge4", true, ""}, } for _, td := range testdata { - var dbfile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(unusedConfig *Config, oldDB *Database) { + var dbfile = Rollback("testdata/test_db.json", "testdata/config.json", func(unusedConfig *Config, oldDB *Database) { var config = NewConfig() var err = config.Update(td.label, td.value) if (err == nil) == td.shouldError { @@ -170,7 +170,7 @@ func TestUpdateValue(t *testing.T) { } func TestConfigIsSet(t *testing.T) { - var dbFile = Rollback("../testata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var dbFile = Rollback("../testata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { if config.IsSet(RrhConfigPath) { t.Errorf("not boolean variable is specified") } @@ -225,7 +225,7 @@ func TestPrintErrors(t *testing.T) { {Fail, "msg1+msg2", 5}, } - var dbFile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var dbFile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { for _, tc := range testcases { var output = CaptureStdout(func() { config.Update(RrhOnError, tc.givesOnError) @@ -245,7 +245,7 @@ func TestPrintErrors(t *testing.T) { } func TestOpenConfigBrokenJson(t *testing.T) { - os.Setenv(RrhConfigPath, "../testdata/broken.json") + os.Setenv(RrhConfigPath, "testdata/broken.json") var config = OpenConfig() if config != nil { t.Error("broken json returns nil") diff --git a/lib/database.go b/database.go similarity index 99% rename from lib/database.go rename to database.go index f6dcf2d..72aa3a0 100644 --- a/lib/database.go +++ b/database.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "encoding/json" diff --git a/lib/database_test.go b/database_test.go similarity index 92% rename from lib/database_test.go rename to database_test.go index e3cf3a6..0ac73d3 100644 --- a/lib/database_test.go +++ b/database_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "fmt" @@ -7,8 +7,8 @@ import ( ) func openDatabase() *Database { - os.Setenv(RrhDatabasePath, "../testdata/database.json") - os.Setenv(RrhConfigPath, "../testdata/config.json") + os.Setenv(RrhDatabasePath, "testdata/database.json") + os.Setenv(RrhConfigPath, "testdata/config.json") var config = OpenConfig() var db, _ = Open(config) return db @@ -29,8 +29,8 @@ func TestRelationStringer(t *testing.T) { } func TestOpenBrokenJson(t *testing.T) { - os.Setenv(RrhConfigPath, "../testdata/config.json") - os.Setenv(RrhDatabasePath, "../testdata/broken.json") + os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(RrhDatabasePath, "testdata/broken.json") var config = OpenConfig() var _, err = Open(config) if err == nil { @@ -63,8 +63,8 @@ func TestAutoCreateGroup(t *testing.T) { } func TestOpenNonExistFile(t *testing.T) { - os.Setenv(RrhConfigPath, "../testdata/config.json") - os.Setenv(RrhDatabasePath, "../testdata/not-exist-file.json") + os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(RrhDatabasePath, "testdata/not-exist-file.json") var config = OpenConfig() var db, _ = Open(config) @@ -77,8 +77,8 @@ func TestOpenNonExistFile(t *testing.T) { } func TestOpenNullDatabase(t *testing.T) { - os.Setenv(RrhConfigPath, "../testdata/config.json") - os.Setenv(RrhDatabasePath, "../testdata/nulldb.json") + os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(RrhDatabasePath, "testdata/nulldb.json") var config = OpenConfig() var db, _ = Open(config) @@ -94,7 +94,7 @@ func TestOpenNullDatabase(t *testing.T) { } func TestStore(t *testing.T) { - var dbFile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var dbFile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { db.CreateGroup("group1", "desc1", false) db.CreateGroup("group2", "desc2", false) db.CreateRepository("repo1", "path1", "desc1", []Remote{}) @@ -346,7 +346,7 @@ func TestFindRelations(t *testing.T) { } func TestUpdateRepository(t *testing.T) { - var dbFile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var dbFile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { if !db.UpdateRepository("repo1", Repository{ID: "newRepo1", Path: "newPath1", Description: "desc1"}) { t.Errorf("Update failed") } @@ -385,7 +385,7 @@ func TestFindTargets(t *testing.T) { } for _, tc := range testcases { - var dbFile = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var dbFile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { var rels = FindTargets(db, tc.groupNames) if len(rels) != tc.size { diff --git a/lib/git.go b/git.go similarity index 99% rename from lib/git.go rename to git.go index 1a4b1a7..01cdd4d 100644 --- a/lib/git.go +++ b/git.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "fmt" diff --git a/lib/git_test.go b/git_test.go similarity index 90% rename from lib/git_test.go rename to git_test.go index 2207341..9729f66 100644 --- a/lib/git_test.go +++ b/git_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "testing" @@ -36,9 +36,9 @@ func TestFindRemotes(t *testing.T) { errorFlag bool count int }{ - {"../testdata/dummygit", true, 0}, - {"../testdata/helloworld", false, 1}, - {"../testdata/fibonacci", false, 1}, + {"testdata/dummygit", true, 0}, + {"testdata/helloworld", false, 1}, + {"testdata/fibonacci", false, 1}, } for _, td := range testdata { var remotes, err = FindRemotes(td.path) diff --git a/internal/add_cmd.go b/internal/add_cmd.go index 7a53b9a..175b947 100644 --- a/internal/add_cmd.go +++ b/internal/add_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -44,7 +44,7 @@ func (add *AddCommand) Synopsis() string { } func (add *AddCommand) showError(errorlist []error, onError string) { - if len(errorlist) == 0 || onError == lib.Ignore { + if len(errorlist) == 0 || onError == rrh.Ignore { return } for _, item := range errorlist { @@ -52,14 +52,14 @@ func (add *AddCommand) showError(errorlist []error, onError string) { } } -func (add *AddCommand) perform(db *lib.Database, opt *addOptions) int { - var onError = db.Config.GetValue(lib.RrhOnError) +func (add *AddCommand) perform(db *rrh.Database, opt *addOptions) int { + var onError = db.Config.GetValue(rrh.RrhOnError) var errorlist = add.AddRepositoriesToGroup(db, opt) add.showError(errorlist, onError) - if onError == lib.Fail || onError == lib.FailImmediately { + if onError == rrh.Fail || onError == rrh.FailImmediately { return 1 } var err2 = db.StoreAndClose() @@ -74,13 +74,13 @@ func (add *AddCommand) perform(db *lib.Database, opt *addOptions) int { Run function performs the command. */ func (add *AddCommand) Run(args []string) int { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var opt, err = add.parse(args, config) if err != nil { fmt.Println(err.Error()) return 1 } - var db, err2 = lib.Open(config) + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -94,9 +94,9 @@ type addOptions struct { args []string } -func (add *AddCommand) buildFlagSet(config *lib.Config) (*flag.FlagSet, *addOptions) { +func (add *AddCommand) buildFlagSet(config *rrh.Config) (*flag.FlagSet, *addOptions) { var opt = addOptions{} - var defaultGroup = config.GetValue(lib.RrhDefaultGroupName) + var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) flags := flag.NewFlagSet("add", flag.ContinueOnError) flags.Usage = func() { fmt.Println(add.Help()) } flags.StringVarP(&opt.group, "group", "g", defaultGroup, "target group") @@ -104,7 +104,7 @@ func (add *AddCommand) buildFlagSet(config *lib.Config) (*flag.FlagSet, *addOpti return flags, &opt } -func (add *AddCommand) parse(args []string, config *lib.Config) (*addOptions, error) { +func (add *AddCommand) parse(args []string, config *rrh.Config) (*addOptions, error) { var flags, opt = add.buildFlagSet(config) if err := flags.Parse(args); err != nil { return nil, err @@ -115,7 +115,7 @@ func (add *AddCommand) parse(args []string, config *lib.Config) (*addOptions, er return opt, nil } -func isDuplicateRepository(db *lib.Database, repoID string, path string) error { +func isDuplicateRepository(db *rrh.Database, repoID string, path string) error { var repo = db.FindRepository(repoID) if repo != nil && repo.Path != path { return fmt.Errorf("%s: duplicate repository id", repoID) @@ -130,16 +130,16 @@ func findIDFromPath(repoID string, absPath string) string { return repoID } -func (add *AddCommand) addRepositoryToGroup(db *lib.Database, rel lib.Relation, path string) []error { +func (add *AddCommand) addRepositoryToGroup(db *rrh.Database, rel rrh.Relation, path string) []error { var absPath, _ = filepath.Abs(path) var id = findIDFromPath(rel.RepositoryID, absPath) - if err1 := lib.IsExistAndGitRepository(absPath, path); err1 != nil { + if err1 := rrh.IsExistAndGitRepository(absPath, path); err1 != nil { return []error{err1} } if err1 := isDuplicateRepository(db, id, absPath); err1 != nil { return []error{err1} } - var remotes, err2 = lib.FindRemotes(absPath) + var remotes, err2 = rrh.FindRemotes(absPath) if err2 != nil { return []error{err2} } @@ -162,7 +162,7 @@ func validateArguments(args []string, repoID string) error { /* AddRepositoriesToGroup registers the given repositories to the specified group. */ -func (add *AddCommand) AddRepositoriesToGroup(db *lib.Database, opt *addOptions) []error { +func (add *AddCommand) AddRepositoriesToGroup(db *rrh.Database, opt *addOptions) []error { var _, err = db.AutoCreateGroup(opt.group, "", false) if err != nil { return []error{err} @@ -172,7 +172,7 @@ func (add *AddCommand) AddRepositoriesToGroup(db *lib.Database, opt *addOptions) } var errorlist = []error{} for _, item := range opt.args { - var list = add.addRepositoryToGroup(db, lib.Relation{RepositoryID: opt.repoID, GroupName: opt.group}, item) + var list = add.addRepositoryToGroup(db, rrh.Relation{RepositoryID: opt.repoID, GroupName: opt.group}, item) errorlist = append(errorlist, list...) } return errorlist diff --git a/internal/add_test.go b/internal/add_test.go index dd3a34d..f65e310 100644 --- a/internal/add_test.go +++ b/internal/add_test.go @@ -4,11 +4,11 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestInvalidOptions(t *testing.T) { - lib.CaptureStdout(func() { + rrh.CaptureStdout(func() { var command, _ = AddCommandFactory() var flag = command.Run([]string{"--invalid-option"}) if flag != 1 { @@ -86,13 +86,13 @@ func TestAdd(t *testing.T) { }, } - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") for _, testcase := range testcases { - var databaseFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var databaseFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = AddCommandFactory() var status = command.Run(testcase.args) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) if status != testcase.statusCode { t.Errorf("%v: status code did not match, wont: %d, got: %d", testcase.args, testcase.statusCode, status) } @@ -118,13 +118,13 @@ func TestAdd(t *testing.T) { } func TestAddToDifferentGroup(t *testing.T) { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - var databaseFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + var databaseFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = AddCommandFactory() command.Run([]string{"../testdata/fibonacci"}) command.Run([]string{"-g", "group1", "../testdata/fibonacci"}) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) if !db.HasGroup("no-group") { t.Error("no-group: group not found") } @@ -142,14 +142,14 @@ func TestAddToDifferentGroup(t *testing.T) { } func TestAddFailed(t *testing.T) { - os.Setenv(lib.RrhConfigPath, "../testdata/nulldb.json") - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(lib.RrhAutoCreateGroup, "false") - defer os.Unsetenv(lib.RrhAutoCreateGroup) + os.Setenv(rrh.RrhConfigPath, "../testdata/nulldb.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.RrhAutoCreateGroup, "false") + defer os.Unsetenv(rrh.RrhAutoCreateGroup) var add = AddCommand{} - var config = lib.OpenConfig() - var db, _ = lib.Open(config) + var config = rrh.OpenConfig() + var db, _ = rrh.Open(config) var data = []addOptions{ {args: []string{"../not-exist-dir"}, group: "no-group"}, diff --git a/internal/clone_cmd.go b/internal/clone_cmd.go index 95d86cd..f34bb7d 100644 --- a/internal/clone_cmd.go +++ b/internal/clone_cmd.go @@ -10,7 +10,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -69,13 +69,13 @@ func (options *cloneOptions) showError(list []error) { Run performs the command. */ func (clone *CloneCommand) Run(args []string) int { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() arguments, err := clone.parse(args, config) if err != nil || len(arguments) == 0 { fmt.Printf(clone.Help()) return 1 } - db, err := lib.Open(config) + db, err := rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 2 @@ -83,12 +83,12 @@ func (clone *CloneCommand) Run(args []string) int { return clone.perform(db, arguments) } -func (clone *CloneCommand) perform(db *lib.Database, arguments []string) int { +func (clone *CloneCommand) perform(db *rrh.Database, arguments []string) int { var count, list = clone.DoClone(db, arguments) if len(list) != 0 { clone.options.showError(list) - var onError = db.Config.GetValue(lib.RrhOnError) - if onError == lib.Fail || onError == lib.FailImmediately { + var onError = db.Config.GetValue(rrh.RrhOnError) + if onError == rrh.Fail || onError == rrh.FailImmediately { return 1 } } @@ -108,9 +108,9 @@ func printResult(count int, dest string, group string) { } } -func (clone *CloneCommand) buildFlagSets(config *lib.Config) (*flag.FlagSet, *cloneOptions) { - var defaultGroup = config.GetValue(lib.RrhDefaultGroupName) - var destination = config.GetValue(lib.RrhCloneDestination) +func (clone *CloneCommand) buildFlagSets(config *rrh.Config) (*flag.FlagSet, *cloneOptions) { + var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) + var destination = config.GetValue(rrh.RrhCloneDestination) var options = cloneOptions{defaultGroup, ".", false} flags := flag.NewFlagSet("clone", flag.ContinueOnError) flags.Usage = func() { fmt.Println(clone.Help()) } @@ -120,7 +120,7 @@ func (clone *CloneCommand) buildFlagSets(config *lib.Config) (*flag.FlagSet, *cl return flags, &options } -func (clone *CloneCommand) parse(args []string, config *lib.Config) ([]string, error) { +func (clone *CloneCommand) parse(args []string, config *rrh.Config) ([]string, error) { var flags, options = clone.buildFlagSets(config) if err := flags.Parse(args); err != nil { return nil, err @@ -130,12 +130,12 @@ func (clone *CloneCommand) parse(args []string, config *lib.Config) ([]string, e return flags.Args(), nil } -func registerPath(db *lib.Database, dest string, repoID string) (*lib.Repository, error) { +func registerPath(db *rrh.Database, dest string, repoID string) (*rrh.Repository, error) { var path, err = filepath.Abs(dest) if err != nil { return nil, err } - var remotes, err2 = lib.FindRemotes(path) + var remotes, err2 = rrh.FindRemotes(path) if err2 != nil { return nil, err2 } @@ -147,7 +147,7 @@ func registerPath(db *lib.Database, dest string, repoID string) (*lib.Repository return repo, nil } -func (clone *CloneCommand) toDir(db *lib.Database, URL string, dest string, repoID string) (*lib.Repository, error) { +func (clone *CloneCommand) toDir(db *rrh.Database, URL string, dest string, repoID string) (*rrh.Repository, error) { clone.printIfVerbose(fmt.Sprintf("git clone %s %s (%s)", URL, dest, repoID)) var cmd = exec.Command("git", "clone", URL, dest) var err = cmd.Run() @@ -170,7 +170,7 @@ func isExistDir(path string) bool { /* DoClone performs `git clone` command and register the cloned repositories to RRH database. */ -func (clone *CloneCommand) DoClone(db *lib.Database, arguments []string) (int, []error) { +func (clone *CloneCommand) DoClone(db *rrh.Database, arguments []string) (int, []error) { if len(arguments) == 1 { var err = clone.doCloneARepository(db, arguments[0]) if err != nil { @@ -181,14 +181,14 @@ func (clone *CloneCommand) DoClone(db *lib.Database, arguments []string) (int, [ return clone.doCloneRepositories(db, arguments) } -func (clone CloneCommand) doCloneRepositories(db *lib.Database, arguments []string) (int, []error) { +func (clone CloneCommand) doCloneRepositories(db *rrh.Database, arguments []string) (int, []error) { var errorlist = []error{} var count = 0 for _, url := range arguments { var increment, err = clone.doCloneEachRepository(db, url) if err != nil { errorlist = append(errorlist, err) - if db.Config.GetValue(lib.RrhOnError) == lib.FailImmediately { + if db.Config.GetValue(rrh.RrhOnError) == rrh.FailImmediately { return count, errorlist } } @@ -197,7 +197,7 @@ func (clone CloneCommand) doCloneRepositories(db *lib.Database, arguments []stri return count, errorlist } -func (clone *CloneCommand) relateTo(db *lib.Database, groupID string, repoID string) error { +func (clone *CloneCommand) relateTo(db *rrh.Database, groupID string, repoID string) error { var _, err = db.AutoCreateGroup(groupID, "", false) if err != nil { return fmt.Errorf("%s: group not found", groupID) @@ -210,7 +210,7 @@ func (clone *CloneCommand) relateTo(db *lib.Database, groupID string, repoID str doCloneEachRepository performes `git clone` for each repository. This function is called repeatedly. */ -func (clone *CloneCommand) doCloneEachRepository(db *lib.Database, URL string) (int, error) { +func (clone *CloneCommand) doCloneEachRepository(db *rrh.Database, URL string) (int, error) { var count int var id = findIDFromURL(URL) var path = filepath.Join(clone.options.dest, id) @@ -224,7 +224,7 @@ func (clone *CloneCommand) doCloneEachRepository(db *lib.Database, URL string) ( return count, err } -func (clone *CloneCommand) doCloneARepository(db *lib.Database, URL string) error { +func (clone *CloneCommand) doCloneARepository(db *rrh.Database, URL string) error { var id, path string if isExistDir(clone.options.dest) { diff --git a/internal/clone_test.go b/internal/clone_test.go index bec1caf..95ec316 100644 --- a/internal/clone_test.go +++ b/internal/clone_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func cleanup(dirs []string) { @@ -16,7 +16,7 @@ func cleanup(dirs []string) { } } -func validate(repo lib.Repository, repoID string, repoPath string) string { +func validate(repo rrh.Repository, repoID string, repoPath string) string { var dir, _ = filepath.Abs(repoPath) if repo.ID != repoID || repo.Path != dir { return fmt.Sprintf("wont: %s (%s), got: %s (%s)", repoID, dir, repo.ID, repo.Path) @@ -38,14 +38,14 @@ func contains(slice []string, checkItem string) bool { } func TestCommand_MultipleProjects(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var clone, _ = CloneCommandFactory() clone.Run([]string{"--verbose", "-d", "../testdata/hoge", "-g", "not-exist-group", "../testdata/helloworld", "../testdata/fibonacci"}) defer cleanup([]string{"../testdata/hoge"}) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) if !db.HasRepository("helloworld") && !db.HasRepository("fibonacci") { t.Fatal("helloworld and fibonacci were not registered.") @@ -70,12 +70,12 @@ func TestCommand_MultipleProjects(t *testing.T) { } func TestCommand_Run(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var clone, _ = CloneCommandFactory() clone.Run([]string{"https://htamada@bitbucket.org/htamada/helloworld.git"}) defer cleanup([]string{"./helloworld"}) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) if !db.HasRepository("helloworld") { t.Fatal("helloworld was not registered.") @@ -92,12 +92,12 @@ func TestCommand_Run(t *testing.T) { } func TestCommand_SpecifyingId(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDb *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDb *rrh.Database) { var clone, _ = CloneCommandFactory() clone.Run([]string{"--dest", "../testdata/newid", "../testdata/helloworld"}) defer cleanup([]string{"../testdata/newid"}) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) if len(db.Repositories) != 3 { t.Fatal("newid was not registered.") @@ -111,8 +111,8 @@ func TestCommand_SpecifyingId(t *testing.T) { } func TestUnknownOption(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { + var output = rrh.CaptureStdout(func() { var clone, _ = CloneCommandFactory() clone.Run([]string{}) }) @@ -125,9 +125,9 @@ func TestUnknownOption(t *testing.T) { } func TestCloneNotGitRepository(t *testing.T) { - os.Setenv(lib.RrhOnError, "FAIL") - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { - var output = lib.CaptureStdout(func() { + os.Setenv(rrh.RrhOnError, "FAIL") + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { + var output = rrh.CaptureStdout(func() { var clone, _ = CloneCommandFactory() clone.Run([]string{"../testdata"}) }) diff --git a/internal/common.go b/internal/common.go index d796122..0ef068c 100644 --- a/internal/common.go +++ b/internal/common.go @@ -3,22 +3,22 @@ package internal import ( "fmt" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) -func printErrors(config *lib.Config, errs []error) int { - var onError = config.GetValue(lib.RrhOnError) - if onError != lib.Ignore { +func printErrors(config *rrh.Config, errs []error) int { + var onError = config.GetValue(rrh.RrhOnError) + if onError != rrh.Ignore { for _, err := range errs { fmt.Println(err.Error()) } } - if len(errs) > 0 && (onError == lib.Fail || onError == lib.FailImmediately) { + if len(errs) > 0 && (onError == rrh.Fail || onError == rrh.FailImmediately) { return 4 } return 0 } -func isFailImmediately(config *lib.Config) bool { - return config.GetValue(lib.RrhOnError) == lib.FailImmediately +func isFailImmediately(config *rrh.Config) bool { + return config.GetValue(rrh.RrhOnError) == rrh.FailImmediately } diff --git a/internal/config_cmd.go b/internal/config_cmd.go index 95fdc27..024ee62 100644 --- a/internal/config_cmd.go +++ b/internal/config_cmd.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/mitchellh/cli" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -75,7 +75,7 @@ func (clc *configListCommand) Help() string { Run performs the command. */ func (config *ConfigCommand) Run(args []string) int { - c := cli.NewCLI("rrh config", lib.VERSION) + c := cli.NewCLI("rrh config", rrh.VERSION) c.Args = args c.Autocomplete = true c.Commands = map[string]cli.CommandFactory{ @@ -99,7 +99,7 @@ func (csc *configSetCommand) Run(args []string) int { fmt.Println(csc.Help()) return 1 } - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var err = config.Update(args[0], args[1]) if err != nil { fmt.Println(err.Error()) @@ -117,7 +117,7 @@ func (cuc *configUnsetCommand) Run(args []string) int { fmt.Println(cuc.Help()) return 1 } - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var err = config.Unset(args[0]) if err != nil { var status = config.PrintErrors(err) @@ -133,14 +133,14 @@ func (cuc *configUnsetCommand) Run(args []string) int { Run performs the command. */ func (clc *configListCommand) Run(args []string) int { - var config = lib.OpenConfig() - for _, label := range lib.AvailableLabels { + var config = rrh.OpenConfig() + for _, label := range rrh.AvailableLabels { fmt.Println(formatVariableAndValue(config, label)) } return 0 } -func formatVariableAndValue(config *lib.Config, label string) string { +func formatVariableAndValue(config *rrh.Config, label string) string { var value, readFrom = config.GetString(label) return fmt.Sprintf("%s: %s (%s)", config.Color.ColorizedLabel(label), config.Color.ColorizeConfigValue(value), readFrom) diff --git a/internal/config_test.go b/internal/config_test.go index 8431e9d..00a076e 100644 --- a/internal/config_test.go +++ b/internal/config_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/mitchellh/go-homedir" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func assert(t *testing.T, actual string, expected string) { @@ -68,26 +68,26 @@ func TestSynopsises(t *testing.T) { } func TestConfigUnset(t *testing.T) { - os.Setenv(lib.RrhOnError, lib.Fail) + os.Setenv(rrh.RrhOnError, rrh.Fail) var testcases = []struct { args []string status int wontValue string - wontFrom lib.ReadFrom + wontFrom rrh.ReadFrom }{ - {[]string{lib.RrhAutoCreateGroup}, 0, "false", lib.Default}, - {[]string{"unknown"}, 5, "", lib.NotFound}, - {[]string{lib.RrhAutoCreateGroup, "tooManyArgs"}, 1, "", ""}, + {[]string{rrh.RrhAutoCreateGroup}, 0, "false", rrh.Default}, + {[]string{"unknown"}, 5, "", rrh.NotFound}, + {[]string{rrh.RrhAutoCreateGroup, "tooManyArgs"}, 1, "", ""}, } for _, tc := range testcases { - var dbfile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbfile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var cuc, _ = configUnsetCommandFactory() var statusCode = cuc.Run(tc.args) if statusCode != tc.status { t.Errorf("%v: status code did not match, wont: %d, got: %d", tc, tc.status, statusCode) } if statusCode == 0 { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var value, from = config.GetString(tc.args[0]) if value != tc.wontValue || from != tc.wontFrom { t.Errorf("%v: did not match: wont: (%s, %s), got: (%s, %s)", tc, tc.wontValue, tc.wontFrom, value, from) @@ -96,13 +96,13 @@ func TestConfigUnset(t *testing.T) { }) defer os.Remove(dbfile) } - os.Unsetenv(lib.RrhOnError) + os.Unsetenv(rrh.RrhOnError) } func ExampleConfigCommand() { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - os.Setenv(lib.RrhHome, "../testdata/") - os.Setenv(lib.RrhDatabasePath, "${RRH_HOME}/test_db.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhHome, "../testdata/") + os.Setenv(rrh.RrhDatabasePath, "${RRH_HOME}/test_db.json") var command, _ = ConfigCommandFactory() command.Run([]string{}) // the output of no arguments are same as list subcommand. // Output: @@ -120,9 +120,9 @@ func ExampleConfigCommand() { // RRH_TIME_FORMAT: relative (default) } func ExampleConfigCommand_Run() { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - os.Setenv(lib.RrhHome, "../testdata/") - os.Setenv(lib.RrhDatabasePath, "${RRH_HOME}/database.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhHome, "../testdata/") + os.Setenv(rrh.RrhDatabasePath, "${RRH_HOME}/database.json") var command, _ = ConfigCommandFactory() command.Run([]string{"list"}) // the output of no arguments are same as list subcommand. // Output: @@ -140,9 +140,9 @@ func ExampleConfigCommand_Run() { // RRH_TIME_FORMAT: relative (default) } func Example_listCommand_Run() { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - os.Setenv(lib.RrhHome, "../testdata/") - os.Unsetenv(lib.RrhDatabasePath) + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhHome, "../testdata/") + os.Unsetenv(rrh.RrhDatabasePath) var clc, _ = configListCommandFactory() clc.Run([]string{}) // Output: @@ -161,24 +161,24 @@ func Example_listCommand_Run() { } func TestLoadConfigFile(t *testing.T) { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") var testdata = []struct { key string value string - from lib.ReadFrom + from rrh.ReadFrom }{ - {lib.RrhAutoDeleteGroup, "false", lib.ConfigFile}, - {lib.RrhAutoCreateGroup, "true", lib.ConfigFile}, - {lib.RrhSortOnUpdating, "true", lib.ConfigFile}, - {lib.RrhConfigPath, "../testdata/config.json", lib.Env}, - {lib.RrhTimeFormat, lib.Relative, lib.Default}, - {lib.RrhOnError, lib.Warn, lib.Default}, - {lib.RrhEnableColorized, "false", lib.Default}, - {"unknown", "", lib.NotFound}, + {rrh.RrhAutoDeleteGroup, "false", rrh.ConfigFile}, + {rrh.RrhAutoCreateGroup, "true", rrh.ConfigFile}, + {rrh.RrhSortOnUpdating, "true", rrh.ConfigFile}, + {rrh.RrhConfigPath, "../testdata/config.json", rrh.Env}, + {rrh.RrhTimeFormat, rrh.Relative, rrh.Default}, + {rrh.RrhOnError, rrh.Warn, rrh.Default}, + {rrh.RrhEnableColorized, "false", rrh.Default}, + {"unknown", "", rrh.NotFound}, } - var config = lib.OpenConfig() + var config = rrh.OpenConfig() for _, data := range testdata { if val, from := config.GetString(data.key); val != data.value || from != data.from { t.Errorf("%s: want: (%s, %s), got: (%s, %s)", data.key, data.value, data.from, val, from) @@ -187,30 +187,30 @@ func TestLoadConfigFile(t *testing.T) { } func TestOpenConfig(t *testing.T) { - os.Unsetenv(lib.RrhHome) - os.Unsetenv(lib.RrhDatabasePath) - os.Unsetenv(lib.RrhConfigPath) + os.Unsetenv(rrh.RrhHome) + os.Unsetenv(rrh.RrhDatabasePath) + os.Unsetenv(rrh.RrhConfigPath) var home, _ = homedir.Dir() var testdata = []struct { key string want string }{ - {lib.RrhHome, fmt.Sprintf("%s/.rrh", home)}, - {lib.RrhConfigPath, fmt.Sprintf("%s/.rrh/config.json", home)}, - {lib.RrhDatabasePath, fmt.Sprintf("%s/.rrh/database.json", home)}, - {lib.RrhDefaultGroupName, "no-group"}, - {lib.RrhCloneDestination, "."}, - {lib.RrhOnError, lib.Warn}, - {lib.RrhAutoCreateGroup, "false"}, - {lib.RrhAutoDeleteGroup, "false"}, - {lib.RrhSortOnUpdating, "false"}, - {lib.RrhTimeFormat, lib.Relative}, + {rrh.RrhHome, fmt.Sprintf("%s/.rrh", home)}, + {rrh.RrhConfigPath, fmt.Sprintf("%s/.rrh/config.json", home)}, + {rrh.RrhDatabasePath, fmt.Sprintf("%s/.rrh/database.json", home)}, + {rrh.RrhDefaultGroupName, "no-group"}, + {rrh.RrhCloneDestination, "."}, + {rrh.RrhOnError, rrh.Warn}, + {rrh.RrhAutoCreateGroup, "false"}, + {rrh.RrhAutoDeleteGroup, "false"}, + {rrh.RrhSortOnUpdating, "false"}, + {rrh.RrhTimeFormat, rrh.Relative}, {"unknown", ""}, } // os.Unsetenv(RrhConfigPath) // os.Unsetenv(RrhHome) - var config = lib.OpenConfig() + var config = rrh.OpenConfig() for _, data := range testdata { if value := config.GetDefaultValue(data.key); value != data.want { t.Errorf("%s: want: %s, got: %s", data.key, data.want, value) @@ -226,20 +226,20 @@ func TestPrintErrors(t *testing.T) { wontStatus int someOutput bool }{ - {lib.Ignore, []error{}, 0, false}, - {lib.Ignore, []error{errors.New("error")}, 0, false}, - {lib.Warn, []error{}, 0, false}, - {lib.Warn, []error{errors.New("error")}, 0, true}, - {lib.Fail, []error{}, 0, false}, - {lib.Fail, []error{errors.New("error")}, 5, true}, - {lib.FailImmediately, []error{}, 0, false}, - {lib.FailImmediately, []error{errors.New("error")}, 5, true}, + {rrh.Ignore, []error{}, 0, false}, + {rrh.Ignore, []error{errors.New("error")}, 0, false}, + {rrh.Warn, []error{}, 0, false}, + {rrh.Warn, []error{errors.New("error")}, 0, true}, + {rrh.Fail, []error{}, 0, false}, + {rrh.Fail, []error{errors.New("error")}, 5, true}, + {rrh.FailImmediately, []error{}, 0, false}, + {rrh.FailImmediately, []error{errors.New("error")}, 5, true}, } - var config = lib.NewConfig() + var config = rrh.NewConfig() for _, tc := range testcases { - config.Update(lib.RrhOnError, tc.onError) - var output = lib.CaptureStdout(func() { + config.Update(rrh.RrhOnError, tc.onError) + var output = rrh.CaptureStdout(func() { var statusCode = config.PrintErrors(tc.error...) if statusCode != tc.wontStatus { t.Errorf("%v: status code did not match, wont: %d, got: %d", tc, tc.wontStatus, statusCode) @@ -257,22 +257,22 @@ func TestConfigSet(t *testing.T) { args []string statusCode int value string - location lib.ReadFrom + location rrh.ReadFrom }{ - {[]string{"RRH_DEFAULT_GROUP_NAME", "newgroup"}, 0, "newgroup", lib.ConfigFile}, + {[]string{"RRH_DEFAULT_GROUP_NAME", "newgroup"}, 0, "newgroup", rrh.ConfigFile}, {[]string{"RRH_DEFAULT_GROUP_NAME"}, 1, "", ""}, {[]string{"RRH_AUTO_DELETE_GROUP", "yes"}, 2, "", ""}, - {[]string{lib.RrhConfigPath, "../testdata/broken.json"}, 2, "", ""}, + {[]string{rrh.RrhConfigPath, "../testdata/broken.json"}, 2, "", ""}, } for _, td := range testdata { - var dbfile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbfile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var set, _ = configSetCommandFactory() var status = set.Run(td.args) if status != td.statusCode { t.Errorf("%v: status code did not match, wont: %d, got: %d", td.args, td.statusCode, status) } if status == 0 { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var value, from = config.GetString(td.args[0]) if value != td.value { t.Errorf("%v: set value did not match, wont: %s, got: %s", td.args, td.value, value) @@ -287,10 +287,10 @@ func TestConfigSet(t *testing.T) { } func TestFormatVariableAndValue(t *testing.T) { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - var config = lib.OpenConfig() - assert(t, formatVariableAndValue(config, lib.RrhDefaultGroupName), "RRH_DEFAULT_GROUP_NAME: no-group (default)") - if config.IsSet(lib.RrhOnError) { + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + var config = rrh.OpenConfig() + assert(t, formatVariableAndValue(config, rrh.RrhDefaultGroupName), "RRH_DEFAULT_GROUP_NAME: no-group (default)") + if config.IsSet(rrh.RrhOnError) { t.Errorf("IsSet accepts only bool variable") } } diff --git a/internal/export_cmd.go b/internal/export_cmd.go index a73da21..cfb6fb1 100644 --- a/internal/export_cmd.go +++ b/internal/export_cmd.go @@ -11,7 +11,7 @@ import ( "github.com/mitchellh/cli" "github.com/mitchellh/go-homedir" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -52,8 +52,8 @@ func (export *ExportCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - db, err := lib.Open(config) + var config = rrh.OpenConfig() + db, err := rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 2 @@ -79,7 +79,7 @@ func hideHome(result string) string { return strings.Replace(result, absPath, "${HOME}", -1) } -func (export *ExportCommand) perform(db *lib.Database) int { +func (export *ExportCommand) perform(db *rrh.Database) int { var result, _ = json.Marshal(db) var stringResult = string(result) if !export.options.noHideHome { diff --git a/internal/export_test.go b/internal/export_test.go index 2347418..c13f5ba 100644 --- a/internal/export_test.go +++ b/internal/export_test.go @@ -6,13 +6,13 @@ import ( "strings" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) -func open2(jsonName string) *lib.Database { - os.Setenv(lib.RrhDatabasePath, fmt.Sprintf("../testdata/%s", jsonName)) - var config = lib.OpenConfig() - var db, _ = lib.Open(config) +func open2(jsonName string) *rrh.Database { + os.Setenv(rrh.RrhDatabasePath, fmt.Sprintf("../testdata/%s", jsonName)) + var config = rrh.OpenConfig() + var db, _ = rrh.Open(config) return db } @@ -40,7 +40,7 @@ func TestUnknownOptions(t *testing.T) { } func TestBrokenDatabase(t *testing.T) { - var dbFile = lib.Rollback("../testdata/broken.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/broken.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var export, _ = ExportCommandFactory() if val := export.Run([]string{}); val != 2 { t.Errorf("broken json successfully read!?: %d", val) @@ -50,8 +50,8 @@ func TestBrokenDatabase(t *testing.T) { } func TestNullDB(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/nulldb.json") - var result = lib.CaptureStdout(func() { + os.Setenv(rrh.RrhDatabasePath, "../testdata/nulldb.json") + var result = rrh.CaptureStdout(func() { var export, _ = ExportCommandFactory() export.Run([]string{}) }) @@ -67,8 +67,8 @@ func TestNullDB(t *testing.T) { } func TestNullDBNoIndent(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/nulldb.json") - var result = lib.CaptureStdout(func() { + os.Setenv(rrh.RrhDatabasePath, "../testdata/nulldb.json") + var result = rrh.CaptureStdout(func() { var export, _ = ExportCommandFactory() export.Run([]string{"--no-indent"}) }) @@ -78,8 +78,8 @@ func TestNullDBNoIndent(t *testing.T) { } func TestTmpDBNoIndent(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var result = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var result = rrh.CaptureStdout(func() { var export, _ = ExportCommandFactory() export.Run([]string{"--no-indent"}) }) diff --git a/internal/fetch_all_cmd.go b/internal/fetch_all_cmd.go index 804d720..8604a44 100644 --- a/internal/fetch_all_cmd.go +++ b/internal/fetch_all_cmd.go @@ -5,7 +5,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -43,14 +43,14 @@ func (fetchAll *FetchAllCommand) validateArguments(args []string) (*fetchOptions Run performs the command. */ func (fetchAll *FetchAllCommand) Run(args []string) int { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() var options, err = fetchAll.validateArguments(args) if err != nil { fmt.Println(err.Error()) return 1 } - var db, err2 = lib.Open(config) + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 1 @@ -58,7 +58,7 @@ func (fetchAll *FetchAllCommand) Run(args []string) int { return printErrors(config, fetchAll.execFetch(db, options)) } -func convertToGroupNames(groups []lib.Group) []string { +func convertToGroupNames(groups []rrh.Group) []string { var result = []string{} for _, group := range groups { result = append(result, group.Name) @@ -66,16 +66,16 @@ func convertToGroupNames(groups []lib.Group) []string { return result } -func (fetchAll *FetchAllCommand) execFetch(db *lib.Database, options *fetchOptions) []error { - var onError = db.Config.GetValue(lib.RrhOnError) +func (fetchAll *FetchAllCommand) execFetch(db *rrh.Database, options *fetchOptions) []error { + var onError = db.Config.GetValue(rrh.RrhOnError) var errorlist = []error{} var fetch = FetchCommand{options} - var relations = lib.FindTargets(db, convertToGroupNames(db.Groups)) + var relations = rrh.FindTargets(db, convertToGroupNames(db.Groups)) var progress = NewProgress(len(relations)) for _, relation := range relations { var err = fetch.FetchRepository(db, &relation, progress) if err != nil { - if onError == lib.FailImmediately { + if onError == rrh.FailImmediately { return []error{err} } errorlist = append(errorlist, err) diff --git a/internal/fetch_cmd.go b/internal/fetch_cmd.go index feafe9e..388c479 100644 --- a/internal/fetch_cmd.go +++ b/internal/fetch_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -87,8 +87,8 @@ func (fetch *FetchCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 1 @@ -96,24 +96,24 @@ func (fetch *FetchCommand) Run(args []string) int { return printErrors(config, fetch.perform(db)) } -func (fetch *FetchCommand) findRelations(db *lib.Database) []lib.Relation { +func (fetch *FetchCommand) findRelations(db *rrh.Database) []rrh.Relation { var args = fetch.options.args if len(args) == 0 { - args = []string{db.Config.GetValue(lib.RrhDefaultGroupName)} + args = []string{db.Config.GetValue(rrh.RrhDefaultGroupName)} } - return lib.FindTargets(db, args) + return rrh.FindTargets(db, args) } -func (fetch *FetchCommand) perform(db *lib.Database) []error { +func (fetch *FetchCommand) perform(db *rrh.Database) []error { var errorlist = []error{} - var onError = db.Config.GetValue(lib.RrhOnError) + var onError = db.Config.GetValue(rrh.RrhOnError) var relations = fetch.findRelations(db) var progress = NewProgress(len(relations)) for _, relation := range relations { var err = fetch.FetchRepository(db, &relation, progress) if err != nil { - if onError == lib.FailImmediately { + if onError == rrh.FailImmediately { return []error{err} } errorlist = append(errorlist, err) @@ -148,7 +148,7 @@ DoFetch executes fetch operation of git. Currently, fetch is conducted by the system call. Ideally, fetch is performed by using go-git. */ -func (fetch *FetchCommand) DoFetch(repo *lib.Repository, relation *lib.Relation, progress *Progress) error { +func (fetch *FetchCommand) DoFetch(repo *rrh.Repository, relation *rrh.Relation, progress *Progress) error { var cmd = exec.Command("git", "fetch", fetch.options.remote) cmd.Dir = repo.Path progress.Increment() @@ -164,7 +164,7 @@ func (fetch *FetchCommand) DoFetch(repo *lib.Repository, relation *lib.Relation, /* FetchRepository execute `git fetch` on the given repository. */ -func (fetch *FetchCommand) FetchRepository(db *lib.Database, relation *lib.Relation, progress *Progress) error { +func (fetch *FetchCommand) FetchRepository(db *rrh.Database, relation *rrh.Relation, progress *Progress) error { var repository = db.FindRepository(relation.RepositoryID) if repository == nil { return fmt.Errorf("%s: repository not found", relation) diff --git a/internal/fetch_test.go b/internal/fetch_test.go index 85e1134..635d7a0 100644 --- a/internal/fetch_test.go +++ b/internal/fetch_test.go @@ -4,11 +4,11 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestPerformFetch(t *testing.T) { - var dbFile = lib.Rollback("../testdata/database.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/database.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var fetch, _ = FetchCommandFactory() var status = fetch.Run([]string{"no-group"}) if status != 0 { diff --git a/internal/group_cmd.go b/internal/group_cmd.go index b8fc824..14efd74 100644 --- a/internal/group_cmd.go +++ b/internal/group_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -123,7 +123,7 @@ SUBCOMMAND Run peforms the command. */ func (group *GroupCommand) Run(args []string) int { - c := cli.NewCLI("rrh group", lib.VERSION) + c := cli.NewCLI("rrh group", rrh.VERSION) c.Args = args c.Autocomplete = true c.Commands = map[string]cli.CommandFactory{ @@ -178,8 +178,8 @@ func (gac *groupAddCommand) Run(args []string) int { if err != nil { return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -187,7 +187,7 @@ func (gac *groupAddCommand) Run(args []string) int { return gac.perform(db) } -func (gac *groupAddCommand) perform(db *lib.Database) int { +func (gac *groupAddCommand) perform(db *rrh.Database) int { if len(gac.options.args) == 0 { fmt.Println(gac.Help()) return 3 @@ -225,7 +225,7 @@ func (glc *groupListCommand) parse(args []string) (*groupListOptions, error) { return opt, nil } -func printGroupInfo(db *lib.Database, group *lib.Group) { +func printGroupInfo(db *rrh.Database, group *rrh.Group) { count := db.ContainsCount(group.Name) unit := "repositories" if count == 1 { @@ -234,7 +234,7 @@ func printGroupInfo(db *lib.Database, group *lib.Group) { fmt.Printf("%s: %s (%d %s, omit: %v)\n", group.Name, group.Description, count, unit, group.OmitList) } -func (gic *groupInfoCommand) perform(db *lib.Database, args []string) int { +func (gic *groupInfoCommand) perform(db *rrh.Database, args []string) int { errs := []error{} for _, arg := range args { group := db.FindGroup(arg) @@ -252,8 +252,8 @@ func (gic *groupInfoCommand) Run(args []string) int { fmt.Println(gic.Help()) return 1 } - var config = lib.OpenConfig() - var db, err = lib.Open(config) + var config = rrh.OpenConfig() + var db, err = rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 2 @@ -261,7 +261,7 @@ func (gic *groupInfoCommand) Run(args []string) int { return gic.perform(db, args) } -func (goc *groupOfCommand) perform(db *lib.Database, repositoryID string) int { +func (goc *groupOfCommand) perform(db *rrh.Database, repositoryID string) int { if !db.HasRepository(repositoryID) { fmt.Printf("%s: repository not found\n", repositoryID) return 3 @@ -276,8 +276,8 @@ func (goc *groupOfCommand) Run(args []string) int { fmt.Println(goc.Help()) return 1 } - var config = lib.OpenConfig() - var db, err = lib.Open(config) + var config = rrh.OpenConfig() + var db, err = rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 2 @@ -293,14 +293,14 @@ func printRepositoryCount(count int) { } } -func findGroupName(name string, nameOnlyFlag bool, config *lib.Config) string { +func findGroupName(name string, nameOnlyFlag bool, config *rrh.Config) string { if nameOnlyFlag { return name } return config.Color.ColorizedGroupName(name) } -func (glc *groupListCommand) printResult(result groupListResult, options *groupListOptions, config *lib.Config) { +func (glc *groupListCommand) printResult(result groupListResult, options *groupListOptions, config *rrh.Config) { fmt.Print(findGroupName(result.Name, options.nameOnly, config)) if !options.nameOnly && options.desc { fmt.Printf(",%s", result.Description) @@ -314,7 +314,7 @@ func (glc *groupListCommand) printResult(result groupListResult, options *groupL fmt.Println() } -func (glc *groupListCommand) printAll(results []groupListResult, options *groupListOptions, config *lib.Config) { +func (glc *groupListCommand) printAll(results []groupListResult, options *groupListOptions, config *rrh.Config) { for _, result := range results { glc.printResult(result, options, config) } @@ -328,8 +328,8 @@ func (glc *groupListCommand) Run(args []string) int { if err != nil { return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -358,7 +358,7 @@ func (grc *groupRemoveCommand) Inquiry(groupName string) bool { if !grc.options.inquiry { return true } - return lib.IsInputYes(fmt.Sprintf("%s: remove group? [yN]", groupName)) + return rrh.IsInputYes(fmt.Sprintf("%s: remove group? [yN]", groupName)) } func (grc *groupRemoveCommand) buildFlagSet() (*flag.FlagSet, *groupRemoveOptions) { @@ -392,8 +392,8 @@ func (grc *groupRemoveCommand) Run(args []string) int { if err != nil { return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -423,8 +423,8 @@ func (guc *groupUpdateCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -516,7 +516,7 @@ type groupListResult struct { Repos []string } -func appendRelations(groupName string, relations []lib.Relation) []string { +func appendRelations(groupName string, relations []rrh.Relation) []string { var repos = []string{} for _, relation := range relations { if relation.GroupName == groupName { @@ -526,7 +526,7 @@ func appendRelations(groupName string, relations []lib.Relation) []string { return repos } -func (glc *groupListCommand) listGroups(db *lib.Database, listOptions *groupListOptions) []groupListResult { +func (glc *groupListCommand) listGroups(db *rrh.Database, listOptions *groupListOptions) []groupListResult { var results = []groupListResult{} for _, group := range db.Groups { var result = groupListResult{group.Name, group.Description, []string{}} @@ -544,7 +544,7 @@ func trueOrFalse(flag string) bool { return false } -func (gac *groupAddCommand) addGroups(db *lib.Database, options *groupAddOptions) error { +func (gac *groupAddCommand) addGroups(db *rrh.Database, options *groupAddOptions) error { for _, groupName := range options.args { var flag = trueOrFalse(options.omit) var _, err = db.CreateGroup(groupName, options.desc, flag) @@ -555,7 +555,7 @@ func (gac *groupAddCommand) addGroups(db *lib.Database, options *groupAddOptions return nil } -func (grc *groupRemoveCommand) removeGroupsImpl(db *lib.Database, groupName string) error { +func (grc *groupRemoveCommand) removeGroupsImpl(db *rrh.Database, groupName string) error { if grc.options.force { db.ForceDeleteGroup(groupName) grc.printIfVerbose(fmt.Sprintf("%s: group removed", groupName)) @@ -568,7 +568,7 @@ func (grc *groupRemoveCommand) removeGroupsImpl(db *lib.Database, groupName stri return nil } -func (grc *groupRemoveCommand) removeGroups(db *lib.Database) error { +func (grc *groupRemoveCommand) removeGroups(db *rrh.Database) error { for _, groupName := range grc.options.args { if !db.HasGroup(groupName) || !grc.Inquiry(groupName) { return nil @@ -580,8 +580,8 @@ func (grc *groupRemoveCommand) removeGroups(db *lib.Database) error { return nil } -func createNewGroup(opt *groupUpdateOptions, prevGroup *lib.Group) lib.Group { - var newGroup = lib.Group{Name: opt.newName, Description: opt.desc, OmitList: strings.ToLower(opt.omitList) == "true"} +func createNewGroup(opt *groupUpdateOptions, prevGroup *rrh.Group) rrh.Group { + var newGroup = rrh.Group{Name: opt.newName, Description: opt.desc, OmitList: strings.ToLower(opt.omitList) == "true"} if opt.desc == "" { newGroup.Description = prevGroup.Description } @@ -594,7 +594,7 @@ func createNewGroup(opt *groupUpdateOptions, prevGroup *lib.Group) lib.Group { return newGroup } -func (guc *groupUpdateCommand) updateGroup(db *lib.Database, opt *groupUpdateOptions) error { +func (guc *groupUpdateCommand) updateGroup(db *rrh.Database, opt *groupUpdateOptions) error { if !db.HasGroup(opt.target) { return fmt.Errorf("%s: group not found", opt.target) } diff --git a/internal/group_test.go b/internal/group_test.go index e2b8f94..d73dcec 100644 --- a/internal/group_test.go +++ b/internal/group_test.go @@ -5,11 +5,11 @@ import ( "strings" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func ExampleGroupCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var gc, _ = GroupCommandFactory() gc.Run([]string{"list"}) }) @@ -21,7 +21,7 @@ func ExampleGroupCommand_Run() { } func Example_groupListCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var glc, _ = groupListCommandFactory() glc.Run([]string{"-d", "-r"}) }) @@ -33,7 +33,7 @@ func Example_groupListCommand_Run() { } func Example_groupOfCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var goc, _ = groupOfCommandFactory() goc.Run([]string{"repo1"}) }) @@ -43,7 +43,7 @@ func Example_groupOfCommand_Run() { } func Example_groupInfoCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var gic, _ = groupInfoCommandFactory() gic.Run([]string{"group1", "group2", "groupN"}) }) @@ -55,8 +55,8 @@ func Example_groupInfoCommand_Run() { } func TestGroupListOnlyName(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var output = rrh.CaptureStdout(func() { var glc, _ = GroupCommandFactory() glc.Run([]string{"list", "--only-groupname"}) }) @@ -82,8 +82,8 @@ ARGUMENTS REPOSITORY_ID show the groups of the repository.`}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var output = rrh.CaptureStdout(func() { var command, _ = groupOfCommandFactory() command.Run(tc.args) }) @@ -116,12 +116,12 @@ func TestAddGroup(t *testing.T) { {[]string{"add"}, 3, []groupChecker{}}, } for _, testcase := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var gac, _ = GroupCommandFactory() if val := gac.Run(testcase.args); val != testcase.statusCode { t.Errorf("%v: test failed, wont: %d, got: %d", testcase.args, testcase.statusCode, val) } - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) for _, checker := range testcase.checkers { if db2.HasGroup(checker.groupName) != checker.existFlag { t.Errorf("%v: group check failed: %s, wont: %v, got: %v", testcase.args, checker.groupName, checker.existFlag, !checker.existFlag) @@ -142,8 +142,8 @@ func TestAddGroup(t *testing.T) { } func TestGroupInfo(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") var testdata = []struct { args []string @@ -154,7 +154,7 @@ func TestGroupInfo(t *testing.T) { {[]string{"group1"}, 0}, } for _, td := range testdata { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var gic = groupInfoCommand{} var status = gic.Run(td.args) if status != td.wontStatus { @@ -166,8 +166,8 @@ func TestGroupInfo(t *testing.T) { } func TestUpdateGroupFailed(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") var testcases = []struct { opt groupUpdateOptions @@ -176,9 +176,9 @@ func TestUpdateGroupFailed(t *testing.T) { {groupUpdateOptions{"newName", "desc", "omitList", "target"}, true}, } for _, testcase := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var guc = groupUpdateCommand{} - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) var err = guc.updateGroup(db, &testcase.opt) if (err != nil) != testcase.errFlag { t.Errorf("%v: test failed: err wont: %v, got: %v: err (%v)", testcase.opt, testcase.errFlag, !testcase.errFlag, err) @@ -216,12 +216,12 @@ func TestUpdateGroup(t *testing.T) { {[]string{"update", "group1", "group4"}, 1, []groupChecker{}, []relation{}}, } for _, testcase := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var guc, _ = GroupCommandFactory() if val := guc.Run(testcase.args); val != testcase.statusCode { t.Errorf("%v: group update failed status code wont: %d, got: %d", testcase.args, testcase.statusCode, val) } - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) for _, gec := range testcase.gexists { if db2.HasGroup(gec.groupName) != gec.existFlag { t.Errorf("%s: exist check failed wont: %v, got: %v", gec.groupName, gec.existFlag, !gec.existFlag) @@ -259,12 +259,12 @@ func TestRemoveGroup(t *testing.T) { {[]string{"rm"}, 1, []groupChecker{}}, } for _, testcase := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var grc, _ = GroupCommandFactory() if val := grc.Run(testcase.args); val != testcase.statusCode { t.Errorf("%v: group remove failed: wont: %d, got: %d", testcase.args, testcase.statusCode, val) } - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) for _, checker := range testcase.checkers { if db2.HasGroup(checker.groupName) != checker.existFlag { t.Errorf("%v: exist check failed: wont: %v, got: %v", testcase.args, checker.existFlag, !checker.existFlag) @@ -285,8 +285,8 @@ func TestRemoveGroup(t *testing.T) { } func TestInvalidOptionInGroupList(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") - lib.CaptureStdout(func() { + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + rrh.CaptureStdout(func() { var glc, _ = groupListCommandFactory() if val := glc.Run([]string{"--unknown-option"}); val != 1 { t.Error("list subcommand accept unknown-option!") diff --git a/internal/import_cmd.go b/internal/import_cmd.go index f83f056..f4ba2df 100644 --- a/internal/import_cmd.go +++ b/internal/import_cmd.go @@ -12,7 +12,7 @@ import ( "github.com/mitchellh/cli" "github.com/mitchellh/go-homedir" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) type importOptions struct { @@ -42,14 +42,14 @@ func (options *importOptions) printIfNeeded(message string) { } } -func eraseDatabase(db *lib.Database, command *ImportCommand) { - db.Groups = []lib.Group{} - db.Repositories = []lib.Repository{} - db.Relations = []lib.Relation{} +func eraseDatabase(db *rrh.Database, command *ImportCommand) { + db.Groups = []rrh.Group{} + db.Repositories = []rrh.Repository{} + db.Relations = []rrh.Relation{} command.options.printIfNeeded("The local database is cleared") } -func perform(db *lib.Database, command *ImportCommand) int { +func perform(db *rrh.Database, command *ImportCommand) int { if command.options.overwrite { eraseDatabase(db, command) } @@ -75,8 +75,8 @@ func (command *ImportCommand) Run(args []string) int { fmt.Println(err1) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { return 2 } @@ -129,8 +129,8 @@ ARGUMENTS DATABASE_JSON the exported RRH database.` } -func readNewDB(path string, config *lib.Config) (*lib.Database, error) { - var db = lib.Database{Timestamp: lib.Now(), Repositories: []lib.Repository{}, Groups: []lib.Group{}, Relations: []lib.Relation{}, Config: config} +func readNewDB(path string, config *rrh.Config) (*rrh.Database, error) { + var db = rrh.Database{Timestamp: rrh.Now(), Repositories: []rrh.Repository{}, Groups: []rrh.Group{}, Relations: []rrh.Relation{}, Config: config} var bytes, err = ioutil.ReadFile(path) if err != nil { return &db, nil @@ -143,7 +143,7 @@ func readNewDB(path string, config *lib.Config) (*lib.Database, error) { return &db, nil } -func (command *ImportCommand) copyDB(from *lib.Database, to *lib.Database) []error { +func (command *ImportCommand) copyDB(from *rrh.Database, to *rrh.Database) []error { var errs = []error{} var errs1 = command.copyGroups(from, to) var errs2 = command.copyRepositories(from, to) @@ -153,7 +153,7 @@ func (command *ImportCommand) copyDB(from *lib.Database, to *lib.Database) []err return append(errs, errs3...) } -func (command *ImportCommand) copyGroup(group lib.Group, to *lib.Database) []error { +func (command *ImportCommand) copyGroup(group rrh.Group, to *rrh.Database) []error { var list = []error{} if to.HasGroup(group.Name) { var successFlag = to.UpdateGroup(group.Name, group) @@ -170,7 +170,7 @@ func (command *ImportCommand) copyGroup(group lib.Group, to *lib.Database) []err return list } -func (command *ImportCommand) copyGroups(from *lib.Database, to *lib.Database) []error { +func (command *ImportCommand) copyGroups(from *rrh.Database, to *rrh.Database) []error { var list = []error{} for _, group := range from.Groups { var errs = command.copyGroup(group, to) @@ -182,7 +182,7 @@ func (command *ImportCommand) copyGroups(from *lib.Database, to *lib.Database) [ return list } -func findOrigin(remotes []lib.Remote) lib.Remote { +func findOrigin(remotes []rrh.Remote) rrh.Remote { for _, remote := range remotes { if remote.Name == "origin" { return remote @@ -191,7 +191,7 @@ func findOrigin(remotes []lib.Remote) lib.Remote { return remotes[0] } -func doClone(repository lib.Repository, remote lib.Remote) error { +func doClone(repository rrh.Repository, remote rrh.Remote) error { var cmd = exec.Command("git", "clone", remote.URL, repository.Path) var err = cmd.Run() if err != nil { @@ -200,7 +200,7 @@ func doClone(repository lib.Repository, remote lib.Remote) error { return nil } -func (command *ImportCommand) cloneRepository(repository lib.Repository) error { +func (command *ImportCommand) cloneRepository(repository rrh.Repository) error { if len(repository.Remotes) == 0 { return fmt.Errorf("%s: could not clone, did not have remotes", repository.ID) } @@ -210,7 +210,7 @@ func (command *ImportCommand) cloneRepository(repository lib.Repository) error { return err } -func (command *ImportCommand) cloneIfNeeded(repository lib.Repository) error { +func (command *ImportCommand) cloneIfNeeded(repository rrh.Repository) error { if !command.options.autoClone { return fmt.Errorf("%s: repository path did not exist at %s", repository.ID, repository.Path) } @@ -218,7 +218,7 @@ func (command *ImportCommand) cloneIfNeeded(repository lib.Repository) error { return nil } -func (command *ImportCommand) copyRepository(repository lib.Repository, to *lib.Database) []error { +func (command *ImportCommand) copyRepository(repository rrh.Repository, to *rrh.Database) []error { if to.HasRepository(repository.ID) { return []error{} } @@ -232,8 +232,8 @@ func (command *ImportCommand) copyRepository(repository lib.Repository, to *lib. return command.copyRepositoryImpl(repository, to) } -func (command *ImportCommand) copyRepositoryImpl(repository lib.Repository, to *lib.Database) []error { - if err := lib.IsExistAndGitRepository(repository.Path, repository.ID); err != nil { +func (command *ImportCommand) copyRepositoryImpl(repository rrh.Repository, to *rrh.Database) []error { + if err := rrh.IsExistAndGitRepository(repository.Path, repository.ID); err != nil { return []error{err} } to.CreateRepository(repository.ID, repository.Path, repository.Description, repository.Remotes) @@ -241,7 +241,7 @@ func (command *ImportCommand) copyRepositoryImpl(repository lib.Repository, to * return []error{} } -func (command *ImportCommand) copyRepositories(from *lib.Database, to *lib.Database) []error { +func (command *ImportCommand) copyRepositories(from *rrh.Database, to *rrh.Database) []error { var list = []error{} for _, repository := range from.Repositories { var errs = command.copyRepository(repository, to) @@ -253,7 +253,7 @@ func (command *ImportCommand) copyRepositories(from *lib.Database, to *lib.Datab return list } -func (command *ImportCommand) copyRelation(rel lib.Relation, to *lib.Database) []error { +func (command *ImportCommand) copyRelation(rel rrh.Relation, to *rrh.Database) []error { var list = []error{} if to.HasGroup(rel.GroupName) && to.HasRepository(rel.RepositoryID) { to.Relate(rel.GroupName, rel.RepositoryID) @@ -264,7 +264,7 @@ func (command *ImportCommand) copyRelation(rel lib.Relation, to *lib.Database) [ return list } -func (command *ImportCommand) copyRelations(from *lib.Database, to *lib.Database) []error { +func (command *ImportCommand) copyRelations(from *rrh.Database, to *rrh.Database) []error { var list = []error{} for _, rel := range from.Relations { var errs = command.copyRelation(rel, to) diff --git a/internal/import_test.go b/internal/import_test.go index c3ba13a..e92a889 100644 --- a/internal/import_test.go +++ b/internal/import_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestImport(t *testing.T) { @@ -48,15 +48,15 @@ func TestImport(t *testing.T) { } for _, testcase := range testcases { - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = ImportCommandFactory() var statusCode = command.Run(testcase.args) if statusCode != testcase.statusCode { t.Errorf("%v: status code did not match: wont: %d, got: %d", testcase.args, testcase.statusCode, statusCode) } - var db, _ = lib.Open(lib.OpenConfig()) + var db, _ = rrh.Open(rrh.OpenConfig()) for _, gcheck := range testcase.gChecks { if db.HasGroup(gcheck.groupName) != gcheck.wontExist { t.Errorf("%v: group %s exist: wont: %v, got: %v", testcase.args, gcheck.groupName, gcheck.wontExist, !gcheck.wontExist) @@ -95,7 +95,7 @@ func TestParsingFailOfArgs(t *testing.T) { } for _, testcase := range testcases { - var got = lib.CaptureStdout(func() { + var got = rrh.CaptureStdout(func() { var command, _ = ImportCommandFactory() command.Run(testcase.args) }) diff --git a/internal/list_cmd.go b/internal/list_cmd.go index 397dc44..9b721b4 100644 --- a/internal/list_cmd.go +++ b/internal/list_cmd.go @@ -5,7 +5,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) type listOptions struct { @@ -38,7 +38,7 @@ func (options *listOptions) isChecked(target bool) bool { return target || options.all } -func (options *listOptions) printResultAsCsv(result Result, repo Repo, remote *lib.Remote) { +func (options *listOptions) printResultAsCsv(result Result, repo Repo, remote *rrh.Remote) { fmt.Printf("%s", result.GroupName) if options.isChecked(options.description) { fmt.Printf(",%s", result.Description) @@ -88,12 +88,12 @@ printColoriezdRepositoryID prints the repository name in color. Coloring escape sequence breaks the printf position arrangement. Therefore, we arranges the positions by spacing behind the colored repository name. */ -func printColoriezdRepositoryID(repoName string, length int, config *lib.Config) { +func printColoriezdRepositoryID(repoName string, length int, config *rrh.Config) { var formatter = fmt.Sprintf(" %%s%%%ds", length-len(repoName)) fmt.Printf(formatter, config.Color.ColorizedRepositoryID(repoName), "") } -func (options *listOptions) printRepo(repo Repo, result Result, maxLength int, config *lib.Config) { +func (options *listOptions) printRepo(repo Repo, result Result, maxLength int, config *rrh.Config) { printColoriezdRepositoryID(repo.Name, maxLength, config) if options.localPath || options.all { fmt.Printf(" %s", repo.Path) @@ -111,7 +111,7 @@ func (options *listOptions) isPrintSimple(result Result) bool { return !options.noOmit && result.OmitList && len(options.args) == 0 } -func printGroupName(result Result, config *lib.Config) int { +func printGroupName(result Result, config *rrh.Config) int { if len(result.Repos) == 1 { fmt.Printf("%s (1 repository)\n", config.Color.ColorizedGroupName(result.GroupName)) } else { @@ -120,7 +120,7 @@ func printGroupName(result Result, config *lib.Config) int { return len(result.Repos) } -func (options *listOptions) printResult(result Result, config *lib.Config) int { +func (options *listOptions) printResult(result Result, config *rrh.Config) int { var repoCount = printGroupName(result, config) if !options.isPrintSimple(result) { if options.description || options.all { @@ -164,7 +164,7 @@ func printGroupAndRepoCount(groupCount int, repoCount int) { fmt.Printf("%d %s, %d %s\n", groupCount, groupLabel, repoCount, repoLabel) } -func (options *listOptions) printResults(results []Result, config *lib.Config) int { +func (options *listOptions) printResults(results []Result, config *rrh.Config) int { if options.csv { return options.printResultsAsCsv(results) } else if options.repoNameOnly || options.groupRepoName { @@ -178,7 +178,7 @@ func (options *listOptions) printResults(results []Result, config *lib.Config) i return 0 } -func (list *ListCommand) findAndPrintResult(db *lib.Database) int { +func (list *ListCommand) findAndPrintResult(db *rrh.Database) int { results, err := list.FindResults(db) if err != nil { fmt.Println(err.Error()) @@ -203,8 +203,8 @@ func (list *ListCommand) Run(args []string) int { if err != nil { return list.printError(err, true, 1) } - var config = lib.OpenConfig() - db, err := lib.Open(config) + var config = rrh.OpenConfig() + db, err := rrh.Open(config) if err != nil { return list.printError(err, false, 2) } @@ -271,7 +271,7 @@ Repo represents the result for showing of repositories. type Repo struct { Name string Path string - Remotes []lib.Remote + Remotes []rrh.Remote } /* @@ -284,7 +284,7 @@ type Result struct { Repos []Repo } -func (list *ListCommand) findList(db *lib.Database, groupName string) (*Result, error) { +func (list *ListCommand) findList(db *rrh.Database, groupName string) (*Result, error) { var repos = []Repo{} var group = db.FindGroup(groupName) if group == nil { @@ -303,7 +303,7 @@ func (list *ListCommand) findList(db *lib.Database, groupName string) (*Result, return &Result{group.Name, group.Description, group.OmitList, repos}, nil } -func (list *ListCommand) findAllGroupNames(db *lib.Database) []string { +func (list *ListCommand) findAllGroupNames(db *rrh.Database) []string { var names = []string{} for _, group := range db.Groups { names = append(names, group.Name) @@ -314,7 +314,7 @@ func (list *ListCommand) findAllGroupNames(db *lib.Database) []string { /* FindResults returns the result list of list command. */ -func (list *ListCommand) FindResults(db *lib.Database) ([]Result, error) { +func (list *ListCommand) FindResults(db *rrh.Database) ([]Result, error) { var groups = list.options.args if len(groups) == 0 { groups = list.findAllGroupNames(db) diff --git a/internal/list_test.go b/internal/list_test.go index 4218275..92d7019 100644 --- a/internal/list_test.go +++ b/internal/list_test.go @@ -4,11 +4,11 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func ExampleListCommand() { - var dbFile = lib.Rollback("../testdata/database.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/database.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var list, _ = ListCommandFactory() list.Run([]string{}) }) @@ -21,7 +21,7 @@ func ExampleListCommand() { } func ExampleListCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var list, _ = ListCommandFactory() list.Run([]string{"--desc", "--path"}) }) @@ -37,14 +37,14 @@ func ExampleListCommand_Run() { } func TestRunByCsvOutput(t *testing.T) { - os.Setenv(lib.RrhDefaultGroupName, "group1") - defer os.Unsetenv(lib.RrhDefaultGroupName) - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var result = lib.CaptureStdout(func() { + os.Setenv(rrh.RrhDefaultGroupName, "group1") + defer os.Unsetenv(rrh.RrhDefaultGroupName) + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var result = rrh.CaptureStdout(func() { var list, _ = ListCommandFactory() list.Run([]string{"--all-entries", "--csv"}) }) - result = lib.ReplaceNewline(result, "&") + result = rrh.ReplaceNewline(result, "&") var want = "group1,desc1,repo1,path1&group3,desc3,repo2,path2,origin,git@github.com:example/repo2.git" if result != want { t.Errorf("result did not match, wont: %s, got: %s", want, result) @@ -64,15 +64,15 @@ func TestSimpleResults(t *testing.T) { {[]string{"not-included-group"}, 3, ""}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var result = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var result = rrh.CaptureStdout(func() { var list, _ = ListCommandFactory() var status = list.Run(tc.args) if status != tc.status { t.Errorf("%v: status code did not match: wont: %d, got: %d", tc.args, tc.status, status) } }) - result = lib.ReplaceNewline(result, ",") + result = rrh.ReplaceNewline(result, ",") if tc.status == 0 && result != tc.result { t.Errorf("%v: result did not match: wont: %s, got: %s", tc.args, tc.result, result) } @@ -82,7 +82,7 @@ func TestSimpleResults(t *testing.T) { } func TestFailedByUnknownOption(t *testing.T) { - lib.CaptureStdout(func() { + rrh.CaptureStdout(func() { var list, _ = ListCommandFactory() if val := list.Run([]string{"--unknown"}); val != 1 { t.Error("unknown option parsed!?") @@ -119,12 +119,12 @@ func TestFindResults(t *testing.T) { targets []string want []Result }{ - {[]string{"group1"}, []Result{{"group1", "desc1", false, []Repo{{"repo1", "path1", []lib.Remote{}}}}}}, + {[]string{"group1"}, []Result{{"group1", "desc1", false, []Repo{{"repo1", "path1", []rrh.Remote{}}}}}}, {[]string{"group2"}, []Result{{"group2", "desc2", false, []Repo{}}}}, } for _, data := range testdata { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { list.options.args = data.targets var results, err = list.FindResults(db) if err != nil { diff --git a/internal/messages_cmd.go b/internal/messages_cmd.go index 47b16b4..7d57fe6 100644 --- a/internal/messages_cmd.go +++ b/internal/messages_cmd.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/mitchellh/cli" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -119,7 +119,7 @@ func (help *HelpCommand) Run(args []string) int { Run performs the command. */ func (version *VersionCommand) Run(args []string) int { - fmt.Printf("rrh version %s\n", lib.VERSION) + fmt.Printf("rrh version %s\n", rrh.VERSION) return 0 } diff --git a/internal/messages_test.go b/internal/messages_test.go index 5cc2a6f..206ef44 100644 --- a/internal/messages_test.go +++ b/internal/messages_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) const defaultHelpMessage = `rrh [GLOBAL OPTIONS] [ARGUMENTS] @@ -47,7 +47,7 @@ func TestHelpCommand(t *testing.T) { } for _, tc := range testcases { var command, _ = HelpCommandFactory() - var message = lib.CaptureStdout(func() { + var message = rrh.CaptureStdout(func() { command.Run(tc.args) }) message = strings.TrimSpace(message) diff --git a/internal/move_cmd.go b/internal/move_cmd.go index d3cbd30..d7c284f 100644 --- a/internal/move_cmd.go +++ b/internal/move_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -61,7 +61,7 @@ type targets struct { to target } -func parseCompound(db *lib.Database, types []string, original string) (target, error) { +func parseCompound(db *rrh.Database, types []string, original string) (target, error) { var groupFound = db.HasGroup(types[0]) var repoFound = db.HasRepository(types[1]) if !groupFound && !repoFound { @@ -76,7 +76,7 @@ func parseCompound(db *lib.Database, types []string, original string) (target, e return target{GroupAndRepoType, types[0], types[1], original}, nil } -func parseEither(db *lib.Database, typeString string) (target, error) { +func parseEither(db *rrh.Database, typeString string) (target, error) { var groupFound = db.HasGroup(typeString) var repositoryFound = db.HasRepository(typeString) if groupFound && repositoryFound { @@ -89,7 +89,7 @@ func parseEither(db *lib.Database, typeString string) (target, error) { return target{GroupOrRepoType, typeString, "", typeString}, nil } -func parseType(db *lib.Database, typeString string) (target, error) { +func parseType(db *rrh.Database, typeString string) (target, error) { if strings.Contains(typeString, "/") { var types = strings.SplitN(typeString, "/", 2) return parseCompound(db, types, typeString) @@ -137,7 +137,7 @@ func isRepositoryToRepository(fromType targetKind, toType targetKind) bool { // return toType != GroupType && toType != GroupOrRepoType // } -func verifyArgumentsOneToOne(db *lib.Database, from target, to target) (targetKind, error) { +func verifyArgumentsOneToOne(db *rrh.Database, from target, to target) (targetKind, error) { if from.kind == Unknown { return Invalid, fmt.Errorf("%s: unknown type not acceptable", from.original) } @@ -170,7 +170,7 @@ func isGroupAndRepoOrRepoType(kind targetKind) bool { return kind == GroupAndRepoType || kind == RepositoryType } -func verifyArgumentsMoreToOne(db *lib.Database, froms []target, to target) (targetKind, error) { +func verifyArgumentsMoreToOne(db *rrh.Database, froms []target, to target) (targetKind, error) { if isNotGroupAndGroupOrRepoType(to.kind) { return Invalid, fmt.Errorf("types of froms and to did not match: from: %v, to: %v (%d)", froms, to.original, to.kind) } @@ -185,14 +185,14 @@ func verifyArgumentsMoreToOne(db *lib.Database, froms []target, to target) (targ return GroupsToGroup, nil } -func verifyArguments(db *lib.Database, froms []target, to target) (targetKind, error) { +func verifyArguments(db *rrh.Database, froms []target, to target) (targetKind, error) { if len(froms) == 1 { return verifyArgumentsOneToOne(db, froms[0], to) } return verifyArgumentsMoreToOne(db, froms, to) } -func convertToTarget(db *lib.Database, froms []string, to string) ([]target, target) { +func convertToTarget(db *rrh.Database, froms []string, to string) ([]target, target) { var targetFrom = []target{} for _, from := range froms { var f, _ = parseType(db, from) @@ -202,7 +202,7 @@ func convertToTarget(db *lib.Database, froms []string, to string) ([]target, tar return targetFrom, targetTo } -func (mv *MoveCommand) performImpl(db *lib.Database, targets targets, executionType targetKind) []error { +func (mv *MoveCommand) performImpl(db *rrh.Database, targets targets, executionType targetKind) []error { switch executionType { case GroupToGroup: return mv.moveGroupToGroup(db, targets.froms[0], targets.to) @@ -221,7 +221,7 @@ func (mv *MoveCommand) performImpl(db *lib.Database, targets targets, executionT return []error{} } -func (mv *MoveCommand) moveRepositoryToRepository(db *lib.Database, from target, to target) error { +func (mv *MoveCommand) moveRepositoryToRepository(db *rrh.Database, from target, to target) error { if from.repositoryName != to.repositoryName { return fmt.Errorf("repository name did not match: %s, %s", from.original, to.original) } @@ -237,7 +237,7 @@ func (mv *MoveCommand) moveRepositoryToRepository(db *lib.Database, from target, return nil } -func (mv *MoveCommand) moveRepositoryToGroup(db *lib.Database, from target, to target) error { +func (mv *MoveCommand) moveRepositoryToGroup(db *rrh.Database, from target, to target) error { if to.kind == GroupType || to.kind == GroupOrRepoType { if _, err := db.AutoCreateGroup(to.original, "", false); err != nil { return err @@ -249,7 +249,7 @@ func (mv *MoveCommand) moveRepositoryToGroup(db *lib.Database, from target, to t db.Relate(to.original, from.repositoryName) return nil } -func (mv *MoveCommand) moveRepositoriesToGroup(db *lib.Database, froms []target, to target) []error { +func (mv *MoveCommand) moveRepositoriesToGroup(db *rrh.Database, froms []target, to target) []error { var list = []error{} for _, from := range froms { var err = mv.moveRepositoryToGroup(db, from, to) @@ -263,7 +263,7 @@ func (mv *MoveCommand) moveRepositoriesToGroup(db *lib.Database, froms []target, return list } -func (mv *MoveCommand) moveGroupsToGroup(db *lib.Database, froms []target, to target) []error { +func (mv *MoveCommand) moveGroupsToGroup(db *rrh.Database, froms []target, to target) []error { var list = []error{} for _, from := range froms { var errs = mv.moveGroupToGroup(db, from, to) @@ -277,7 +277,7 @@ func (mv *MoveCommand) moveGroupsToGroup(db *lib.Database, froms []target, to ta return list } -func (mv *MoveCommand) moveGroupToGroup(db *lib.Database, from target, to target) []error { +func (mv *MoveCommand) moveGroupToGroup(db *rrh.Database, from target, to target) []error { if _, err := db.AutoCreateGroup(to.groupName, "", false); err != nil { return []error{err} } @@ -291,7 +291,7 @@ func (mv *MoveCommand) moveGroupToGroup(db *lib.Database, from target, to target return []error{} } -func (mv *MoveCommand) perform(db *lib.Database) int { +func (mv *MoveCommand) perform(db *rrh.Database) int { var from, to = convertToTarget(db, mv.options.from, mv.options.to) var executionType, err = verifyArguments(db, from, to) if err != nil { @@ -314,8 +314,8 @@ func (mv *MoveCommand) Run(args []string) int { fmt.Println(err1.Error()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 diff --git a/internal/move_test.go b/internal/move_test.go index 86ae722..c35ea88 100644 --- a/internal/move_test.go +++ b/internal/move_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestParseError(t *testing.T) { @@ -17,11 +17,11 @@ func TestParseError(t *testing.T) { {[]string{"group1/repo1", "group3/repo5"}, 4}, {[]string{"group1/repo1", "repo2", "group5"}, 4}, } - os.Setenv(lib.RrhOnError, lib.Fail) - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(lib.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.RrhOnError, rrh.Fail) + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") - lib.CaptureStdout(func() { + rrh.CaptureStdout(func() { for _, testcase := range testcases { var mv, _ = MoveCommandFactory() var status = mv.Run(testcase.args) @@ -30,7 +30,7 @@ func TestParseError(t *testing.T) { } } }) - defer os.Unsetenv(lib.RrhOnError) + defer os.Unsetenv(rrh.RrhOnError) } func TestMoveCommand(t *testing.T) { @@ -66,11 +66,11 @@ func TestMoveCommand(t *testing.T) { {"group1", "repo1", false}}}, } for _, item := range cases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var mv, _ = MoveCommandFactory() mv.Run(item.args) - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) for _, rel := range item.relations { if db.HasRelation(rel.group, rel.repo) != rel.hasRelation { t.Errorf("rrh mv %v failed: relation: group %s and repo %s: %v", item.args, rel.group, rel.repo, !rel.hasRelation) @@ -98,7 +98,7 @@ func TestParseType(t *testing.T) { {"not-exist", GroupOrRepoType, false, "group not found"}, } - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { for _, item := range cases { var got, err = parseType(db, item.gives) if got.kind != item.wont && (item.errorFlag && err == nil) { @@ -132,7 +132,7 @@ func TestVerifyArguments(t *testing.T) { {[]string{"repo1"}, "group5/repo1", RepositoryToRepository, false, ""}, } - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { for _, item := range cases { var froms, to = convertToTarget(db, item.givesFrom, item.givesTo) var got, _ = verifyArguments(db, froms, to) @@ -163,9 +163,9 @@ func TestMergeType(t *testing.T) { } func TestMisc(t *testing.T) { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() if isFailImmediately(config) { - t.Errorf("onError wont: %s, got: %s", lib.Warn, config.GetValue(lib.RrhOnError)) + t.Errorf("onError wont: %s, got: %s", rrh.Warn, config.GetValue(rrh.RrhOnError)) } } @@ -188,8 +188,8 @@ func TestVerifyArgumentsOneToOne(t *testing.T) { {GroupType, RepositoryType, Invalid, true}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var db, _ = lib.Open(config) + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var db, _ = rrh.Open(config) var resultType, err = verifyArgumentsOneToOne(db, target{kind: tc.fromType}, target{kind: tc.toType}) if resultType != tc.resultType { t.Errorf("%v: result type did not match, wont: %d, got: %d", tc, tc.resultType, resultType) diff --git a/internal/open.go b/internal/open.go index aaff11a..9f35708 100644 --- a/internal/open.go +++ b/internal/open.go @@ -7,7 +7,7 @@ import ( "github.com/mitchellh/cli" "github.com/skratchdot/open-golang/open" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -115,21 +115,21 @@ func convertURL(url string) (string, error) { return url, nil } -func generateWebPageURL(repo *lib.Repository) (string, error) { +func generateWebPageURL(repo *rrh.Repository) (string, error) { if len(repo.Remotes) == 0 { return "", fmt.Errorf("%s: remote repository not found", repo.ID) } return convertURL(repo.Remotes[0].URL) } -func execOpen(repo *lib.Repository, opts *openOptions) (string, error) { +func execOpen(repo *rrh.Repository, opts *openOptions) (string, error) { if opts.browserFlag { return generateWebPageURL(repo) } return repo.Path, nil } -func performEach(arg string, opts *openOptions, db *lib.Database) error { +func performEach(arg string, opts *openOptions, db *rrh.Database) error { repo := db.FindRepository(arg) if repo == nil { return fmt.Errorf("%s: repository not found", arg) @@ -142,8 +142,8 @@ func performEach(arg string, opts *openOptions, db *lib.Database) error { } func performOpen(args []string, opts *openOptions) int { - config := lib.OpenConfig() - db, err := lib.Open(config) + config := rrh.OpenConfig() + db, err := rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 1 diff --git a/internal/prune_cmd.go b/internal/prune_cmd.go index a2e624f..5dda131 100644 --- a/internal/prune_cmd.go +++ b/internal/prune_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -15,18 +15,18 @@ PruneCommand represents a command. type PruneCommand struct { verbose bool dryrun bool - mc *lib.MessageCenter + mc *rrh.MessageCenter } /* PruneCommandFactory returns an instance of the PruneCommand. */ func PruneCommandFactory() (cli.Command, error) { - return &PruneCommand{verbose: false, dryrun: false, mc: lib.NewMessageCenter()}, nil + return &PruneCommand{verbose: false, dryrun: false, mc: rrh.NewMessageCenter()}, nil } -func printResults(prune *PruneCommand, repos []lib.Repository, groups []lib.Group) { - prune.mc.Print(os.Stdout, lib.VERBOSE) +func printResults(prune *PruneCommand, repos []rrh.Repository, groups []rrh.Group) { + prune.mc.Print(os.Stdout, rrh.VERBOSE) for _, repo := range repos { fmt.Printf("%s: repository pruned (no relations)\n", repo.ID) } @@ -42,7 +42,7 @@ func dryrunMode(mode bool) string { return " (dry-run mode)" } -func (prune *PruneCommand) perform(db *lib.Database) bool { +func (prune *PruneCommand) perform(db *rrh.Database) bool { var count = prune.removeNotExistRepository(db) var repos, groups = db.PruneTargets() fmt.Printf("Pruned %d groups, %d repositories%s\n", len(groups), len(repos)+count, dryrunMode(prune.dryrun)) @@ -80,8 +80,8 @@ func (prune *PruneCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - var db, err = lib.Open(config) + var config = rrh.OpenConfig() + var db, err = rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 1 @@ -92,7 +92,7 @@ func (prune *PruneCommand) Run(args []string) int { return 0 } -func (prune *PruneCommand) deleteNotExistRepository(db *lib.Database, repo string) int { +func (prune *PruneCommand) deleteNotExistRepository(db *rrh.Database, repo string) int { pushMessage(prune, repo, "not exists") var err = db.DeleteRepository(repo) if err != nil { @@ -101,7 +101,7 @@ func (prune *PruneCommand) deleteNotExistRepository(db *lib.Database, repo strin return 1 } -func (prune *PruneCommand) removeNotExistRepository(db *lib.Database) int { +func (prune *PruneCommand) removeNotExistRepository(db *rrh.Database) int { var removeRepos = []string{} for _, repo := range db.Repositories { var _, err = os.Stat(repo.Path) diff --git a/internal/prune_test.go b/internal/prune_test.go index f77b34e..b6b5f31 100644 --- a/internal/prune_test.go +++ b/internal/prune_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestSynopsis(t *testing.T) { @@ -41,7 +41,7 @@ func TestPrune(t *testing.T) { []groupExistChecker{{"group1", true}, {"group2", false}, {"group3", true}}, []repositoryExistChecker{{"repo1", true}, {"repo2", true}, {"repo3", false}}, } - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { db.Prune() for _, gc := range tc.gchecker { @@ -59,7 +59,7 @@ func TestPrune(t *testing.T) { } func TestPruneCommandRunFailedByBrokenDBFile(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") var prune, _ = PruneCommandFactory() if prune.Run([]string{}) != 1 { t.Error("broken database read successfully.") @@ -67,7 +67,7 @@ func TestPruneCommandRunFailedByBrokenDBFile(t *testing.T) { } func TestPruneCommandRunFailedByInvalidArgs(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") var prune, _ = PruneCommandFactory() if prune.Run([]string{"--help"}) != 1 { t.Error("successing invalid option parsing.") @@ -75,7 +75,7 @@ func TestPruneCommandRunFailedByInvalidArgs(t *testing.T) { } func ExamplePruneCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var prune, _ = PruneCommandFactory() prune.Run([]string{}) }) @@ -84,7 +84,7 @@ func ExamplePruneCommand_Run() { } func ExamplePruneCommand_Run_DryrunMode() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var prune, _ = PruneCommandFactory() prune.Run([]string{"--dry-run"}) }) @@ -98,7 +98,7 @@ func ExamplePruneCommand_Run_DryrunMode() { } func ExamplePruneCommand_Run_VerboseMode() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var prune, _ = PruneCommandFactory() prune.Run([]string{"--verbose"}) }) diff --git a/internal/remove_cmd.go b/internal/remove_cmd.go index b6c1924..ec88fb6 100644 --- a/internal/remove_cmd.go +++ b/internal/remove_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) type removeOptions struct { @@ -36,12 +36,12 @@ func (options *removeOptions) printIfVerbose(message string) { } } -func (rm *RemoveCommand) executeRemoveGroup(db *lib.Database, groupName string) error { +func (rm *RemoveCommand) executeRemoveGroup(db *rrh.Database, groupName string) error { var group = db.FindGroup(groupName) if group == nil { return fmt.Errorf("%s: group not found", groupName) } - if rm.options.inquiry && !lib.IsInputYes(fmt.Sprintf("%s: Remove group? [yN]> ", groupName)) { + if rm.options.inquiry && !rrh.IsInputYes(fmt.Sprintf("%s: Remove group? [yN]> ", groupName)) { rm.options.printIfVerbose(fmt.Sprintf("%s: group do not removed", groupName)) return nil } @@ -57,11 +57,11 @@ func (rm *RemoveCommand) executeRemoveGroup(db *lib.Database, groupName string) return err } -func (rm *RemoveCommand) executeRemoveRepository(db *lib.Database, repoID string) error { +func (rm *RemoveCommand) executeRemoveRepository(db *rrh.Database, repoID string) error { if !db.HasRepository(repoID) { return fmt.Errorf("%s: repository not found", repoID) } - if rm.options.inquiry && !lib.IsInputYes(fmt.Sprintf("%s: Remove repository? [yN]> ", repoID)) { + if rm.options.inquiry && !rrh.IsInputYes(fmt.Sprintf("%s: Remove repository? [yN]> ", repoID)) { rm.options.printIfVerbose(fmt.Sprintf("%s: repository do not removed", repoID)) return nil } @@ -72,13 +72,13 @@ func (rm *RemoveCommand) executeRemoveRepository(db *lib.Database, repoID string return nil } -func (rm *RemoveCommand) executeRemoveFromGroup(db *lib.Database, groupName string, repoID string) error { +func (rm *RemoveCommand) executeRemoveFromGroup(db *rrh.Database, groupName string, repoID string) error { db.Unrelate(groupName, repoID) rm.options.printIfVerbose(fmt.Sprintf("%s: removed from group %s", repoID, groupName)) return nil } -func (rm *RemoveCommand) executeRemove(db *lib.Database, target string) error { +func (rm *RemoveCommand) executeRemove(db *rrh.Database, target string) error { var data = strings.Split(target, "/") if len(data) == 2 { return rm.executeRemoveFromGroup(db, data[0], data[1]) @@ -97,7 +97,7 @@ func (rm *RemoveCommand) executeRemove(db *lib.Database, target string) error { return fmt.Errorf("%s: not found in repositories and groups", target) } -func (rm *RemoveCommand) perform(db *lib.Database) int { +func (rm *RemoveCommand) perform(db *rrh.Database) int { var result = 0 for _, target := range rm.options.args { var err = rm.executeRemove(db, target) @@ -107,7 +107,7 @@ func (rm *RemoveCommand) perform(db *lib.Database) int { } } if result == 0 { - if db.Config.IsSet(lib.RrhAutoDeleteGroup) { + if db.Config.IsSet(rrh.RrhAutoDeleteGroup) { db.Prune() } db.StoreAndClose() @@ -124,8 +124,8 @@ func (rm *RemoveCommand) Run(args []string) int { return 1 } rm.options = options - var config = lib.OpenConfig() - var db, err1 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err1 = rrh.Open(config) if err1 != nil { fmt.Println(err1.Error()) return 2 diff --git a/internal/remove_test.go b/internal/remove_test.go index 4e1e1fe..a4fef7a 100644 --- a/internal/remove_test.go +++ b/internal/remove_test.go @@ -4,11 +4,11 @@ import ( "os" "testing" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func ExampleRemoveCommand_Run() { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() rm.Run([]string{"-v", "group2", "repo1"}) }) @@ -18,7 +18,7 @@ func ExampleRemoveCommand_Run() { } func TestCommandUnknownGroupAndRepository(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var rm = RemoveCommand{} var err = rm.executeRemove(db, "not_exist_group_and_repository") if err.Error() != "not_exist_group_and_repository: not found in repositories and groups" { @@ -39,7 +39,7 @@ func TestRemoveRepository(t *testing.T) { {"repo1", true, "group1", 0}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var rm = RemoveCommand{&removeOptions{}} var err = rm.executeRemoveRepository(db, tc.repositoryName) if (err == nil) != tc.removeSuccess { @@ -57,7 +57,7 @@ func TestRemoveRepository(t *testing.T) { } func TestRemoveCommandForGroup(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var rm = RemoveCommand{&removeOptions{}} if err := rm.executeRemoveGroup(db, "unknown-group"); err == nil { t.Error("unknown-group: found") @@ -74,9 +74,9 @@ func TestRemoveCommandForGroup(t *testing.T) { } func TestRemoveCommandRemoveTargetIsBothInGroupAndRepository(t *testing.T) { - var dbFile = lib.Rollback("../testdata/nulldb.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/nulldb.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { db.CreateGroup("groupOrRepo", "same name as Repository", false) - db.CreateRepository("groupOrRepo", "unknownpath", "desc", []lib.Remote{}) + db.CreateRepository("groupOrRepo", "unknownpath", "desc", []rrh.Remote{}) var rm = RemoveCommand{&removeOptions{}} var err = rm.executeRemove(db, "groupOrRepo") if err.Error() != "groupOrRepo: exists in repositories and groups" { @@ -87,7 +87,7 @@ func TestRemoveCommandRemoveTargetIsBothInGroupAndRepository(t *testing.T) { } func TestRemoveEntryFailed(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, db *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var rm = RemoveCommand{&removeOptions{}} var err = rm.executeRemoveFromGroup(db, "group2", "repo2") if err != nil { @@ -98,10 +98,10 @@ func TestRemoveEntryFailed(t *testing.T) { } func TestRemoveRelation(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() rm.Run([]string{"-v", "group1/repo1"}) - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) if len(db2.Repositories) != 2 && len(db2.Groups) != 3 { t.Error("repositories and groups are removed!") } @@ -113,10 +113,10 @@ func TestRemoveRelation(t *testing.T) { } func TestRunRemoveRepository(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() rm.Run([]string{"-v", "group2", "repo1"}) - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) if len(db2.Repositories) != 1 && len(db2.Groups) != 2 { t.Errorf("repositories: %d, groups: %d\n", len(db2.Repositories), len(db2.Groups)) } @@ -128,11 +128,11 @@ func TestRunRemoveRepository(t *testing.T) { } func TestRemoveRepository2(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() - os.Setenv(lib.RrhAutoDeleteGroup, "true") + os.Setenv(rrh.RrhAutoDeleteGroup, "true") rm.Run([]string{"-v", "group2", "repo1"}) - var db2, _ = lib.Open(config) + var db2, _ = rrh.Open(config) if len(db2.Repositories) != 1 && len(db2.Groups) != 0 { t.Errorf("repositories: %d, groups: %d\n", len(db2.Repositories), len(db2.Groups)) } @@ -141,7 +141,7 @@ func TestRemoveRepository2(t *testing.T) { } func TestBrokenDatabaseOnRemoveCommand(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") var rm, _ = RemoveCommandFactory() if result := rm.Run([]string{}); result != 2 { t.Errorf("broken database are successfully read!?") @@ -149,7 +149,7 @@ func TestBrokenDatabaseOnRemoveCommand(t *testing.T) { } func TestUnknownOptionsOnRemoveCommand(t *testing.T) { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() if result := rm.Run([]string{"--unknown"}); result != 1 { t.Errorf("unknown option was not failed: %d", result) diff --git a/internal/repository_cmd.go b/internal/repository_cmd.go index c49d589..f20ac28 100644 --- a/internal/repository_cmd.go +++ b/internal/repository_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -98,12 +98,12 @@ func (info *repositoryInfoCommand) parseOptions(args []string) error { return nil } -func groupList(result lib.Repository, db *lib.Database) string { +func groupList(result rrh.Repository, db *rrh.Database) string { var groups = db.FindRelationsOfRepository(result.ID) return strings.Join(groups, ", ") } -func (options *repositoryInfoOptions) printInfo(result lib.Repository, db *lib.Database) { +func (options *repositoryInfoOptions) printInfo(result rrh.Repository, db *rrh.Database) { var config = db.Config fmt.Printf("%-12s %s\n", config.Color.ColorizedLabel("ID:"), config.Color.ColorizedRepositoryID(result.ID)) fmt.Printf("%-12s %s\n", config.Color.ColorizedLabel("Groups:"), groupList(result, db)) @@ -114,14 +114,14 @@ func (options *repositoryInfoOptions) printInfo(result lib.Repository, db *lib.D } } -func printRemoteInfo(remotes []lib.Remote, config *lib.Config) { +func printRemoteInfo(remotes []rrh.Remote, config *rrh.Config) { fmt.Printf("%-12s\n", config.Color.ColorizedLabel("Remote:")) for _, remote := range remotes { fmt.Printf(" %s: %s\n", config.Color.ColorizedLabel(remote.Name), remote.URL) } } -func (options *repositoryInfoOptions) printInfoResult(result lib.Repository, db *lib.Database) { +func (options *repositoryInfoOptions) printInfoResult(result rrh.Repository, db *rrh.Database) { var config = db.Config if options.csv { fmt.Printf("%s,%s,%s\n", config.Color.ColorizedRepositoryID(result.ID), result.Description, result.Path) @@ -130,13 +130,13 @@ func (options *repositoryInfoOptions) printInfoResult(result lib.Repository, db } } -func (info *repositoryInfoCommand) perform(db *lib.Database, args []string) int { +func (info *repositoryInfoCommand) perform(db *rrh.Database, args []string) int { var results, errs = findResults(db, args) - var onError = db.Config.GetValue(lib.RrhOnError) + var onError = db.Config.GetValue(rrh.RrhOnError) for _, result := range results { info.options.printInfoResult(result, db) } - if len(errs) > 0 && onError != lib.Ignore { + if len(errs) > 0 && onError != rrh.Ignore { return printErrors(db.Config, errs) } return 0 @@ -148,8 +148,8 @@ func (info *repositoryInfoCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -158,14 +158,14 @@ func (info *repositoryInfoCommand) Run(args []string) int { return info.perform(db, info.options.args) } -func printListWithGroup(db *lib.Database, result lib.Repository) { +func printListWithGroup(db *rrh.Database, result rrh.Repository) { var groups = db.FindRelationsOfRepository(result.ID) for _, group := range groups { fmt.Printf("%s/%s\n", group, result.ID) } } -func printListResult(db *lib.Database, result lib.Repository, options *repositoryListOptions) { +func printListResult(db *rrh.Database, result rrh.Repository, options *repositoryListOptions) { if options.group { printListWithGroup(db, result) } @@ -177,13 +177,13 @@ func printListResult(db *lib.Database, result lib.Repository, options *repositor } } -func (list *repositoryListCommand) perform(db *lib.Database, args []string) int { +func (list *repositoryListCommand) perform(db *rrh.Database, args []string) int { var results, errs = findAll(db, args) - var onError = db.Config.GetValue(lib.RrhOnError) + var onError = db.Config.GetValue(rrh.RrhOnError) for _, result := range results { printListResult(db, result, list.options) } - if len(errs) > 0 && onError != lib.Ignore { + if len(errs) > 0 && onError != rrh.Ignore { return printErrors(db.Config, errs) } return 0 @@ -215,8 +215,8 @@ func (list *repositoryListCommand) Run(args []string) int { fmt.Println(err.Error()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -256,8 +256,8 @@ func (update *repositoryUpdateCommand) Run(args []string) int { fmt.Printf(update.Help()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -265,7 +265,7 @@ func (update *repositoryUpdateCommand) Run(args []string) int { return update.execute(db) } -func (update *repositoryUpdateCommand) execute(db *lib.Database) int { +func (update *repositoryUpdateCommand) execute(db *rrh.Database) int { var err3 = update.perform(db, update.options.repositoryID) if err3 != nil { fmt.Println(err3.Error()) @@ -299,7 +299,7 @@ func (ur *repositoryUpdateRemotesCommand) parseOptions(args []string) error { return nil } -func createString(remotes []lib.Remote) string { +func createString(remotes []rrh.Remote) string { var remoteStrings = []string{} for _, r := range remotes { remoteStrings = append(remoteStrings, r.String()) @@ -307,11 +307,11 @@ func createString(remotes []lib.Remote) string { return strings.Join(remoteStrings, ",") } -func createStrings(remotes1, remotes2 []lib.Remote) string { +func createStrings(remotes1, remotes2 []rrh.Remote) string { return fmt.Sprintf("{ %s } -> { %s }", createString(remotes1), createString(remotes2)) } -func isSameRemotes(remotes1, remotes2 []lib.Remote) bool { +func isSameRemotes(remotes1, remotes2 []rrh.Remote) bool { if len(remotes1) != len(remotes2) { return false } @@ -323,8 +323,8 @@ func isSameRemotes(remotes1, remotes2 []lib.Remote) bool { return true } -func (ur *repositoryUpdateRemotesCommand) updateRemote(repo *lib.Repository) (*lib.Repository, bool) { - var remotes, err = lib.FindRemotes(repo.Path) +func (ur *repositoryUpdateRemotesCommand) updateRemote(repo *rrh.Repository) (*rrh.Repository, bool) { + var remotes, err = rrh.FindRemotes(repo.Path) if err != nil { fmt.Printf("%s: %s\n", repo.Path, err.Error()) } @@ -338,7 +338,7 @@ func (ur *repositoryUpdateRemotesCommand) updateRemote(repo *lib.Repository) (*l return repo, false } -func (ur *repositoryUpdateRemotesCommand) execute(db *lib.Database) int { +func (ur *repositoryUpdateRemotesCommand) execute(db *rrh.Database) int { var updateFlag = false for i, repo := range db.Repositories { var repo2, flag = ur.updateRemote(&repo) @@ -357,8 +357,8 @@ func (ur *repositoryUpdateRemotesCommand) Run(args []string) int { fmt.Printf(ur.Help()) return 1 } - var config = lib.OpenConfig() - var db, err2 = lib.Open(config) + var config = rrh.OpenConfig() + var db, err2 = rrh.Open(config) if err2 != nil { fmt.Println(err2.Error()) return 2 @@ -370,7 +370,7 @@ func (ur *repositoryUpdateRemotesCommand) Run(args []string) int { Run performs the command. */ func (repository *RepositoryCommand) Run(args []string) int { - c := cli.NewCLI("rrh repository", lib.VERSION) + c := cli.NewCLI("rrh repository", rrh.VERSION) c.Args = args c.Commands = map[string]cli.CommandFactory{ "list": repositoryListCommandFactory, @@ -460,22 +460,22 @@ func (repository *RepositoryCommand) Synopsis() string { return "manages repositories." } -func findAll(db *lib.Database, args []string) ([]lib.Repository, []error) { +func findAll(db *rrh.Database, args []string) ([]rrh.Repository, []error) { if len(args) > 0 { return findResults(db, args) } return db.Repositories, []error{} } -func findResults(db *lib.Database, args []string) ([]lib.Repository, []error) { - var results = []lib.Repository{} +func findResults(db *rrh.Database, args []string) ([]rrh.Repository, []error) { + var results = []rrh.Repository{} var errs = []error{} for _, arg := range args { var repo = db.FindRepository(arg) if repo == nil { errs = append(errs, fmt.Errorf("%s: repository not found", arg)) - if db.Config.GetValue(lib.RrhOnError) == lib.FailImmediately { - return []lib.Repository{}, errs + if db.Config.GetValue(rrh.RrhOnError) == rrh.FailImmediately { + return []rrh.Repository{}, errs } } else { results = append(results, *repo) @@ -484,7 +484,7 @@ func findResults(db *lib.Database, args []string) ([]lib.Repository, []error) { return results, errs } -func (update *repositoryUpdateCommand) perform(db *lib.Database, targetRepoID string) error { +func (update *repositoryUpdateCommand) perform(db *rrh.Database, targetRepoID string) error { var repo = db.FindRepository(targetRepoID) if repo == nil { return fmt.Errorf("%s: repository not found", targetRepoID) @@ -496,8 +496,8 @@ func (update *repositoryUpdateCommand) perform(db *lib.Database, targetRepoID st return nil } -func buildNewRepo(options *repositoryUpdateOptions, repo *lib.Repository) lib.Repository { - var newRepo = lib.Repository{ID: repo.ID, Path: repo.Path, Description: repo.Description} +func buildNewRepo(options *repositoryUpdateOptions, repo *rrh.Repository) rrh.Repository { + var newRepo = rrh.Repository{ID: repo.ID, Path: repo.Path, Description: repo.Description} if options.description != "" { newRepo.Description = options.description } diff --git a/internal/repository_test.go b/internal/repository_test.go index 19c529a..6ba0a66 100644 --- a/internal/repository_test.go +++ b/internal/repository_test.go @@ -6,11 +6,11 @@ import ( "testing" "github.com/mitchellh/cli" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func Example_repositoryUpdateRemotesCommand_Run() { - var dbFile = lib.Rollback("../testdata/remotes.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/remotes.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = repositoryUpdateRemotesCommandFactory() command.Run([]string{"--verbose", "--dry-run"}) }) @@ -35,8 +35,8 @@ func TestRepository(t *testing.T) { {[]string{"list", "--with-group", "repo1"}, 0, "group1/repo1", false}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var output = rrh.CaptureStdout(func() { var command, _ = RepositoryCommandFactory() var status = command.Run(tc.args) if status != tc.status { @@ -45,7 +45,7 @@ func TestRepository(t *testing.T) { }) if !tc.ignoreOutput { output = strings.TrimSpace(output) - output = lib.ReplaceNewline(output, "+") + output = rrh.ReplaceNewline(output, "+") if output != tc.output { t.Errorf("%v: output did not match, wont: %s, got: %s", tc.args, tc.output, output) } @@ -72,8 +72,8 @@ func TestListRepository(t *testing.T) { {[]string{"--invalid-option"}, 1, "", true}, } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var output = rrh.CaptureStdout(func() { var listCommand, _ = repositoryListCommandFactory() var status = listCommand.Run(tc.args) if status != tc.status { @@ -82,7 +82,7 @@ func TestListRepository(t *testing.T) { }) if !tc.ignoreOutput { output = strings.TrimSpace(output) - output = lib.ReplaceNewline(output, "+") + output = rrh.ReplaceNewline(output, "+") if output != tc.output { t.Errorf("%v: output did not match, wont: %s, got: %s", tc.args, tc.output, output) } @@ -108,8 +108,8 @@ func TestInfoRepository(t *testing.T) { } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { - var output = lib.CaptureStdout(func() { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { + var output = rrh.CaptureStdout(func() { var infoCommand, _ = repositoryInfoCommandFactory() var status = infoCommand.Run(tc.args) if status != tc.status { @@ -118,7 +118,7 @@ func TestInfoRepository(t *testing.T) { }) if !tc.ignoreOutput { output = strings.TrimSpace(output) - output = lib.ReplaceNewline(output, "+") + output = rrh.ReplaceNewline(output, "+") if output != tc.output { t.Errorf("%v: result did not match, wont: \"%s\", got: \"%s\"", tc.args, tc.output, output) } @@ -133,10 +133,10 @@ func TestUpdateRepository(t *testing.T) { args []string statusCode int newRepoID string - wontRepo *lib.Repository + wontRepo *rrh.Repository }{ - {[]string{"--id", "newRepo1", "--path", "newPath1", "--desc", "desc1", "repo1"}, 0, "newRepo1", &lib.Repository{ID: "newRepo1", Description: "desc1", Path: "newPath1"}}, - {[]string{"-d", "desc2", "repo2"}, 0, "repo2", &lib.Repository{ID: "repo2", Description: "desc2", Path: "path2"}}, + {[]string{"--id", "newRepo1", "--path", "newPath1", "--desc", "desc1", "repo1"}, 0, "newRepo1", &rrh.Repository{ID: "newRepo1", Description: "desc1", Path: "newPath1"}}, + {[]string{"-d", "desc2", "repo2"}, 0, "repo2", &rrh.Repository{ID: "repo2", Description: "desc2", Path: "path2"}}, {[]string{"repo4"}, 3, "repo4", nil}, // unknown repository {[]string{"--invalid-option"}, 1, "never used", nil}, // invalid option {[]string{}, 1, "never used", nil}, // missing arguments. @@ -144,7 +144,7 @@ func TestUpdateRepository(t *testing.T) { } for _, tc := range testcases { - var dbFile = lib.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *lib.Config, oldDB *lib.Database) { + var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var updateCommand, _ = repositoryUpdateCommandFactory() var status = updateCommand.Run(tc.args) if status != tc.statusCode { @@ -153,7 +153,7 @@ func TestUpdateRepository(t *testing.T) { if status != 0 { return } - var db, _ = lib.Open(config) + var db, _ = rrh.Open(config) var repo = db.FindRepository(tc.newRepoID) if repo == nil { t.Errorf("%s: new repository do not found", tc.newRepoID) @@ -255,7 +255,7 @@ func TestSynopsisOfRepository(t *testing.T) { } func TestRepositoryCommandRunFailedByBrokenDBFile(t *testing.T) { - os.Setenv(lib.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") var testcases = []struct { comGenerator func() (cli.Command, error) diff --git a/internal/status_cmd.go b/internal/status_cmd.go index 7eeeb4c..f84918f 100644 --- a/internal/status_cmd.go +++ b/internal/status_cmd.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/cli" flag "github.com/spf13/pflag" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) /* @@ -26,19 +26,19 @@ const ( type statusOptions struct { csv bool - option *lib.StatusOption + option *rrh.StatusOption format string } -func (options *statusOptions) strftime(time *time.Time, config *lib.Config) string { +func (options *statusOptions) strftime(time *time.Time, config *rrh.Config) string { if time == nil { return "" } switch options.format { case relative: - return lib.HumanizeTime(*time) + return rrh.HumanizeTime(*time) case notSpecified: - return lib.Strftime(*time, config) + return rrh.Strftime(*time, config) } return time.Format(timeformat) } @@ -47,7 +47,7 @@ func (options *statusOptions) strftime(time *time.Time, config *lib.Config) stri StatusCommandFactory returns an instance of the StatusCommand. */ func StatusCommandFactory() (cli.Command, error) { - return &StatusCommand{&statusOptions{false, lib.NewStatusOption(), notSpecified}}, nil + return &StatusCommand{&statusOptions{false, rrh.NewStatusOption(), notSpecified}}, nil } /* @@ -68,7 +68,7 @@ ARGUMENTS the command shows the result of the default group.` } -func (status *StatusCommand) parseFmtString(results []lib.Status) string { +func (status *StatusCommand) parseFmtString(results []rrh.Status) string { var max = 0 for _, result := range results { var len = len(result.BranchName) @@ -79,14 +79,14 @@ func (status *StatusCommand) parseFmtString(results []lib.Status) string { return fmt.Sprintf(" %%-%ds %%-22s %%s\n", max) } -func (status *StatusCommand) printResultInCsv(results []lib.Status, config *lib.Config) { +func (status *StatusCommand) printResultInCsv(results []rrh.Status, config *rrh.Config) { for _, result := range results { var timeString = status.options.strftime(result.LastModified, config) fmt.Printf("%s,%s,%s,%s,%s\n", result.Relation.GroupName, result.Relation.RepositoryID, result.BranchName, timeString, result.Description) } } -func (status *StatusCommand) printResult(results []lib.Status, config *lib.Config) { +func (status *StatusCommand) printResult(results []rrh.Status, config *rrh.Config) { var groupName = results[0].Relation.GroupName var repositoryName = results[0].Relation.RepositoryID fmt.Printf("%s\n %s\n", config.Color.ColorizedGroupName(groupName), config.Color.ColorizedRepositoryID(repositoryName)) @@ -108,7 +108,7 @@ func (status *StatusCommand) printResult(results []lib.Status, config *lib.Confi } } -func (status *StatusCommand) runStatus(db *lib.Database, arg string) int { +func (status *StatusCommand) runStatus(db *rrh.Database, arg string) int { var errorFlag = 0 var result, err = status.executeStatus(db, arg) if len(err) != 0 { @@ -130,13 +130,13 @@ func (status *StatusCommand) runStatus(db *lib.Database, arg string) int { Run performs the command. */ func (status *StatusCommand) Run(args []string) int { - var config = lib.OpenConfig() + var config = rrh.OpenConfig() arguments, err := status.parse(args, config) if err != nil { fmt.Println(err.Error()) return 1 } - db, err := lib.Open(config) + db, err := rrh.Open(config) if err != nil { fmt.Println(err.Error()) return 1 @@ -150,7 +150,7 @@ func (status *StatusCommand) Run(args []string) int { } func (status *StatusCommand) buildFlagSet() (*flag.FlagSet, *statusOptions) { - var options = statusOptions{false, lib.NewStatusOption(), notSpecified} + var options = statusOptions{false, rrh.NewStatusOption(), notSpecified} flags := flag.NewFlagSet("status", flag.ExitOnError) flags.Usage = func() { fmt.Println(status.Help()) } flags.BoolVarP(&options.csv, "csv", "c", false, "csv format") @@ -160,14 +160,14 @@ func (status *StatusCommand) buildFlagSet() (*flag.FlagSet, *statusOptions) { return flags, &options } -func (status *StatusCommand) parse(args []string, config *lib.Config) ([]string, error) { +func (status *StatusCommand) parse(args []string, config *rrh.Config) ([]string, error) { var flags, options = status.buildFlagSet() if err := flags.Parse(args); err != nil { return nil, err } status.options = options if len(flags.Args()) == 0 { - return []string{config.GetValue(lib.RrhDefaultGroupName)}, nil + return []string{config.GetValue(rrh.RrhDefaultGroupName)}, nil } return flags.Args(), nil } @@ -179,12 +179,12 @@ func (status *StatusCommand) Synopsis() string { return "show git status of repositories." } -func (status *StatusCommand) executeStatus(db *lib.Database, name string) ([]lib.Status, []error) { +func (status *StatusCommand) executeStatus(db *rrh.Database, name string) ([]rrh.Status, []error) { if db.HasGroup(name) { return status.executeStatusOnGroup(db, name) } if db.HasRepository(name) { - var results, err = status.options.option.StatusOfRepository(db, &lib.Relation{GroupName: "unknown-group", RepositoryID: name}) + var results, err = status.options.option.StatusOfRepository(db, &rrh.Relation{GroupName: "unknown-group", RepositoryID: name}) if err != nil { return results, []error{err} } @@ -193,15 +193,15 @@ func (status *StatusCommand) executeStatus(db *lib.Database, name string) ([]lib return nil, []error{fmt.Errorf("%s: group and repository not found", name)} } -func (status *StatusCommand) executeStatusOnGroup(db *lib.Database, groupName string) ([]lib.Status, []error) { +func (status *StatusCommand) executeStatusOnGroup(db *rrh.Database, groupName string) ([]rrh.Status, []error) { var group = db.FindGroup(groupName) if group == nil { return nil, []error{fmt.Errorf("%s: group not found", groupName)} } var errors = []error{} - var results = []lib.Status{} + var results = []rrh.Status{} for _, repoID := range db.FindRelationsOfGroup(groupName) { - var sr, err = status.options.option.StatusOfRepository(db, &lib.Relation{GroupName: groupName, RepositoryID: repoID}) + var sr, err = status.options.option.StatusOfRepository(db, &rrh.Relation{GroupName: groupName, RepositoryID: repoID}) if err != nil { errors = append(errors, err) } else { diff --git a/internal/status_test.go b/internal/status_test.go index f2c0baa..e41538c 100644 --- a/internal/status_test.go +++ b/internal/status_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/tamada/rrh/lib" + "github.com/tamada/rrh" ) func TestStrftime(t *testing.T) { @@ -15,12 +15,12 @@ func TestStrftime(t *testing.T) { time *time.Time wontMessage string }{ - {lib.Relative, &targetTime, "1 week ago"}, - {lib.Relative, nil, ""}, + {rrh.Relative, &targetTime, "1 week ago"}, + {rrh.Relative, nil, ""}, {notSpecified, &targetTime, "1 week ago"}, {absolute, &targetTime, targetTime.Format("2006-01-02 03:04:05-07")}, } - var config = lib.OpenConfig() + var config = rrh.OpenConfig() for _, tc := range testcases { statusOptions.format = tc.timeFormat diff --git a/lib/message_test.go b/message_test.go similarity index 98% rename from lib/message_test.go rename to message_test.go index ee348cd..7ccb308 100644 --- a/lib/message_test.go +++ b/message_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "bytes" diff --git a/lib/messages.go b/messages.go similarity index 99% rename from lib/messages.go rename to messages.go index 40cca46..815f307 100644 --- a/lib/messages.go +++ b/messages.go @@ -1,4 +1,4 @@ -package lib +package rrh import "io" diff --git a/lib/rrhtime.go b/rrhtime.go similarity index 98% rename from lib/rrhtime.go rename to rrhtime.go index c59320c..3c7d91a 100644 --- a/lib/rrhtime.go +++ b/rrhtime.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "fmt" diff --git a/lib/testutils.go b/testutils.go similarity index 96% rename from lib/testutils.go rename to testutils.go index 07e9478..b0d6efb 100644 --- a/lib/testutils.go +++ b/testutils.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "bytes" @@ -11,7 +11,7 @@ import ( func copyfile(fromfile string) string { var content, _ = ioutil.ReadFile(fromfile) - var file, _ = ioutil.TempFile("../testdata/", "tmp") + var file, _ = ioutil.TempFile(".", "tmp") file.Write(content) defer file.Close() return file.Name() diff --git a/lib/util.go b/util.go similarity index 99% rename from lib/util.go rename to util.go index 9c1a218..4468612 100644 --- a/lib/util.go +++ b/util.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "bufio" diff --git a/lib/util_test.go b/util_test.go similarity index 90% rename from lib/util_test.go rename to util_test.go index 4bcfe3c..b02ca2c 100644 --- a/lib/util_test.go +++ b/util_test.go @@ -1,4 +1,4 @@ -package lib +package rrh import ( "fmt" @@ -34,10 +34,10 @@ func TestGitRepositoryCheck(t *testing.T) { path string errorFlag bool }{ - {"../testdata/fibonacci", false}, - {"../testdata/database.json", true}, - {"../testdata/other", true}, - {"../not-exist", true}, + {"testdata/fibonacci", false}, + {"testdata/database.json", true}, + {"testdata/other", true}, + {"testdata/not-exist", true}, } for _, testcase := range testcases { var absPath, _ = filepath.Abs(testcase.path) @@ -50,7 +50,7 @@ func TestGitRepositoryCheck(t *testing.T) { func TestStrftime(t *testing.T) { os.Setenv(RrhTimeFormat, Relative) - os.Setenv(RrhConfigPath, "../testdata/config.json") + os.Setenv(RrhConfigPath, "testdata/config.json") var now = time.Now() var testcases = []struct { @@ -80,7 +80,7 @@ func TestStrftime(t *testing.T) { } func TestRollback(t *testing.T) { - var file = Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *Config, db *Database) { + var file = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { db.ForceDeleteGroup("group1") db.ForceDeleteGroup("group2") db.DeleteRepository("repo1") From fc8076871a2cfc603808d3981f119aa8b0211cc1 Mon Sep 17 00:00:00 2001 From: Haruaki Tamada Date: Thu, 23 Apr 2020 17:13:49 +0900 Subject: [PATCH 2/9] update repetitious contant names, such as rrh.RrhHome -> rrh.Home. --- cmd/rrh-new/main.go | 4 +- cmd/rrh/main.go | 2 +- colorable_output.go | 4 +- colorable_output_test.go | 4 +- config.go | 74 +++++++++++++++++------------------ config_test.go | 50 ++++++++++++------------ database.go | 6 +-- database_test.go | 18 ++++----- internal/add_cmd.go | 4 +- internal/add_test.go | 12 +++--- internal/clone_cmd.go | 8 ++-- internal/clone_test.go | 2 +- internal/common.go | 4 +- internal/config_test.go | 78 ++++++++++++++++++------------------- internal/export_test.go | 6 +-- internal/fetch_all_cmd.go | 2 +- internal/fetch_cmd.go | 4 +- internal/group_test.go | 10 ++--- internal/import_test.go | 2 +- internal/list_test.go | 4 +- internal/move_test.go | 10 ++--- internal/prune_test.go | 4 +- internal/remove_cmd.go | 2 +- internal/remove_test.go | 4 +- internal/repository_cmd.go | 6 +-- internal/repository_test.go | 2 +- internal/status_cmd.go | 2 +- testutils.go | 8 ++-- util.go | 2 +- util_test.go | 10 ++--- 30 files changed, 174 insertions(+), 174 deletions(-) diff --git a/cmd/rrh-new/main.go b/cmd/rrh-new/main.go index d71eac5..16fa58c 100644 --- a/cmd/rrh-new/main.go +++ b/cmd/rrh-new/main.go @@ -46,7 +46,7 @@ ARGUMENTS func buildFlagSet(config *rrh.Config) (*flag.FlagSet, *newOptions) { var opt = newOptions{info: new(repositoryInfo)} - var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) + var defaultGroup = config.GetValue(rrh.DefaultGroupName) flags := flag.NewFlagSet("new", flag.ContinueOnError) flags.Usage = func() { fmt.Println(getHelpMessage()) } flags.StringVarP(&opt.info.description, "description", "d", "", "specifys description of the project") @@ -202,7 +202,7 @@ func createRepository(db *rrh.Database, arg string, opts *newOptions) error { } func isOnError(config *rrh.Config, handler string) bool { - var onError = config.GetValue(rrh.RrhOnError) + var onError = config.GetValue(rrh.OnError) return onError == handler } diff --git a/cmd/rrh/main.go b/cmd/rrh/main.go index ad7c903..7cf449d 100644 --- a/cmd/rrh/main.go +++ b/cmd/rrh/main.go @@ -104,7 +104,7 @@ func executeExternalCommand(args []string) (int, error) { func (opts *rrhOptions) updateConfigPath() { if opts.configPath != "" { - os.Setenv(rrh.RrhConfigPath, opts.configPath) + os.Setenv(rrh.ConfigPath, opts.configPath) } } diff --git a/colorable_output.go b/colorable_output.go index fba93c4..75d338f 100644 --- a/colorable_output.go +++ b/colorable_output.go @@ -124,8 +124,8 @@ The function is automatically called on loading the config file. */ func InitializeColor(config *Config) *Color { var color = Color{colorSettings{}, colorFuncs{}} - var settingString = config.GetValue(RrhColor) - if config.IsSet(RrhEnableColorized) && settingString != "" { + var settingString = config.GetValue(ColorSetting) + if config.IsSet(EnableColorized) && settingString != "" { color.parse(settingString) } color.updateFuncs() diff --git a/colorable_output_test.go b/colorable_output_test.go index 8599861..0ff753d 100644 --- a/colorable_output_test.go +++ b/colorable_output_test.go @@ -8,9 +8,9 @@ import ( ) func TestEnableColorize(t *testing.T) { - os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(ConfigPath, "testdata/config.json") var config = OpenConfig() - config.Update(RrhEnableColorized, "true") + config.Update(EnableColorized, "true") var cs = InitializeColor(config) var groupName1 = cs.ColorizedGroupName("group") diff --git a/config.go b/config.go index 8ae4ad1..b16e4c2 100644 --- a/config.go +++ b/config.go @@ -19,31 +19,31 @@ const VERSION = "1.1.0" The environment variable names. */ const ( - RrhAutoDeleteGroup = "RRH_AUTO_DELETE_GROUP" - RrhAutoCreateGroup = "RRH_AUTO_CREATE_GROUP" - RrhCloneDestination = "RRH_CLONE_DESTINATION" - RrhColor = "RRH_COLOR" - RrhConfigPath = "RRH_CONFIG_PATH" - RrhDatabasePath = "RRH_DATABASE_PATH" - RrhDefaultGroupName = "RRH_DEFAULT_GROUP_NAME" - RrhEnableColorized = "RRH_ENABLE_COLORIZED" - RrhHome = "RRH_HOME" - RrhOnError = "RRH_ON_ERROR" - RrhSortOnUpdating = "RRH_SORT_ON_UPDATING" - RrhTimeFormat = "RRH_TIME_FORMAT" + AutoDeleteGroup = "RRH_AUTO_DELETE_GROUP" + AutoCreateGroup = "RRH_AUTO_CREATE_GROUP" + CloneDestination = "RRH_CLONE_DESTINATION" + ColorSetting = "RRH_COLOR" + ConfigPath = "RRH_CONFIG_PATH" + DatabasePath = "RRH_DATABASE_PATH" + DefaultGroupName = "RRH_DEFAULT_GROUP_NAME" + EnableColorized = "RRH_ENABLE_COLORIZED" + Home = "RRH_HOME" + OnError = "RRH_ON_ERROR" + SortOnUpdating = "RRH_SORT_ON_UPDATING" + TimeFormat = "RRH_TIME_FORMAT" ) /* AvailableLabels represents the labels availables in the config. */ var AvailableLabels = []string{ - RrhAutoCreateGroup, RrhAutoDeleteGroup, RrhCloneDestination, RrhColor, - RrhConfigPath, RrhDatabasePath, RrhDefaultGroupName, RrhEnableColorized, - RrhHome, RrhOnError, RrhSortOnUpdating, RrhTimeFormat, + AutoCreateGroup, AutoDeleteGroup, CloneDestination, ColorSetting, + ConfigPath, DatabasePath, DefaultGroupName, EnableColorized, + Home, OnError, SortOnUpdating, TimeFormat, } var boolLabels = []string{ - RrhAutoCreateGroup, RrhAutoDeleteGroup, RrhEnableColorized, - RrhSortOnUpdating, + AutoCreateGroup, AutoDeleteGroup, EnableColorized, + SortOnUpdating, } /* @@ -92,24 +92,24 @@ type ReadFrom string var defaultValues = Config{ values: map[string]string{ - RrhAutoCreateGroup: "false", - RrhAutoDeleteGroup: "false", - RrhCloneDestination: ".", - RrhColor: "repository:fg=red+group:fg=magenta+label:op=bold+configValue:fg=green", - RrhConfigPath: "${RRH_HOME}/config.json", - RrhDatabasePath: "${RRH_HOME}/database.json", - RrhDefaultGroupName: "no-group", - RrhEnableColorized: "false", - RrhHome: "${HOME}/.rrh", - RrhOnError: Warn, - RrhSortOnUpdating: "false", - RrhTimeFormat: Relative, + AutoCreateGroup: "false", + AutoDeleteGroup: "false", + CloneDestination: ".", + ColorSetting: "repository:fg=red+group:fg=magenta+label:op=bold+configValue:fg=green", + ConfigPath: "${RRH_HOME}/config.json", + DatabasePath: "${RRH_HOME}/database.json", + DefaultGroupName: "no-group", + EnableColorized: "false", + Home: "${HOME}/.rrh", + OnError: Warn, + SortOnUpdating: "false", + TimeFormat: Relative, }, Color: &Color{}, } func (config *Config) isOnErrorIgnoreOrWarn() bool { - var onError = config.GetValue(RrhOnError) + var onError = config.GetValue(OnError) return onError == Ignore || onError == Warn } @@ -128,7 +128,7 @@ PrintErrors prints errors and returns the status code by following the value of If the value of RrhOnError is Ignore or Warn, this method returns 0, otherwise, non-zero value. */ func (config *Config) PrintErrors(errs ...error) int { - if config.GetValue(RrhOnError) != Ignore { + if config.GetValue(OnError) != Ignore { for _, err := range errs { printErrorImpl(err) } @@ -180,8 +180,8 @@ func validateArgumentsOnUpdate(label string, value string) error { if !contains(AvailableLabels, label) { return fmt.Errorf("%s: unknown variable name", label) } - if label == RrhConfigPath { - return fmt.Errorf("%s: cannot set in config file", RrhConfigPath) + if label == ConfigPath { + return fmt.Errorf("%s: cannot set in config file", ConfigPath) } return nil } @@ -204,7 +204,7 @@ func (config *Config) Update(label string, value string) error { if contains(boolLabels, label) { return config.updateBoolValue(label, value) } - if label == RrhOnError { + if label == OnError { var newValue, err = normalizeValueOfOnError(value) if err != nil { return err @@ -232,7 +232,7 @@ func (config *Config) replaceHome(value string) string { value = strings.Replace(value, "${HOME}", home, 1) } if strings.Contains(value, "${RRH_HOME}") { - var rrhHome = config.GetValue(RrhHome) + var rrhHome = config.GetValue(Home) value = strings.Replace(value, "${RRH_HOME}", strings.TrimRight(rrhHome, "/"), -1) } return value @@ -290,7 +290,7 @@ func (config *Config) findDefaultValue(label string) (string, ReadFrom) { StoreConfig saves the store. */ func (config *Config) StoreConfig() error { - var configPath = config.GetValue(RrhConfigPath) + var configPath = config.GetValue(ConfigPath) var err1 = CreateParentDir(configPath) if err1 != nil { return err1 @@ -315,7 +315,7 @@ The load path is based on `RrhConfigPath` of the environment variables. */ func OpenConfig() *Config { var config = NewConfig() - var configPath, _ = config.getStringFromEnv(RrhConfigPath) + var configPath, _ = config.getStringFromEnv(ConfigPath) bytes, err := ioutil.ReadFile(configPath) if err != nil { return config diff --git a/config_test.go b/config_test.go index 76d7044..cc6708d 100644 --- a/config_test.go +++ b/config_test.go @@ -18,8 +18,8 @@ func TestValidateArgumentsOnUpdate(t *testing.T) { wontError bool wontMessage string }{ - {RrhHome, "~/.rrh", false, ""}, - {RrhConfigPath, "~/.rrh_config", true, RrhConfigPath + ": cannot set in config file"}, + {Home, "~/.rrh", false, ""}, + {ConfigPath, "~/.rrh_config", true, ConfigPath + ": cannot set in config file"}, {"UnknownVariableName", "hoge", true, "UnknownVariableName: unknown variable name"}, } @@ -92,14 +92,14 @@ func TestUpdateTrueFalseValue(t *testing.T) { wantError bool wantValue string }{ - {RrhAutoDeleteGroup, "True", false, "true"}, - {RrhAutoDeleteGroup, "FALSE", false, "false"}, - {RrhAutoDeleteGroup, "FALSE", false, "false"}, - {RrhAutoDeleteGroup, "YES", true, ""}, - {RrhAutoCreateGroup, "FALSE", false, "false"}, - {RrhAutoCreateGroup, "YES", true, ""}, - {RrhSortOnUpdating, "FALSE", false, "false"}, - {RrhSortOnUpdating, "YES", true, ""}, + {AutoDeleteGroup, "True", false, "true"}, + {AutoDeleteGroup, "FALSE", false, "false"}, + {AutoDeleteGroup, "FALSE", false, "false"}, + {AutoDeleteGroup, "YES", true, ""}, + {AutoCreateGroup, "FALSE", false, "false"}, + {AutoCreateGroup, "YES", true, ""}, + {SortOnUpdating, "FALSE", false, "false"}, + {SortOnUpdating, "YES", true, ""}, } for _, data := range testdata { @@ -129,8 +129,8 @@ func TestUpdateOnError(t *testing.T) { for _, data := range testdata { var dbfile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, oldDB *Database) { - if err := config.Update(RrhOnError, data.key); (err == nil) != data.success { - t.Errorf("%s: set to \"%s\", success: %v", RrhOnError, data.key, data.success) + if err := config.Update(OnError, data.key); (err == nil) != data.success { + t.Errorf("%s: set to \"%s\", success: %v", OnError, data.key, data.success) } }) defer os.Remove(dbfile) @@ -144,11 +144,11 @@ func TestUpdateValue(t *testing.T) { shouldError bool wontValue string }{ - {RrhConfigPath, "hogehoge", true, ""}, - {RrhHome, "hoge1", false, "hoge1"}, - {RrhDatabasePath, "hoge2", false, "hoge2"}, - {RrhDefaultGroupName, "hoge3", false, "hoge3"}, - {RrhTimeFormat, "not-relative-string", false, "not-relative-string"}, + {ConfigPath, "hogehoge", true, ""}, + {Home, "hoge1", false, "hoge1"}, + {DatabasePath, "hoge2", false, "hoge2"}, + {DefaultGroupName, "hoge3", false, "hoge3"}, + {TimeFormat, "not-relative-string", false, "not-relative-string"}, {"unknown", "hoge4", true, ""}, } for _, td := range testdata { @@ -171,11 +171,11 @@ func TestUpdateValue(t *testing.T) { func TestConfigIsSet(t *testing.T) { var dbFile = Rollback("../testata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { - if config.IsSet(RrhConfigPath) { + if config.IsSet(ConfigPath) { t.Errorf("not boolean variable is specified") } var home, _ = homedir.Dir() - if config.GetDefaultValue(RrhConfigPath) != filepath.Join(home, ".rrh/config.json") { + if config.GetDefaultValue(ConfigPath) != filepath.Join(home, ".rrh/config.json") { t.Errorf("RrhConfigPath did not match") } var _, from1 = config.findDefaultValue("UnknownVariable") @@ -190,15 +190,15 @@ func TestConfigIsSet(t *testing.T) { if err == nil { t.Errorf("Unknown variable can Unset") } - var beforeFlag = config.IsSet(RrhAutoCreateGroup) - config.Unset(RrhAutoCreateGroup) - var afterFlag = config.IsSet(RrhAutoCreateGroup) + var beforeFlag = config.IsSet(AutoCreateGroup) + config.Unset(AutoCreateGroup) + var afterFlag = config.IsSet(AutoCreateGroup) if afterFlag || !beforeFlag { t.Errorf("beforeFlag should be true, and afterFlag should be false after Unset of RrhAutoCreateGroup") } config.StoreConfig() var config2 = OpenConfig() - var afterFlag2 = config2.IsSet(RrhAutoCreateGroup) + var afterFlag2 = config2.IsSet(AutoCreateGroup) if afterFlag2 { t.Errorf("afterFlag2 should be false because unset and store the config") } @@ -228,7 +228,7 @@ func TestPrintErrors(t *testing.T) { var dbFile = Rollback("testdata/test_db.json", "testdata/config.json", func(config *Config, db *Database) { for _, tc := range testcases { var output = CaptureStdout(func() { - config.Update(RrhOnError, tc.givesOnError) + config.Update(OnError, tc.givesOnError) var status = config.PrintErrors(errs...) if status != tc.wontStatus { t.Errorf("Status code of printErrors did not match, wont %d, got %d", tc.wontStatus, status) @@ -245,7 +245,7 @@ func TestPrintErrors(t *testing.T) { } func TestOpenConfigBrokenJson(t *testing.T) { - os.Setenv(RrhConfigPath, "testdata/broken.json") + os.Setenv(ConfigPath, "testdata/broken.json") var config = OpenConfig() if config != nil { t.Error("broken json returns nil") diff --git a/database.go b/database.go index 72aa3a0..6ea6f90 100644 --- a/database.go +++ b/database.go @@ -155,7 +155,7 @@ func (db *Database) FindGroup(groupID string) *Group { } func sortIfNeeded(db *Database) { - if !db.Config.IsSet(RrhSortOnUpdating) { + if !db.Config.IsSet(SortOnUpdating) { return } sort.Slice(db.Repositories, func(i, j int) bool { @@ -198,7 +198,7 @@ func (db *Database) AutoCreateGroup(groupID string, description string, omitList if db.HasGroup(groupID) { return db.FindGroup(groupID), nil } - if db.Config.IsSet(RrhAutoCreateGroup) { + if db.Config.IsSet(AutoCreateGroup) { return db.CreateGroup(groupID, description, omitList) } return nil, fmt.Errorf("%s: could not create group", groupID) @@ -476,7 +476,7 @@ func (db *Database) ForceDeleteGroup(groupID string) error { } func databasePath(config *Config) string { - return config.GetValue(RrhDatabasePath) + return config.GetValue(DatabasePath) } /* diff --git a/database_test.go b/database_test.go index 0ac73d3..3e80cb9 100644 --- a/database_test.go +++ b/database_test.go @@ -7,8 +7,8 @@ import ( ) func openDatabase() *Database { - os.Setenv(RrhDatabasePath, "testdata/database.json") - os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(DatabasePath, "testdata/database.json") + os.Setenv(ConfigPath, "testdata/config.json") var config = OpenConfig() var db, _ = Open(config) return db @@ -29,8 +29,8 @@ func TestRelationStringer(t *testing.T) { } func TestOpenBrokenJson(t *testing.T) { - os.Setenv(RrhConfigPath, "testdata/config.json") - os.Setenv(RrhDatabasePath, "testdata/broken.json") + os.Setenv(ConfigPath, "testdata/config.json") + os.Setenv(DatabasePath, "testdata/broken.json") var config = OpenConfig() var _, err = Open(config) if err == nil { @@ -55,7 +55,7 @@ func TestAutoCreateGroup(t *testing.T) { t.Errorf("existing group did not match, wont: %v, got: %v", Group{"group1", "desc1", true}, group2) } - db.Config.Update(RrhAutoCreateGroup, "false") + db.Config.Update(AutoCreateGroup, "false") var _, err3 = db.AutoCreateGroup("failgroup", "desc", true) if err3 == nil { t.Errorf("auto create group should fail: %s", err3.Error()) @@ -63,8 +63,8 @@ func TestAutoCreateGroup(t *testing.T) { } func TestOpenNonExistFile(t *testing.T) { - os.Setenv(RrhConfigPath, "testdata/config.json") - os.Setenv(RrhDatabasePath, "testdata/not-exist-file.json") + os.Setenv(ConfigPath, "testdata/config.json") + os.Setenv(DatabasePath, "testdata/not-exist-file.json") var config = OpenConfig() var db, _ = Open(config) @@ -77,8 +77,8 @@ func TestOpenNonExistFile(t *testing.T) { } func TestOpenNullDatabase(t *testing.T) { - os.Setenv(RrhConfigPath, "testdata/config.json") - os.Setenv(RrhDatabasePath, "testdata/nulldb.json") + os.Setenv(ConfigPath, "testdata/config.json") + os.Setenv(DatabasePath, "testdata/nulldb.json") var config = OpenConfig() var db, _ = Open(config) diff --git a/internal/add_cmd.go b/internal/add_cmd.go index 175b947..c85e1ef 100644 --- a/internal/add_cmd.go +++ b/internal/add_cmd.go @@ -53,7 +53,7 @@ func (add *AddCommand) showError(errorlist []error, onError string) { } func (add *AddCommand) perform(db *rrh.Database, opt *addOptions) int { - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) var errorlist = add.AddRepositoriesToGroup(db, opt) @@ -96,7 +96,7 @@ type addOptions struct { func (add *AddCommand) buildFlagSet(config *rrh.Config) (*flag.FlagSet, *addOptions) { var opt = addOptions{} - var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) + var defaultGroup = config.GetValue(rrh.DefaultGroupName) flags := flag.NewFlagSet("add", flag.ContinueOnError) flags.Usage = func() { fmt.Println(add.Help()) } flags.StringVarP(&opt.group, "group", "g", defaultGroup, "target group") diff --git a/internal/add_test.go b/internal/add_test.go index f65e310..5ba6a72 100644 --- a/internal/add_test.go +++ b/internal/add_test.go @@ -86,7 +86,7 @@ func TestAdd(t *testing.T) { }, } - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") for _, testcase := range testcases { var databaseFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = AddCommandFactory() @@ -118,7 +118,7 @@ func TestAdd(t *testing.T) { } func TestAddToDifferentGroup(t *testing.T) { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var databaseFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = AddCommandFactory() command.Run([]string{"../testdata/fibonacci"}) @@ -142,10 +142,10 @@ func TestAddToDifferentGroup(t *testing.T) { } func TestAddFailed(t *testing.T) { - os.Setenv(rrh.RrhConfigPath, "../testdata/nulldb.json") - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(rrh.RrhAutoCreateGroup, "false") - defer os.Unsetenv(rrh.RrhAutoCreateGroup) + os.Setenv(rrh.ConfigPath, "../testdata/nulldb.json") + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.AutoCreateGroup, "false") + defer os.Unsetenv(rrh.AutoCreateGroup) var add = AddCommand{} var config = rrh.OpenConfig() diff --git a/internal/clone_cmd.go b/internal/clone_cmd.go index f34bb7d..a85928e 100644 --- a/internal/clone_cmd.go +++ b/internal/clone_cmd.go @@ -87,7 +87,7 @@ func (clone *CloneCommand) perform(db *rrh.Database, arguments []string) int { var count, list = clone.DoClone(db, arguments) if len(list) != 0 { clone.options.showError(list) - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) if onError == rrh.Fail || onError == rrh.FailImmediately { return 1 } @@ -109,8 +109,8 @@ func printResult(count int, dest string, group string) { } func (clone *CloneCommand) buildFlagSets(config *rrh.Config) (*flag.FlagSet, *cloneOptions) { - var defaultGroup = config.GetValue(rrh.RrhDefaultGroupName) - var destination = config.GetValue(rrh.RrhCloneDestination) + var defaultGroup = config.GetValue(rrh.DefaultGroupName) + var destination = config.GetValue(rrh.CloneDestination) var options = cloneOptions{defaultGroup, ".", false} flags := flag.NewFlagSet("clone", flag.ContinueOnError) flags.Usage = func() { fmt.Println(clone.Help()) } @@ -188,7 +188,7 @@ func (clone CloneCommand) doCloneRepositories(db *rrh.Database, arguments []stri var increment, err = clone.doCloneEachRepository(db, url) if err != nil { errorlist = append(errorlist, err) - if db.Config.GetValue(rrh.RrhOnError) == rrh.FailImmediately { + if db.Config.GetValue(rrh.OnError) == rrh.FailImmediately { return count, errorlist } } diff --git a/internal/clone_test.go b/internal/clone_test.go index 95ec316..b8cf0a7 100644 --- a/internal/clone_test.go +++ b/internal/clone_test.go @@ -125,7 +125,7 @@ func TestUnknownOption(t *testing.T) { } func TestCloneNotGitRepository(t *testing.T) { - os.Setenv(rrh.RrhOnError, "FAIL") + os.Setenv(rrh.OnError, "FAIL") var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, db *rrh.Database) { var output = rrh.CaptureStdout(func() { var clone, _ = CloneCommandFactory() diff --git a/internal/common.go b/internal/common.go index 0ef068c..c4cc9b2 100644 --- a/internal/common.go +++ b/internal/common.go @@ -7,7 +7,7 @@ import ( ) func printErrors(config *rrh.Config, errs []error) int { - var onError = config.GetValue(rrh.RrhOnError) + var onError = config.GetValue(rrh.OnError) if onError != rrh.Ignore { for _, err := range errs { fmt.Println(err.Error()) @@ -20,5 +20,5 @@ func printErrors(config *rrh.Config, errs []error) int { } func isFailImmediately(config *rrh.Config) bool { - return config.GetValue(rrh.RrhOnError) == rrh.FailImmediately + return config.GetValue(rrh.OnError) == rrh.FailImmediately } diff --git a/internal/config_test.go b/internal/config_test.go index 00a076e..36fe796 100644 --- a/internal/config_test.go +++ b/internal/config_test.go @@ -68,16 +68,16 @@ func TestSynopsises(t *testing.T) { } func TestConfigUnset(t *testing.T) { - os.Setenv(rrh.RrhOnError, rrh.Fail) + os.Setenv(rrh.OnError, rrh.Fail) var testcases = []struct { args []string status int wontValue string wontFrom rrh.ReadFrom }{ - {[]string{rrh.RrhAutoCreateGroup}, 0, "false", rrh.Default}, + {[]string{rrh.AutoCreateGroup}, 0, "false", rrh.Default}, {[]string{"unknown"}, 5, "", rrh.NotFound}, - {[]string{rrh.RrhAutoCreateGroup, "tooManyArgs"}, 1, "", ""}, + {[]string{rrh.AutoCreateGroup, "tooManyArgs"}, 1, "", ""}, } for _, tc := range testcases { var dbfile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { @@ -96,13 +96,13 @@ func TestConfigUnset(t *testing.T) { }) defer os.Remove(dbfile) } - os.Unsetenv(rrh.RrhOnError) + os.Unsetenv(rrh.OnError) } func ExampleConfigCommand() { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") - os.Setenv(rrh.RrhHome, "../testdata/") - os.Setenv(rrh.RrhDatabasePath, "${RRH_HOME}/test_db.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") + os.Setenv(rrh.Home, "../testdata/") + os.Setenv(rrh.DatabasePath, "${RRH_HOME}/test_db.json") var command, _ = ConfigCommandFactory() command.Run([]string{}) // the output of no arguments are same as list subcommand. // Output: @@ -120,9 +120,9 @@ func ExampleConfigCommand() { // RRH_TIME_FORMAT: relative (default) } func ExampleConfigCommand_Run() { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") - os.Setenv(rrh.RrhHome, "../testdata/") - os.Setenv(rrh.RrhDatabasePath, "${RRH_HOME}/database.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") + os.Setenv(rrh.Home, "../testdata/") + os.Setenv(rrh.DatabasePath, "${RRH_HOME}/database.json") var command, _ = ConfigCommandFactory() command.Run([]string{"list"}) // the output of no arguments are same as list subcommand. // Output: @@ -140,9 +140,9 @@ func ExampleConfigCommand_Run() { // RRH_TIME_FORMAT: relative (default) } func Example_listCommand_Run() { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") - os.Setenv(rrh.RrhHome, "../testdata/") - os.Unsetenv(rrh.RrhDatabasePath) + os.Setenv(rrh.ConfigPath, "../testdata/config.json") + os.Setenv(rrh.Home, "../testdata/") + os.Unsetenv(rrh.DatabasePath) var clc, _ = configListCommandFactory() clc.Run([]string{}) // Output: @@ -161,20 +161,20 @@ func Example_listCommand_Run() { } func TestLoadConfigFile(t *testing.T) { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var testdata = []struct { key string value string from rrh.ReadFrom }{ - {rrh.RrhAutoDeleteGroup, "false", rrh.ConfigFile}, - {rrh.RrhAutoCreateGroup, "true", rrh.ConfigFile}, - {rrh.RrhSortOnUpdating, "true", rrh.ConfigFile}, - {rrh.RrhConfigPath, "../testdata/config.json", rrh.Env}, - {rrh.RrhTimeFormat, rrh.Relative, rrh.Default}, - {rrh.RrhOnError, rrh.Warn, rrh.Default}, - {rrh.RrhEnableColorized, "false", rrh.Default}, + {rrh.AutoDeleteGroup, "false", rrh.ConfigFile}, + {rrh.AutoCreateGroup, "true", rrh.ConfigFile}, + {rrh.SortOnUpdating, "true", rrh.ConfigFile}, + {rrh.ConfigPath, "../testdata/config.json", rrh.Env}, + {rrh.TimeFormat, rrh.Relative, rrh.Default}, + {rrh.OnError, rrh.Warn, rrh.Default}, + {rrh.EnableColorized, "false", rrh.Default}, {"unknown", "", rrh.NotFound}, } @@ -187,24 +187,24 @@ func TestLoadConfigFile(t *testing.T) { } func TestOpenConfig(t *testing.T) { - os.Unsetenv(rrh.RrhHome) - os.Unsetenv(rrh.RrhDatabasePath) - os.Unsetenv(rrh.RrhConfigPath) + os.Unsetenv(rrh.Home) + os.Unsetenv(rrh.DatabasePath) + os.Unsetenv(rrh.ConfigPath) var home, _ = homedir.Dir() var testdata = []struct { key string want string }{ - {rrh.RrhHome, fmt.Sprintf("%s/.rrh", home)}, - {rrh.RrhConfigPath, fmt.Sprintf("%s/.rrh/config.json", home)}, - {rrh.RrhDatabasePath, fmt.Sprintf("%s/.rrh/database.json", home)}, - {rrh.RrhDefaultGroupName, "no-group"}, - {rrh.RrhCloneDestination, "."}, - {rrh.RrhOnError, rrh.Warn}, - {rrh.RrhAutoCreateGroup, "false"}, - {rrh.RrhAutoDeleteGroup, "false"}, - {rrh.RrhSortOnUpdating, "false"}, - {rrh.RrhTimeFormat, rrh.Relative}, + {rrh.Home, fmt.Sprintf("%s/.rrh", home)}, + {rrh.ConfigPath, fmt.Sprintf("%s/.rrh/config.json", home)}, + {rrh.DatabasePath, fmt.Sprintf("%s/.rrh/database.json", home)}, + {rrh.DefaultGroupName, "no-group"}, + {rrh.CloneDestination, "."}, + {rrh.OnError, rrh.Warn}, + {rrh.AutoCreateGroup, "false"}, + {rrh.AutoDeleteGroup, "false"}, + {rrh.SortOnUpdating, "false"}, + {rrh.TimeFormat, rrh.Relative}, {"unknown", ""}, } // os.Unsetenv(RrhConfigPath) @@ -238,7 +238,7 @@ func TestPrintErrors(t *testing.T) { var config = rrh.NewConfig() for _, tc := range testcases { - config.Update(rrh.RrhOnError, tc.onError) + config.Update(rrh.OnError, tc.onError) var output = rrh.CaptureStdout(func() { var statusCode = config.PrintErrors(tc.error...) if statusCode != tc.wontStatus { @@ -262,7 +262,7 @@ func TestConfigSet(t *testing.T) { {[]string{"RRH_DEFAULT_GROUP_NAME", "newgroup"}, 0, "newgroup", rrh.ConfigFile}, {[]string{"RRH_DEFAULT_GROUP_NAME"}, 1, "", ""}, {[]string{"RRH_AUTO_DELETE_GROUP", "yes"}, 2, "", ""}, - {[]string{rrh.RrhConfigPath, "../testdata/broken.json"}, 2, "", ""}, + {[]string{rrh.ConfigPath, "../testdata/broken.json"}, 2, "", ""}, } for _, td := range testdata { var dbfile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { @@ -287,10 +287,10 @@ func TestConfigSet(t *testing.T) { } func TestFormatVariableAndValue(t *testing.T) { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var config = rrh.OpenConfig() - assert(t, formatVariableAndValue(config, rrh.RrhDefaultGroupName), "RRH_DEFAULT_GROUP_NAME: no-group (default)") - if config.IsSet(rrh.RrhOnError) { + assert(t, formatVariableAndValue(config, rrh.DefaultGroupName), "RRH_DEFAULT_GROUP_NAME: no-group (default)") + if config.IsSet(rrh.OnError) { t.Errorf("IsSet accepts only bool variable") } } diff --git a/internal/export_test.go b/internal/export_test.go index c13f5ba..7685c4a 100644 --- a/internal/export_test.go +++ b/internal/export_test.go @@ -10,7 +10,7 @@ import ( ) func open2(jsonName string) *rrh.Database { - os.Setenv(rrh.RrhDatabasePath, fmt.Sprintf("../testdata/%s", jsonName)) + os.Setenv(rrh.DatabasePath, fmt.Sprintf("../testdata/%s", jsonName)) var config = rrh.OpenConfig() var db, _ = rrh.Open(config) return db @@ -50,7 +50,7 @@ func TestBrokenDatabase(t *testing.T) { } func TestNullDB(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/nulldb.json") + os.Setenv(rrh.DatabasePath, "../testdata/nulldb.json") var result = rrh.CaptureStdout(func() { var export, _ = ExportCommandFactory() export.Run([]string{}) @@ -67,7 +67,7 @@ func TestNullDB(t *testing.T) { } func TestNullDBNoIndent(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/nulldb.json") + os.Setenv(rrh.DatabasePath, "../testdata/nulldb.json") var result = rrh.CaptureStdout(func() { var export, _ = ExportCommandFactory() export.Run([]string{"--no-indent"}) diff --git a/internal/fetch_all_cmd.go b/internal/fetch_all_cmd.go index 8604a44..75badd1 100644 --- a/internal/fetch_all_cmd.go +++ b/internal/fetch_all_cmd.go @@ -67,7 +67,7 @@ func convertToGroupNames(groups []rrh.Group) []string { } func (fetchAll *FetchAllCommand) execFetch(db *rrh.Database, options *fetchOptions) []error { - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) var errorlist = []error{} var fetch = FetchCommand{options} var relations = rrh.FindTargets(db, convertToGroupNames(db.Groups)) diff --git a/internal/fetch_cmd.go b/internal/fetch_cmd.go index 388c479..f1fde6a 100644 --- a/internal/fetch_cmd.go +++ b/internal/fetch_cmd.go @@ -99,14 +99,14 @@ func (fetch *FetchCommand) Run(args []string) int { func (fetch *FetchCommand) findRelations(db *rrh.Database) []rrh.Relation { var args = fetch.options.args if len(args) == 0 { - args = []string{db.Config.GetValue(rrh.RrhDefaultGroupName)} + args = []string{db.Config.GetValue(rrh.DefaultGroupName)} } return rrh.FindTargets(db, args) } func (fetch *FetchCommand) perform(db *rrh.Database) []error { var errorlist = []error{} - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) var relations = fetch.findRelations(db) var progress = NewProgress(len(relations)) diff --git a/internal/group_test.go b/internal/group_test.go index d73dcec..c44629d 100644 --- a/internal/group_test.go +++ b/internal/group_test.go @@ -142,8 +142,8 @@ func TestAddGroup(t *testing.T) { } func TestGroupInfo(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var testdata = []struct { args []string @@ -166,8 +166,8 @@ func TestGroupInfo(t *testing.T) { } func TestUpdateGroupFailed(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var testcases = []struct { opt groupUpdateOptions @@ -285,7 +285,7 @@ func TestRemoveGroup(t *testing.T) { } func TestInvalidOptionInGroupList(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") rrh.CaptureStdout(func() { var glc, _ = groupListCommandFactory() if val := glc.Run([]string{"--unknown-option"}); val != 1 { diff --git a/internal/import_test.go b/internal/import_test.go index e92a889..58412d6 100644 --- a/internal/import_test.go +++ b/internal/import_test.go @@ -48,7 +48,7 @@ func TestImport(t *testing.T) { } for _, testcase := range testcases { - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var command, _ = ImportCommandFactory() var statusCode = command.Run(testcase.args) diff --git a/internal/list_test.go b/internal/list_test.go index 92d7019..968980b 100644 --- a/internal/list_test.go +++ b/internal/list_test.go @@ -37,8 +37,8 @@ func ExampleListCommand_Run() { } func TestRunByCsvOutput(t *testing.T) { - os.Setenv(rrh.RrhDefaultGroupName, "group1") - defer os.Unsetenv(rrh.RrhDefaultGroupName) + os.Setenv(rrh.DefaultGroupName, "group1") + defer os.Unsetenv(rrh.DefaultGroupName) var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var result = rrh.CaptureStdout(func() { var list, _ = ListCommandFactory() diff --git a/internal/move_test.go b/internal/move_test.go index c35ea88..c6c137e 100644 --- a/internal/move_test.go +++ b/internal/move_test.go @@ -17,9 +17,9 @@ func TestParseError(t *testing.T) { {[]string{"group1/repo1", "group3/repo5"}, 4}, {[]string{"group1/repo1", "repo2", "group5"}, 4}, } - os.Setenv(rrh.RrhOnError, rrh.Fail) - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") - os.Setenv(rrh.RrhConfigPath, "../testdata/config.json") + os.Setenv(rrh.OnError, rrh.Fail) + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.ConfigPath, "../testdata/config.json") rrh.CaptureStdout(func() { for _, testcase := range testcases { @@ -30,7 +30,7 @@ func TestParseError(t *testing.T) { } } }) - defer os.Unsetenv(rrh.RrhOnError) + defer os.Unsetenv(rrh.OnError) } func TestMoveCommand(t *testing.T) { @@ -165,7 +165,7 @@ func TestMergeType(t *testing.T) { func TestMisc(t *testing.T) { var config = rrh.OpenConfig() if isFailImmediately(config) { - t.Errorf("onError wont: %s, got: %s", rrh.Warn, config.GetValue(rrh.RrhOnError)) + t.Errorf("onError wont: %s, got: %s", rrh.Warn, config.GetValue(rrh.OnError)) } } diff --git a/internal/prune_test.go b/internal/prune_test.go index b6b5f31..01219ba 100644 --- a/internal/prune_test.go +++ b/internal/prune_test.go @@ -59,7 +59,7 @@ func TestPrune(t *testing.T) { } func TestPruneCommandRunFailedByBrokenDBFile(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.DatabasePath, "../testdata/broken.json") var prune, _ = PruneCommandFactory() if prune.Run([]string{}) != 1 { t.Error("broken database read successfully.") @@ -67,7 +67,7 @@ func TestPruneCommandRunFailedByBrokenDBFile(t *testing.T) { } func TestPruneCommandRunFailedByInvalidArgs(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/test_db.json") + os.Setenv(rrh.DatabasePath, "../testdata/test_db.json") var prune, _ = PruneCommandFactory() if prune.Run([]string{"--help"}) != 1 { t.Error("successing invalid option parsing.") diff --git a/internal/remove_cmd.go b/internal/remove_cmd.go index ec88fb6..6fecf79 100644 --- a/internal/remove_cmd.go +++ b/internal/remove_cmd.go @@ -107,7 +107,7 @@ func (rm *RemoveCommand) perform(db *rrh.Database) int { } } if result == 0 { - if db.Config.IsSet(rrh.RrhAutoDeleteGroup) { + if db.Config.IsSet(rrh.AutoDeleteGroup) { db.Prune() } db.StoreAndClose() diff --git a/internal/remove_test.go b/internal/remove_test.go index a4fef7a..e105070 100644 --- a/internal/remove_test.go +++ b/internal/remove_test.go @@ -130,7 +130,7 @@ func TestRunRemoveRepository(t *testing.T) { func TestRemoveRepository2(t *testing.T) { var dbFile = rrh.Rollback("../testdata/test_db.json", "../testdata/config.json", func(config *rrh.Config, oldDB *rrh.Database) { var rm, _ = RemoveCommandFactory() - os.Setenv(rrh.RrhAutoDeleteGroup, "true") + os.Setenv(rrh.AutoDeleteGroup, "true") rm.Run([]string{"-v", "group2", "repo1"}) var db2, _ = rrh.Open(config) if len(db2.Repositories) != 1 && len(db2.Groups) != 0 { @@ -141,7 +141,7 @@ func TestRemoveRepository2(t *testing.T) { } func TestBrokenDatabaseOnRemoveCommand(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.DatabasePath, "../testdata/broken.json") var rm, _ = RemoveCommandFactory() if result := rm.Run([]string{}); result != 2 { t.Errorf("broken database are successfully read!?") diff --git a/internal/repository_cmd.go b/internal/repository_cmd.go index f20ac28..46dede0 100644 --- a/internal/repository_cmd.go +++ b/internal/repository_cmd.go @@ -132,7 +132,7 @@ func (options *repositoryInfoOptions) printInfoResult(result rrh.Repository, db func (info *repositoryInfoCommand) perform(db *rrh.Database, args []string) int { var results, errs = findResults(db, args) - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) for _, result := range results { info.options.printInfoResult(result, db) } @@ -179,7 +179,7 @@ func printListResult(db *rrh.Database, result rrh.Repository, options *repositor func (list *repositoryListCommand) perform(db *rrh.Database, args []string) int { var results, errs = findAll(db, args) - var onError = db.Config.GetValue(rrh.RrhOnError) + var onError = db.Config.GetValue(rrh.OnError) for _, result := range results { printListResult(db, result, list.options) } @@ -474,7 +474,7 @@ func findResults(db *rrh.Database, args []string) ([]rrh.Repository, []error) { var repo = db.FindRepository(arg) if repo == nil { errs = append(errs, fmt.Errorf("%s: repository not found", arg)) - if db.Config.GetValue(rrh.RrhOnError) == rrh.FailImmediately { + if db.Config.GetValue(rrh.OnError) == rrh.FailImmediately { return []rrh.Repository{}, errs } } else { diff --git a/internal/repository_test.go b/internal/repository_test.go index 6ba0a66..d6ff9bd 100644 --- a/internal/repository_test.go +++ b/internal/repository_test.go @@ -255,7 +255,7 @@ func TestSynopsisOfRepository(t *testing.T) { } func TestRepositoryCommandRunFailedByBrokenDBFile(t *testing.T) { - os.Setenv(rrh.RrhDatabasePath, "../testdata/broken.json") + os.Setenv(rrh.DatabasePath, "../testdata/broken.json") var testcases = []struct { comGenerator func() (cli.Command, error) diff --git a/internal/status_cmd.go b/internal/status_cmd.go index f84918f..a3debcb 100644 --- a/internal/status_cmd.go +++ b/internal/status_cmd.go @@ -167,7 +167,7 @@ func (status *StatusCommand) parse(args []string, config *rrh.Config) ([]string, } status.options = options if len(flags.Args()) == 0 { - return []string{config.GetValue(rrh.RrhDefaultGroupName)}, nil + return []string{config.GetValue(rrh.DefaultGroupName)}, nil } return flags.Args(), nil } diff --git a/testutils.go b/testutils.go index b0d6efb..8b2a60d 100644 --- a/testutils.go +++ b/testutils.go @@ -24,8 +24,8 @@ func Rollback(dbFile, configFile string, f func(config *Config, db *Database)) s var newDBFile = copyfile(dbFile) var newConfigFile = copyfile(configFile) defer os.Remove(newConfigFile) - os.Setenv(RrhConfigPath, newConfigFile) - os.Setenv(RrhDatabasePath, newDBFile) + os.Setenv(ConfigPath, newConfigFile) + os.Setenv(DatabasePath, newDBFile) var config = OpenConfig() var db, err = Open(config) @@ -35,8 +35,8 @@ func Rollback(dbFile, configFile string, f func(config *Config, db *Database)) s f(config, db) - os.Setenv(RrhConfigPath, configFile) // replace the path of config file. - os.Setenv(RrhDatabasePath, dbFile) + os.Setenv(ConfigPath, configFile) // replace the path of config file. + os.Setenv(DatabasePath, dbFile) return newDBFile } diff --git a/util.go b/util.go index 4468612..e72470f 100644 --- a/util.go +++ b/util.go @@ -34,7 +34,7 @@ func CreateParentDir(path string) error { Strftime returns the string of the given time. */ func Strftime(time time.Time, config *Config) string { - var format = config.GetValue(RrhTimeFormat) + var format = config.GetValue(TimeFormat) if format != Relative { return time.Format(format) } diff --git a/util_test.go b/util_test.go index b02ca2c..67a0356 100644 --- a/util_test.go +++ b/util_test.go @@ -49,8 +49,8 @@ func TestGitRepositoryCheck(t *testing.T) { } func TestStrftime(t *testing.T) { - os.Setenv(RrhTimeFormat, Relative) - os.Setenv(RrhConfigPath, "testdata/config.json") + os.Setenv(TimeFormat, Relative) + os.Setenv(ConfigPath, "testdata/config.json") var now = time.Now() var testcases = []struct { @@ -68,15 +68,15 @@ func TestStrftime(t *testing.T) { var config = OpenConfig() for _, test := range testcases { - os.Setenv(RrhTimeFormat, test.formatter) + os.Setenv(TimeFormat, test.formatter) var time = Strftime(test.time, config) if time != test.wont { t.Errorf("wont: %s, got: %s", test.wont, time) } } - os.Unsetenv(RrhTimeFormat) - os.Unsetenv(RrhConfigPath) + os.Unsetenv(TimeFormat) + os.Unsetenv(ConfigPath) } func TestRollback(t *testing.T) { From cf9250a3ce9bbf7a6ac514209523ceb734411375 Mon Sep 17 00:00:00 2001 From: Haruaki Tamada Date: Fri, 24 Apr 2020 09:51:18 +0900 Subject: [PATCH 3/9] ref #86 introduce dist target for Makefile --- Makefile | 31 +++++++++++++++++++++++++------ go.sum | 1 + 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 5afc667..29ef164 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,8 @@ GO=go +SHELL=/bin/bash NAME := rrh VERSION := 1.1.0 -REVISION := $(shell git rev-parse --short HEAD) +DIST := $(NAME)-$(VERSION) all: test build @@ -34,6 +35,28 @@ build: setup @$(call _buildSubcommand,rrh-helloworld) @$(call _buildSubcommand,rrh-new) + +# refer from https://pod.hatenablog.com/entry/2017/06/13/150342 +define _createDist + echo -n "create dist/$(DIST)_$(1)_$(2).tar.gz ...." + mkdir -p dist/$(1)_$(2)/$(DIST)/bin + GOOS=$1 GOARCH=$2 go build -o dist/$(1)_$(2)/$(DIST)/bin/$(NAME)$(3) cmd/$(NAME)/*.go + GOOS=$1 GOARCH=$2 go build -o dist/$(1)_$(2)/$(DIST)/bin/rrh-helloworld$(3) cmd/rrh-helloworld/*.go + GOOS=$1 GOARCH=$2 go build -o dist/$(1)_$(2)/$(DIST)/bin/rrh-new$(3) cmd/rrh-new/*.go + cp -r completions dist/$(1)_$(2)/$(DIST) + cp -r README.md LICENSE CODE_OF_CONDUCT.md CONTRIBUTING.md dist/$(1)_$(2)/$(DIST) + tar cfz dist/$(DIST)_$(1)_$(2).tar.gz -C dist/$(1)_$(2) $(DIST) + echo "done." +endef + +dist: build + @$(call _createDist,darwin,amd64,) + @$(call _createDist,darwin,386,) + @$(call _createDist,windows,amd64,.exe) + @$(call _createDist,windows,386,.exe) + @$(call _createDist,linux,amd64,) + @$(call _createDist,linux,386,) + lint: setup format $(GO) vet $$(go list ./...) for pkg in $$(go list ./...); do \ @@ -47,10 +70,6 @@ format: setup # Other packages are no problem, their have the same name with directories. goimports -w $$(go list ./... | sed 's/github.com\/tamada\/rrh//g' | sed 's/^\///g') -install: test build - $(GO) install - . ./completions/bash/rrh - clean: $(GO) clean - rm -rf rrh rrh-helloworld rrh-new + rm -rf rrh rrh-helloworld rrh-new dist diff --git a/go.sum b/go.sum index 3704a49..59f7832 100644 --- a/go.sum +++ b/go.sum @@ -94,6 +94,7 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190522044717-8097e1b27ff5 h1:f005F/Jl5JLP036x7QIvUVhNTqxvSYwFIiyOh2q12iU= golang.org/x/sys v0.0.0-20190522044717-8097e1b27ff5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd h1:/e+gpKk9r3dJobndpTytxS2gOy6m5uvpg+ISQoEcusQ= From 1ea93655121a5b61adb9ed8039a4a2adcd24f041 Mon Sep 17 00:00:00 2001 From: Haruaki Tamada Date: Fri, 24 Apr 2020 10:37:37 +0900 Subject: [PATCH 4/9] add github actions --- .github/workflows/build.yaml | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/build.yaml diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..6ace4b1 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,35 @@ +name: build +on: + push: + branches: + - "**" +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - ubuntu-latest + - macOS-latest + - windows-latest + steps: + - name: setup go + uses: actions/setup-go@v1 + with: + go-version: 1.14 + - name: checkout + uses: actions/checkout@v1 + - name: build + run: make + - name: Convert coverage to lcov + uses: jandelgado/gcov2lcov-action@v1.0.0 + with: + infile: coverage.out + outfile: coverage.lcov + if: "matrix.os == 'ubuntu-latest'" + - name: coveralls + uses: coverallsapp/github-action@v1.0.1 + with: + github-token: ${{ secrets.github_token }} + path-to-lcov: coverage.lcov + if: "matrix.os == 'ubuntu-latest'" From b4e5e6813e1a463ad96f53a4285db495e0cb8134 Mon Sep 17 00:00:00 2001 From: Haruaki Tamada Date: Fri, 24 Apr 2020 10:52:41 +0900 Subject: [PATCH 5/9] update document for ship v1.2.0 --- docs/Makefile | 6 +++--- docs/config.toml | 2 ++ docs/content/_index.md | 22 +++++++++++----------- docs/content/about.md | 2 ++ docs/content/usage.md | 2 +- docs/layouts/partials/header-nav.html | 2 +- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/docs/Makefile b/docs/Makefile index ac19d6b..a709ebe 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -2,14 +2,14 @@ PWD := ${CURDIR} DOCKER_IMAGE_NAME := "wwwrrh" CONTAINER_REMOVE_FLAG := "--rm" BASE_URL := "https://tamada.github.io/rrh" +HUGO_THEME := "cayman-hugo-theme" JOJOMI_VERSION := 0.69.0 build: - docker run ${CONTAINER_REMOVE_FLAG} -d --name ${DOCKER_IMAGE_NAME} -p 1313:1313 -v "${PWD}":/src -v ${PWD}/public:/output -e HUGO_THEME=cayman-hugo-theme -e HUGO_BASEURL=${BASE_URL} jojomi/hugo:${JOJOMI_VERSION} + docker run ${CONTAINER_REMOVE_FLAG} -d --name ${DOCKER_IMAGE_NAME}_build -v "${PWD}":/src -v ${PWD}/public:/output -e HUGO_THEME=$(HUGO_THEME) -e HUGO_BASEURL=${BASE_URL} jojomi/hugo:${JOJOMI_VERSION} start: - docker run ${CONTAINER_REMOVE_FLAG} -d --name ${DOCKER_IMAGE_NAME} -p 1313:1313 -v "${PWD}":/src -v "$(PWD)"/public:/output -e HUGO_THEME=cayman-hugo-theme -e HUGO_WATCH="true" -e HUGO_BASEURL=${BASE_URL} jojomi/hugo:${JOJOMI_VERSION} + docker run ${CONTAINER_REMOVE_FLAG} -d --name ${DOCKER_IMAGE_NAME} -p 1313:1313 -v "${PWD}":/src -v "$(PWD)"/public:/output -e HUGO_THEME=$(HUGO_THEME) -e HUGO_WATCH="true" -e HUGO_BASEURL=${BASE_URL} jojomi/hugo:${JOJOMI_VERSION} stop: docker stop wwwrrh - diff --git a/docs/config.toml b/docs/config.toml index 99c0716..52a25b5 100644 --- a/docs/config.toml +++ b/docs/config.toml @@ -3,6 +3,8 @@ languageCode = "en-us" defaultContentLanguage = "en" title = "rrh" theme = "cayman-hugo-theme" +enableEmoji = true +googleAnalytics = "UA-62401730-6" pygmentsCodefences = true pygmentsStyle = "pygments" diff --git a/docs/content/_index.md b/docs/content/_index.md index b61fce5..94a024b 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -15,10 +15,10 @@ RRH is a simple git repository manager. * [:bookmark_tabs: Description](description) * [:anchor: Installation](installation) - * [:beer: Homebrew](installation#beer-homebrew) + * [:beer: Homebrew](installation#-homebrew) * [Golang](installation#golang) - * [:hammer_and_wrench: Build form source codes](installation#hammer_and_wrench-build-from-source-codes) - * [:white_check_mark: Requirements](installation#white_check_mark-requirements) + * [:hammer_and_wrench: Build form source codes](installation#-build-from-source-codes) + * [:white_check_mark: Requirements](installation#-requirements) * [:fork_and_knife: Usage](usage) * [Getting Started](usage#getting-started) * [Command references](usage#command-references) @@ -30,11 +30,11 @@ RRH is a simple git repository manager. * [`cdrrh`](utilities#cdrrh) * [`rrhpeco`](utilities#rrhpeco) * [:smile: About the Project](about) - * [:raised_hand: Contribution](about#raised_hand-contribution) - * [:green_book: Code of Conduct](about#green_book-code-of-conduct) - * [:scroll: License](about#scroll-license) - * [:speech_balloon: Discussion](about#speech_balloon-discussion) - * [:busts_in_silhouette: Authors](about#busts_in_silhouette-authors) - * [:question: Why the project name RRH](about#question-why-the-project-name-rrh) - * [:handshake: Attributions](about#handshake-attributions) - * [:paw_prints: Version histories](about#paw_prints-version-histories) + * [:raised_hand: Contribution](about#-contribution) + * [:green_book: Code of Conduct](about#-code-of-conduct) + * [:scroll: License](about#-license) + * [:speech_balloon: Discussion](about#-discussion) + * [:busts_in_silhouette: Authors](about#-authors) + * [:question: Why the project name RRH](about#-why-the-project-name-rrh) + * [:handshake: Attributions](about#-attributions) + * [:paw_prints: Version histories](about#-version-histories) diff --git a/docs/content/about.md b/docs/content/about.md index 58a2e41..c0a0492 100644 --- a/docs/content/about.md +++ b/docs/content/about.md @@ -62,6 +62,8 @@ RRH means "Repositories, Ready to Hack" or "Remote Repositories Head," are not t ## :paw_prints: Version histories +* [v1.2.0](https://github.com/tamada/rrh/releases/tag/v1.2.0) (24 Apr, 2020) + * [\#83](https://github.com/tamada/rrh/issues/83) (introduce `rrh open` sub command) * [v1.1.0](https://github.com/tamada/rrh/releases/tag/v1.1.0) (18 Dec, 2018) * [\#79](https://github.com/tamada/rrh/issues/79) (add `rrh group info` sub command) * [\#77](https://github.com/tamada/rrh/issues/77) (introduce `rrh repository update-remotes` sub command) diff --git a/docs/content/usage.md b/docs/content/usage.md index 1b108af..91d3095 100644 --- a/docs/content/usage.md +++ b/docs/content/usage.md @@ -8,7 +8,7 @@ title: ":fork_and_knife: Usage" * `rrh list` shows managed repositories. * `rrh add ` adds the given repository under the `rrh` management. -* type [`cdrrh`](#cdrrh) on Terminal, then type TAB, TAB, TAB! +* type [`cdrrh`](../utilities/#cdrrh) on Terminal, then type TAB, TAB, TAB! ## Command references diff --git a/docs/layouts/partials/header-nav.html b/docs/layouts/partials/header-nav.html index fd57cfe..348babd 100644 --- a/docs/layouts/partials/header-nav.html +++ b/docs/layouts/partials/header-nav.html @@ -1,6 +1,6 @@