Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
a57aabf
Copied initial files over and addressred some PR comments
jgonz120 Dec 20, 2023
05ed3db
Test updates
jgonz120 Dec 21, 2023
c285f0f
optimized string split
jgonz120 Dec 21, 2023
c06e3f5
cleanup
jgonz120 Dec 21, 2023
ef90a51
switch to stream
jgonz120 Dec 21, 2023
4c31cbf
fix typo
jgonz120 Dec 21, 2023
b787826
fix typo
jgonz120 Dec 21, 2023
c627b25
create static json reader state
jgonz120 Dec 21, 2023
ef35381
typo
jgonz120 Dec 21, 2023
084986d
typo
jgonz120 Dec 21, 2023
5850754
added lazy string split
jgonz120 Dec 22, 2023
014739f
using
jgonz120 Dec 22, 2023
d28a482
Update unit tests
jgonz120 Dec 22, 2023
c9cb53f
unit tests
jgonz120 Dec 22, 2023
d083e23
fix references
jgonz120 Dec 22, 2023
0b22126
Fix typo
jgonz120 Dec 22, 2023
e81974f
Added test for invalid logs
jgonz120 Jan 4, 2024
d2cc5d6
removed extra name assignment from package spec reader
jgonz120 Jan 4, 2024
2de68c4
use array empty
jgonz120 Jan 4, 2024
79e2b71
move public method up
jgonz120 Jan 4, 2024
ccd6fe1
remove uneeded string list
jgonz120 Jan 4, 2024
8d719c6
use false string
jgonz120 Jan 4, 2024
212b7bd
add is final block to test
jgonz120 Jan 4, 2024
b5a82d7
rename test
jgonz120 Jan 4, 2024
82363ee
style
jgonz120 Jan 4, 2024
0cc4e51
style
jgonz120 Jan 4, 2024
c525dc8
add tests for validating empty streams on creationg of utf8jsonstream…
jgonz120 Jan 4, 2024
4e5112a
Added test and implemented string split in two
jgonz120 Jan 5, 2024
2398980
fix validation for lazy string split
jgonz120 Jan 8, 2024
1693913
reduce methods in LikeFileFormat
jgonz120 Jan 8, 2024
e0ef66d
set the list values with the results directly
jgonz120 Jan 8, 2024
b4d0169
store environment variable to avoid calling GetEnvironmentVariable se…
jgonz120 Jan 8, 2024
f060670
switch to splitintwo
jgonz120 Jan 9, 2024
4602b44
Update conditional for framework
jgonz120 Jan 9, 2024
a240062
Caching the parsed NugetVersion and VersionRange objects.
jgonz120 Jan 11, 2024
0883567
Fixes from PR
jgonz120 Jan 11, 2024
c4adaf7
Avoid creating empty lists
jgonz120 Jan 11, 2024
bda30bb
Revert "Caching the parsed NugetVersion and VersionRange objects."
jgonz120 Jan 17, 2024
fb7ebd5
Fix netwonsoft json parsing
jgonz120 Jan 17, 2024
32aba9a
Add missing reference
jgonz120 Jan 17, 2024
8853734
added some examples of the json to be parsed
jgonz120 Jan 17, 2024
1b29455
Fix references in comments
jgonz120 Jan 17, 2024
1877448
Fixes from PR
jgonz120 Jan 22, 2024
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
6 changes: 6 additions & 0 deletions src/NuGet.Core/NuGet.ProjectModel/JsonUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ internal static JObject LoadJson(TextReader reader)
}
}

internal static T LoadJson<T>(Stream stream, IUtf8JsonStreamReaderConverter<T> converter)
{
var streamingJsonReader = new Utf8JsonStreamReader(stream);
return converter.Read(ref streamingJsonReader);
}

