Compare commits

..

No commits in common. "main" and "v0.1.0" have entirely different histories.
main ... v0.1.0

17 changed files with 76 additions and 302 deletions

View File

@ -1,29 +0,0 @@
name: CI
on:
push:
branches: [ "main" ]
paths:
- '**.go'
pull_request:
branches: [ "main" ]
paths:
- '**.go'
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
timeout-minutes: 3
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Install golangci-lint
run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run golangci-lint
run: golangci-lint run ./...

View File

@ -1,30 +0,0 @@
name: Auto-Update Go Modules
on:
schedule:
- cron: "0 0 * * 1" # Runs every Monday at midnight
jobs:
update-go-modules:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
- name: Update Dependencies
run: |
go get -u ./...
go mod tidy
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add go.mod go.sum
git commit -m "chore: auto-update Go modules"
git push

1
.gitignore vendored
View File

@ -9,7 +9,6 @@
*.dll
*.so
*.dylib
bin/
# Test binary, built with `go test -c`
*.test

View File

@ -1,54 +0,0 @@
run:
# timeout for analysis, e.g. 30s, 3m, default is 1m
timeout: 3m
# exclude test files
tests: true
linters:
# Set to true runs only fast linters.
# Good option for 'lint on save', pre-commit hook or CI.
fast: true
disable-all: true
enable:
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- gofmt
- gofumpt
- misspell
- unparam
- gosec
- asciicheck
- errname
- gci
- godot
- goimports
- revive
linters-settings:
gofmt:
rewrite-rules:
- pattern: 'interface{}'
replacement: 'any'
- pattern: 'a[b:len(a)]'
replacement: 'a[b:]'
misspell:
locale: UK
errcheck:
check-type-assertions: true
issues:
max-same-issues: 0
max-issues-per-linter: 0
exclude-use-default: false
exclude:
# gosec: Duplicated errcheck checks
- G104
# gosec: integer overflow conversion int -> uint32
- G115

View File

@ -5,29 +5,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
# [0.4.0] - 2025-04-05
### Changed
- `-loglevel` flag is now of type string. It accepts any one of trace, debug, info, warn, error, fatal or panic.
- It defaults to warn.
# [0.3.0] - 2025-14-03
### Added
- CLI may now accept multiple template names, example `gignore go python`. One will be appended after the other.
### Changed
- Filewriter now opens file in append mode.
# [0.2.0] - 2025-10-03
### Fixed
- Template .gitignore are now written concurrently.
# [0.1.0] - 2025-09-03
### Added

View File

