From d69eacef658fba49678afb937422a3eb43c759ec Mon Sep 17 00:00:00 2001 From: TJ Hoplock Date: Fri, 26 Apr 2019 18:12:35 -0400 Subject: [PATCH] initial public release! \o/ Basic functionality is there for pretty much all commands/aspects of things, but it definitely could still use some polish. And I'm sure more features/use cases/edge cases will come up along the way. --- .gitignore | 17 +++++ LICENSE | 21 ++++++ README.md | 106 +++++++++++++++++++++++++++++++ cmd/copy.go | 73 +++++++++++++++++++++ cmd/create.go | 79 +++++++++++++++++++++++ cmd/edit.go | 108 +++++++++++++++++++++++++++++++ cmd/list.go | 148 +++++++++++++++++++++++++++++++++++++++++++ cmd/paste.go | 54 ++++++++++++++++ cmd/remove.go | 68 ++++++++++++++++++++ cmd/rename.go | 74 ++++++++++++++++++++++ cmd/root.go | 146 ++++++++++++++++++++++++++++++++++++++++++ cmd/show.go | 68 ++++++++++++++++++++ helpers/template.go | 51 +++++++++++++++ helpers/utilities.go | 36 +++++++++++ helpers/yaml.go | 67 ++++++++++++++++++++ main.go | 27 ++++++++ 16 files changed, 1143 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/copy.go create mode 100644 cmd/create.go create mode 100644 cmd/edit.go create mode 100644 cmd/list.go create mode 100644 cmd/paste.go create mode 100644 cmd/remove.go create mode 100644 cmd/rename.go create mode 100644 cmd/root.go create mode 100644 cmd/show.go create mode 100644 helpers/template.go create mode 100644 helpers/utilities.go create mode 100644 helpers/yaml.go create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f7bd5ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Random swap and lock files from editors +*.swp +*.lock +*.vim diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..57ee9a8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2019 TJ Hoplock + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c79e119 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# Clip - A Templated Clipboard Manager + +## Overview +Clip is a CLI tool to let you manage templates and copy them to your clipboard so you can easily paste them into other forms or software. Clip templates can be templated using [Go templates](https://golang.org/pkg/text/template/), and they can be assigned tags to organize and filter your templates. Variables to be used in the templates can be either embedded directly into the template or put into the `clip` config file so they're available to all templates. Examples of the [config file](#Configuration) and [template files](#Templates) can be found below. + +## Usage +(To see all available subcommands, run `clip --help`) + +## Configuration +Clip uses a single configuration file (by default located at `$HOME/.clip.yml`). A basic config file will be created for you when you first run the command, but there are currently only 3 required keys: +``` +~ $ cat $HOME/.clip.yml +editor: nano +templatedir: /your/home/directory/clip +vars: + name: Clip User +``` +You'll need to edit this config file directly to change these default values. + +Template configuration can be done almost entirely through the `clip` CLI and it's subcommands (create, edit, remove, rename, list, etc) + +## Templates +Clip templates are YAML files with [Golang templated](https://golang.org/pkg/text/template/) text snippets and variables to use for substitutions in the template. Templates exist in a directory managed by Clip. By default, the template directory is `$HOME/clip/`, but this can be changed by editing the `templatedir` setting in the config file or passing the `--templatedir` flag at runtime. + +The base template that gets created is pretty simple: +``` +# See README.md for detailed information and examples +tags: [] + +template: + vars: {} + text: | +``` +What the keys do: + +| Key | Description | Configuration | +| --- | ----------- | ------------- | +| `tags` | Metadata tags that you'd like to apply to this template (purely for your organizational needs) | List | +| `template:vars` | Variables that will be available to the Go templating system when it renders your clip template. These variables override any global variables with the same name you define in the Clip config file. | Accepts an arbitrary number of `key: value` pairs to define variables and their values | +| `template:text` | The text to be rendered through Go's template system and loaded onto your clipboard | Accepts a YAML multi-line string (be careful with indentation!) | + +Example template: +``` +~ $ clip show readme-template-example +# See README.md for detailed information and examples +tags: + - personal + - side-project + - golang + +template: + vars: + name: "tjhop" + greeting: "Hello, Clip User!" + signature: "Have fun!" + text: | + {{ .greeting }} + + This is the general format of a Clip template file. The tags assigned to this template can be used to filter output when using the `list` command, like so: + `clip list --tagsonly` + `clip list --tags personal,golang + + More info can be found using the `--help` flag on any of the subcommands, too. + + {{ .signature }} + {{ .name }} +``` + +After copying the template, we'll end up with the following content on our clipboard: +``` +~ $ clip copy readme-template-example +~ $ clip paste +Hello, Clip User! + +This is the general format of a Clip template file. The tags assigned to this template can be used to filter output when using the `list` command, like so: +`clip list --tagsonly` +`clip list --tags personal,golang + +More info can be found using the `--help` flag on any of the subcommands, too. + +Have fun! +tjhop +``` + +## Building +Builds are using `go1.12.1` using [gox](https://github.com/mitchellh/gox): + +``` +~/go/src/github.com/tjhop/clip -> COMMIT=$(git rev-parse --short HEAD | tr -d "[ \r\n\']"); +TAG=$(git describe --always --tags --abbrev=0 | tr -d "[v\r\n]"); +echo "commit: $COMMIT"; echo "tag: $TAG"; +gox -ldflags="-X github.com/tjhop/clip/cmd/root.builddate=$(date +%Y-%m-%d) + -X github.com/tjhop/clip/cmd/root.version=$TAG + -X github.com/tjhop/clip/cmd/root.commit=$COMMIT" \ + -osarch "linux/amd64" -output="$GOBIN/{{ .OS }}/{{ .Arch }}/clip" \ + -osarch "darwin/amd64" -output="$GOBIN/{{ .OS }}/{{ .Arch }}/clip" +``` + +## TODO +- [ ] allow editing Clip config directly through `clip` commands like template files? +- [ ] allow using different config file locations (viper has the ability to search config paths, I just couldn't think of other places I'd want the config during development) +- [ ] figure out how to post release binaries on github (never done it before ¯\\\_(ツ)_/¯) +- [ ] figure out how to report version/commit info that I'm bothering to embed in the build + +## Credits/Thanks +Clip is written using the [Cobra](https://github.com/spf13/cobra) and [Viper](https://github.com/spf13/viper) libraries, with the clipboard management provided by [atotto/clipboard library](https://github.com/atotto/clipboard). They made my life a heck of a life easier, so thanks to them <3. diff --git a/cmd/copy.go b/cmd/copy.go new file mode 100644 index 0000000..94fd5c1 --- /dev/null +++ b/cmd/copy.go @@ -0,0 +1,73 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "strings" + "path" + "path/filepath" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/atotto/clipboard" + + "github.com/tjhop/clip/helpers" +) + +var copyCmd = &cobra.Command{ + Use: "copy ", + Aliases: []string{"load", "in"}, + Short: "Copy a Clip template to your clipboard", + Long: `Copy a Clip template to your clipboard`, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + templateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := writeClipTemplateToClipboard(templateFilename) + if err != nil { + fmt.Printf("Failed to copy Clip template '%s' to clipboard: %v\n", strings.TrimSuffix(path.Base(templateFilename), filepath.Ext(templateFilename)), err) + } + }, +} + +func init() { + rootCmd.AddCommand(copyCmd) +} + +func writeClipTemplateToClipboard(filename string) error { + tmpl, err := helpers.LoadTemplateFile(filename) + if err != nil { + return fmt.Errorf("Couldn't load Clip template file '%s': %v\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename)), err) + } + + renderedTemplateString, err := helpers.ExecuteTemplate(tmpl) + if err != nil { + return fmt.Errorf("Failed to render Go Template: %v\n", err) + } + + err = clipboard.WriteAll(renderedTemplateString) + if err != nil { + return fmt.Errorf("Failed to write Clip template to clipboard: %v\n", err) + } + + return nil +} diff --git a/cmd/create.go b/cmd/create.go new file mode 100644 index 0000000..e1453da --- /dev/null +++ b/cmd/create.go @@ -0,0 +1,79 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "strings" + "path" + "path/filepath" + "io/ioutil" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const baseTemplateFileString string = +`# See README.md for detailed information and examples +tags: [] + +template: + vars: {} + text: | +` + +// createCmd represents the create command +var createCmd = &cobra.Command{ + Use: "create ", + Aliases: []string{"add", "make"}, + Short: "Create a new Clip template", + Long: `Create a Clip template. Clip templates are YAML files with embedded Go templates and variables. +`, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + templateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := writeTemplateFile(templateFilename) + if err != nil { + fmt.Printf("Call to create template failed: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(createCmd) +} + +func writeTemplateFile(filename string) error { + // create template file if it doesn't exist + if _, err := os.Stat(filename); os.IsNotExist(err) { + err := ioutil.WriteFile(filename, []byte(baseTemplateFileString), 0644) + if err != nil { + return fmt.Errorf("Failed to create template file: %v\n", err) + } + + fmt.Printf("Clip template '%s' created\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))) + } else { + fmt.Printf("A Clip template with the name '%s' already exists\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))) + } + + return nil +} diff --git a/cmd/edit.go b/cmd/edit.go new file mode 100644 index 0000000..5efedd5 --- /dev/null +++ b/cmd/edit.go @@ -0,0 +1,108 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "os/exec" + "strings" + "path" + "path/filepath" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var ( + editor string +) + +var editCmd = &cobra.Command{ + Use: "edit ", + Short: "Open Clip template in text editor", + Long: `Open Clip template in text editor. + +Clip will check the following locations for the editor to use: + Clip config file + Command line flag (--editor) + $EDITOR environment variable + Default (nano) +`, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + templateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := openClipTemplateInEditor(templateFilename) + if err != nil { + fmt.Printf("Failed to open Clip template for editing: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(editCmd) + + // command Line flags + editCmd.Flags().StringVarP(&editor, "editor", "e", "", "location of template directory (default is $HOME/clip)") + + // use viper to bind config to CLI flags + viper.BindPFlag("editor", editCmd.Flags().Lookup("editor")) +} + +func openClipTemplateInEditor(filename string) error { + var editor string + + // check if clip template exists yet. if it doesn't, make it + if _, err := os.Stat(filename); os.IsNotExist(err) { + err = writeTemplateFile(filename) + if err != nil { + return fmt.Errorf("Call to create Clip template file failed: %v\n", err) + } + } + + if viper.GetString("editor") != "" { + editor = viper.GetString("editor") + _, err := exec.LookPath(editor) + if err != nil { + return fmt.Errorf("Could not find an editor named '%s' in your PATH: %v\n", editor, err) + } + } else if os.Getenv("EDITOR") != "" { + editor = os.Getenv("EDITOR") + _, err := exec.LookPath(editor) + if err != nil { + return fmt.Errorf("Could not find an editor named '%s' in your PATH: %v\n", editor, err) + } + } else { + return fmt.Errorf("No editor defined!") + } + + // build command to run + cmd := exec.Command(editor, filename) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + return fmt.Errorf("Failed to open Clip template '%s' in %s: %v\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename)), editor, err) + } + + return nil +} diff --git a/cmd/list.go b/cmd/list.go new file mode 100644 index 0000000..6ec249c --- /dev/null +++ b/cmd/list.go @@ -0,0 +1,148 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "strings" + "sort" + "path/filepath" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/tjhop/clip/helpers" +) + +var ( + tags []string + tagsOnly bool +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Long: `List available Clip templates (can be filtered by tag) or list the available tags. + +Example: + clip list + clip list --tags-only + clip list --tags personal,work`, + Short: "List available Clip templates/tags", + Run: func(cmd *cobra.Command, args []string) { + list() + }, +} + +func init() { + rootCmd.AddCommand(listCmd) + + // command Line flags + listCmd.Flags().StringSliceVar(&tags, "tags", []string{}, "comma separated list of tags to filter templates") + listCmd.Flags().BoolVar(&tagsOnly, "tags-only", false, "list all tags used in the templates") + listCmd.Flags().BoolVar(&tagsOnly, "listtags", false, "alias for '--tags-only' flag") + listCmd.Flags().BoolVar(&tagsOnly, "showtags", false, "alias for '--tags-only' flag") +} + +func list() { + if tagsOnly == true { + err := listTemplateTags(viper.GetString("templatedir")) + if err != nil { + fmt.Printf("Call to list Clip template tags failed: %v\n", err) + } + } else { + err := listTemplates(viper.GetString("templatedir")) + if err != nil { + fmt.Printf("Call to list Clip templates failed: %v\n", err) + } + } +} + +func listTemplates(dir string) error { + var files []string + + // walk the template directory and get the files + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if !info.IsDir() && (filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml") { + filenameWithoutExtension := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name())) + + // if `--tags` filter was provided, check if file contains one of the provided tags + if len(tags) > 0 { + for _, tag := range tags { + tmpl, err := helpers.LoadTemplateFile(dir + "/" + info.Name()) + if err != nil { + return fmt.Errorf("Couldn't load Clip template '%s' to check for tags: %v\n", filenameWithoutExtension, err) + } + + if helpers.Contains(tmpl.Tags, tag) && !helpers.Contains(files, filenameWithoutExtension) { + files = append(files, filenameWithoutExtension) + } + } + } else { + files = append(files, filenameWithoutExtension) + } + } + return nil + }) + + if err != nil { + return fmt.Errorf("Failed to walk template directory: %v\n", err) + } + + for _, file := range files { + fmt.Println(file) + } + + return nil +} + +func listTemplateTags(dir string) error { + var tags []string + + // walk the template directory and get the files + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if !info.IsDir() && (filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml") { + tmpl, err := helpers.LoadTemplateFile(dir + "/" + info.Name()) + if err != nil { + return fmt.Errorf("Couldn't load Clip template to check for tags: %v\n", err) + } + + for _, tag := range tmpl.Tags { + if !helpers.Contains(tags, tag) { + tags = append(tags, tag) + } + } + } + return nil + }) + + if err != nil { + return fmt.Errorf("Failed to walk template directory: %v\n", err) + } + + sort.Strings(tags) + for _, tag := range tags { + fmt.Println(tag) + } + + return nil +} diff --git a/cmd/paste.go b/cmd/paste.go new file mode 100644 index 0000000..f986afb --- /dev/null +++ b/cmd/paste.go @@ -0,0 +1,54 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/atotto/clipboard" +) + +var pasteCmd = &cobra.Command{ + Use: "paste", + Aliases: []string{"out", "print"}, + Short: "Print clipboard contents to stdout", + Run: func(cmd *cobra.Command, args []string) { + err := writeClipboardToStdout() + if err != nil { + fmt.Printf("Call to print clipboard contents failed: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(pasteCmd) +} + +func writeClipboardToStdout() error { + str, err := clipboard.ReadAll() + if err != nil { + return fmt.Errorf("Failed to dump clipboard contents to variable: %v\n", err) + } + + fmt.Println(str) + return nil +} diff --git a/cmd/remove.go b/cmd/remove.go new file mode 100644 index 0000000..904f314 --- /dev/null +++ b/cmd/remove.go @@ -0,0 +1,68 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "path" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// removeCmd represents the remove command +var removeCmd = &cobra.Command{ + Use: "remove ", + Aliases: []string{"delete"}, + Short: "Remove a Clip template", + Long: `Delete a Clip template from your template folder`, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + templateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := removeTemplateFile(templateFilename) + if err != nil { + fmt.Printf("Call to remove Clip template failed: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(removeCmd) +} + +func removeTemplateFile(filename string) error { + // check if template even exists + if _, err := os.Stat(filename); os.IsNotExist(err) { + fmt.Printf("Couldn't find a Clip template with the name: '%s'\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))) + } else { + err := os.Remove(filename) + if err != nil { + return fmt.Errorf("Failed to remove Clip template file: %v\n", err) + } + + fmt.Printf("Clip template '%s' removed\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))) + } + + return nil +} diff --git a/cmd/rename.go b/cmd/rename.go new file mode 100644 index 0000000..4a64cd2 --- /dev/null +++ b/cmd/rename.go @@ -0,0 +1,74 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "path" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// renameCmd represents the rename command +var renameCmd = &cobra.Command{ + Use: "rename ", + Aliases: []string{"move"}, + Short: "Rename a Clip template", + Long: `Rename an existing Clip template. The Clip template must already exist, +and the new name must be available.`, + Args: cobra.ExactArgs(2), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("rename called") + sourceTemplateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 2] + ".yml" + destinationTemplateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := renameTemplateFile(sourceTemplateFilename, destinationTemplateFilename) + if err != nil { + fmt.Printf("Call to rename template failed: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(renameCmd) +} + +func renameTemplateFile(sourceFilename, destinationFilename string) error { + // check to ensure source template exists + if _, err := os.Stat(sourceFilename); os.IsNotExist(err) { + fmt.Printf("Couldn't find a Clip template with the name: '%s'\n", strings.TrimSuffix(path.Base(sourceFilename), filepath.Ext(sourceFilename))) + } + + // check to ensure destination template does not exist + if _, err := os.Stat(destinationFilename); err == nil { + fmt.Printf("No action taken: Found an existing Clip template with the name: '%s'\n", strings.TrimSuffix(path.Base(destinationFilename), filepath.Ext(destinationFilename))) + } + + err := os.Rename(sourceFilename, destinationFilename) + if err != nil { + return fmt.Errorf("Failed to rename clip template file: %v\n", err) + } + + return nil +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..48c34e2 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,146 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "path" + + homedir "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/tjhop/clip/helpers" +) + +// let's declare some vars +var ( + cfgFile string // location of config file + templateDir string // location of template directory + + // These vars will be set by the linker during build time + // ie, builds will be run using gox like so: + // gox -ldflags="-X github.com/tjhop/clip/cmd/root.builddate=$(date +%Y-%m-%d)" \ + // -osarch "linux/amd64" -output="$GOBIN/{{ OS }}/{{ Arch }}/clip + // -osarch "darwin/amd64" -output="$GOBIN/{{ OS }}/{{ Arch }}/clip + version string + commit string + builddate string +) + +// rootCmd is the bare `clip` command that cobra executes +var rootCmd = &cobra.Command{ + Use: "clip", + Short: "Golang template and clipboard editor", + Long: `Clip is a CLI tool to build and manage templated snippets and +interact with the systems's clipboard`, + Args: cobra.MaximumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + // If no subcommand is provided, run `clip list` by default + listCmd.Run(cmd, args) + } else if len(args) == 1 { + // If no subcommand is provided but a command line arg is + // provided, then run `clip copy $arg` by default + copyCmd.Run(cmd, args) + } + }, +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } +} + +func init() { + // functions that will always be run when this app is called + // https://godoc.org/github.com/spf13/cobra#OnInitialize + cobra.OnInitialize(initClip) + + // config defaults + viper.SetDefault("editor", "nano") + viper.SetDefault("vars", map[string]interface{}{"name": "Clip User"}) + + // command Line flags + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.clip.yml)") + rootCmd.PersistentFlags().StringVarP(&templateDir, "templatedir", "t", "", "location of template directory (default is $HOME/clip)") + + // use viper to bind config to CLI flags + viper.BindPFlag("templatedir", rootCmd.PersistentFlags().Lookup("templatedir")) +} + +// initClip will set config defaults, read in config file, and initialize clip template directory if it doesn't exist yet +func initClip() { + cfgName := "clip" + home, err := homedir.Dir() + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + if cfgFile != "" { + viper.SetConfigFile(cfgFile) + } else { + // Set config file to home directory + name ".clip.yml" + cfgFile = path.Join(home, "." + cfgName) + ".yml" + viper.SetConfigType("yaml") + viper.SetConfigFile(cfgFile) + } + + if viper.GetString("templatedir") != "" { + viper.Set("templatedir", templateDir) + } else { + viper.Set("templatedir", home + "/" + cfgName) + } + + viper.AutomaticEnv() // read in environment variables that match + viper.SetEnvPrefix(cfgName) + + // If a config file is found, read it in. + if err := viper.ReadInConfig(); err != nil { + // I should be able to use Viper to create+write the config for me if it + // doesn't exist, but the `SafeWriteConfig` function is still broken upstream: + // https://github.com/spf13/viper/pull/450/files + + fmt.Println("Clip config file not found; writing config file to: ", viper.ConfigFileUsed()) + // check if config file exists + if _, err := os.Stat(viper.ConfigFileUsed()); os.IsNotExist(err) { + err := helpers.WriteConfigFile(viper.ConfigFileUsed(), viper.AllSettings()) + if err != nil { + fmt.Println("Call to write Clip configuration file failed: ", err) + os.Exit(1) + } + } + } + + // if template directory doesn't exist, create it + if _, err := os.Stat(viper.GetString("templatedir")); os.IsNotExist(err) { + err = os.MkdirAll(viper.GetString("templatedir"), 0755) + if err != nil { + fmt.Printf("Could not initialize template directory: %v\n", err) + } else { + fmt.Println("Template directory created at: " + viper.GetString("templatedir")) + } + } +} diff --git a/cmd/show.go b/cmd/show.go new file mode 100644 index 0000000..11bda7e --- /dev/null +++ b/cmd/show.go @@ -0,0 +1,68 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package cmd + +import ( + "fmt" + "os" + "strings" + "path" + "path/filepath" + "io/ioutil" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var showCmd = &cobra.Command{ + Use: "show ", + Aliases: []string{"cat", "dump"}, + Short: "Show the raw Clip template file", + Long: `Show the output of the raw clip template file (pretty much just cat the file)`, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + templateFilename := viper.GetString("templatedir") + "/" + os.Args[len(os.Args) - 1] + ".yml" + err := showClipTemplate(templateFilename) + if err != nil { + fmt.Printf("Call to show template failed: %v\n", err) + } + }, +} + +func init() { + rootCmd.AddCommand(showCmd) +} + +func showClipTemplate(filename string) error { + // check if template file exists + if _, err := os.Stat(filename); os.IsNotExist(err) { + fmt.Printf("Couldn't find a clip template with the name: '%s'\n", strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))) + } else { + buf, err := ioutil.ReadFile(filename) + if err != nil { + return fmt.Errorf("Failed to read template file: %v\n", err) + } + + fmt.Println(string(buf)) + } + + return nil +} diff --git a/helpers/template.go b/helpers/template.go new file mode 100644 index 0000000..01e0089 --- /dev/null +++ b/helpers/template.go @@ -0,0 +1,51 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package helpers + +import ( + "bytes" + "fmt" + "text/template" + + "github.com/spf13/viper" +) + +func ExecuteTemplate(tmpl TemplateFile) (string, error) { + var gotmpl bytes.Buffer + varmap := make(map[string]string) + + // add default variables from config file to varmap + for k, v := range viper.GetStringMapString("vars") { + varmap[k] = v + } + // merge template vars to default vars from config file + for k, v := range tmpl.Template.Vars { + varmap[k] = v + } + + t := template.Must(template.New("Clip Template").Parse(tmpl.Template.Text)) + err := t.Execute(&gotmpl, varmap) + if err != nil { + return "", fmt.Errorf("Failed to execute template: %v\n", err) + } + + return gotmpl.String(), nil +} diff --git a/helpers/utilities.go b/helpers/utilities.go new file mode 100644 index 0000000..eca5249 --- /dev/null +++ b/helpers/utilities.go @@ -0,0 +1,36 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package helpers + +import ( + "strings" +) + +// helper function to check if a string exists in a slice +func Contains(slice []string, str string) bool { + for _, sliceString := range slice { + if str == sliceString || strings.Contains(sliceString, str) { + return true + } + } + + return false +} diff --git a/helpers/yaml.go b/helpers/yaml.go new file mode 100644 index 0000000..a30caf8 --- /dev/null +++ b/helpers/yaml.go @@ -0,0 +1,67 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package helpers + +import ( + "fmt" + "io/ioutil" + + "gopkg.in/yaml.v2" +) + +type TemplateFile struct { + Tags []string `yaml: "tags"` + + Template struct { + Vars map[string]string `yaml: "vars"` + + Text string `yaml: "text"` + } `yaml: "template"` +} + +func LoadTemplateFile(filename string) (TemplateFile, error) { + bytes, err := ioutil.ReadFile(filename) + if err != nil { + return TemplateFile{}, err + } + + var tmpl TemplateFile + err = yaml.Unmarshal(bytes, &tmpl) + if err != nil { + return TemplateFile{}, err + } + + return tmpl, nil +} + +func WriteConfigFile(filename string, data interface{}) error { + bytes, err := yaml.Marshal(data) + if err != nil { + return fmt.Errorf("Could not marshal data:\n%#v\n...to yaml: %v", data, err) + } + + err = ioutil.WriteFile(filename, bytes, 0644) + if err != nil { + return fmt.Errorf("Could not open file '%s' to write data: %v", filename, err) + } + + return nil +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..b8d58da --- /dev/null +++ b/main.go @@ -0,0 +1,27 @@ +// Copyright © 2019 TJ Hoplock +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package main + +import "github.com/tjhop/clip/cmd" + +func main() { + cmd.Execute() +}