運行時獲取類庫信息
Intro
在我們向別的開源項目提 issue 的時候,可能經常會遇到別人會讓我們提供使用的版本信息,如果別的開源項目類庫集成了 source link,我們可以從程序集信息中獲取到版本以及對應的 commit 信息,這樣我們就可以直接找到對應版本的 commit 對應的代碼版本,這樣也就可以更加方便的了解對應源碼了
那我們是不是也可以在運行時獲取類庫的 commit 信息呢,答案是肯定的
Sample
我們集成了 source link 的話,在程序集信息中是可以獲取到 git 相關的信息, source link 的單步調試也是基于此來擴展的調試時下載對應源文件的
這里是我集成了 source link 的一個開源項目,反編譯 dll 的時候可以看到一些 git 相關的信息
AssemblyInfomationVersion
中的信息由兩部分組成,一部分是原始的 package 版本號,另外一部分是對應 commit hash,我們結合 RepositoryUrl
就可以很方便的找到對應的代碼了
RepositoryUrl
則是在一個 AssemblyMetadata
的 attribute 中
Implement
我們可以定義一個 model 來表示程序集的信息,這樣以后擴展起來也會更加的方便,示例如下:
public?class?LibraryInfo
{public?required?Version?LibraryVersion?{?get;?init;?}public?required?string?LibraryHash?{?get;?init;?}public?required?string?RepositoryUrl?{?get;?init;?}
}
然后通過反射從程序集中獲取程序集的信息
public?static?LibraryInfo?GetLibraryInfo(Assembly?assembly)
{Guard.NotNull(assembly);var?assemblyInformation?=?assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();var?repositoryUrl?=?assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(x?=>?nameof(LibraryInfo.RepositoryUrl).Equals(x.Key))?.Value????string.Empty;if?(assemblyInformation?is?not?null){var?informationalVersionSplit?=?assemblyInformation.InformationalVersion.Split('+');if?(Version.TryParse(informationalVersionSplit[0],?out?var?version)){return?new?LibraryInfo(){LibraryVersion?=?version,LibraryHash?=?informationalVersionSplit.Length?>?1???informationalVersionSplit[1]?:?string.Empty,RepositoryUrl?=?repositoryUrl};}}return?new?LibraryInfo(){LibraryVersion?=?assembly.GetName().Version!,LibraryHash?=?string.Empty,RepositoryUrl?=?repositoryUrl};
}
為了使用方便添加一個根據類型獲取的 overload
public?static?LibraryInfo?GetLibraryInfo(Type?type)?=>?GetLibraryInfo(Guard.NotNull(type).Assembly);
More
使用 dotnet-exec
?來測試一下
dotnet-exec?'ApplicationHelper.GetLibraryInfo(typeof(WeihanLi.Npoi.CsvHelper))'?--reference?"nuget:WeihanLi.Npoi,2.4.2"
從輸出結果我們可以看到我們已經拿到 commit hash 和 RepositoryUrl
信息了,對應的 Github commit 地址就是:https://github.com/WeihanLi/WeihanLi.Npoi/tree/8e2c1dee6efee9b7b4b12f16272f266c9ad09233
最后還是建議大家在自己開源類庫項目中集成 source link,不僅方便調試,還可以比較方便準確的獲取對應版本的 commit 信息,這樣別人使用遇到問題的話也會比較方便的進行 debug 和查找源代碼
References
https://github.com/dotnet/sourcelink
https://github.com/WeihanLi/WeihanLi.Common/blob/1.0.58/src/WeihanLi.Common/Helpers/ApplicationHelper.cs