Skip to content
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
19 changes: 19 additions & 0 deletions toolkit/tools/internal/rpm/rpm.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,25 @@ func SetMacroDir(newMacroDir string) (origenv []string, err error) {
return
}

// ExtractNameFromRPMPath strips the version from an RPM file name. i.e. pkg-name-1.2.3-4.cm2.x86_64.rpm -> pkg-name
func ExtractNameFromRPMPath(rpmFilePath string) (packageName string, err error) {
baseName := filepath.Base(rpmFilePath)

// If the path is invalid, return empty string. We consider any string that has at least 1 '-' characters valid.
if !strings.Contains(baseName, "-") {
err = fmt.Errorf("invalid RPM file path '%s', can't extract name", rpmFilePath)
return
}

rpmFileSplit := strings.Split(baseName, "-")
packageName = strings.Join(rpmFileSplit[:len(rpmFileSplit)-2], "-")
if packageName == "" {
err = fmt.Errorf("invalid RPM file path '%s', can't extract name", rpmFilePath)
return
}
return
}

// getCommonBuildArgs will generate arguments to pass to 'rpmbuild'.
func getCommonBuildArgs(outArch, srpmFile string, defines map[string]string) (buildArgs []string, err error) {
const (
Expand Down
48 changes: 48 additions & 0 deletions toolkit/tools/internal/rpm/rpm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,51 @@ func TestShouldNotFindCheckSectionInSpecWithoutCheckSection(t *testing.T) {
assert.NoError(t, err)
assert.False(t, hasCheckSection)
}

func TestExtractNameFromRPMPath(t *testing.T) {
tests := []struct {
name string
rpmFile string
expected string
err error
}{
{
name: "valid rpm file",
rpmFile: "/path/to/pkg-1.0.0-1.noarch.rpm",
expected: "pkg",
err: nil,
},
{
name: "valid rpm file with complex name",
rpmFile: "/path/to/pkg-name-1.0.0-1.noarch.rpm",
expected: "pkg-name",
err: nil,
},
{
name: "invalid rpm file",
rpmFile: "/path/to/garbage.rpm",
expected: "",
err: fmt.Errorf("invalid RPM file path '%s', can't extract name", "/path/to/garbage.rpm"),
},
{
name: "empty rpm file",
rpmFile: "",
expected: "",
err: fmt.Errorf("invalid RPM file path '%s', can't extract name", ""),
},
{
name: "just a hyphen",
rpmFile: "-",
expected: "",
err: fmt.Errorf("invalid RPM file path '%s', can't extract name", "-"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual, err := ExtractNameFromRPMPath(tt.rpmFile)
assert.Equal(t, tt.err, err)
assert.Equal(t, tt.expected, actual)
})
}
}