internal static PackageDependency ReadPackageDependency(string property, JToken json)
{
var versionStr = json.Value<string>();
Expand Down
138 changes: 138 additions & 0 deletions src/NuGet.Core/NuGet.ProjectModel/LazyStringSplit.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace NuGet.ProjectModel
{
/// <summary>
/// Splits a string by a delimiter, producing substrings lazily during enumeration.
/// Skips empty items, behaving equivalently to <see cref="string.Split(char[])"/> with
/// <see cref="StringSplitOptions.RemoveEmptyEntries"/>.
/// </summary>
/// <remarks>
/// Unlike <see cref="string.Split(char[])"/> and overloads, <see cref="LazyStringSplit"/>
/// does not allocate an array for the return, and allocates strings on demand during
/// enumeration. A custom enumerator type is used so that the only allocations made are
/// the substrings themselves. We also avoid the large internal arrays assigned by the
/// methods on <see cref="string"/>.
/// </remarks>
internal readonly struct LazyStringSplit : IEnumerable<string>
{
private readonly string _input;
private readonly char _delimiter;

public LazyStringSplit(string input, char delimiter)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException(nameof(input));
}

_input = input;
_delimiter = delimiter;
}

public Enumerator GetEnumerator() => new(this);

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

IEnumerator<string> IEnumerable<string>.GetEnumerator() => GetEnumerator();

public IEnumerable<T> Select<T>(Func<string, T> func)
{
foreach (string value in this)
{
yield return func(value);
}
}

public string First()
{
return FirstOrDefault() ?? throw new InvalidOperationException("Sequence is empty.");
}

public string? FirstOrDefault()
{
var enumerator = new Enumerator(this);
return enumerator.MoveNext() ? enumerator.Current : null;
}

public struct Enumerator : IEnumerator<string>
{
private readonly string _input;
private readonly char _delimiter;
private int _index;

internal Enumerator(in LazyStringSplit split)
{
_index = 0;
_input = split._input;
_delimiter = split._delimiter;
Current = null!;
}

public string Current { get; private set; }

public bool MoveNext()
{
while (_index != _input.Length)
{
int delimiterIndex = _input.IndexOf(_delimiter, _index);

if (delimiterIndex == -1)
{
Current = _input.Substring(_index);
_index = _input.Length;
return true;
}

int length = delimiterIndex - _index;

if (length == 0)
{
_index++;
continue;
}

Current = _input.Substring(_index, length);
_index = delimiterIndex + 1;
return true;
}

return false;
}

object IEnumerator.Current => Current;

void IEnumerator.Reset()
{
_index = 0;
Current = null!;
}

void IDisposable.Dispose() { }
}
}

internal static class LazyStringSplitExtensions
{
/// <remarks>
/// This extension method has special knowledge of the <see cref="LazyStringSplit"/> type and
/// can compute its result without allocation.
/// </remarks>
/// <inheritdoc cref="Enumerable.FirstOrDefault{TSource}(IEnumerable{TSource})"/>
public static string? FirstOrDefault(this LazyStringSplit lazyStringSplit)
{
LazyStringSplit.Enumerator enumerator = lazyStringSplit.GetEnumerator();

return enumerator.MoveNext()
? enumerator.Current
: null;
}
}
}
73 changes: 63 additions & 10 deletions src/NuGet.Core/NuGet.ProjectModel/LockFile/LockFileFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Common;
Expand Down Expand Up @@ -60,11 +61,10 @@ public LockFile Parse(string lockFileContent, string path)

public LockFile Parse(string lockFileContent, ILogger log, string path)
{
using (var reader = new StringReader(lockFileContent))
byte[] byteArray = Encoding.UTF8.GetBytes(lockFileContent);
using (var stream = new MemoryStream(byteArray))
{
#pragma warning disable CS0612 // Type or member is obsolete
return Read(reader, log, path);
#pragma warning restore CS0612 // Type or member is obsolete
return Read(stream, log, path);
}
}

Expand All @@ -88,21 +88,51 @@ public LockFile Read(Stream stream, string path)

public LockFile Read(Stream stream, ILogger log, string path)
{
using (var textReader = new StreamReader(stream))
return Read(stream, log, path, EnvironmentVariableWrapper.Instance);
}

internal LockFile Read(string filePath, IEnvironmentVariableReader environmentVariableReader)
{
using (var stream = File.OpenRead(filePath))
{
#pragma warning disable CS0612 // Type or member is obsolete
return Read(textReader, log, path);
#pragma warning restore CS0612 // Type or member is obsolete
return Read(stream, NullLogger.Instance, filePath, environmentVariableReader);
}
}

[Obsolete]
internal LockFile Parse(string lockFileContent, string path, IEnvironmentVariableReader environmentVariableReader)
{
byte[] byteArray = Encoding.UTF8.GetBytes(lockFileContent);
using (var stream = new MemoryStream(byteArray))
{
return Read(stream, NullLogger.Instance, path, environmentVariableReader);
}
}

internal LockFile Read(Stream stream, ILogger log, string path, IEnvironmentVariableReader environmentVariableReader)
{
var useNj = environmentVariableReader.GetEnvironmentVariable("NUGET_EXPERIMENTAL_USE_NJ_FOR_FILE_PARSING");
if (string.IsNullOrEmpty(useNj) || useNj.Equals("false", StringComparison.OrdinalIgnoreCase))
{
return Utf8JsonRead(stream, log, path);
}
else
{
using (var reader = new StreamReader(stream))
{
#pragma warning disable CS0618 // Type or member is obsolete
return Read(reader, log, path);
#pragma warning restore CS0618 // Type or member is obsolete
}
}
}

[Obsolete("This method is deprecated. Use Read(Stream, string) instead.")]
public LockFile Read(TextReader reader, string path)
{
return Read(reader, NullLogger.Instance, path);
}

[Obsolete]
[Obsolete("This method is deprecated. Use Read(Stream, ILogger, string) instead.")]
public LockFile Read(TextReader reader, ILogger log, string path)
{
try
Expand Down Expand Up @@ -167,6 +197,29 @@ public string Render(LockFile lockFile)
}
}

private LockFile Utf8JsonRead(Stream stream, ILogger log, string path)
{
try
{
var lockFile = JsonUtility.LoadJson<LockFile>(stream, Utf8JsonReaderExtensions.LockFileConverter);
lockFile.Path = path;
return lockFile;
}
catch (Exception ex)
{
log.LogInformation(string.Format(CultureInfo.CurrentCulture,
Strings.Log_ErrorReadingLockFile,
path, ex.Message));

// Ran into parsing errors, mark it as unlocked and out-of-date
return new LockFile
{
Version = int.MinValue,
Path = path
};
}
}

[Obsolete]
private static LockFile ReadLockFile(JObject cursor, string path)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using NuGet.Common;

namespace NuGet.ProjectModel
{
/// <summary>
/// A <see cref="JsonStreamReaderConverter{T}"/> to allow read JSON into <see cref="AssetsLogMessage"/>
/// </summary>
internal class Utf8JsonStreamAssetsLogMessageConverter : IUtf8JsonStreamReaderConverter<AssetsLogMessage>
{
private static readonly byte[] LevelPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.LEVEL);
private static readonly byte[] CodePropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.CODE);
private static readonly byte[] WarningLevelPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.WARNING_LEVEL);
private static readonly byte[] FilePathPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.FILE_PATH);
private static readonly byte[] StartLineNumberPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.START_LINE_NUMBER);
private static readonly byte[] StartColumnNumberPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.START_COLUMN_NUMBER);
private static readonly byte[] EndLineNumberPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.END_LINE_NUMBER);
private static readonly byte[] EndColumnNumberPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.END_COLUMN_NUMBER);
private static readonly byte[] MessagePropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.MESSAGE);
private static readonly byte[] LibraryIdPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.LIBRARY_ID);
private static readonly byte[] TargetGraphsPropertyName = Encoding.UTF8.GetBytes(LogMessageProperties.TARGET_GRAPHS);

public AssetsLogMessage Read(ref Utf8JsonStreamReader reader)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException("Expected StartObject, found " + reader.TokenType);
}

var isValid = true;
LogLevel level = default;
NuGetLogCode code = default;
//matching default warning level when AssetLogMessage object is created
WarningLevel warningLevel = WarningLevel.Severe;
string message = default;
string filePath = default;
int startLineNumber = default;
int startColNumber = default;
int endLineNumber = default;
int endColNumber = default;
string libraryId = default;
IReadOnlyList<string> targetGraphs = null;

while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
{
if (!isValid)
{
reader.Skip();
}
if (reader.ValueTextEquals(LevelPropertyName))
{
var levelString = reader.ReadNextTokenAsString();
isValid &= Enum.TryParse(levelString, out level);
}
else if (reader.ValueTextEquals(CodePropertyName))
{
var codeString = reader.ReadNextTokenAsString();
isValid &= Enum.TryParse(codeString, out code);
}
else if (reader.ValueTextEquals(WarningLevelPropertyName))
{
reader.Read();
warningLevel = (WarningLevel)Enum.ToObject(typeof(WarningLevel), reader.GetInt32());
}
else if (reader.ValueTextEquals(FilePathPropertyName))
{
filePath = reader.ReadNextTokenAsString();
}
else if (reader.ValueTextEquals(StartLineNumberPropertyName))
{
reader.Read();
startLineNumber = reader.GetInt32();
}
else if (reader.ValueTextEquals(StartColumnNumberPropertyName))
{
reader.Read();
startColNumber = reader.GetInt32();
}
else if (reader.ValueTextEquals(EndLineNumberPropertyName))
{
reader.Read();
endLineNumber = reader.GetInt32();
}
else if (reader.ValueTextEquals(EndColumnNumberPropertyName))
{
reader.Read();
endColNumber = reader.GetInt32();
}
else if (reader.ValueTextEquals(MessagePropertyName))
{
message = reader.ReadNextTokenAsString();
}
else if (reader.ValueTextEquals(LibraryIdPropertyName))
{
libraryId = reader.ReadNextTokenAsString();
}
else if (reader.ValueTextEquals(TargetGraphsPropertyName))
{
reader.Read();
targetGraphs = (List<string>)reader.ReadStringArrayAsIList();
}
else
{
reader.Skip();
}
}
if (isValid)
{
var assetLogMessage = new AssetsLogMessage(level, code, message)
{
TargetGraphs = targetGraphs ?? Array.Empty<string>(),
FilePath = filePath,
EndColumnNumber = endColNumber,
EndLineNumber = endLineNumber,
LibraryId = libraryId,
StartColumnNumber = startColNumber,
StartLineNumber = startLineNumber,
WarningLevel = warningLevel
};
return assetLogMessage;
}
return null;
}
}
}
Loading