refactor: linting checks for all platforms

This commit is contained in:
Jan De Dobbeleer 2020-11-12 09:43:32 +01:00 committed by Jan De Dobbeleer
parent 3c812f916e
commit 8fb190e074
49 changed files with 537 additions and 443 deletions

View file

@ -9,6 +9,7 @@ root = true
indent_style = space
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
; Go Code - match go fmt
[*.go]

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
* text=auto eol=lf

View file

@ -27,7 +27,6 @@ jobs:
- name: Checkout code
uses: actions/checkout@v2
- name: Golang CI
if: matrix.os == 'ubuntu-latest'
uses: golangci/golangci-lint-action@v2
with:
version: v1.31

0
.gitignore vendored Executable file → Normal file
View file

50
.golangci.yml Normal file
View file

@ -0,0 +1,50 @@
linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dupl
- errcheck
- exhaustive
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- golint
- goprintffuncname
- gosimple
- govet
- ineffassign
- interfacer
- misspell
- nakedret
- noctx
- nolintlint
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
- lll
linters-settings:
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-tags:
- experimental
disabled-checks:
- ifElseChain
lll:
line-length: 180

View file

@ -27,7 +27,7 @@ func (e *engine) getPowerlineColor(foreground bool) string {
return e.previousActiveSegment.Background
}
func (e *engine) writePowerLineSeparator(background string, foreground string, end bool) {
func (e *engine) writePowerLineSeparator(background, foreground string, end bool) {
symbol := e.activeSegment.PowerlineSymbol
if end {
symbol = e.previousActiveSegment.PowerlineSymbol
@ -75,7 +75,7 @@ func (e *engine) renderSegmentText(text string) {
e.renderPlainSegment(text)
case Diamond:
e.renderDiamondSegment(text)
default:
case Powerline:
e.renderPowerLineSegment(text)
}
e.previousActiveSegment = e.activeSegment
@ -135,7 +135,7 @@ func (e *engine) render() {
cursorMove := e.renderer.setCursorForRightWrite(blockText, block.HorizontalOffset)
e.renderer.print(cursorMove)
e.renderer.print(blockText)
default:
case Left:
e.renderer.print(e.renderBlockSegments(block))
}
}

View file

@ -16,6 +16,11 @@ import (
"github.com/shirou/gopsutil/process"
)
const (
unknown = "unknown"
windowsPlatform = "windows"
)
type environmentInfo interface {
getenv(key string) string
getcwd() string
@ -31,12 +36,12 @@ type environmentInfo interface {
getPlatform() string
hasCommand(command string) bool
runCommand(command string, args ...string) (string, error)
runShellCommand(shell string, command string) string
runShellCommand(shell, command string) string
lastErrorCode() int
getArgs() *args
getBatteryInfo() (*battery.Battery, error)
getShellName() string
getWindowTitle(imageName string, windowTitleRegex string) (string, error)
getWindowTitle(imageName, windowTitleRegex string) (string, error)
}
type environment struct {
@ -124,8 +129,8 @@ func (env *environment) getRuntimeGOOS() string {
}
func (env *environment) getPlatform() string {
if runtime.GOOS == "windows" {
return "windows"
if runtime.GOOS == windowsPlatform {
return windowsPlatform
}
p, _, _, _ := host.PlatformInformation()
@ -146,7 +151,7 @@ func (env *environment) runCommand(command string, args ...string) (string, erro
return strings.TrimSpace(string(out)), nil
}
func (env *environment) runShellCommand(shell string, command string) string {
func (env *environment) runShellCommand(shell, command string) string {
out, err := exec.Command(shell, "-c", command).Output()
if err != nil {
log.Println(err)
@ -177,14 +182,14 @@ func (env *environment) getShellName() string {
p, _ := process.NewProcess(int32(pid))
name, err := p.Name()
if err != nil {
return "unknown"
return unknown
}
if name == "cmd.exe" {
p, _ = p.Parent()
name, err = p.Name()
}
if err != nil {
return "unknown"
return unknown
}
shell := strings.Replace(name, ".exe", "", 1)
return strings.Trim(shell, " ")

2
environment_unix.go Executable file → Normal file
View file

@ -15,6 +15,6 @@ func (env *environment) homeDir() string {
return os.Getenv("HOME")
}
func (env *environment) getWindowTitle(imageName string, windowTitleRegex string) (string, error) {
func (env *environment) getWindowTitle(imageName, windowTitleRegex string) (string, error) {
return "", errors.New("not implemented")
}

6
environment_windows.go Executable file → Normal file
View file

@ -25,7 +25,9 @@ func (env *environment) isRunningAsRoot() bool {
if err != nil {
return false
}
defer windows.FreeSid(sid)
defer func() {
_ = windows.FreeSid(sid)
}()
// This appears to cast a null pointer so I'm not sure why this
// works, but this guy says it does and it Works for Me™:
@ -48,6 +50,6 @@ func (env *environment) homeDir() string {
return home
}
func (env *environment) getWindowTitle(imageName string, windowTitleRegex string) (string, error) {
func (env *environment) getWindowTitle(imageName, windowTitleRegex string) (string, error) {
return getWindowTitle(imageName, windowTitleRegex)
}

View file

@ -35,7 +35,7 @@ func getImagePid(imageName string) ([]int, error) {
}
// getWindowTitle returns the title of a window linked to a process name
func getWindowTitle(imageName string, windowTitleRegex string) (string, error) {
func getWindowTitle(imageName, windowTitleRegex string) (string, error) {
processPid, err := getImagePid(imageName)
if err != nil {
return "", nil
@ -73,7 +73,9 @@ func processes() ([]WindowsProcess, error) {
if err != nil {
return nil, syscall.GetLastError()
}
defer windows.CloseHandle(handle)
defer func() {
_ = windows.CloseHandle(handle)
}()
// get process infor by looping through the snapshot
var entry windows.ProcessEntry32
@ -109,8 +111,8 @@ var (
)
// EnumWindows call EnumWindows from user32 and returns all active windows
func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0)
func EnumWindows(enumFunc, lparam uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, enumFunc, lparam, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
@ -122,10 +124,10 @@ func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) {
}
// GetWindowText returns the title and text of a window from a window handle
func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) {
func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (length int32, err error) {
r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount))
len = int32(r0)
if len == 0 {
length = int32(r0)
if length == 0 {
if e1 != 0 {
err = error(e1)
} else {
@ -135,7 +137,7 @@ func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32,
return
}
// GetWindowTitle searchs for a window attached to the pid
// GetWindowTitle searches for a window attached to the pid
func GetWindowTitle(pid int, windowTitleRegex string) (syscall.Handle, string, error) {
var hwnd syscall.Handle
var title string
@ -166,8 +168,8 @@ func GetWindowTitle(pid int, windowTitleRegex string) (syscall.Handle, string, e
return 1 // continue enumeration
})
// Enumerates all top-level windows on the screen
EnumWindows(cb, 0)
if hwnd == 0 {
err = EnumWindows(cb, 0)
if err != nil || hwnd == 0 {
return 0, "", fmt.Errorf("No window with title '%b' found", pid)
}
return hwnd, title, nil

0
main.go Executable file → Normal file
View file

View file

@ -6,8 +6,11 @@ import (
"github.com/stretchr/testify/assert"
)
const (
expected = "expected"
)
func TestGetString(t *testing.T) {
expected := "expected"
values := map[Property]interface{}{TextProperty: expected}
properties := properties{
values: values,
@ -17,7 +20,6 @@ func TestGetString(t *testing.T) {
}
func TestGetStringNoEntry(t *testing.T) {
expected := "expected"
values := map[Property]interface{}{}
properties := properties{
values: values,
@ -27,7 +29,6 @@ func TestGetStringNoEntry(t *testing.T) {
}
func TestGetStringNoTextEntry(t *testing.T) {
expected := "expected"
values := map[Property]interface{}{TextProperty: true}
properties := properties{
values: values,
@ -37,7 +38,7 @@ func TestGetStringNoTextEntry(t *testing.T) {
}
func TestGetColor(t *testing.T) {
expected := "#123456"
expected := expectedColor
values := map[Property]interface{}{UserColor: expected}
properties := properties{
values: values,
@ -47,7 +48,7 @@ func TestGetColor(t *testing.T) {
}
func TestDefaultColorWithInvalidColorCode(t *testing.T) {
expected := "#123456"
expected := expectedColor
values := map[Property]interface{}{UserColor: "invalid"}
properties := properties{
values: values,
@ -57,7 +58,7 @@ func TestDefaultColorWithInvalidColorCode(t *testing.T) {
}
func TestDefaultColorWithUnavailableProperty(t *testing.T) {
expected := "#123456"
expected := expectedColor
values := map[Property]interface{}{}
properties := properties{
values: values,

26
renderer.go Executable file → Normal file
View file

@ -68,7 +68,9 @@ type Renderer struct {
const (
// Transparent implies a transparent color
Transparent string = "transparent"
Transparent = "transparent"
zsh = "zsh"
bash = "bash"
)
func (r *Renderer) init(shell string) {
@ -77,7 +79,7 @@ func (r *Renderer) init(shell string) {
rANSI: "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))",
}
switch shell {
case "zsh":
case zsh:
r.formats.single = "%%{\x1b[%sm%%}%s%%{\x1b[0m%%}"
r.formats.full = "%%{\x1b[%sm\x1b[%sm%%}%s%%{\x1b[0m%%}"
r.formats.transparent = "%%{\x1b[%s;49m\x1b[7m%%}%s%%{\x1b[m\x1b[0m%%}"
@ -87,7 +89,7 @@ func (r *Renderer) init(shell string) {
r.formats.title = "%%{\033]0;%s\007%%}"
r.formats.creset = "%{\x1b[0m%}"
r.formats.clearOEL = "%{\x1b[K%}"
case "bash":
case bash:
r.formats.single = "\\[\x1b[%sm\\]%s\\[\x1b[0m\\]"
r.formats.full = "\\[\x1b[%sm\x1b[%sm\\]%s\\[\x1b[0m\\]"
r.formats.transparent = "\\[\x1b[%s;49m\x1b[7m\\]%s\\[\x1b[m\x1b[0m\\]"
@ -122,7 +124,7 @@ func (r *Renderer) getAnsiFromColorString(colorString string, isBackground bool)
return style.Code()
}
func (r *Renderer) writeColoredText(background string, foreground string, text string) {
func (r *Renderer) writeColoredText(background, foreground, text string) {
var coloredText string
if foreground == Transparent && background != "" {
ansiColor := r.getAnsiFromColorString(background, false)
@ -138,12 +140,12 @@ func (r *Renderer) writeColoredText(background string, foreground string, text s
r.Buffer.WriteString(coloredText)
}
func (r *Renderer) writeAndRemoveText(background string, foreground string, text string, textToRemove string, parentText string) string {
func (r *Renderer) writeAndRemoveText(background, foreground, text, textToRemove, parentText string) string {
r.writeColoredText(background, foreground, text)
return strings.Replace(parentText, textToRemove, "", 1)
}
func (r *Renderer) write(background string, foreground string, text string) {
func (r *Renderer) write(background, foreground, text string) {
// first we match for any potentially valid color enclosed in <>
rex := regexp.MustCompile(`<([#A-Za-z0-9]+)>(.*?)<\/>`)
match := rex.FindAllStringSubmatch(text, -1)
@ -166,12 +168,12 @@ func (r *Renderer) lenWithoutANSI(str string) int {
re := regexp.MustCompile(r.formats.rANSI)
stripped := re.ReplaceAllString(str, "")
switch r.shell {
case "zsh":
stripped = strings.Replace(stripped, "%{", "", -1)
stripped = strings.Replace(stripped, "%}", "", -1)
case "bash":
stripped = strings.Replace(stripped, "\\[", "", -1)
stripped = strings.Replace(stripped, "\\]", "", -1)
case zsh:
stripped = strings.ReplaceAll(stripped, "%{", "")
stripped = strings.ReplaceAll(stripped, "%}", "")
case bash:
stripped = strings.ReplaceAll(stripped, "\\[", "")
stripped = strings.ReplaceAll(stripped, "\\]", "")
}
var i norm.Iter
i.InitString(norm.NFD, stripped)

11
renderer_test.go Executable file → Normal file
View file

@ -4,8 +4,12 @@ import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gookit/color"
"github.com/stretchr/testify/assert"
)
const (
inputText = "This is white, <#ff5733>this is orange</>, white again"
)
func TestWriteAndRemoveText(t *testing.T) {
@ -13,7 +17,6 @@ func TestWriteAndRemoveText(t *testing.T) {
Buffer: new(bytes.Buffer),
}
renderer.init("pwsh")
inputText := "This is white, <#ff5733>this is orange</>, white again"
text := renderer.writeAndRemoveText("#193549", "#fff", "This is white, ", "This is white, ", inputText)
assert.Equal(t, "<#ff5733>this is orange</>, white again", text)
assert.NotContains(t, renderer.string(), "<#ff5733>")
@ -24,7 +27,6 @@ func TestWriteAndRemoveTextColored(t *testing.T) {
Buffer: new(bytes.Buffer),
}
renderer.init("pwsh")
inputText := "This is white, <#ff5733>this is orange</>, white again"
text := renderer.writeAndRemoveText("#193549", "#ff5733", "this is orange", "<#ff5733>this is orange</>", inputText)
assert.Equal(t, "This is white, , white again", text)
assert.NotContains(t, renderer.string(), "<#ff5733>")
@ -35,8 +37,7 @@ func TestWriteColorOverride(t *testing.T) {
Buffer: new(bytes.Buffer),
}
renderer.init("pwsh")
text := "This is white, <#ff5733>this is orange</>, white again"
renderer.write("#193549", "#ff5733", text)
renderer.write("#193549", "#ff5733", inputText)
assert.NotContains(t, renderer.string(), "<#ff5733>")
}

View file

@ -144,5 +144,5 @@ func (segment *Segment) mapSegmentWithWriter(env environmentInfo) error {
segment.props = props
return nil
}
return errors.New("Unable to map writer")
return errors.New("unable to map writer")
}

View file

@ -58,7 +58,7 @@ func (b *batt) enabled() bool {
case battery.Full:
colorPorperty = ChargedColor
icon = b.props.getString(ChargedIcon, "")
default:
case battery.Empty, battery.Unknown:
b.percentageText = percentageText
return true
}

View file

@ -8,6 +8,10 @@ import (
"github.com/stretchr/testify/assert"
)
const (
expectedColor = "#768954"
)
func setupBatteryTests(state battery.State, batteryLevel float64, props *properties) *batt {
env := &MockedEnvironment{}
bt := &battery.Battery{
@ -55,7 +59,7 @@ func TestBatteryDischarging(t *testing.T) {
}
func TestBatteryBackgroundColor(t *testing.T) {
expected := "#768954"
expected := expectedColor
props := &properties{
background: "#111111",
values: map[Property]interface{}{
@ -70,7 +74,7 @@ func TestBatteryBackgroundColor(t *testing.T) {
}
func TestBatteryBackgroundColorInvalid(t *testing.T) {
expected := "#768954"
expected := expectedColor
props := &properties{
background: expected,
values: map[Property]interface{}{
@ -85,7 +89,7 @@ func TestBatteryBackgroundColorInvalid(t *testing.T) {
}
func TestBatteryForegroundColor(t *testing.T) {
expected := "#768954"
expected := expectedColor
props := &properties{
foreground: "#111111",
values: map[Property]interface{}{
@ -100,7 +104,7 @@ func TestBatteryForegroundColor(t *testing.T) {
}
func TestBatteryForegroundColorInvalid(t *testing.T) {
expected := "#768954"
expected := expectedColor
props := &properties{
foreground: expected,
values: map[Property]interface{}{

4
segment_git.go Executable file → Normal file
View file

@ -28,7 +28,7 @@ type gitStatus struct {
changed bool
}
func (s *gitStatus) string(prefix string, color string) string {
func (s *gitStatus) string(prefix, color string) string {
var status string
stringIfValue := func(value int, prefix string) string {
if value > 0 {
@ -170,7 +170,7 @@ func (g *git) init(props *properties, env environmentInfo) {
g.env = env
}
func (g *git) getStatusDetailString(status *gitStatus, color Property, icon Property, defaultIcon string) string {
func (g *git) getStatusDetailString(status *gitStatus, color, icon Property, defaultIcon string) string {
prefix := g.props.getString(icon, defaultIcon)
foregroundColor := g.props.getColor(color, g.props.foreground)
if !g.props.getBool(DisplayStatusDetail, true) {

43
segment_git_test.go Executable file → Normal file
View file

@ -6,6 +6,10 @@ import (
"github.com/stretchr/testify/assert"
)
const (
changesColor = "#BD8BDE"
)
func TestEnabledGitNotFound(t *testing.T) {
env := new(MockedEnvironment)
env.On("hasCommand", "git").Return(false)
@ -70,12 +74,12 @@ func setupHEADContextEnv(context *detachedContext) *git {
env.On("getFileContent", "/.git/MERGE_HEAD").Return(context.mergeHEAD)
env.On("hasFiles", "/.git/CHERRY_PICK_HEAD").Return(context.cherryPick)
env.On("hasFiles", "/.git/MERGE_HEAD").Return(context.merge)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "rev-parse", "--short", "HEAD"}).Return(context.currentCommit, nil)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "describe", "--tags", "--exact-match"}).Return(context.tagName, nil)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "name-rev", "--name-only", "--exclude=tags/*", context.origin}).Return(context.origin, nil)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "name-rev", "--name-only", "--exclude=tags/*", context.onto}).Return(context.onto, nil)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "name-rev", "--name-only", "--exclude=tags/*", context.cherryPickSHA}).Return(context.cherryPickSHA, nil)
env.On("runCommand", "git", []string{"-c", "core.quotepath=false", "-c", "color.status=false", "name-rev", "--name-only", "--exclude=tags/*", context.mergeHEAD}).Return(context.mergeHEAD, nil)
env.mockGitCommand(context.currentCommit, "rev-parse", "--short", "HEAD")
env.mockGitCommand(context.tagName, "describe", "--tags", "--exact-match")
env.mockGitCommand(context.origin, "name-rev", "--name-only", "--exclude=tags/*", context.origin)
env.mockGitCommand(context.onto, "name-rev", "--name-only", "--exclude=tags/*", context.onto)
env.mockGitCommand(context.cherryPickSHA, "name-rev", "--name-only", "--exclude=tags/*", context.cherryPickSHA)
env.mockGitCommand(context.mergeHEAD, "name-rev", "--name-only", "--exclude=tags/*", context.mergeHEAD)
g := &git{
env: env,
repo: &gitRepo{
@ -85,6 +89,11 @@ func setupHEADContextEnv(context *detachedContext) *git {
return g
}
func (m *MockedEnvironment) mockGitCommand(returnValue string, args ...string) {
args = append([]string{"-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
m.On("runCommand", "git", args).Return(returnValue, nil)
}
func TestGetGitDetachedCommitHash(t *testing.T) {
want := "\uf417lalasha1"
context := &detachedContext{
@ -411,7 +420,7 @@ func TestGetUpstreamSymbolGit(t *testing.T) {
}
func TestGetStatusColorLocalChangesStaging(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{
changed: true,
@ -429,7 +438,7 @@ func TestGetStatusColorLocalChangesStaging(t *testing.T) {
}
func TestGetStatusColorLocalChangesWorking(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{},
working: &gitStatus{
@ -448,7 +457,7 @@ func TestGetStatusColorLocalChangesWorking(t *testing.T) {
}
func TestGetStatusColorAheadAndBehind(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{},
working: &gitStatus{},
@ -467,7 +476,7 @@ func TestGetStatusColorAheadAndBehind(t *testing.T) {
}
func TestGetStatusColorAhead(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{},
working: &gitStatus{},
@ -486,7 +495,7 @@ func TestGetStatusColorAhead(t *testing.T) {
}
func TestGetStatusColorBehind(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{},
working: &gitStatus{},
@ -505,7 +514,7 @@ func TestGetStatusColorBehind(t *testing.T) {
}
func TestGetStatusColorDefault(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{},
working: &gitStatus{},
@ -516,7 +525,7 @@ func TestGetStatusColorDefault(t *testing.T) {
repo: repo,
props: &properties{
values: map[Property]interface{}{
BehindColor: "#BD8BDE",
BehindColor: changesColor,
},
},
}
@ -524,7 +533,7 @@ func TestGetStatusColorDefault(t *testing.T) {
}
func TestSetStatusColorBackground(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{
changed: true,
@ -534,7 +543,7 @@ func TestSetStatusColorBackground(t *testing.T) {
repo: repo,
props: &properties{
values: map[Property]interface{}{
LocalChangesColor: "#BD8BDE",
LocalChangesColor: changesColor,
ColorBackground: false,
},
foreground: "#ffffff",
@ -546,7 +555,7 @@ func TestSetStatusColorBackground(t *testing.T) {
}
func TestSetStatusColorForeground(t *testing.T) {
expected := "#BD8BDE"
expected := changesColor
repo := &gitRepo{
staging: &gitStatus{
changed: true,
@ -556,7 +565,7 @@ func TestSetStatusColorForeground(t *testing.T) {
repo: repo,
props: &properties{
values: map[Property]interface{}{
LocalChangesColor: "#BD8BDE",
LocalChangesColor: changesColor,
ColorBackground: true,
},
foreground: "#ffffff",

0
segment_golang_test.go Executable file → Normal file
View file

0
segment_kubectl_test.go Executable file → Normal file
View file

14
segment_node_test.go Executable file → Normal file
View file

@ -6,6 +6,10 @@ import (
"github.com/stretchr/testify/assert"
)
const (
node114 = "1.14"
)
type nodeArgs struct {
enabled bool
nodeVersion string
@ -49,7 +53,7 @@ func TestNodeWriterDisabledNoJSorTSFiles(t *testing.T) {
}
func TestNodeEnabledJSFiles(t *testing.T) {
expected := "1.14"
expected := node114
args := &nodeArgs{
enabled: true,
nodeVersion: expected,
@ -62,7 +66,7 @@ func TestNodeEnabledJSFiles(t *testing.T) {
}
func TestNodeEnabledTsFiles(t *testing.T) {
expected := "1.14"
expected := node114
args := &nodeArgs{
enabled: true,
nodeVersion: expected,
@ -75,7 +79,7 @@ func TestNodeEnabledTsFiles(t *testing.T) {
}
func TestNodeEnabledJsAndTsFiles(t *testing.T) {
expected := "1.14"
expected := node114
args := &nodeArgs{
enabled: true,
nodeVersion: expected,
@ -92,7 +96,7 @@ func TestNodeEnabledNoVersion(t *testing.T) {
expected := ""
args := &nodeArgs{
enabled: true,
nodeVersion: "1.14",
nodeVersion: node114,
hasJS: true,
displayVersion: false,
}
@ -102,7 +106,7 @@ func TestNodeEnabledNoVersion(t *testing.T) {
}
func TestNodeEnabledNodeVersion(t *testing.T) {
expected := "1.14"
expected := node114
args := &nodeArgs{
enabled: true,
nodeVersion: expected,

View file

@ -67,7 +67,7 @@ func (n *osInfo) enabled() bool {
func (n *osInfo) string() string {
goos := n.env.getRuntimeGOOS()
switch goos {
case "windows":
case windowsPlatform:
return n.props.getString(Windows, "\uE62A")
case "darwin":
return n.props.getString(MacOS, "\uF179")

4
segment_path.go Executable file → Normal file
View file

@ -96,7 +96,7 @@ func (pt *path) getAgnosterFullPath() string {
if string(pwd[0]) == pathSeparator {
pwd = pwd[1:]
}
return strings.Replace(pwd, pathSeparator, folderSeparator, -1)
return strings.ReplaceAll(pwd, pathSeparator, folderSeparator)
}
func (pt *path) inHomeDir(pwd string) bool {
@ -162,7 +162,7 @@ func base(path string, env environmentInfo) string {
}
// If empty now, it had only slashes.
if path == "" {
return string(env.getPathSeperator())
return env.getPathSeperator()
}
return path
}

52
segment_path_test.go Executable file → Normal file
View file

@ -78,7 +78,7 @@ func (env *MockedEnvironment) runCommand(command string, args ...string) (string
return arguments.String(0), arguments.Error(1)
}
func (env *MockedEnvironment) runShellCommand(shell string, command string) string {
func (env *MockedEnvironment) runShellCommand(shell, command string) string {
args := env.Called(shell, command)
return args.String(0)
}
@ -108,13 +108,21 @@ func (env *MockedEnvironment) getShellName() string {
return args.String(0)
}
func (env *MockedEnvironment) getWindowTitle(imageName string, windowTitleRegex string) (string, error) {
func (env *MockedEnvironment) getWindowTitle(imageName, windowTitleRegex string) (string, error) {
args := env.Called(imageName)
return args.String(0), args.Error(1)
}
const (
homeGates = "/home/gates"
homeBill = "/home/bill"
homeJan = "/usr/home/jan"
homeBillWindows = "C:\\Users\\Bill"
levelDir = "/level"
)
func TestIsInHomeDirTrue(t *testing.T) {
home := "/home/bill"
home := homeBill
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
path := &path{
@ -126,10 +134,10 @@ func TestIsInHomeDirTrue(t *testing.T) {
func TestIsInHomeDirLevelTrue(t *testing.T) {
level := rand.Intn(100)
home := "/home/bill"
home := homeBill
pwd := home
for i := 0; i < level; i++ {
pwd += "/level"
pwd += levelDir
}
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -250,7 +258,7 @@ func TestRootLocationEmptyDir(t *testing.T) {
}
func TestIsInHomeDirFalse(t *testing.T) {
home := "/home/bill"
home := homeBill
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
path := &path{
@ -261,7 +269,7 @@ func TestIsInHomeDirFalse(t *testing.T) {
}
func TestPathDepthInHome(t *testing.T) {
home := "/home/bill"
home := homeBill
pwd := home
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -288,10 +296,10 @@ func TestPathDepthInHomeTrailing(t *testing.T) {
func TestPathDepthInHomeMultipleLevelsDeep(t *testing.T) {
level := rand.Intn(100)
home := "/home/bill"
home := homeBill
pwd := home
for i := 0; i < level; i++ {
pwd += "/level"
pwd += levelDir
}
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -305,10 +313,10 @@ func TestPathDepthInHomeMultipleLevelsDeep(t *testing.T) {
func TestPathDepthOutsideHomeMultipleLevelsDeep(t *testing.T) {
level := rand.Intn(100)
home := "/home/gates"
home := homeGates
pwd := "/usr"
for i := 0; i < level; i++ {
pwd += "/level"
pwd += levelDir
}
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -321,7 +329,7 @@ func TestPathDepthOutsideHomeMultipleLevelsDeep(t *testing.T) {
}
func TestPathDepthOutsideHomeZeroLevelsDeep(t *testing.T) {
home := "/home/gates"
home := homeGates
pwd := "/usr/"
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -334,7 +342,7 @@ func TestPathDepthOutsideHomeZeroLevelsDeep(t *testing.T) {
}
func TestPathDepthOutsideHomeOneLevelDeep(t *testing.T) {
home := "/home/gates"
home := homeGates
pwd := "/usr/location"
env := new(MockedEnvironment)
env.On("homeDir", nil).Return(home)
@ -363,7 +371,7 @@ func TestGetAgnosterFullPath(t *testing.T) {
assert.Equal(t, "usr > location > whatever", got)
}
func testWritePathInfo(home string, pwd string, pathSeparator string) string {
func testWritePathInfo(home, pwd, pathSeparator string) string {
props := &properties{
values: map[Property]interface{}{
FolderSeparatorIcon: " > ",
@ -383,14 +391,14 @@ func testWritePathInfo(home string, pwd string, pathSeparator string) string {
}
func TestWritePathInfoWindowsOutsideHome(t *testing.T) {
home := "C:\\Users\\Bill"
home := homeBillWindows
want := "C: > f > f > location"
got := testWritePathInfo(home, "C:\\Program Files\\Go\\location", "\\")
assert.Equal(t, want, got)
}
func TestWritePathInfoWindowsInsideHome(t *testing.T) {
home := "C:\\Users\\Bill"
home := homeBillWindows
location := home + "\\Documents\\Bill\\location"
want := "~ > f > f > location"
got := testWritePathInfo(home, location, "\\")
@ -398,28 +406,28 @@ func TestWritePathInfoWindowsInsideHome(t *testing.T) {
}
func TestWritePathInfoWindowsOutsideHomeZeroLevels(t *testing.T) {
home := "C:\\Users\\Bill"
home := homeBillWindows
want := "C: > location"
got := testWritePathInfo(home, "C:\\location", "\\")
assert.Equal(t, want, got)
}
func TestWritePathInfoWindowsOutsideHomeOneLevels(t *testing.T) {
home := "C:\\Users\\Bill"
home := homeBillWindows
want := "C: > f > location"
got := testWritePathInfo(home, "C:\\Program Files\\location", "\\")
assert.Equal(t, want, got)
}
func TestWritePathInfoUnixOutsideHome(t *testing.T) {
home := "/usr/home/jan"
home := homeJan
want := "mnt > f > f > location"
got := testWritePathInfo(home, "/mnt/go/test/location", "/")
assert.Equal(t, want, got)
}
func TestWritePathInfoUnixInsideHome(t *testing.T) {
home := "/usr/home/jan"
home := homeJan
location := home + "/docs/jan/location"
want := "~ > f > f > location"
got := testWritePathInfo(home, location, "/")
@ -427,14 +435,14 @@ func TestWritePathInfoUnixInsideHome(t *testing.T) {
}
func TestWritePathInfoUnixOutsideHomeZeroLevels(t *testing.T) {
home := "/usr/home/jan"
home := homeJan
want := "mnt > location"
got := testWritePathInfo(home, "/mnt/location", "/")
assert.Equal(t, want, got)
}
func TestWritePathInfoUnixOutsideHomeOneLevels(t *testing.T) {
home := "/usr/home/jan"
home := homeJan
want := "mnt > f > location"
got := testWritePathInfo(home, "/mnt/folder/location", "/")
assert.Equal(t, want, got)

24
segment_python_test.go Executable file → Normal file
View file

@ -50,11 +50,15 @@ func bootStrapPythonTest(args *pythonArgs) *python {
return python
}
const (
python345 = "Python 3.4.5"
)
func TestPythonWriterDisabledNoPythonFiles(t *testing.T) {
args := newPythonArgs()
args.hasPyFiles = false
args.hasNotebookFiles = false
args.python3Version = "Python 3.4.5"
args.python3Version = python345
python := bootStrapPythonTest(args)
assert.False(t, python.enabled(), "there are no Python files in the current folder")
}
@ -63,7 +67,7 @@ func TestPythonWriterDisabledHasPythonFiles(t *testing.T) {
args := newPythonArgs()
args.hasPyFiles = true
args.hasNotebookFiles = false
args.python3Version = "Python 3.4.5"
args.python3Version = python345
python := bootStrapPythonTest(args)
assert.True(t, python.enabled(), "there should be a Python file in the current folder")
}
@ -72,7 +76,7 @@ func TestPythonWriterDisabledHasJupyterNotebookFiles(t *testing.T) {
args := newPythonArgs()
args.hasPyFiles = false
args.hasNotebookFiles = true
args.python3Version = "Python 3.4.5"
args.python3Version = python345
python := bootStrapPythonTest(args)
assert.True(t, python.enabled(), "there should be a Jupyter Notebook file in the current folder")
}
@ -81,7 +85,7 @@ func TestPythonWriterDisabledHasPyAndJupyterNotebookFiles(t *testing.T) {
args := newPythonArgs()
args.hasPyFiles = true
args.hasNotebookFiles = true
args.python3Version = "Python 3.4.5"
args.python3Version = python345
python := bootStrapPythonTest(args)
assert.True(t, python.enabled(), "there should be a Jupyter Notebook file in the current folder")
}
@ -102,7 +106,7 @@ func TestPythonWriterDisabledNoPythonInstalled(t *testing.T) {
func TestPythonWriterEnabledNoVirtualEnv(t *testing.T) {
args := newPythonArgs()
args.python3Version = "Python 3.4.5"
args.python3Version = python345
python := bootStrapPythonTest(args)
assert.True(t, python.enabled())
assert.Equal(t, "3.4.5", python.string())
@ -110,7 +114,7 @@ func TestPythonWriterEnabledNoVirtualEnv(t *testing.T) {
func TestPythonWriterEnabledVirtualEnvOverrule(t *testing.T) {
args := newPythonArgs()
args.python3Version = "Python 3.4.5"
args.python3Version = python345
args.condaEnvName = "myenv"
props := &properties{
values: map[Property]interface{}{
@ -125,7 +129,7 @@ func TestPythonWriterEnabledVirtualEnvOverrule(t *testing.T) {
func TestPythonWriterEnabledVirtualEnv(t *testing.T) {
args := newPythonArgs()
args.python3Version = "Python 3.4.5"
args.python3Version = python345
args.condaEnvName = "myenv"
expected := fmt.Sprintf("%s %s", args.condaEnvName, "3.4.5")
props := &properties{
@ -142,7 +146,7 @@ func TestPythonWriterEnabledVirtualEnv(t *testing.T) {
func TestPythonWriterEnabledWithVirtualEnv(t *testing.T) {
args := newPythonArgs()
args.virtualEnvName = "venv"
args.python3Version = "Python 3.4.5"
args.python3Version = python345
expected := fmt.Sprintf("%s %s", args.virtualEnvName, "3.4.5")
python := bootStrapPythonTest(args)
assert.True(t, python.enabled())
@ -162,7 +166,7 @@ func TestPythonWriterEnabledWithCondaEnvPath(t *testing.T) {
func TestPythonWriterEnabledWithCondaDefaultEnv(t *testing.T) {
args := newPythonArgs()
args.condaDefaultName = "conda2"
args.python3Version = "Python 3.4.5"
args.python3Version = python345
expected := fmt.Sprintf("%s %s", args.condaDefaultName, "3.4.5")
python := bootStrapPythonTest(args)
assert.True(t, python.enabled())
@ -183,7 +187,7 @@ func TestPythonWriterEnabledWithTwoValidEnvs(t *testing.T) {
args := newPythonArgs()
args.condaEnvName = "conda"
args.condaDefaultName = "conda2"
args.python3Version = "Python 3.4.5"
args.python3Version = python345
expected := fmt.Sprintf("%s %s", args.condaEnvName, "3.4.5")
python := bootStrapPythonTest(args)
assert.True(t, python.enabled())

4
segment_session.go Executable file → Normal file
View file

@ -49,7 +49,9 @@ func (s *session) getFormattedText() string {
if s.activeSSHSession() {
ssh = s.props.getString(SSHIcon, "\uF817 ")
}
return fmt.Sprintf("%s<%s>%s</>%s<%s>%s</>", ssh, s.props.getColor(UserColor, s.props.foreground), username, separator, s.props.getColor(HostColor, s.props.foreground), computername)
userColor := s.props.getColor(UserColor, s.props.foreground)
hostColor := s.props.getColor(HostColor, s.props.foreground)
return fmt.Sprintf("%s<%s>%s</>%s<%s>%s</>", ssh, userColor, username, separator, hostColor, computername)
}
func (s *session) getComputerName() string {

0
segment_session_test.go Executable file → Normal file
View file

0
segment_shell_test.go Executable file → Normal file
View file

View file

@ -9,18 +9,19 @@ import (
)
type spotifyArgs struct {
spotifyDarwinRunning string
spotifyDarwinStatus string
spotifyDarwinArtist string
spotifyDarwinTrack string
running string
status string
artist string
track string
runError error
}
func bootStrapSpotifyDarwinTest(args *spotifyArgs) *spotify {
env := new(MockedEnvironment)
env.On("runCommand", "osascript", []string{"-e", "application \"Spotify\" is running"}).Return(args.spotifyDarwinRunning, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(args.spotifyDarwinStatus, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(args.spotifyDarwinArtist, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to name of current track as string"}).Return(args.spotifyDarwinTrack, nil)
env.On("runCommand", "osascript", []string{"-e", "application \"Spotify\" is running"}).Return(args.running, args.runError)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(args.status, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(args.artist, nil)
env.On("runCommand", "osascript", []string{"-e", "tell application \"Spotify\" to name of current track as string"}).Return(args.track, nil)
props := &properties{}
s := &spotify{
env: env,
@ -31,7 +32,7 @@ func bootStrapSpotifyDarwinTest(args *spotifyArgs) *spotify {
func TestSpotifyDarwinEnabledAndSpotifyNotRunning(t *testing.T) {
args := &spotifyArgs{
spotifyDarwinRunning: "false",
running: "false",
}
s := bootStrapSpotifyDarwinTest(args)
assert.Equal(t, false, s.enabled())
@ -39,10 +40,10 @@ func TestSpotifyDarwinEnabledAndSpotifyNotRunning(t *testing.T) {
func TestSpotifyDarwinEnabledAndSpotifyPlaying(t *testing.T) {
args := &spotifyArgs{
spotifyDarwinRunning: "true",
spotifyDarwinStatus: "playing",
spotifyDarwinArtist: "Candlemass",
spotifyDarwinTrack: "Spellbreaker",
running: "true",
status: "playing",
artist: "Candlemass",
track: "Spellbreaker",
}
s := bootStrapSpotifyDarwinTest(args)
assert.Equal(t, true, s.enabled())
@ -51,10 +52,10 @@ func TestSpotifyDarwinEnabledAndSpotifyPlaying(t *testing.T) {
func TestSpotifyDarwinEnabledAndSpotifyPaused(t *testing.T) {
args := &spotifyArgs{
spotifyDarwinRunning: "true",
spotifyDarwinStatus: "paused",
spotifyDarwinArtist: "Candlemass",
spotifyDarwinTrack: "Spellbreaker",
running: "true",
status: "paused",
artist: "Candlemass",
track: "Spellbreaker",
}
s := bootStrapSpotifyDarwinTest(args)
assert.Equal(t, true, s.enabled())

2
segment_spotify_test.go Executable file → Normal file
View file

@ -1,5 +1,3 @@
// +build windows
package main
import (

View file

@ -10,13 +10,13 @@ import (
)
type spotifyArgs struct {
spotifyWindowsTitle string
spotifyNotRunningError error
title string
runError error
}
func bootStrapSpotifyWindowsTest(args *spotifyArgs) *spotify {
env := new(MockedEnvironment)
env.On("getWindowTitle", "spotify.exe").Return(args.spotifyWindowsTitle, args.spotifyNotRunningError)
env.On("getWindowTitle", "spotify.exe").Return(args.title, args.runError)
props := &properties{}
s := &spotify{
env: env,
@ -27,7 +27,7 @@ func bootStrapSpotifyWindowsTest(args *spotifyArgs) *spotify {
func TestSpotifyWindowsEnabledAndSpotifyNotRunning(t *testing.T) {
args := &spotifyArgs{
spotifyNotRunningError: errors.New(""),
runError: errors.New(""),
}
s := bootStrapSpotifyWindowsTest(args)
assert.Equal(t, false, s.enabled())
@ -35,7 +35,7 @@ func TestSpotifyWindowsEnabledAndSpotifyNotRunning(t *testing.T) {
func TestSpotifyWindowsEnabledAndSpotifyPlaying(t *testing.T) {
args := &spotifyArgs{
spotifyWindowsTitle: "Candlemass - Spellbreaker",
title: "Candlemass - Spellbreaker",
}
s := bootStrapSpotifyWindowsTest(args)
assert.Equal(t, true, s.enabled())
@ -44,7 +44,7 @@ func TestSpotifyWindowsEnabledAndSpotifyPlaying(t *testing.T) {
func TestSpotifyWindowsEnabledAndSpotifyStopped(t *testing.T) {
args := &spotifyArgs{
spotifyWindowsTitle: "Spotify premium",
title: "Spotify premium",
}
s := bootStrapSpotifyWindowsTest(args)
assert.Equal(t, true, s.enabled())

0
segment_terraform_test.go Executable file → Normal file
View file

0
segment_test.go Executable file → Normal file
View file

0
settings.go Executable file → Normal file
View file