Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove some redundant variable assignments #6184

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public NuGetProject TryCreateNuGetProject(
// Treat projects with project.json as build integrated projects
// Search for projectName.project.json first, then project.json
// If the name cannot be determined, search only for project.json
string projectJsonPath = null;
string projectJsonPath;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd feel more strongly about accepting this PR if it was coupled with a rule change as well: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0059.

if (string.IsNullOrEmpty(projectNameFromMSBuildPath))
{
projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,6 @@ internal static PackageIdentity UpdateResolvedVersion(LibraryDependency projectL
/// <param name="transitivePackages">Cached transitive package information</param>
internal static IReadOnlyList<PackageIdentity> UpdateTransitiveDependencies(IList<LockFileTargetLibrary> libraries, Dictionary<string, ProjectInstalledPackage> installedPackages, Dictionary<string, ProjectInstalledPackage> transitivePackages)
{
NuGetVersion resolvedVersion = default;

var packageIdentities = new List<PackageIdentity>();

// get the dependencies for this target framework
Expand All @@ -80,7 +78,7 @@ internal static IReadOnlyList<PackageIdentity> UpdateTransitiveDependencies(ILis
// don't add transitive packages if they are not packages
if (!installedPackages.ContainsKey(package.Name) && package.Type == LibraryType.Package.Value)
{
resolvedVersion = package.Version ?? new NuGetVersion(0, 0, 0);
NuGetVersion resolvedVersion = package.Version ?? new NuGetVersion(0, 0, 0);

var packageIdentity = new PackageIdentity(package.Name, resolvedVersion);
transitivePackages[package.Name] = new ProjectInstalledPackage(new VersionRange(package.Version), packageIdentity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ internal static string GetBinaryLoggerParameters(IEnvironmentVariableReader envi
}

// Default parameters
return binaryLoggerParameters = "LogFile=nuget.binlog";
return "LogFile=nuget.binlog";
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task<int> ExecuteCommand(PackageReferenceArgs packageReferenceArgs,
packageReferenceArgs.Logger.LogWarning(string.Format(CultureInfo.CurrentCulture,
Strings.Warn_AddPkgWithoutRestore));

VersionRange versionRange = default;
VersionRange versionRange;
if (packageReferenceArgs.NoVersion)
{
versionRange = packageReferenceArgs.Prerelease ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ internal static IEnumerable<FormattedCell> ToFormattedStringTable<T>(
var subsequentRow = new List<FormattedCell>();
for (var colIndex = 0; colIndex < valueSelectors.Length; colIndex++)
{
var formattedDataCell = (FormattedCell)null;
FormattedCell formattedDataCell;
if (columnQueues.TryGetValue(colIndex, out var thisColumnQueue)) // we have at least one remaining value for this column
{
formattedDataCell = thisColumnQueue.Dequeue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -490,8 +490,8 @@ private async Task<IEnumerable<RestoreTargetGraph>> GenerateRestoreGraphsAsync(T
CacheFile cacheFile,
CancellationToken token)
{
string assetFilePath = null;
string cacheFilePath = null;
string assetFilePath;
string cacheFilePath;
var msbuildOutputFiles = Enumerable.Empty<MSBuildOutputFile>();

using (telemetry.StartIndependentInterval(CreateRestoreResultDuration))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,24 +74,21 @@ public static List<MSBuildOutputFile> GenerateMultiTargetFailureFiles(
string propsPath,
ProjectStyle restoreType)
{
XDocument targetsXML = null;
XDocument propsXML = null;

// Create an error file for MSBuild to stop the build.
targetsXML = GenerateMultiTargetFrameworkWarning();
XDocument targetsXML = GenerateMultiTargetFrameworkWarning();

if (restoreType == ProjectStyle.PackageReference)
{
propsXML = GenerateEmptyImportsFile();
}

var files = new List<MSBuildOutputFile>()
return new List<MSBuildOutputFile>()
{
new MSBuildOutputFile(propsPath, propsXML),
new MSBuildOutputFile(targetsPath, targetsXML),
};

return files;
}

private static string ReplacePathsWithMacros(string path, IEnvironmentVariableReader environmentVariableReader)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -969,20 +969,15 @@ private static bool IsType(this IMSBuildItem item, string type)
private static NuGetVersion GetVersion(IMSBuildItem item)
{
var versionString = item.GetProperty("Version");
NuGetVersion version = null;

if (string.IsNullOrEmpty(versionString))
{
// Default to 1.0.0 if the property does not exist
version = new NuGetVersion(1, 0, 0);
}
else
{
// Snapshot versions are not allowed in .NETCore
version = NuGetVersion.Parse(versionString);
return new NuGetVersion(1, 0, 0);
}

return version;
// Snapshot versions are not allowed in .NETCore
return NuGetVersion.Parse(versionString);
}

public static void Dump(IEnumerable<IMSBuildItem> items, ILogger log)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public static void LogFetchMessages(

foreach (var fetchResult in preFetchTasks)
{
string message = null;
string message;

if (fetchResult.InPackagesFolder)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -654,8 +654,7 @@ public async Task<IReadOnlyList<PackageSpec>> GetPackageSpecsAsync(DependencyGra
return (new List<PackageSpec>(), null);
}

PackageSpec packageSpec = null;
if (!context.PackageSpecCache.TryGetValue(ProjectSystem.ProjectFileFullPath, out packageSpec))
if (!context.PackageSpecCache.TryGetValue(ProjectSystem.ProjectFileFullPath, out var packageSpec))
{
packageSpec = new PackageSpec(new List<TargetFrameworkInformation>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public static class JsonConfigUtility
/// </summary>
public static IEnumerable<PackageDependency> GetDependencies(JObject json)
{
JToken node = null;
if (json.TryGetValue(DEPENDENCIES_TAG, out node))
if (json.TryGetValue(DEPENDENCIES_TAG, out var node))
{
foreach (var dependency in node)
{
Expand Down Expand Up @@ -96,8 +95,7 @@ public static void AddDependency(JObject json, PackageDependency dependency)

JObject dependencySet = null;

JToken node = null;
if (json.TryGetValue(DEPENDENCIES_TAG, out node))
if (json.TryGetValue(DEPENDENCIES_TAG, out var node))
{
dependencySet = node as JObject;
}
Expand All @@ -121,8 +119,7 @@ public static void AddDependency(JObject json, PackageDependency dependency)
/// </summary>
public static void RemoveDependency(JObject json, string packageId)
{
JToken node = null;
if (json.TryGetValue(DEPENDENCIES_TAG, out node))
if (json.TryGetValue(DEPENDENCIES_TAG, out var node))
{
foreach (var dependency in node.ToArray())
{
Expand All @@ -142,8 +139,7 @@ public static IEnumerable<NuGetFramework> GetFrameworks(JObject json)
{
var results = new List<NuGetFramework>();

JToken node = null;
if (json.TryGetValue(FRAMEWORKS_TAG, out node))
if (json.TryGetValue(FRAMEWORKS_TAG, out var node))
{
foreach (var frameworkNode in node.ToArray())
{
Expand Down Expand Up @@ -172,8 +168,7 @@ public static void AddFramework(JObject json, NuGetFramework framework)

JObject frameworkSet = null;

JToken node = null;
if (json.TryGetValue(FRAMEWORKS_TAG, out node))
if (json.TryGetValue(FRAMEWORKS_TAG, out var node))
{
frameworkSet = node as JObject;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public static bool ContentEquals(Stream stream, Stream otherStream)
public static bool IsBinary(Stream stream)
{
// Quick and dirty trick to check if a stream represents binary content.
// We read the first 30 bytes. If there's a character 0 in those bytes,
// we assume this is a binary file.
// We read the first 30 bytes. If there's a character 0 in those bytes,
// we assume this is a binary file.
var a = new byte[30];
var bytesRead = stream.Read(a, 0, 30);
var byteZeroIndex = Array.FindIndex(a, 0, bytesRead, d => d == 0);
Expand Down Expand Up @@ -104,7 +104,7 @@ private static bool CompareBinary(Stream stream, Stream otherStream)
var buffer = new byte[4 * 1024];
var otherBuffer = new byte[4 * 1024];

var bytesRead = 0;
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
Expand Down
11 changes: 4 additions & 7 deletions src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public IEnumerable<PackageReference> GetPackages()
/// <summary>
/// Reads all package node entries in the config.
/// </summary>
/// <param name="allowDuplicatePackageIds">If True validation will be performed to ensure that
/// <param name="allowDuplicatePackageIds">If True validation will be performed to ensure that
/// only one entry exists for each unique package id.</param>
public IEnumerable<PackageReference> GetPackages(bool allowDuplicatePackageIds)
{
Expand All @@ -151,8 +151,7 @@ public IEnumerable<PackageReference> GetPackages(bool allowDuplicatePackageIds)
Strings.ErrorNullOrEmptyPackageId));
}

string version = null;
if (!PackagesConfig.TryGetAttribute(package, PackagesConfig.VersionAttributeName, out version)
if (!PackagesConfig.TryGetAttribute(package, PackagesConfig.VersionAttributeName, out var version)
|| String.IsNullOrEmpty(version))
{
throw new PackagesConfigReaderException(string.Format(
Expand All @@ -162,8 +161,7 @@ public IEnumerable<PackageReference> GetPackages(bool allowDuplicatePackageIds)
version));
}

NuGetVersion semver = null;
if (!NuGetVersion.TryParse(version, out semver))
if (!NuGetVersion.TryParse(version, out var semver))
{
throw new PackagesConfigReaderException(string.Format(
CultureInfo.CurrentCulture,
Expand All @@ -172,9 +170,8 @@ public IEnumerable<PackageReference> GetPackages(bool allowDuplicatePackageIds)
version));
}

string attributeValue = null;
VersionRange allowedVersions = null;
if (PackagesConfig.TryGetAttribute(package, PackagesConfig.allowedVersionsAttributeName, out attributeValue))
if (PackagesConfig.TryGetAttribute(package, PackagesConfig.allowedVersionsAttributeName, out var attributeValue))
{
if (!VersionRange.TryParse(attributeValue, out allowedVersions))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ private void FillBuffer()
_stream.Position = _bufferStartPosition;

var totalBytesRead = 0;
var bytesRead = 0;
int bytesRead;
var offset = 0;
var count = _buffer.Length;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,23 @@ public static IRfc3161TimestampRequest Create(
throw new ArgumentNullException(nameof(messageHash));
}

IRfc3161TimestampRequest iRfc3161TimestampRequest = null;
#if IS_DESKTOP
iRfc3161TimestampRequest = new Rfc3161TimestampRequestNet472Wrapper(
return new Rfc3161TimestampRequestNet472Wrapper(
messageHash,
hashAlgorithm,
requestedPolicyId,
nonce,
requestSignerCertificates,
extensions);
#else
iRfc3161TimestampRequest = new Rfc3161TimestampRequestNetstandard21Wrapper(
return new Rfc3161TimestampRequestNetstandard21Wrapper(
messageHash,
hashAlgorithm,
requestedPolicyId,
nonce,
requestSignerCertificates,
extensions);
#endif
return iRfc3161TimestampRequest;

}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ public PackageSignatureVerifier(IEnumerable<ISignatureVerificationProvider> veri
throw new ArgumentNullException(nameof(settings));
}

var valid = false;
var trustResults = new List<PackageVerificationResult>();

var packageSigningTelemetryEvent = new PackageSigningTelemetryEvent();
using (var telemetry = TelemetryActivity.Create(parentId, packageSigningTelemetryEvent))
{
var isSigned = await package.IsSignedAsync(token);
bool valid;
if (isSigned)
{
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1965,7 +1965,7 @@ private static void ReadTargetFrameworks(PackageSpec packageSpec, JsonTextReader
[Obsolete]
private static void AddTargetFramework(PackageSpec packageSpec, NuGetFramework frameworkName, NuGetFramework secondaryFramework, TargetFrameworkInformation targetFrameworkInformation)
{
NuGetFramework updatedFramework = frameworkName;
NuGetFramework updatedFramework;

if (targetFrameworkInformation.Imports.Length > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public static LockFileValidationResult IsLockFileValid(DependencyGraphSpec dgSpe

if (p2pSpec != null)
{
TargetFrameworkInformation p2pSpecTargetFrameworkInformation = default;
TargetFrameworkInformation p2pSpecTargetFrameworkInformation;
if (p2pSpec.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig || p2pSpec.RestoreMetadata.ProjectStyle == ProjectStyle.Unknown)
{
// Skip compat check and dependency check for non PR projects.
Expand All @@ -248,7 +248,7 @@ public static LockFileValidationResult IsLockFileValid(DependencyGraphSpec dgSpe

if (hasChanged)
{
// P2P transitive package dependencies have changed
// P2P transitive package dependencies have changed
invalidReasons.Add(message);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@ public ODataServiceDocumentResourceV2Provider()
public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
{
ODataServiceDocumentResourceV2 serviceDocument = null;
ODataServiceDocumentCacheInfo cacheInfo = null;
var url = source.PackageSource.Source;

var utcNow = DateTime.UtcNow;
var entryValidCutoff = utcNow.Subtract(MaxCacheDuration);

// check the cache before downloading the file
if (!_cache.TryGetValue(url, out cacheInfo) || entryValidCutoff > cacheInfo.CachedTime)
if (!_cache.TryGetValue(url, out var cacheInfo) || entryValidCutoff > cacheInfo.CachedTime)
{
// Track if the semaphore needs to be released
var release = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,24 +177,16 @@ private static bool IsAllowedLibraryFile(string path)
/// </summary>
private static NuspecReader GetNuspec(string manifestPath, string expandedPath)
{
NuspecReader nuspec = null;

// Verify that the nuspec has the correct name before opening it
if (File.Exists(manifestPath))
{
nuspec = new NuspecReader(File.OpenRead(manifestPath));
}
else
{
// Scan the folder for the nuspec
using (var folderReader = new PackageFolderReader(expandedPath))
{
// This will throw if the nuspec is not found
nuspec = new NuspecReader(folderReader.GetNuspec());
}
return new NuspecReader(File.OpenRead(manifestPath));
}

return nuspec;
// Scan the folder for the nuspec
using var folderReader = new PackageFolderReader(expandedPath);
// This will throw if the nuspec is not found
return new NuspecReader(folderReader.GetNuspec());
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,11 @@ public static LocalPackageSourceInfo GetPackage(
string id,
NuGetVersion version)
{
LocalPackageInfo package = null;

for (var i = 0; i < repositories.Count; i++)
{
var repository = repositories[i];

package = repository.FindPackage(id, version);
LocalPackageInfo package = repository.FindPackage(id, version);

if (package != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public async Task HandleResponseAsync(
var requestPayload = MessageUtilities.DeserializePayload<GetCredentialsRequest>(request);
var packageSource = GetPackageSource(requestPayload.PackageSourceRepository);

GetCredentialsResponse responsePayload = null;
GetCredentialsResponse responsePayload;

if (packageSource.IsHttp &&
string.Equals(
Expand Down
Loading
Loading