mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-29 12:44:22 +01:00
1 parent
780fb4a8f1
commit
93f292c3df
224 files changed
+4424
-5485
No files matched your search
@@ -0,0 +1,105 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Verbose bool
|
||||
Redact bool
|
||||
}
|
||||
|
||||
func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding {
|
||||
var findings []report.Finding
|
||||
linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1)
|
||||
|
||||
// check if we should skip file based on the global allowlist
|
||||
if cfg.Allowlist.PathAllowed(filePath) {
|
||||
return findings
|
||||
}
|
||||
|
||||
for _, r := range cfg.Rules {
|
||||
pathSkip := false
|
||||
if r.Allowlist.CommitAllowed(commit) {
|
||||
continue
|
||||
}
|
||||
if r.Allowlist.PathAllowed(filePath) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if path should be considered
|
||||
if r.Path != nil {
|
||||
if r.Path.Match([]byte(filePath)) {
|
||||
if r.Regex == nil {
|
||||
// This is a path only rule
|
||||
f := report.Finding{
|
||||
Description: r.Description,
|
||||
File: filePath,
|
||||
RuleID: r.RuleID,
|
||||
Context: fmt.Sprintf("file detected: %s", filePath),
|
||||
Tags: r.Tags,
|
||||
}
|
||||
findings = append(findings, f)
|
||||
pathSkip = true
|
||||
}
|
||||
} else {
|
||||
pathSkip = true
|
||||
}
|
||||
}
|
||||
if pathSkip {
|
||||
continue
|
||||
}
|
||||
|
||||
matchIndices := r.Regex.FindAllIndex(b, -1)
|
||||
for _, m := range matchIndices {
|
||||
location := getLocation(linePairs, m[0], m[1])
|
||||
f := report.Finding{
|
||||
Description: r.Description,
|
||||
File: filePath,
|
||||
RuleID: r.RuleID,
|
||||
StartLine: location.startLine,
|
||||
EndLine: location.endLine,
|
||||
StartColumn: location.startColumn,
|
||||
EndColumn: location.endColumn,
|
||||
Secret: strings.Trim(string(b[m[0]:m[1]]), "\n"),
|
||||
Context: limit(strings.Trim(string(b[location.startLineIndex:location.endLineIndex]), "\n")),
|
||||
Tags: r.Tags,
|
||||
}
|
||||
|
||||
if r.Allowlist.RegexAllowed(f.Secret) {
|
||||
continue
|
||||
}
|
||||
|
||||
if r.EntropySet() {
|
||||
include, entropy := r.IncludeEntropy(strings.Trim(string(b[m[0]:m[1]]), "\n"))
|
||||
if include {
|
||||
f.Entropy = float32(entropy)
|
||||
findings = append(findings, f)
|
||||
}
|
||||
} else {
|
||||
findings = append(findings, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings
|
||||
}
|
||||
|
||||
func limit(s string) string {
|
||||
if len(s) > 500 {
|
||||
return s[:500] + "..."
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func printFinding(f report.Finding) {
|
||||
var b []byte
|
||||
b, _ = json.MarshalIndent(f, "", " ")
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
func TestDetectFindings(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
opts Options
|
||||
filePath string
|
||||
bytes []byte
|
||||
commit string
|
||||
expectedFindings []report.Finding
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
cfgName: "simple",
|
||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "tmp.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_aws_re",
|
||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_path",
|
||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_commit",
|
||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{},
|
||||
commit: "allowthiscommit",
|
||||
},
|
||||
{
|
||||
cfgName: "entropy_group",
|
||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Discord API key",
|
||||
Secret: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
File: "tmp.go",
|
||||
RuleID: "discord-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
||||
filePath: "tmp.py",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Generic API Key",
|
||||
Secret: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
File: "tmp.py",
|
||||
RuleID: "generic-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "path_only",
|
||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
||||
filePath: "tmp.py",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Python Files",
|
||||
Context: "file detected: tmp.py",
|
||||
File: "tmp.py",
|
||||
RuleID: "python-files-only",
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "bad_entropy_group",
|
||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
||||
filePath: "tmp.go",
|
||||
expectedFindings: []report.Finding{},
|
||||
wantError: fmt.Errorf("Discord API key invalid regex entropy group 5, max regex entropy group 3"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
viper.Reset()
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName(tt.cfgName)
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
viper.Unmarshal(&vc)
|
||||
cfg, err := vc.Translate()
|
||||
if tt.wantError != nil {
|
||||
if err == nil {
|
||||
t.Errorf("expected error")
|
||||
}
|
||||
assert.Equal(t, tt.wantError, err)
|
||||
}
|
||||
|
||||
findings := DetectFindings(cfg, tt.bytes, tt.filePath, tt.commit)
|
||||
for _, f := range findings {
|
||||
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
|
||||
f.Date = ""
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/sync/errgroup"
|
||||
godocutil "golang.org/x/tools/godoc/util"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
// FromFiles opens the directory or file specified in source and checks each file against the rules
|
||||
// from the configuration. If any secrets are found, they are added to the list of findings.
|
||||
func FromFiles(source string, cfg config.Config, outputOptions Options) ([]*report.Finding, error) {
|
||||
var (
|
||||
findings []*report.Finding
|
||||
mu sync.Mutex
|
||||
)
|
||||
g, _ := errgroup.WithContext(context.Background())
|
||||
paths := make(chan string)
|
||||
g.Go(func() error {
|
||||
defer close(paths)
|
||||
return filepath.Walk(source,
|
||||
func(path string, fInfo os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fInfo.Name() == ".git" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if fInfo.Mode().IsRegular() {
|
||||
paths <- path
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
for pa := range paths {
|
||||
p := pa
|
||||
g.Go(func() error {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !godocutil.IsText(b) {
|
||||
return nil
|
||||
}
|
||||
fis := DetectFindings(cfg, b, p, "")
|
||||
for _, fi := range fis {
|
||||
fi.File = p
|
||||
if outputOptions.Redact {
|
||||
fi.Redact()
|
||||
}
|
||||
if outputOptions.Verbose {
|
||||
printFinding(fi)
|
||||
}
|
||||
mu.Lock()
|
||||
findings = append(findings, &fi)
|
||||
mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
return findings, err
|
||||
}
|
||||
|
||||
return findings, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
// TestFromGit tests the FromGit function
|
||||
func TestFromFiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
opts Options
|
||||
source string
|
||||
expectedFindings []*report.Finding
|
||||
}{
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "nogit"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []*report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 19,
|
||||
EndLine: 19,
|
||||
StartColumn: 16,
|
||||
EndColumn: 35,
|
||||
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "../testdata/repos/nogit/main.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "nogit", "main.go"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []*report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 19,
|
||||
EndLine: 19,
|
||||
StartColumn: 16,
|
||||
EndColumn: 35,
|
||||
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "../testdata/repos/nogit/main.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
viper.Unmarshal(&vc)
|
||||
cfg, _ := vc.Translate()
|
||||
|
||||
findings, err := FromFiles(tt.source, cfg, tt.opts)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
godocutil "golang.org/x/tools/godoc/util"
|
||||
)
|
||||
|
||||
// FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration
|
||||
// struct. Files from the gitdiff.File channel are then checked against each rule in the configuration to
|
||||
// check for secrets. If any secrets are found, they are added to the list of findings.
|
||||
func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Options) []*report.Finding {
|
||||
var findings []*report.Finding
|
||||
mu := sync.Mutex{}
|
||||
wg := sync.WaitGroup{}
|
||||
for f := range files {
|
||||
|
||||
wg.Add(1)
|
||||
go func(f *gitdiff.File) {
|
||||
defer wg.Done()
|
||||
if f.IsBinary {
|
||||
return
|
||||
}
|
||||
|
||||
if f.IsDelete {
|
||||
return
|
||||
}
|
||||
|
||||
commitSHA := ""
|
||||
|
||||
// Check if commit is allowed
|
||||
if f.PatchHeader != nil {
|
||||
commitSHA = f.PatchHeader.SHA
|
||||
|
||||
if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, tf := range f.TextFragments {
|
||||
if f.TextFragments == nil {
|
||||
// TODO fix this in gitleaks gitdiff fork
|
||||
// https://github.com/gitleaks/gitleaks/issues/11
|
||||
continue
|
||||
}
|
||||
|
||||
if !godocutil.IsText([]byte(tf.Raw(gitdiff.OpAdd))) {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) {
|
||||
// don't add to start/end lines if finding is from a file only rule
|
||||
if !strings.HasPrefix(fi.Context, "file detected") {
|
||||
fi.StartLine += int(tf.NewPosition)
|
||||
fi.EndLine += int(tf.NewPosition)
|
||||
}
|
||||
if f.PatchHeader != nil {
|
||||
fi.Commit = f.PatchHeader.SHA
|
||||
fi.Message = f.PatchHeader.Message()
|
||||
if f.PatchHeader.Author != nil {
|
||||
fi.Author = f.PatchHeader.Author.Name
|
||||
fi.Email = f.PatchHeader.Author.Email
|
||||
}
|
||||
fi.Date = f.PatchHeader.AuthorDate.String()
|
||||
}
|
||||
|
||||
if outputOptions.Redact {
|
||||
fi.Redact()
|
||||
}
|
||||
|
||||
if outputOptions.Verbose {
|
||||
printFinding(fi)
|
||||
}
|
||||
mu.Lock()
|
||||
findings = append(findings, &fi)
|
||||
mu.Unlock()
|
||||
|
||||
}
|
||||
}
|
||||
}(f)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return findings
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/git"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
const repoBasePath = "../testdata/repos/"
|
||||
const expectPath = "../testdata/expected/"
|
||||
const configPath = "../testdata/config/"
|
||||
|
||||
// TestFromGit tests the FromGit function
|
||||
func TestFromGit(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
opts Options
|
||||
source string
|
||||
logOpts string
|
||||
expected string
|
||||
expectedFindings []*report.Finding
|
||||
}{
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "small"),
|
||||
expected: filepath.Join(expectPath, "git", "small.txt"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []*report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
StartColumn: 19,
|
||||
EndColumn: 38,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "main.go",
|
||||
// Line: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
||||
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
|
||||
Author: "Zachary Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "Accidentally add a secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
StartColumn: 17,
|
||||
EndColumn: 36,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "foo/foo.go",
|
||||
// Line: "\taws_token := \"AKIALALEMEL33243OLIA\"",
|
||||
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "small"),
|
||||
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
|
||||
logOpts: "--all foo...",
|
||||
cfgName: "simple",
|
||||
expectedFindings: []*report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
StartColumn: 17,
|
||||
EndColumn: 36,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
// Line: "\taws_token := \"AKIALALEMEL33243OLIA\"",
|
||||
File: "foo/foo.go",
|
||||
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := moveDotGit("dotGit", ".git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer moveDotGit(".git", "dotGit")
|
||||
|
||||
for _, tt := range tests {
|
||||
files, err := git.GitLog(tt.source, tt.logOpts)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err = viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
viper.Unmarshal(&vc)
|
||||
cfg, _ := vc.Translate()
|
||||
|
||||
findings := FromGit(files, cfg, tt.opts)
|
||||
for _, f := range findings {
|
||||
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
|
||||
f.Date = ""
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
|
||||
func moveDotGit(from, to string) error {
|
||||
repoDirs, err := os.ReadDir("../testdata/repos")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dir := range repoDirs {
|
||||
if to == ".git" {
|
||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
||||
if os.IsNotExist(err) {
|
||||
// dont want to delete the only copy of .git accidentally
|
||||
continue
|
||||
}
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
||||
}
|
||||
if !dir.IsDir() {
|
||||
continue
|
||||
}
|
||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
|
||||
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
||||
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package detect
|
||||
|
||||
// Location represents a location in a file
|
||||
type Location struct {
|
||||
startLine int
|
||||
endLine int
|
||||
startColumn int
|
||||
endColumn int
|
||||
startLineIndex int
|
||||
endLineIndex int
|
||||
}
|
||||
|
||||
func getLocation(linePairs [][]int, start int, end int) Location {
|
||||
var (
|
||||
prevNewLine int
|
||||
location Location
|
||||
)
|
||||
|
||||
for lineNum, pair := range linePairs {
|
||||
newLineByteIndex := pair[0]
|
||||
if prevNewLine <= start && start < newLineByteIndex {
|
||||
location.startLine = lineNum
|
||||
location.endLine = lineNum
|
||||
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
|
||||
location.startLineIndex = prevNewLine
|
||||
location.endLineIndex = newLineByteIndex
|
||||
}
|
||||
if prevNewLine < end && end <= newLineByteIndex {
|
||||
location.endLine = lineNum
|
||||
location.endColumn = (end - prevNewLine)
|
||||
location.endLineIndex = newLineByteIndex
|
||||
}
|
||||
|
||||
prevNewLine = pair[0]
|
||||
}
|
||||
|
||||
return location
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGetLocation tests the getLocation function.
|
||||
func TestGetLocation(t *testing.T) {
|
||||
tests := []struct {
|
||||
linePairs [][]int
|
||||
start int
|
||||
end int
|
||||
wantLocation Location
|
||||
}{
|
||||
{
|
||||
linePairs: [][]int{
|
||||
{0, 39},
|
||||
{40, 55},
|
||||
{56, 57},
|
||||
},
|
||||
start: 35,
|
||||
end: 38,
|
||||
wantLocation: Location{
|
||||
startLine: 1,
|
||||
startColumn: 36,
|
||||
endLine: 1,
|
||||
endColumn: 38,
|
||||
startLineIndex: 0,
|
||||
endLineIndex: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
linePairs: [][]int{
|
||||
{0, 39},
|
||||
{40, 55},
|
||||
{56, 57},
|
||||
},
|
||||
start: 40,
|
||||
end: 44,
|
||||
wantLocation: Location{
|
||||
startLine: 2,
|
||||
startColumn: 1,
|
||||
endLine: 2,
|
||||
endColumn: 4,
|
||||
startLineIndex: 40,
|
||||
endLineIndex: 56,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
loc := getLocation(test.linePairs, test.start, test.end)
|
||||
if loc != test.wantLocation {
|
||||
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
|
||||
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
|
||||
|
||||
t.Error("got", loc, "want", test.wantLocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user