Skip to content

Commit

Permalink
Merge pull request #2 from AH-dark/refactor/cli-framework
Browse files Browse the repository at this point in the history
refactor: use cli framework and handlers structure
  • Loading branch information
purofle authored Oct 5, 2023
2 parents 8e8a7c8 + c1ffe8d commit cefd429
Show file tree
Hide file tree
Showing 29 changed files with 652 additions and 291 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
go-version: 1.21

- name: Build
run: |
Expand Down
75 changes: 75 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
analyze:
name: Analyze
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [ 'go' ]

steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.

# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality


# Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2

# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun

# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.

# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"
52 changes: 52 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: Tag Release

on:
push:
tags:
- '*'

permissions:
contents: write
packages: write

jobs:
release:
name: Release

runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Setup Go
uses: actions/setup-go@v3
with:
go-version: '1.21'

- name: Cache Go modules
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Import GPG key
id: import_gpg
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
passphrase: ${{ secrets.PASSPHRASE }}

- name: Release
uses: goreleaser/goreleaser-action@v4
if: startsWith(github.ref, 'refs/tags/')
with:
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ github.token }}
GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
### GoReleaser template
/dist/

### VisualStudioCode template
.vscode/*
!.vscode/settings.json
Expand Down
77 changes: 77 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
project_name: fadian-go

before:
hooks:
- go mod tidy

builds:
- id: fadian-go
main: .
binary: fadian-go
env:
- CGO_ENABLED=0
- >-
{{- if eq .Os "darwin" }}
{{- if eq .Arch "amd64"}}CC=o64-clang{{- end }}
{{- if eq .Arch "arm64"}}CC=aarch64-apple-darwin20.2-clang{{- end }}
{{- end }}
{{- if eq .Os "windows" }}
{{- if eq .Arch "amd64" }}CC=x86_64-w64-mingw32-gcc{{- end }}
{{- end }}
ldflags:
- -s -w -X main.version={{ .Version }} -X main.commit={{ .Commit }}
goos:
- "linux"
- "windows"
- "darwin"
goarch:
- "amd64"
- "arm64"

universal_binaries:
- id: fadian-go

signs:
- artifacts: checksum
args: ["--batch", "-u", "{{ .Env.GPG_FINGERPRINT }}", "--output", "${signature}", "--detach-sign", "${artifact}"]

archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of uname.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip
files:
- LICENSE
- README.md
- public-key.pem

release:
github:
owner: afadian
name: fadian-go
draft: true
replace_existing_draft: true
prerelease: auto
mode: append

checksum:
name_template: 'checksums.txt'

snapshot:
name_template: "{{ incpatch .Version }}-snapshot"

changelog:
sort: asc
filters:
exclude:
- '^doc:'
- '^test:'
45 changes: 37 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,48 @@

## Usage

### Command Line

```bash
$ ./fadian-go --help

USAGE:
fadian-go [global options] command [command options] [arguments...]

COMMANDS:
fadian 发癫
fabing 发病
help, h Shows a list of commands or help for one command

GLOBAL OPTIONS:
--num value 重复次数 (default: 1)
--help, -h show help
--version, -v print the version

OPTIONS:
--name value, -n value 对谁发病/发癫
--interactive, -i 是否交互式发病 (default: false)
--help, -h show help
```
Usage of fadian-go:
-d 是否开启调试模式
-f 是否进入发病模式
-i 是否进入交互模式
-name string 发癫对象
-num int 发病/发癫次数 (default 1)

If you want to use interactive mode, you can use `-i` or `--interactive` option.

### Debug

You should set `DEBUG` environment variable to `true` to enable debug mode.

```bash
DEBUG=true ./fadian-go
```

## Build with source code
## Build

1. Clone this repository: `git clone https://github.com/afadian/fadian-go.git`
1. Clone this repository: `git clone git@github.com:afadian/fadian.git`
2. Run `cd fadian-go` to enter the project directory.
3. Run `go mod download` to download dependencies.
4. Run `go build -o fadian-go` to build the project.
5. Run `./fadian-go` to run the project.

## License

This project is licensed under the GNU Affero General Public License v3.0. See [LICENSE](LICENSE) for more details.
14 changes: 14 additions & 0 deletions cli/0module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package cli

import (
"github.com/afadian/fadian-go/cli/commands"
"go.uber.org/fx"
)

func Module() fx.Option {
return fx.Options(
commands.Module(),
fx.Provide(NewApp),
fx.Invoke(InvokeApp),
)
}
69 changes: 69 additions & 0 deletions cli/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cli

import (
"context"
"fmt"
"go.uber.org/zap"
"os"
"time"

"github.com/urfave/cli/v2"
"go.uber.org/fx"
)

type Params struct {
fx.In
Version string `name:"version"`
Commit string `name:"commit"`

Commands []*cli.Command `group:"root_commands"`
HandleNotFound cli.CommandNotFoundFunc
}

func NewApp(params Params) *cli.App {
app := &cli.App{
Name: "fadian-go",
Usage: "发癫",
Version: fmt.Sprintf("%s-%s", params.Version, params.Commit),
Copyright: fmt.Sprintf("2022-%d © 爱发癫 All Rights Reserved", time.Now().Year()),
Authors: []*cli.Author{
{Name: "AH Dark", Email: "[email protected]"},
{Name: "Kevin Williams", Email: "[email protected]"},
{Name: "Purofle", Email: "[email protected]"},
},
EnableBashCompletion: true,
CommandNotFound: params.HandleNotFound,
Commands: params.Commands,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "debug",
Hidden: true,
Usage: "是否开启调试模式",
EnvVars: []string{"DEBUG"},
},
&cli.IntFlag{
Name: "num",
Usage: "重复次数",
Value: 1,
},
},
}

app.Setup()

zap.L().Debug("app initialized")

return app
}

func InvokeApp(app *cli.App, lc fx.Lifecycle) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
if err := app.RunContext(ctx, os.Args); err != nil {
zap.L().Warn("app run failed", zap.Error(err))
}

return nil
},
})
}
11 changes: 11 additions & 0 deletions cli/commands/0module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package commands

import "go.uber.org/fx"

func Module() fx.Option {
return fx.Module("cli.commands",
fx.Provide(HandleNotFound),
fx.Provide(fx.Annotate(HandleFabing, fx.ResultTags(`group:"root_commands"`))),
fx.Provide(fx.Annotate(HandleFadian, fx.ResultTags(`group:"root_commands"`))),
)
}
Loading

0 comments on commit cefd429

Please sign in to comment.