@ -1,19 +1,7 @@
![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white)
![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black)
![macOS](https://img.shields.io/badge/mac%20os-000000?style=for-the-badge&logo=macos&logoColor=F0F0F0)
# Gignore - Generate .gitinore files
## Install
With Go tools:
```bash
go generate ./...
go install ./cmd/gignore
```
With [Task][task]:
```bash
@ -29,12 +17,8 @@ Usage of gignore:
Flags:
-dir string
directory containing .gitignore templates (default "gitignoreio")
-l int
log level (shorthand) (default 3)
-list
list available templates
-loglevel int
log level (default 3)
-ls
list available templates (shorthand)
@ -44,7 +28,7 @@ Example:
## Custom Templates
It's possible to add your own custom templates, simply create a directory in `internal/registry/templates`. You'll need to [reinstall](https://github.com/onyx-and-iris/gignore?tab=readme-ov-file#install) the project before you can load the new templates.
It's possible to add your own custom templates, simply create a directory in `internal/registry/templates`. You'll need to rebuild the project before you can load the new templates.
Then pass the dir name as a flag, for example:
@ -56,37 +40,14 @@ You may set an environment variable `GIGNORE_TEMPLATE_DIR` to avoid passing the
If a template is requested but not found in the custom directory then the gitignoreio registry will act as a fallback.
## Logging
The `-loglevel` flag allows you to control the verbosity of the application's logging output.
Acceptable values for this flag are:
- `trace`
- `debug`
- `info`
- `warn`
- `error`
- `fatal`
- `panic`
For example, to set the log level to `debug`, you can use:
```bash
gignore -loglevel=debug -dir=custom go
```
The default log level is `warn` if the flag is not specified.
## Special Thanks
[gitignore.io][gitignoreio] For providing such a useful .gitignore service
[cuonglm][cuonglm] For writing the [gogi][gogi] client library for gitignore.io
[gigo][gigo] For writing the Go client library for gitignore.io
[task]: https://taskfile.dev/
[gitignoreio]: https://www.toptal.com/developers/gitignore
[cuonglm]: https://github.com/cuonglm
[gogi]: https://github.com/cuonglm/gogi
[ignore]: https://github.com/neptship/ignore
[gigo]: https://github.com/mh-cbon/gigo
[ignore]: https://github.com/neptship/ignore

View File

@ -23,6 +23,13 @@ tasks:
- task: build-windows
- task: build-linux
release:
desc: Generate the gitignore.io templates and then build the gignore project for Windows and Linux
deps: [generate]
cmds:
- task: build-windows
- task: build-linux
vet:
desc: Vet the code
deps: [fmt]
@ -35,26 +42,19 @@ tasks:
- go fmt ./...
generate:
desc: |
Generate the gitignore.io templates.
This task will be skipped if the templates already exist.
You may use the `--force` flag to regenerate the templates.
desc: Generate the gitignore.io templates
cmds:
- go generate ./...
status:
- ls internal/registry/templates/gitignoreio/*.gitignore >/dev/null || exit 1
- go generate .
build-windows:
desc: Build the gignore project for Windows
cmds:
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}
internal: true
build-linux:
desc: Build the gignore project for Linux
cmds:
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}
internal: true
test:
desc: Run tests
@ -71,8 +71,3 @@ tasks:
desc: Clean the build artifacts
cmds:
- '{{.SHELL}} rm -r {{.BIN_DIR}}'
prune:
desc: Empty the gitignoreio template registry
cmds:
- '{{.SHELL}} rm internal/registry/templates/gitignoreio/*.gitignore'

View File

@ -1,17 +1,16 @@
// Package main generates gitignore.io templates using the gogi library.
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/cuonglm/gogi"
log "github.com/sirupsen/logrus"
)
func main() {
log.Info("Generating gitignore.io templates...")
fmt.Println("Generating gitignore.io templates...")
gogiClient, _ := gogi.NewHTTPClient()
@ -20,22 +19,10 @@ func main() {
log.Fatal(err)
}
errChan := make(chan error)
for _, template := range templates {
go func() {
err := createTemplate(template)
if err != nil {
errChan <- fmt.Errorf("Failed to create template %s: %v", template.Name, err)
return
}
errChan <- nil
}()
}
for range templates {
if err := <-errChan; err != nil {
log.Error(err)
err := createTemplate(template)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create template %s: %v\n", template.Name, err)
}
}
}

View File

@ -1,41 +1,34 @@
// Package main provides the entry point for the gignore command-line tool,
// which generates .gitignore files based on specified templates.
package main
import (
"flag"
"fmt"
"os"
"slices"
"github.com/onyx-and-iris/gignore"
log "github.com/sirupsen/logrus"
)
func exit(err error) {
_, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
func main() {
flag.Usage = func() {
w := flag.CommandLine.Output()
fmt.Fprint(w, "Usage of gignore:\n")
fmt.Fprint(w, " gignore [flags] <template>\n")
fmt.Fprintf(w, " gignore [flags] <template>\n")
fmt.Fprint(w, "\n")
fmt.Fprint(w, "Flags:\n")
flag.PrintDefaults()
fmt.Fprint(w, "\n")
fmt.Fprint(w, "Example:\n")
fmt.Fprintf(w, "Example:\n")
fmt.Fprint(w, " gignore go\n")
}
var (
list bool
templateDir string
loglevel string
loglevel int
)
flag.BoolVar(&list, "list", false, "list available templates")
@ -46,48 +39,41 @@ func main() {
getEnv("GIGNORE_TEMPLATE_DIR", "gitignoreio"),
"directory containing .gitignore templates",
)
flag.StringVar(&loglevel, "loglevel", "warn", "log level")
flag.StringVar(&loglevel, "l", "warn", "log level (shorthand)")
flag.IntVar(&loglevel, "loglevel", int(log.WarnLevel), "log level")
flag.IntVar(&loglevel, "l", int(log.WarnLevel), "log level (shorthand)")
flag.Parse()
level, err := log.ParseLevel(loglevel)
if err != nil {
exit(fmt.Errorf("invalid log level: %s", loglevel))
if slices.Contains(log.AllLevels, log.Level(loglevel)) {
log.SetLevel(log.Level(loglevel))
}
log.SetLevel(level)
client := gignore.New(gignore.WithTemplateDirectory(templateDir))
if list {
if err := listTemplates(client); err != nil {
exit(fmt.Errorf("failed to list templates: %v", err))
}
listTemplates(client)
return
}
args := flag.Args()
if len(args) == 0 {
if len(args) != 1 {
flag.Usage()
return
}
for _, arg := range args {
err := client.Create(arg)
if err != nil {
exit(fmt.Errorf("failed to create .gitignore file: %v", err))
}
fmt.Printf("√ created %s .gitignore file\n", arg)
err := client.Create(args[0])
if err != nil {
log.Fatalf("failed to create .gitignore file: %v", err)
}
fmt.Printf("√ created %s .gitignore file\n", args[0])
}
func listTemplates(client *gignore.Client) error {
func listTemplates(client *gignore.GignoreClient) {
templates, err := client.List()
if err != nil {
return err
log.Fatalf("failed to list templates: %v", err)
}
for _, template := range templates {
fmt.Println(template)
}
return nil
}

View File

@ -4,7 +4,7 @@ import "os"
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if value == "" {
if len(value) == 0 {
return defaultValue
}
return value

View File

@ -1,16 +1,16 @@
// Package gignore provides a way to manage .gitignore files and templates.
package gignore
import (
"fmt"
"strings"
"github.com/onyx-and-iris/gignore/internal/registry"
)
type templateNotFoundError struct {
template string
templatesSearched []string
template string
registry *registry.TemplateRegistry
}
func (e *templateNotFoundError) Error() string {
return fmt.Sprintf("template '%s' not found in %s registry", e.template, strings.Join(e.templatesSearched, ", "))
return fmt.Sprintf("template '%s' not found in %s registry", e.template, e.registry.Directory)
}

View File

@ -3,70 +3,65 @@ package gignore
import (
"io"
log "github.com/sirupsen/logrus"
"github.com/onyx-and-iris/gignore/internal/filewriter"
"github.com/onyx-and-iris/gignore/internal/registry"
log "github.com/sirupsen/logrus"
)
//go:generate go run cmd/gen/main.go
//go:generate go run cmd/gen/gen.go
// Client is a client for managing .gitignore templates.
type Client struct {
type GignoreClient struct {
registry *registry.TemplateRegistry
writer io.Writer
}
// New creates a new Client with the provided options.
func New(options ...Option) *Client {
c := &Client{
registry.New(),
filewriter.New(),
}
func New(options ...Option) *GignoreClient {
gc := &GignoreClient{
registry.NewTemplateRegistry(),
filewriter.New()}
for _, option := range options {
option(c)
option(gc)
}
return c
return gc
}
// List returns a list of available .gitignore templates.
func (c *Client) List() ([]string, error) {
return c.registry.List()
func (g *GignoreClient) List() ([]string, error) {
return g.registry.ListTemplates()
}
// Create generates a .gitignore file from the specified template.
func (c *Client) Create(template string) error {
ok, err := c.registry.Contains(template)
func (g *GignoreClient) Create(template string) error {
ok, err := g.registry.Contains(template)
if err != nil {
return err
}
if !ok {
templateNotFoundErr := &templateNotFoundError{template, []string{c.registry.Directory}}
if c.registry.Directory == "gitignoreio" {
templateNotFoundErr := &templateNotFoundError{template, g.registry}
if g.registry.Directory == "gitignoreio" {
return templateNotFoundErr
}
c.registry.Directory = "gitignoreio"
ok, err = c.registry.Contains(template)
log.Errorf("%s. Checking default registry...", templateNotFoundErr)
g.registry.Directory = "gitignoreio"
ok, err = g.registry.Contains(template)
if err != nil {
return err
}
if !ok {
templateNotFoundErr.templatesSearched = append(templateNotFoundErr.templatesSearched, c.registry.Directory)
return templateNotFoundErr
}
log.Debugf("template '%s' found in gitignoreio registry", template)
} else {
log.Debugf("template '%s' found in %s registry", template, c.registry.Directory)
log.Infof("template '%s' found in default gitignoreio registry", template)
}
content, err := c.registry.Get(template)
content, err := g.registry.GetTemplate(template)
if err != nil {
return err
}
_, err = c.writer.Write(content)
_, err = g.writer.Write(content)
if err != nil {
return err
}

2
go.mod
View File

@ -7,4 +7,4 @@ require (
github.com/sirupsen/logrus v1.9.3
)
require golang.org/x/sys v0.32.0 // indirect
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect

3
go.sum
View File

@ -10,9 +10,8 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -1,4 +1,3 @@
// Package filewriter provides functionality to write content to a .gitignore file.
package filewriter
import (
@ -7,14 +6,11 @@ import (
"os"
)
// FileWriter provides functionality to write content to a .gitignore file.
type FileWriter struct {
targetFileName string
}
// New creates a new FileWriter with the default target file name.
func New() *FileWriter {
return &FileWriter{".gitignore"}
return &FileWriter{}
}
func (fw *FileWriter) writeContent(content []byte, dst io.Writer) (int64, error) {
@ -29,14 +25,14 @@ func (fw *FileWriter) writeContent(content []byte, dst io.Writer) (int64, error)
}
func (fw *FileWriter) Write(content []byte) (int, error) {
f, err := os.OpenFile(fw.targetFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
f, err := os.Create(".gitignore")
if err != nil {
return 0, err
}
defer f.Close()
const header = "# Auto-generated .gitignore by gignore: github.com/onyx-and-iris/gignore\n"
const footer = "\n# End of gignore: github.com/onyx-and-iris/gignore\n"
const header = `# Auto-generated .gitignore by gignore: github.com/onyx-and-iris/gignore`
const footer = `# End of gignore: github.com/onyx-and-iris/gignore`
var sz int64
n, err := fw.writeContent([]byte(header), f)

View File

@ -1,4 +1,3 @@
// Package registry provides functionality to manage and retrieve gitignore templates.
package registry
import (
@ -11,14 +10,12 @@ import (
//go:embed templates
var templates embed.FS
// TemplateRegistry provides methods to manage and retrieve gitignore templates.
type TemplateRegistry struct {
templates fs.FS
Directory string
}
// New creates a new instance of TemplateRegistry.
func New() *TemplateRegistry {
func NewTemplateRegistry() *TemplateRegistry {
return &TemplateRegistry{
templates: templates,
}
@ -28,7 +25,6 @@ func (t *TemplateRegistry) filePath(name string) string {
return fmt.Sprintf("templates/%s/%s.gitignore", t.Directory, name)
}
// Contains checks if a template with the given name exists in the registry.
func (t *TemplateRegistry) Contains(name string) (bool, error) {
_, err := fs.Stat(t.templates, t.filePath(name))
if err != nil {
@ -41,8 +37,7 @@ func (t *TemplateRegistry) Contains(name string) (bool, error) {
return true, nil
}
// Get retrieves the content of the gitignore template with the given name.
func (t *TemplateRegistry) Get(name string) ([]byte, error) {
func (t *TemplateRegistry) GetTemplate(name string) ([]byte, error) {
data, err := fs.ReadFile(t.templates, t.filePath(name))
if err != nil {
return nil, err
@ -50,8 +45,7 @@ func (t *TemplateRegistry) Get(name string) ([]byte, error) {
return data, nil
}
// List lists all the gitignore templates in the registry.
func (t *TemplateRegistry) List() ([]string, error) {
func (t *TemplateRegistry) ListTemplates() ([]string, error) {
var paths []string
err := fs.WalkDir(

View File

@ -1,11 +1,9 @@
package gignore
// Option is a function that configures a GignoreClient.
type Option func(*Client)
type Option func(*GignoreClient)
// WithTemplateDirectory sets the template directory for the GignoreClient.
func WithTemplateDirectory(directory string) Option {
return func(c *Client) {
c.registry.Directory = directory
return func(g *GignoreClient) {
g.registry.Directory = directory
}
}