Skip to content

Refactored NuGet.Configuration - #2370

Merged
PatoBeltran merged 22 commits into
devfrom
dev-pato-refactor-config
Sep 18, 2018
Merged

PatoBeltran merged 22 commits into
devfrom
dev-pato-refactor-config

Conversation

@PatoBeltran

@PatoBeltran PatoBeltran commented Jul 30, 2018 •

Copy link
Copy Markdown
Contributor

Improved API for parsing nuget.config by creating an object model that is easily extensible and updated current API usage to conform with the new usage patterns.

Previously, the nuget.config logic was centered around Settings.cs, which was in charge of loading all nuget.configs, figuring out how to merge them and giving an API to the user to interact with the content of the config files. Because of this, the usage was limited for interacting with nuget.config. The API was too specific for parsing only a few elements and enabling new elements was difficult because this meant adding a bunch of APIs specific for any new element.

This PR adds an abstraction of a single nuget.config file (SettingsFile.cs), with its own abstraction of its content (NugetConfiguration.cs), making it easy to parse and add new elements. Then the Settings object is only in charge of finding and loading every single config file and merging their settings together. The settings file give the user a way to interact with the computed values, instead of with the values from the config files directly.

The users of the APIs were also updated to follow the new pattern. PackageSourceProvider was the one with the heaviest usage of the API and was rewritten to follow the principles of the new API.

Given that this is a big PR, here are the most important files, be sure to pay special attention to all of the files in this list, most of the changes in other files are just updates to use the new API instead of the old one:

Setting file parsing

SettingBase.cs
SettingText.cs
SettingElement.cs
ISettingsGroup.cs
SettingsGroup.cs
NuGetConfiguration.cs
SettingSection.cs
ParsedSettingSection.cs
MergedSettingSection.cs
SettingItem.cs
AddItem.cs
ClearItem.cs
CredentialsItem.cs
SourceItem.cs
UnknownItem.cs

SettingFactory.cs

Settings API

ISettings.cs
Settings.cs
SettingsFile.cs
SettingsUtility.cs

Important changes in the way it uses the settings API

IPackageSourceProvider.cs
PackageSourceProvider.cs

Tests: Settings File Parsing

SettingsFileParsingTests/SettingsFileTests.cs
SettingsFileParsingTests/NuGetConfigurationTests.cs
SettingsFileParsingTests/SettingSectionTests.cs
SettingsFileParsingTests/AddItemTests.cs
SettingsFileParsingTests/SourceItemTests.cs
SettingsFileParsingTests/ClearItemTests.cs
SettingsFileParsingTests/CredentialsItemTests.cs

Tests: Settings API

SettingsTests.cs
SettingsUtilityTests.cs

Tests: Important changes in the way it uses the settings API

PackageSourceProviderTests.cs

