Skip to content
Open
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 CycloneDX/Interfaces/IProjectFileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@ public interface IProjectFileService
Task<HashSet<DotnetDependency>> RecursivelyGetProjectReferencesAsync(string projectFilePath);
Component GetComponent(DotnetDependency dotnetDependency);
bool IsTestProject(string projectFilePath);
string GetProjectVersion(string projectFilePath);
}
}
8 changes: 8 additions & 0 deletions CycloneDX/Runner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@ public async Task<int> HandleCommandAsync(RunOptions options)

};

if (string.IsNullOrEmpty(setVersion) && SolutionOrProjectFile.ToLowerInvariant().EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
{
var projectVersion = projectFileService.GetProjectVersion(fullSolutionOrProjectFilePath);
if (!string.IsNullOrEmpty(projectVersion))
{
topLevelComponent.Version = projectVersion;
}
}

if (options.includeProjectReferences
&&
Expand Down
36 changes: 36 additions & 0 deletions CycloneDX/Services/ProjectFileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,42 @@ static internal string GetProjectProperty(string projectFilePath, string baseInt

public bool DisablePackageRestore { get; set; }

/// <summary>
/// Extracts the version from a .csproj file.
/// </summary>
/// <param name="projectFilePath">The path to the .csproj file.</param>
/// <returns>The version string if found, otherwise null.</returns>
public string GetProjectVersion(string projectFilePath)
{
if (!_fileSystem.File.Exists(projectFilePath))
{
Console.Error.WriteLine($"Project file \"{projectFilePath}\" does not exist");
return null;
}

try
{
var projectContent = _fileSystem.File.ReadAllText(projectFilePath);
var versionMatch = Regex.Match(projectContent, "<Version>(.*?)</Version>", RegexOptions.IgnoreCase);
if (versionMatch.Success)
{
return versionMatch.Groups[1].Value;
}

var assemblyVersionMatch = Regex.Match(projectContent, "<AssemblyVersion>(.*?)</AssemblyVersion>", RegexOptions.IgnoreCase);
if (assemblyVersionMatch.Success)
{
return assemblyVersionMatch.Groups[1].Value;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error reading project file \"{projectFilePath}\": {ex.Message}");
}

return null;
}

/// <summary>
/// Analyzes a single Project file for NuGet package references.
/// </summary>
Expand Down