Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
eyalbe4 committed Aug 20, 2024
2 parents df5347e + ac1bd16 commit b485942
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 40 deletions.
7 changes: 4 additions & 3 deletions artifactory/services/buildinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package services

import (
"encoding/json"
"fmt"
buildinfo "github.com/jfrog/build-info-go/entities"
"net/http"

Expand Down Expand Up @@ -61,14 +62,14 @@ func (bis *BuildInfoService) PublishBuildInfo(build *buildinfo.BuildInfo, projec
if bis.IsDryRun() {
log.Info("[Dry run] Logging Build info preview...")
log.Output(clientutils.IndentJson(content))
return summary, err
return summary, nil
}
httpClientsDetails := bis.GetArtifactoryDetails().CreateHttpClientDetails()
utils.SetContentType("application/vnd.org.jfrog.artifactory+json", &httpClientsDetails.Headers)
log.Info("Deploying build info...")
log.Info(fmt.Sprintf("Publishing build info for <%s>/<%s>...", build.Name, build.Number))
resp, body, err := bis.client.SendPut(bis.GetArtifactoryDetails().GetUrl()+"api/build"+utils.GetProjectQueryParam(projectKey), content, &httpClientsDetails)
if err != nil {
return summary, err
return summary, fmt.Errorf("error occurred while publishing build info: %s", err.Error())
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK, http.StatusCreated, http.StatusNoContent); err != nil {
return summary, err
Expand Down
42 changes: 24 additions & 18 deletions artifactory/services/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package services
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
Expand All @@ -14,8 +15,13 @@ import (
"github.com/jfrog/jfrog-client-go/utils/errorutils"
)

const tokenPath = "api/security/token"
const APIKeyPath = "api/security/apiKey"
const (
tokenPath = "api/security/token"
APIKeyPath = "api/security/apiKey"
errorMsgPrefix = "error occurred while attempting to"
unexpectedServerResponsePrefix = "got unexpected server response while attempting to"
couldntParseServerResponsePrefix = "couldn't parse server response while attempting to"
)

type SecurityService struct {
client *jfroghttpclient.JfrogHttpClient
Expand Down Expand Up @@ -94,7 +100,7 @@ func (ss *SecurityService) GetAPIKey() (string, error) {
func getApiKeyFromBody(body []byte) (string, error) {
var data = make(map[string]interface{})
if err := json.Unmarshal(body, &data); err != nil {
return "", errorutils.CheckErrorf("unable to decode json. Error: %w Upstream response: %s", err, string(body))
return "", errorutils.CheckErrorf("unable to decode json. Error: %s Upstream response: %s", err.Error(), string(body))
}

if len(data) == 0 {
Expand All @@ -114,15 +120,15 @@ func (ss *SecurityService) CreateToken(params CreateTokenParams) (auth.CreateTok
resp, body, err := ss.client.SendPostForm(artifactoryUrl+tokenPath, data, &httpClientsDetails)
tokenInfo := auth.CreateTokenResponseData{}
if err != nil {
return tokenInfo, err
return tokenInfo, fmt.Errorf("%s create token: %w", errorMsgPrefix, err)
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
return tokenInfo, err
return tokenInfo, fmt.Errorf("%s create token: %w", unexpectedServerResponsePrefix, err)
}
if err = json.Unmarshal(body, &tokenInfo); err != nil {
return tokenInfo, errorutils.CheckError(err)
return tokenInfo, errorutils.CheckErrorf("%s create token: %s", couldntParseServerResponsePrefix, err.Error())
}
return tokenInfo, err
return tokenInfo, nil
}

func (ss *SecurityService) GetTokens() (GetTokensResponseData, error) {
Expand All @@ -131,15 +137,15 @@ func (ss *SecurityService) GetTokens() (GetTokensResponseData, error) {
resp, body, _, err := ss.client.SendGet(artifactoryUrl+tokenPath, true, &httpClientsDetails)
tokens := GetTokensResponseData{}
if err != nil {
return tokens, err
return tokens, fmt.Errorf("%s get tokens: %w", errorMsgPrefix, err)
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
return tokens, err
return tokens, fmt.Errorf("%s get tokens: %w", unexpectedServerResponsePrefix, err)
}
if err = json.Unmarshal(body, &tokens); err != nil {
return tokens, errorutils.CheckError(err)
return tokens, errorutils.CheckErrorf("%s get tokens: %s", couldntParseServerResponsePrefix, err.Error())
}
return tokens, err
return tokens, nil
}

func (ss *SecurityService) GetUserTokens(username string) ([]string, error) {
Expand All @@ -163,15 +169,15 @@ func (ss *SecurityService) RefreshToken(params ArtifactoryRefreshTokenParams) (a
resp, body, err := ss.client.SendPostForm(artifactoryUrl+tokenPath, data, &httpClientsDetails)
tokenInfo := auth.CreateTokenResponseData{}
if err != nil {
return tokenInfo, err
return tokenInfo, fmt.Errorf("%s refresh token: %w", errorMsgPrefix, err)
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
return tokenInfo, err
return tokenInfo, fmt.Errorf("%s refresh token: %w", unexpectedServerResponsePrefix, err)
}
if err = json.Unmarshal(body, &tokenInfo); err != nil {
return tokenInfo, errorutils.CheckError(err)
return tokenInfo, errorutils.CheckErrorf("%s refresh token: %s", couldntParseServerResponsePrefix, err.Error())
}
return tokenInfo, err
return tokenInfo, nil
}

func (ss *SecurityService) RevokeToken(params RevokeTokenParams) (string, error) {
Expand All @@ -181,12 +187,12 @@ func (ss *SecurityService) RevokeToken(params RevokeTokenParams) (string, error)
data := buildRevokeTokenUrlValues(params)
resp, body, err := ss.client.SendPostForm(requestFullUrl, data, &httpClientsDetails)
if err != nil {
return "", err
return "", fmt.Errorf("%s revoke token: %w", errorMsgPrefix, err)
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
return "", err
return "", fmt.Errorf("%s revoke token: %w", unexpectedServerResponsePrefix, err)
}
return string(body), err
return string(body), nil
}

func buildCreateTokenUrlValues(params CreateTokenParams) url.Values {
Expand Down
2 changes: 1 addition & 1 deletion artifactory/services/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func (ss *SystemService) sendGet(endpoint string) ([]byte, error) {
httpDetails := (*ss.artDetails).CreateHttpClientDetails()
resp, body, _, err := ss.client.SendGet((*ss.artDetails).GetUrl()+apiSystem+endpoint, true, &httpDetails)
if err != nil {
return nil, err
return nil, fmt.Errorf("error occurred while attempting to get JFrog Artifactory %s: %s", endpoint, err.Error())
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK, http.StatusCreated); err != nil {
return nil, fmt.Errorf("got unexpected server response while attempting to get JFrog Artifactory %s:\n%s", endpoint, err.Error())
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ require (
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/gookit/color v1.5.4
github.com/jfrog/archiver/v3 v3.6.1
github.com/jfrog/build-info-go v1.9.33
github.com/jfrog/build-info-go v1.9.34
github.com/jfrog/gofrog v1.7.5
github.com/minio/sha256-simd v1.0.1
github.com/stretchr/testify v1.9.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOl
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jfrog/archiver/v3 v3.6.1 h1:LOxnkw9pOn45DzCbZNFV6K0+6dCsQ0L8mR3ZcujO5eI=
github.com/jfrog/archiver/v3 v3.6.1/go.mod h1:VgR+3WZS4N+i9FaDwLZbq+jeU4B4zctXL+gL4EMzfLw=
github.com/jfrog/build-info-go v1.9.33 h1:TEeTHDc3tEwZe/7kKhm1hQDd5vA/HnVhp1ZczUOWExk=
github.com/jfrog/build-info-go v1.9.33/go.mod h1:JTGnENexG1jRhKWCkQtZuDb0PerlzlSzF5OmMLG9kfc=
github.com/jfrog/build-info-go v1.9.34 h1:bPnW58VpclbpBe/x8XEu/2BIviEOoJrJ5PkRRcmU3Co=
github.com/jfrog/build-info-go v1.9.34/go.mod h1:6mdtqjREK76bHNODXakqKR/+ksJ9dvfLS7H57BZtnLY=
github.com/jfrog/gofrog v1.7.5 h1:dFgtEDefJdlq9cqTRoe09RLxS5Bxbe1Ev5+E6SmZHcg=
github.com/jfrog/gofrog v1.7.5/go.mod h1:jyGiCgiqSSR7k86hcUSu67XVvmvkkgWTmPsH25wI298=
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
Expand Down
7 changes: 2 additions & 5 deletions tests/artifactoryctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package tests

import (
"context"
"errors"
"testing"
"time"

Expand Down Expand Up @@ -40,8 +39,6 @@ func testCtxTimeout(t *testing.T) {
assert.NoError(t, err)
time.Sleep(time.Millisecond * 300)
_, err = sm.GetVersion()
assert.Error(t, err)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fail()
}
// Expect timeout error
assert.ErrorContains(t, err, context.DeadlineExceeded.Error())
}
11 changes: 9 additions & 2 deletions utils/io/fileutils/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"bytes"
"encoding/json"
"errors"
biutils "github.com/jfrog/build-info-go/utils"
"io"
"net/url"
"os"
Expand All @@ -14,6 +13,8 @@ import (
"reflect"
"strings"

biutils "github.com/jfrog/build-info-go/utils"

"github.com/jfrog/build-info-go/entities"
"github.com/jfrog/gofrog/crypto"
gofrog "github.com/jfrog/gofrog/io"
Expand All @@ -31,14 +32,20 @@ func GetFileSeparator() string {
return string(os.PathSeparator)
}

// Check if path exists.
// Checks if the path exists.
// If path points at a symlink and `preserveSymLink == true`,
// function will return `true` regardless of the symlink target
func IsPathExists(path string, preserveSymLink bool) bool {
_, err := GetFileInfo(path, preserveSymLink)
return !os.IsNotExist(err)
}

// Checks if the path is accessible.
func IsPathAccessible(path string) bool {
_, err := GetFileInfo(path, true)
return err == nil
}

// Check if path points at a file.
// If path points at a symlink and `preserveSymLink == true`,
// function will return `true` regardless of the symlink target
Expand Down
56 changes: 54 additions & 2 deletions utils/io/fileutils/files_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,70 @@
package fileutils

import (
biutils "github.com/jfrog/build-info-go/utils"
"github.com/jfrog/jfrog-client-go/utils/io"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"

biutils "github.com/jfrog/build-info-go/utils"
"github.com/jfrog/jfrog-client-go/utils/io"

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

func TestIsPathExistsAndIsPathAccessible(t *testing.T) {
var symlinkPath string
symlinkCreated := false

// Create a temporary file
tempFile, err := os.CreateTemp("", "testfile")
assert.NoError(t, err)

// Close the file immediately after creation to ensure it is not locked
assert.NoError(t, tempFile.Close())

defer func() {
// Remove the symlink before removing the file it references.
if symlinkCreated {
assert.NoError(t, os.Remove(symlinkPath))
}
assert.NoError(t, os.Remove(tempFile.Name()))
}()

// Test for an existing file
assert.True(t, IsPathExists(tempFile.Name(), false))
assert.True(t, IsPathAccessible(tempFile.Name()))

// Test for a non-existing file
assert.False(t, IsPathExists(tempFile.Name()+"_nonexistent", false))

// Create a temporary directory
tempDir := t.TempDir()

// Test for an existing directory
assert.True(t, IsPathExists(tempDir, false))
assert.True(t, IsPathAccessible(tempDir))

// Test for a non-existing directory
assert.False(t, IsPathExists(tempDir+"_nonexistent", false))
assert.False(t, IsPathAccessible(tempDir+"_nonexistent"))

// Create a symlink and test with preserveSymLink true and false
symlinkPath = tempFile.Name() + "_symlink"
err = os.Symlink(tempFile.Name(), symlinkPath)
assert.NoError(t, err)
// It is best to remove the symlink before removing the file it
// references. We use this variable to flag to the defer function
// to remove the symlink.
symlinkCreated = true

assert.True(t, IsPathExists(symlinkPath, true))
assert.True(t, IsPathExists(symlinkPath, false))
assert.True(t, IsPathAccessible(symlinkPath))
}

func TestIsSsh(t *testing.T) {
testRuns := []struct {
url string
Expand Down
2 changes: 1 addition & 1 deletion utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (
const (
Development = "development"
Agent = "jfrog-client-go"
Version = "1.44.1"
Version = "1.44.2"
)

type MinVersionProduct string
Expand Down
10 changes: 5 additions & 5 deletions utils/vcsdetails.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ func (vc *VcsCache) getCacheSize() int32 {
return atomic.LoadInt32(vc.vcsDirSize)
}

// Search for '.git' directory inside 'path', incase there is one, extract the details and add a new entry to the cache(key:path in the file system ,value: git revision & url).
// otherwise, search in the parent folder and try:
// 1. search for .git, and save the details for the current dir and all subpath
// Search for '.git' directory inside 'path'. In case there is one,
// extract the details and add a new entry to the cache(key:path in the file system ,value: git revision & url).
// Otherwise, move in the parent folder and do the following:
// 1. Search for .git, and save the details for the current dir and all subpath
// 2. .git not found, go to parent dir and repeat
// 3. not found on the root directory, add all subpath to cache with nil as a value
func (vc *VcsCache) GetVcsDetails(path string) (revision, refUrl, branch string, err error) {
Expand Down Expand Up @@ -91,8 +92,7 @@ func (vc *VcsCache) clearCacheIfExceedsMax() {
}

func tryGetGitDetails(path string) (string, string, string, error) {
exists := fileutils.IsPathExists(filepath.Join(path, ".git"), false)
if exists {
if fileutils.IsPathAccessible(filepath.Join(path, ".git")) {
return extractGitDetails(path)
}
return "", "", "", nil
Expand Down

0 comments on commit b485942

Please sign in to comment.