Skip to content

Commit

Permalink
Merge pull request #52 from kasaikou/fix/add-comment
Browse files Browse the repository at this point in the history
Add comment test's check point
  • Loading branch information
kasaikou committed Apr 20, 2024
2 parents 7e45e9f + 7672def commit e7971d2
Show file tree
Hide file tree
Showing 12 changed files with 206 additions and 54 deletions.
2 changes: 0 additions & 2 deletions cli/console_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package cli

import (
"bytes"
"fmt"
"io"
"os"

Expand Down Expand Up @@ -162,7 +161,6 @@ func TerminalWidth() LoggerOption {

func TerminalAutoDetect(file *os.File) LoggerOption {
if term.IsTerminal(int(file.Fd())) {
fmt.Println("terminal mode")
return TerminalWidth()
} else {
return UnlimitedWidth()
Expand Down
3 changes: 2 additions & 1 deletion cmd/docstak/entrypoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ func entrypoint(args parseArgResult) int {
}

switch len(enabledFeature) {
case 0:

case 0: // Default feature (execute task).
return run(ctx, args)

case 1:
Expand Down
11 changes: 11 additions & 0 deletions cmd/docstak/entrypoint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestWithEmptyArgs(t *testing.T) {
assert.NotEqual(t, 0, entrypoint(parseArgs([]string{})))
}
15 changes: 8 additions & 7 deletions cmd/docstak/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,22 @@ package main
import "github.com/spf13/pflag"

type parseArgResult struct {
Verbose *bool
Quiet *bool
Help *bool
DryRun *bool
Cmds []string
Verbose *bool `json:"verbose,omitempty"`
Quiet *bool `json:"quiet,omitempty"`
Help *bool `json:"help,omitempty"`
DryRun *bool `json:"dry_run,omitempty"`
Cmds []string `json:"cmds,omitempty"`
}

func parseArgs() parseArgResult {
func parseArgs(args []string) parseArgResult {

pflag := pflag.NewFlagSet("", pflag.ExitOnError)
verbose := pflag.BoolP("verbose", "v", true, "Be verbose (default).")
quiet := pflag.BoolP("quiet", "q", false, "Output only error message with stderr.")
help := pflag.BoolP("help", "h", false, "Output help information.")
dryRun := pflag.Bool("dry-run", false, "Output the operation configuration but do not execute.")

pflag.Parse()
pflag.Parse(args)
cmds := pflag.Args()

return parseArgResult{
Expand Down
24 changes: 15 additions & 9 deletions cmd/docstak/flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,25 @@ limitations under the License.
package main

import (
"os"
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
)

func P[T any](val T) *T { return &val }

func TestFlag(t *testing.T) {
os.Args = append(os.Args, "-v", "-q", "fmt", "test")
args := parseArgs()

assert.Equal(t, true, *args.Verbose)
assert.Equal(t, true, *args.Quiet)
assert.Equal(t, false, *args.Help)
assert.Contains(t, args.Cmds, "fmt")
assert.Contains(t, args.Cmds, "test")
resultArgs := parseArgs([]string{"-v", "-q", "fmt", "test"})
expect := parseArgResult{
Verbose: P(true),
Quiet: P(true),
Help: P(false),
DryRun: P(false),
Cmds: []string{"fmt", "test"},
}

resultJson, _ := json.MarshalIndent(resultArgs, "", " ")
expectJson, _ := json.MarshalIndent(expect, "", " ")
assert.Equal(t, string(expectJson), string(resultJson))
}
2 changes: 1 addition & 1 deletion cmd/docstak/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ package main
import "os"

func main() {
os.Exit(entrypoint(parseArgs()))
os.Exit(entrypoint(parseArgs(os.Args[1:])))
}
4 changes: 4 additions & 0 deletions cmd/docstak/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ func run(ctx context.Context, args parseArgResult) int {

logger := slog.New(cw.NewLoggerHandler(nil))
ctx = docstak.WithLogger(ctx, logger)
if len(args.Cmds) < 1 {
logger.Error("set no task")
return -1
}
document, success := app.NewLocalDocument(ctx)
if !success {
return -1
Expand Down
3 changes: 2 additions & 1 deletion docstak.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ skips:
```

```sh
go mod tidy && git diff --no-patch --exit-code go.sum
go mod tidy &&
git diff --no-patch --exit-code go.sum
```

### ci/fmt
Expand Down
31 changes: 21 additions & 10 deletions docstak/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,23 @@ func newExecuteOptions() *executeOptions {

type ExecuteOption func(eo *executeOptions) error

// An optional argument for setting subcommands in the Execute() function.
func ExecuteOptCalls(keys ...string) ExecuteOption {
return func(eo *executeOptions) error {
eo.called = append(eo.called, keys...)
return nil
}
}

// An optional argument for setting pre- and post-processing when executing tasks using Execute() function.
func ExecuteOptProcessExec(fn func(ctx context.Context, task model.DocumentTask, runner *srun.ScriptRunner) (int, error)) ExecuteOption {
return func(eo *executeOptions) error {
eo.onExec = fn
return nil
}
}

// Plan and execute the task.
func ExecuteContext(ctx context.Context, document model.Document, options ...ExecuteOption) int {

logger := GetLogger(ctx)
Expand Down Expand Up @@ -95,6 +98,7 @@ func ExecuteContext(ctx context.Context, document model.Document, options ...Exe
return executeTasks(ctx, document, option, tasks)
}

// Plan and execute the task.
func executeTasks(ctx context.Context, document model.Document, option *executeOptions, executeTasks []string) int {
wg := sync.WaitGroup{}

Expand All @@ -110,6 +114,7 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO
defer cancel()
taskChs := make([]chan taskResp, 0, len(executeTasks))

// Create a Goroutine for each task.
for i := range executeTasks {
ch := make(chan taskResp, len(executeTasks))
defer close(ch)
Expand All @@ -125,6 +130,7 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO

<-chEnded

// Wait for ctx.Done() or dependent tasks finish.
for len(depends) > 0 {
select {
case <-ctx.Done():
Expand All @@ -134,6 +140,15 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO
}
}

// Terminates when there no scripts set for the task.
if len(task.Scripts) == 0 {
chRes <- taskResp{
Call: task.Call,
Exit: 0,
}
}

// Execute one or more set in a task in parallel using Goroutine.
ch := make(chan taskResp)
wg := sync.WaitGroup{}
for j := range task.Scripts {
Expand All @@ -153,24 +168,17 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO
}
defer wg.Wait()

// Wait for all scripts run in Goroutine finish.
ended := 0

if len(task.Scripts) == 0 {
chRes <- taskResp{
Call: task.Call,
Exit: 0,
}
}

for ended < len(task.Scripts) {
select {
case <-ctx.Done():
return
case result := <-ch:
ended++
if ended >= len(task.Scripts) {
if ended >= len(task.Scripts) { // If all tasks are finished.
chRes <- result
} else if result.Exit != 0 {
} else if result.Exit != 0 { // If the script fails.
chRes <- result
}
}
Expand All @@ -187,6 +195,7 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO
taskChs[i] <- taskResp{}
}

// Wait for all tasks finish in Goroutine finish.
for {
select {
case <-ctx.Done():
Expand All @@ -209,9 +218,11 @@ func executeTasks(ctx context.Context, document model.Document, option *executeO
}
}

// Execute task with executeOptions
func executeTask(ctx context.Context, task model.DocumentTask, script model.DocumentTaskScript, option *executeOptions) int {
logger := GetLogger(ctx)

// Generate script runner with script, command, and command's args.
runner := srun.NewScriptRunner(script.Config.ExecPath, script.Config.CmdOpt, script.Script, script.Config.Args...)

for key, value := range task.Envs {
Expand Down
44 changes: 22 additions & 22 deletions docstak/files/markdown/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ type FileEnvironment struct {
}

type ParseResult struct {
Title string
Description string
Tasks []ParseResultTask
Config ParseResultGlobalConfig
Title string `json:"title"`
Description string `json:"description"`
Tasks []ParseResultTask `json:"tasks,omitempty"`
Config ParseResultGlobalConfig `json:"config,omitempty"`
}

type ParseResultGlobalConfig struct {
Expand All @@ -49,41 +49,41 @@ type ParseResultGlobalConfig struct {
}

type ParseResultTask struct {
Title string
HeadingLavel int
Description string
Config ParseResultTaskConfig
Commands []ParseResultCommand
Title string `json:"title"`
HeadingLevel int `json:"heading-level"`
Description string `json:"description"`
Config ParseResultTaskConfig `json:"config,omitempty"`
Commands []ParseResultCommand `json:"commands,omitempty"`
}

type ParseResultTaskConfig struct {
Environ ParseResultTaskConfigEnvs `json:"environ" yaml:"environ"`
Requires ParseResultTaskConfigRequires `json:"requires" yaml:"requires"`
Skips ParseResultTaskConfigSkips `json:"skips" yaml:"skips"`
Previous []string `json:"previous" yaml:"previous"`
Environ ParseResultTaskConfigEnvs `json:"environ,omitempty" yaml:"environ"`
Requires ParseResultTaskConfigRequires `json:"requires,omitempty" yaml:"requires"`
Skips ParseResultTaskConfigSkips `json:"skips,omitempty" yaml:"skips"`
Previous []string `json:"previous,omitempty" yaml:"previous"`
}

type ParseResultTaskConfigEnvs struct {
Dotenvs []string `json:"dotenv" yaml:"dotenv"`
Variables map[string]string `json:"vars" yaml:"vars"`
Dotenvs []string `json:"dotenv,omitempty" yaml:"dotenv"`
Variables map[string]string `json:"vars,omitempty" yaml:"vars"`
}

type ParseResultTaskConfigSkips struct {
File ParseResultTaskConfigFiles `json:"file" yaml:"file"`
File ParseResultTaskConfigFiles `json:"file,omitempty" yaml:"file"`
}

type ParseResultTaskConfigRequires struct {
File ParseResultTaskConfigFiles `json:"file" yaml:"file"`
File ParseResultTaskConfigFiles `json:"file,omitempty" yaml:"file"`
}

type ParseResultTaskConfigFiles struct {
Exists []string `json:"exist" yaml:"exist"`
NotChangeds []string `json:"not-changed" yaml:"not-changed"`
Exists []string `json:"exist,omitempty" yaml:"exist"`
NotChangeds []string `json:"not-changed,omitempty" yaml:"not-changed"`
}

type ParseResultCommand struct {
Lang string
Code string
Lang string `json:"lang"`
Code string `json:"code"`
}

var (
Expand Down Expand Up @@ -133,7 +133,7 @@ func ParseMarkdown(ctx context.Context, markdown MarkdownOption) (ParseResult, e
}
result.Tasks = append(result.Tasks, ParseResultTask{
Title: titleStr,
HeadingLavel: node.Level,
HeadingLevel: node.Level,
})
selected = &result.Tasks[len(result.Tasks)-1]

Expand Down

0 comments on commit e7971d2

Please sign in to comment.