@PatoBeltran PatoBeltran self-assigned this Jul 30, 2018
@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch from 824fcdd to 2702296 Compare July 31, 2018 00:09
@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch 3 times, most recently from c430883 to fc2dcfa Compare August 1, 2018 23:24
@PatoBeltran PatoBeltran changed the title WIP: Refactored NuGet.Configuration Refactored NuGet.Configuration Aug 1, 2018
@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch 4 times, most recently from bff7188 to 42acc11 Compare August 2, 2018 22:59
namespace NuGet.Configuration
{
// This could also be an abstract generic class where T is a settingsItem if we wanted to constraint each section to an specific type of item
public sealed class SettingsSection : SettingsCollection<SettingsItem>, IEquatable<SettingsSection>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Currently, this class is a generic Section class for all sections... This class could be made abstract and extend a class for each of the currently known and used sections, that way we could specify rules for each of the sections (for example, let packageSources be cleared but not config). @NuGet/nuget-client do you think this is worth it? or should we just keep it as a general Section element?

@zhili1208

Copy link
Copy Markdown
Contributor

looks like ISettings API is totally changed, I believe lots of tools which are using nuget library depends on that API. two questions here 1. do we have to totally change the interface? 2. If we have to do that, do we have any plan which can make user migrate their code to new nuget version easily?

@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch from 7d611b7 to 613826b Compare August 8, 2018 18:52
@PatoBeltran

Copy link
Copy Markdown
Contributor Author

@zhili1208 I added back the old API in ISettings and marked them as obsolete. The only three things that I removed from ISettings where Priority, Root and Filename. Root and Filename do not make sense to be part of ISettings since ISettings refers to a collection of computed config files, not just one. And Priority seems to be something that should not be public in the Settings implementation. In SettingsUtility there are methods to get the roots and file paths of all the configs used in a given ISettings object. Do you think this is an acceptable modification of the ISettings API?

@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch 4 times, most recently from 0773b82 to ce31a0b Compare August 10, 2018 00:30
@rohit21agrawal

Copy link
Copy Markdown
Contributor

why can't we leave ISettings as is for backward compat, and make a new one like ISettings2 and use it everywhere in our code?

/// <summary>
/// Folder under which the config file is present
/// </summary>
string Root { get; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

similar to APIs there might be usage of these members as well, so why not mark them obsolete as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ISettings used to be not only the computed settings but also a single nuget.config, therefore it has a pointer to the root and filename. In the new design, ISettingsFile is the pointer to a single nuget.config, but ISettings only manages the computed values. If we only mark them as deprecated, what values should the implementation return?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ISettings used to be not only the computed settings but also a single nuget.config, therefore it has a pointer to the root and filename. Have the same value even with new design...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ISettings used to point to one specific nuget.config, and had pointers to the next nuget.config, thus depending on which ISettings you called you could have gotten a different setting value (most of out higher level APIs exposed only one of this configs). The new ISettings points to n nuget.config (i.e. the computed settings), therefore there is no reference to "the same value" as the previous design. What root and filename of which config do you think we should be showing if we left this option?

If we are really concerned about deleting this, we could mark them obsolete with error = true and have the implementation just return an empty string, but that would have the same "breaking" effect for anyone that is actually using this (which I don't expect to be anyone, since SettingsUtility has utility methods to extract the root or filename of all SettingsFile for a given ISetting)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Discussed offline, if @rrelyea is fine with breaking existing usage of these interface in 15.9 then I'm fine too.

@jainaashish jainaashish left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Not yet done, will continue to review and post my feedback.

/// <summary>
/// Adds or updates the given <paramref name="item"/> to the settings.
/// If the <paramref name="item"/> has to be added this method will add it
/// in the furthest compatible settings file.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

can you elaborate furthest compatible settings file?

/// </summary>
NuGetConfiguration RootElement { get; }

bool IsDirty { get; set; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

missing documentation

/// <summary>
/// Interface to expose a NuGet settings file
/// </summary>
internal interface ISettingsFile

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I'd imagine the define is each ISettingFile manage it's own nuget.config then why doesn't this interface expose functionality to add/update data to this setting file?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You can interact with the elements directly because the RootElement is exposed. I could add a SetItemInSection to have a similar behavior than ISettings, but I thought it was enough to expose the elements and let the user interact with them directly. This is an internal interface, therefore the only users should be inside NuGet.Configuration.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Why would you like to expose RootElement instead of let each SettingFile manages their own content? And that'd also help if tomorrow we want to expose individual setting files in UI or dynamic reloading of config files.

/// <summary>
/// Root element for the settings abstraction
/// </summary>
NuGetConfiguration RootElement { get; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

why should it expose RootElement? shouldn't SettingFIle handle all manupulation for NuGetConfiguration since this a wrapper over it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think handling all the manipulation from this class is limiting. At the end of the day, the user of this interface knows how the data is stored and how to handle it. If we add specific methods for interacting with the config files here we would be constrained to these APIs (the same way we were constraint by the previous APIs in ISettings). This is the reason I opted for exposing the root element and letting the user handle the data directly. Also, note that this is an internal API, therefore the user should know how the data works.

Any non-internal user should always interact with the computed settings through ISettings instead of ISettingsFile.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

If we add specific methods for interacting with the config files here we would be constrained to these APIs (the same way we were constraint by the previous APIs in ISettings).

Not really, what i'm asking is to have apis similar to ISettings to manage sections which isn't constraint by current data.

This is the reason I opted for exposing the root element and letting the user handle the data directly

This is the part I dont understand, if we have already defined an interface to interact with individual setting file then why would I expose an element to directly handle the underneath data?

Also, note that this is an internal API, therefore the user should know how the data works.

This has nothing to do with either internal or public as long as there are multiple layers and each layer knows what it's suppose to do. In current code, It feels like there are multiple layers but functionality and responsibilities are not distributed among them... Also, if you properly handle all the data manipulation at ISettingFile then tomorrow exposing individual config files in UI, will be far more convenient and doable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My initial thought was that adding an API to manage this would not be necessary since the providers that could call directly into this will know how to handle the API, but I can add the following methods to ISettingsFile and not expose the root element so that the API is consistent with ISettings:

SettingsSection GetSection(string sectionName); 

bool CreateSection(SettingsSection section, bool isBatchOperation = false); 

bool SetItemInSection(string sectionName, SettingsItem item, bool isBatchOperation = false); 

if (_computedSections.TryGetValue(sectionName, out var section))
{
throw new ArgumentException(Resources.Settings_FileName_Cannot_Be_A_Path, nameof(fileName));
if (section.TryUpdateChildItem(item, isBatchOperation))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

How this change propagated to corresponding SettingFile? Does SettingSection and SettingFile also interact with each other? I hope not... SettingFile and SettingSection should be independent of each other.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Each item has a reference to its parent element (which is in the tree of a specific SettingsFile), so each item will update itself and the corresponding SettingsFile and then the computed settings will be recomputed.

var outputSettingsFile = GetOutputSettingsFileForSection(sectionName);

// Set is an add
return outputSettingsFile != null && outputSettingsFile.RootElement.AddItemInSection(sectionName, item.Copy(), isBatchOperation);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

how does this get refreshed in _computedSections?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

On any edit to a specific ISettingsFile and event is triggered and _computedSections is recalculated.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ahh I see, dont you think it might be little over-do? Since each time, you need to handle a event to merge all the setting files, where you already know which file has changed.

Also, would it be possible to update multiple setting files at the same time? If not, then you can go for simple solution.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We do know what file has changed, but we don't know how those changes could affect the final computed settings until we recompute everything. Think of what if the change means that a clear was removed, or that a setting is added to the first config but there is already a setting closer to the user that will override this (thus nothing would change in the computed settings). I think that to store all the state to know exactly what changed and how to update the computed settings would make this code really complicated. If you have a simpler solution which is more efficient I would love to hear it.

To answer your question about editing multiple configs, every update operation has a flag (isBatchOperation), which tells the method if Save() should be called in the config that changed. Basically, if you are editing multiple settings (updates, adds, removes) you can specify this in every operation and save until the end. If you are only messing with ISettings (i.e computed settings), the update operations will update the data in memory, and saving will flush the data to the files.

var curr = _settingsHead;
while (curr != null)
{
curr.SettingsChanged += (_, __) => { RefreshSettingValues(); };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

do you really need to rely on SettingsChanged event from SettingFile to take latest changes in ISettings? If I'm not wrong then every change in any of the SettingFile happens through ISettings...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

As I just focused this refactor in getting the same behavior as we had previously, then all the changes happen from ISettings, but this is not true for the whole API. The API has the capability for users only editing one ISettingsFile directly (e.g. if we add the ability to edit specific configs in the UI), therefore I made it so that if there is any change with any of the ISettingsFile used in a given ISettings then we recompute the merged values.

The previous code calculated the merged values in every Get operation, I updated this to make get more performant (since we do way more gets than sets), and only recompute the values on each set. Therefore I would say that this code is way more performant than the previous.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Even if we allow editing individual config file through UI, that will also be through Settings or would we allow editing multiple files at the same time?

I think we can take all this discussion offline and finalize it...?

var computedSections = new Dictionary<string, SettingsSection>();

var curr = _settingsHead;
while (curr != null)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As I mentioned above... this adds unnecessary additional perf cost of merge all the settings files over and over again each time you change a single item in any of the file.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I don't believe this perf cost is unnecessary. This is only done on each set operation (i.e. when a settings file is saved). By doing this we gain the freedom in the API to interact with either computed settings or directly with a settings file without having a wrapper in between where you are limited to the exposed interface of that given wrapper.

The previous code computed and merged all settings files on every get operation, this update changes that to compute everything on sets because set operations are way less common than get operations.

var clearedSections = writteableSettingsFiles.Select(s => s.RootElement.GetSection(sectionName)).Where(s => s != null && s.HasClearChild());
if (clearedSections.Any())
{
return clearedSections.Last().Origin;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It seems your SettingSection is doing all the magic... :) But it's really hard to read... not sure if this was the existing code but anything we can do to improve readability?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

What do you mean? This method is finding the "most compatible" config file to add something in a given section. I agree that this looks like a hack, but this is only to keep the current behavior of how to write things in configs, I'm happy to discuss this again if you don't agree about what config we should be adding things for each section.

private void RefreshSettingValues()
{
MergeSettingFilesValues();
SettingsChanged?.Invoke(this, EventArgs.Empty);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SettingsChanged event should not be raised here since you haven't saved the file yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This method is only called from the SettingsChanged of a specific SettingsFile, I could remove this method and only make it inline in the event handler so that no one can call this without changing a file.

@jainaashish

Copy link
Copy Markdown

I discussed it offline with Pato, and we're clearly on the same page in terms of design and implementation. I feel like there should have been a clear design discussion before making lot of assumptions. But never too late, I propose we discuss it as a team and decide the right way forward so that we can quickly and effectively make progress here.

@PatoBeltran can you please set up some time to finalize the design and behavior?

cc @NuGet/nuget-client

@PatoBeltran

Copy link
Copy Markdown
Contributor Author

@NuGet/nuget-client I updated the PR with the feedback that I received. The whole API has only one point of interaction (i.e. ISettings), whenever a user gets a hold of a section or an item this is a copy of the actual abstraction, so modifying it won't cause settings to change unless it is passed through ISettings methods, which won't save to disk until the user explicitly calls ISettings.SaveToDisk()

The only open question left is: should the settingsChanged event be fired once the In-memory abstraction of settings changed or when the disk changed? Currently, it works with the later, but it can be easily changed.

/// <param name="sectionName">section where the <paramref name="item"/> has to be added. If this section does not exist, one will be created.</param>
/// <param name="item">item to be added to the settings.</param>
/// <returns>true if the item was successfully updated or added in the settings</returns>
void AddOrUpdate(string sectionName, SettingItem item);

@jainaashish jainaashish Sep 7, 2018 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

change the method return type to bool

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I explicitly made this void because I wanted to give more info to the user in the case it didn't succeed. If the add or update failed is because it is trying to update a machine-wide config, therefore I want the user to have this information instead of just returning false and ignoring the changes.

@jainaashish jainaashish left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Great job Pato 👍 this looks great. Although I've not gone through all the file changes but the important ones and looks good to me.

/// <param name="sectionName">Section where the <paramref name="item"/> is stored. If this section does not exist, the method will throw</param>
/// <param name="item">item to be removed from the settings</param>
/// <remarks> If the <paramref name="item"/> is in a machine wide config this method will throw</remarks>
void Remove(string sectionName, SettingItem item);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dow e also neede removeSection api?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We could add it, the same effect would happen if you remove all the items in a section. I don't think there is any scenario where removing the whole section makes sense, that's why I didn't think to add it.

/// <summary>
/// Flushes any update that has been done in memory through the ISettings API to the settings file in disk.
/// </summary>
void SaveToDisk();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

so does it mean that there is no batch or non-batch modes now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Every update messes with the in-memory abstraction only and the user has to explicitly save to get it in disk. This is the same pattern followed by the dotnet configuration API.

if (_computedSections.TryGetValue(sectionName, out var section))
{
throw new ArgumentException("root cannot be null or empty", nameof(root));
section.Add(item);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

what if item already exists in computedSection, odes it also update? if yes, then may be change it to AddorUpdate?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Since _computedSection only has pointers to the items that are held in the settingsFile the AddOrUpdate above this line takes care of the update scenario. I will add some comments to clarify this.


// Operation is an add
var outputSettingsFile = GetOutputSettingFileForSection(sectionName);
if (outputSettingsFile != null)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

when would it not get outputSettingFile? and if there are cases like those, then may be throw appropriate error..?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We could throw. This basically means that if there is no writeable file we ignore the update. I opted to ignore instead of throw to keep the same behavior as before, but I'm in favor of throwing to have a better error experience.

}

if (!FileSystemUtility.IsPathAFile(fileName))
Debug.Assert(item.IsAbstract());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remove these Debug Asserts

});

IsDirty = false;
SettingsChanged?.Invoke(this, EventArgs.Empty);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

shouldn't this SettingChanged event be raised only once per SaveToDisk in Settings.cs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You could subscribe to this SettingsChange if you want to know if a specific settingsFile changed. Settings subscribe to this event on each settings file. You are right that on settings I need to make sure this event shouldn't trigger the Settings event more than once. Good catch!

internal bool TryGetSection(string sectionName, out SettingSection section)
{
var result = _rootElement.Sections.TryGetValue(sectionName, out var parsedSection);
section = parsedSection;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

you can directly use parsedSection while reading from rootElement.


internal override SettingBase Clone()
{
return new AbstractSettingSection(Name, Attributes, Items.Select(s => s.Clone() as SettingItem));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wasn't able to follow Attributes origin but just make sure that you're doing proper cloning.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In our current schema, there are no sections with attributes... This refactor enables the possibility to add attributes in sections... sections inherit from SettingElement which is the one that manages the attributes, there's where this variable comes from.

@nkolev92 nkolev92 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Mostly minor stuff and only one that absolutely has to change (the credentials casing thing).

Did as much as much I can :)
Lots of great improvements here, and the API changes are as minimal as possible.

<data name="Option_ConfigFile" xml:space="preserve">
<value>The NuGet configuration file. If not specified, file %AppData%\NuGet\NuGet.config is used as configuration file.</value>
<comment>Please don't localize "%AppData%\NuGet\NuGet.config".</comment>
<value>The NuGet configuration file. If specified, only the settings from this file will be used. If not specified, the hierarchy of configuration files from the current directory will be used. To learn more about nuget configuration go to https://docs.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior</value>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we should setup a fw link here. More future proof.
PMs should be able to help with that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

cc. @anangaur

@@ -1,4 +1,4 @@
using System;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

revert this file.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Actually this one is missing a header, so maybe add a header :)

return new RestoreSummary(
result.Restored,
"packages.config projects",
Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Did you verify that the configs are printed in the same order when you do restores before/after this change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, this does not changes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe add a test verifying order?

var sourceList = SourceProvider.LoadPackageSources().ToList();
var existingSource = sourceList.Where(ps => String.Equals(Name, ps.Name, StringComparison.OrdinalIgnoreCase));
if (!existingSource.Any())
var packageSource = SourceProvider.GetPackageSourceWithName(Name);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: ByName?

}

public bool DeleteValue(string section, string key)
public void AddOrUpdate(string sectionName, SettingItem item)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not keep the bools for op result?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I opted to use void and throw in the case where there is a failure, this way we can give more information to the user as of why the operation failed. Most of the times this failure is because there is no writeable config or because there was some bug in the implementation, throwing will give more context about what is happening.

<value>Unable to update setting since it is in a machine wide NuGet.Config</value>
</data>
<data name="Error_CouldNotDisableSources" xml:space="preserve">
<value>Could not add disabled package source</value>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: add . to all the messages.

<value>Environment variable '{0}' must contain an absolute path, the full path of '{1}' cannot be determined.</value>
</data>
<data name="SectionDoesNotExist" xml:space="preserve">
<value>The section does not exist in the settings</value>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should we saty which section?

}

// This is public for testing
public AbstractSettingSection(string name, params SettingItem[] children)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you have internalsVisibleTo, doesn't need to be public.


namespace NuGet.Configuration
{
public sealed class AbstractSettingSection : SettingSection

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm confused as to what this AbstractSettingSection represents.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

There are two types of sections... the ones that are actual sections that were read from a file and have a pointer to a settings file and the ones that are a collection of computer values... I decided to separate this two in AbstractSettingSection and ParsedSettingSection to have the code be a little easier to read, since the abstract sections are only an in-memory representation (i.e. don't map to one specific section in a file), but the parsed sections have a counterpart in a file.

Do you think this is not clear enough? what would you propose to make it better?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@nkolev92 do you think InMemorySettingSection is a better name?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

VirtualSettingSection? MergedSettingSection?

public static class SettingsUtility
{
public static readonly string ConfigSection = "config";
//TODO: Delete all obsolete APIs.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Link the issue and TODO.

@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch from f7f7c57 to 857555c Compare September 11, 2018 23:00
@PatoBeltran
PatoBeltran force-pushed the dev-pato-refactor-config branch from dfdc635 to c8a61f8 Compare September 12, 2018 19:04
return new RestoreSummary(
result.Restored,
"packages.config projects",
Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe add a test verifying order?

bool authTypesEmpty = String.IsNullOrEmpty(ValidAuthenticationTypes);
var usernameEmpty = string.IsNullOrEmpty(Username);
var passwordEmpty = string.IsNullOrEmpty(Password);
var authTypesEmpty = string.IsNullOrEmpty(ValidAuthenticationTypes);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isUsernameEmpty, isPasswordEmpty, and isAuthTypesEmpty.

{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is incorrect. If you were only checking if name is null then it would be appropriate to throw an ArgumentNullException; however, because you're checking for both null and a zero-length string, you either need to throw two separate exceptions or throw one exception that is appropriate for both cases. I suggest the latter option as it's simpler:

if (string.IsNullOrEmpty(name))
{
    throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(name));
}

Like here.

This feedback applies throughout the PR.

<data name="Option_ConfigFile" xml:space="preserve">
<value>The NuGet configuration file. If not specified, file %AppData%\NuGet\NuGet.config is used as configuration file.</value>
<comment>Please don't localize "%AppData%\NuGet\NuGet.config".</comment>
<value>The NuGet configuration file. If specified, only the settings from this file will be used. If not specified, the hierarchy of configuration files from the current directory will be used. To learn more about nuget configuration go to https://docs.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior</value>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  • Remove extra space in "...files from..."
  • Properly capitalize NuGet in "To learn more about nuget configuration..."
  • Terminate the last sentence with a period.

var dependencySetting = SettingsUtility.GetConfigValue(ConfigSettings, "dependencyversion");
DependencyBehavior behavior;
bool success = Enum.TryParse(dependencySetting, true, out behavior);
var success = Enum.TryParse(dependencySetting, true, out behavior);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Add an ignoreCase: named parameter to the mysterious literal true.


var unknown = other as UnknownItem;

var otherChildren = new Dictionary<SettingBase, SettingBase>(unknown.MutableChildren);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

unknown could be null.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I will add a null check on base.Update(...) so all of the items are covered from this issue.

.Select(setting => setting.Value)
.Select(f => f as AddItem)
.Where(f => f != null)
.Select(f => f.GetValueAsPath())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

return fallbackValues
    .OfType<AddItem>()
    .Select(folder => folder.GetValueAsPath())
    .ToList();

using NuGet.Common;
using Xunit;
using System.Linq;
using NuGet.Configuration;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sort


public static byte[] GetFileHash(string fileName)
{
var hashAlgorithm = SHA512.Create();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

HashAlgorithm implements IDisposable. You need to wrap this with a using statement.

.Select(GetFileName);

var expected = new[] { "a", "b", "c", "d", "x", "y" };
var expected = new[] { "x", "y", "c", "d", "a", "b" };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this change correct? Would returning the fallback folders in a different order affect package resolution?

@PatoBeltran

Copy link
Copy Markdown
Contributor Author

@dtivel addressed most comments, missing adding additional tests. I also want to improve the error message experience for "Unable to parse config" to give a reason of what it found.

/// <returns>True if credentials object is valid</returns>
public bool IsValid() => !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(PasswordText);

private Lazy<int> _hashCode { get; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

private readonly Lazy<int> _hashCode;

...and move to the top of the class (where fields typically go).

public virtual string Value
{
get => Settings.ApplyEnvironmentTransform(Attributes[ConfigurationConstants.ValueAttribute]);
set => AddOrUpdateAttribute(ConfigurationConstants.ValueAttribute, value ?? string.Empty);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why add ?? string.Empty?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Add items should always have Key and Value attributes, but Value can be empty... Therefore if a user set's it to null we don't want to delete it, but set it to empty.


internal AddItem _password { get; set; }

internal AddItem _validAuthenticationTypes { get; set; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is a non-standard naming convention for properties. The property names should be Username, Password, and ValidAuthenticationTypes, respectively. However, I suspect that you made these private fields internal properties so that one instance of this class can access the non-public members of another instance of the class. If so, it is sufficient to make these private fields. Can they also be readonly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

_username and password can be made readonly _validAuthenticationTypes can be deleted or re-created, therefore it cannot be readonly.

}
else if (string.Equals(item.Key, ConfigurationConstants.PasswordToken, StringComparison.OrdinalIgnoreCase))
{
if (_password != null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It looks like you're trying to block config files which have multiple password elements in the same credentials section. This looks like new behavior. Why enforce this on passwords but not other elements (like username and valid authentication types)?

Will this pattern be enforced more generally (across other settings)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We have never enforced this on code (i.e. failed reading) but we have never used more than one password if present, and it is implicit in our documentation and in the way we write the credentials that only one of this should be present. I could add validation also to make sure there is only one _username and one _validAuthenticationTypes.

What do you mean with this pattern being enforced more generally? CredentialsItem is making its own rules about how it should be constructed, each item can do the same. As for general add items in a section, this existing tests says that we should ignore duplicates instead of failing. Do you think is a better idea to follow this on CredentialsItem and just ignore any duplicates?

/// <summary>
/// Convenience method to add an element to an origin
/// </summary>
/// <remarks>Each setting can override this method to inlcude any descendants to the origin</remarks>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

include


internal static void ConnectSettingsFilesLinkedList(IList<SettingsFile> settingFiles)
{
settingFiles[0].Priority = settingFiles.Count;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What if settingFiles is empty?

@PatoBeltran
PatoBeltran merged commit fc0c207 into dev Sep 18, 2018
@PatoBeltran
PatoBeltran deleted the dev-pato-refactor-config branch September 18, 2018 00:18
PatoBeltran added a commit that referenced this pull request Sep 18, 2018
Improved API for parsing nuget.config by creating an object model that
is easily extensible and updated current API usage to conform with the
new usage patterns.
PatoBeltran added a commit that referenced this pull request Oct 17, 2018
Improved API for parsing nuget.config by creating an object model that
is easily extensible and updated current API usage to conform with the
new usage patterns.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants