Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial implementation of state export log. #2886

Merged
merged 1 commit into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/state/internal/cmdtree/cmdtree.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func New(prime *primer.Values, args ...string) *CmdTree {
newExportGithubActionCommand(prime),
newExportDocsCommand(prime),
newExportEnvCommand(prime),
newLogCommand(prime),
)

platformsCmd := newPlatformsCommand(prime)
Expand Down
35 changes: 35 additions & 0 deletions cmd/state/internal/cmdtree/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,38 @@ func newExportEnvCommand(prime *primer.Values) *captain.Command {

return cmd
}

func newLogCommand(prime *primer.Values) *captain.Command {
runner := export.NewLog(prime)
params := &export.LogParams{}

cmd := captain.NewCommand(
"log",
locale.Tl("export_log_title", "Show Log File"),
locale.Tl("export_log_description", "Show the path to a State Tool log file"),
prime,
[]*captain.Flag{
{
Name: "index",
Shorthand: "i",
Description: locale.Tl("flag_export_log_index", "The 0-based index of the log file to show, starting with the newest"),
Value: &params.Index,
},
},
[]*captain.Argument{
{
Name: "prefix",
Description: locale.Tl("arg_export_log_prefix", "The prefix of the log file to show (e.g. state or state-svc). The default is 'state'"),
Required: false,
Value: &params.Prefix,
},
},
func(ccmd *captain.Command, _ []string) error {
return runner.Run(params)
})

cmd.SetSupportsStructuredOutput()
cmd.SetUnstable(true)

return cmd
}
84 changes: 84 additions & 0 deletions internal/runners/export/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package export

import (
"path/filepath"
"regexp"
"sort"
"strconv"

"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/fileutils"
"github.com/ActiveState/cli/internal/logging"
"github.com/ActiveState/cli/internal/output"
)

type Log struct {
output.Outputer
}

func NewLog(prime primeable) *Log {
return &Log{prime.Output()}
}

type LogParams struct {
Prefix string
Index int
}

type logFile struct {
Name string
Timestamp int
}

var ErrInvalidLogIndex = errs.New("invalid index")
var ErrInvalidLogPrefix = errs.New("invalid log prefix")
var ErrLogNotFound = errs.New("log not found")

func (l *Log) Run(params *LogParams) (rerr error) {
defer rationalizeError(&rerr)

if params.Index < 0 {
return ErrInvalidLogIndex
}
if params.Prefix == "" {
params.Prefix = "state"
}

// Fetch list of log files.
logDir := filepath.Dir(logging.FilePath())
logFiles := fileutils.ListDirSimple(logDir, false)

// Filter down the list based on the given prefix.
filteredLogFiles := []*logFile{}
regex, err := regexp.Compile(params.Prefix + `-\d+-(\d+)\.log`)
if err != nil {
return ErrInvalidLogPrefix
}
for _, file := range logFiles {
if regex.MatchString(file) {
timestamp, err := strconv.Atoi(regex.FindStringSubmatch(file)[1])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the regex.MatchString guarantee that we will find a second group? If not the indexing of the slice here is a potential panic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, if there is a match, the capture from the pattern guarantees a valid index.

if err != nil {
continue
}
filteredLogFiles = append(filteredLogFiles, &logFile{file, timestamp})
}
}

// Sort logs in ascending order by name (which include timestamp), not modification time.
sort.SliceStable(filteredLogFiles, func(i, j int) bool {
return filteredLogFiles[i].Timestamp > filteredLogFiles[j].Timestamp // sort ascending, not descending
})

if params.Index >= len(filteredLogFiles) {
return ErrLogNotFound
}

l.Outputer.Print(output.Prepare(
filteredLogFiles[params.Index].Name,
&struct {
LogFile string `json:"logFile"`
}{filteredLogFiles[params.Index].Name},
))

return nil
}
36 changes: 36 additions & 0 deletions internal/runners/export/rationalize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package export

import (
"errors"

"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/locale"
)

func rationalizeError(err *error) {
switch {
// export log with invalid --index.
case errors.Is(*err, ErrInvalidLogIndex):
*err = errs.WrapUserFacing(*err,
locale.Tl("err_export_log_invalid_index", "Index must be >= 0"),
errs.SetInput(),
)

// export log <prefix> with invalid <prefix>.
case errors.Is(*err, ErrInvalidLogPrefix):
*err = errs.WrapUserFacing(*err,
locale.Tl("err_export_log_invalid_prefix", "Invalid log prefix"),
errs.SetInput(),
errs.SetTips(
locale.Tl("export_log_prefix_tip", "Try a prefix like 'state' or 'state-svc'"),
),
)

// export log does not turn up a log file.
case errors.Is(*err, ErrLogNotFound):
*err = errs.WrapUserFacing(*err,
locale.Tl("err_export_log_out_of_bounds", "Log file not found"),
errs.SetInput(),
)
}
}
25 changes: 25 additions & 0 deletions test/integration/export_int_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package integration

import (
"path/filepath"
"testing"
"time"

Expand Down Expand Up @@ -98,6 +99,24 @@ func (suite *ExportIntegrationTestSuite) TestExport_Env() {
suite.Assert().NotContains(cp.Output(), "ACTIVESTATE_ACTIVATED")
}

func (suite *ExportIntegrationTestSuite) TestLog() {
suite.OnlyRunForTags(tagsuite.Export)
ts := e2e.New(suite.T(), false)
defer ts.ClearCache()

cp := ts.Spawn("export", "log")
cp.Expect(filepath.Join(ts.Dirs.Config, "logs"))
cp.ExpectRe(`state-\d+`)
cp.Expect(".log")
cp.ExpectExitCode(0)

cp = ts.Spawn("export", "log", "state-svc")
cp.Expect(filepath.Join(ts.Dirs.Config, "logs"))
cp.ExpectRe(`state-svc-\d+`)
cp.Expect(".log")
cp.ExpectExitCode(0)
}

func (suite *ExportIntegrationTestSuite) TestJSON() {
suite.OnlyRunForTags(tagsuite.Export, tagsuite.JSON)
ts := e2e.New(suite.T(), false)
Expand Down Expand Up @@ -132,6 +151,12 @@ func (suite *ExportIntegrationTestSuite) TestJSON() {
cp.Expect(`}`)
cp.ExpectExitCode(0)
// AssertValidJSON(suite.T(), cp) // recipe is too large to fit in terminal snapshot

cp = ts.Spawn("export", "log", "-o", "json")
cp.Expect(`{"logFile":"`)
cp.Expect(`.log"}`)
cp.ExpectExitCode(0)
AssertValidJSON(suite.T(), cp)
}

func TestExportIntegrationTestSuite(t *testing.T) {
Expand Down
Loading