/// <summary> /// Constructor. It creates an empty temp file under the temp directory / NuGet, with /// extension <paramref name="extension" />. /// </summary> /// <param name="extension">The extension of the temp file.</param> public TempFile (string extension) { if (string.IsNullOrEmpty (extension)) throw new ArgumentNullException (nameof (extension)); string tempDirectory = NuGetEnvironment.GetFolderPath (NuGetFolderPath.Temp); Directory.CreateDirectory (tempDirectory); int count = 0; do { filePath = Path.Combine (tempDirectory, Path.GetRandomFileName () + extension); if (!File.Exists (filePath)) { try { // create an empty file using (var filestream = File.Open (filePath, FileMode.CreateNew)) { } // file is created successfully. return; } catch { // Ignore and try again } } count++; } while (count < 3); throw new InvalidOperationException ("Failed to create NuGet temp file."); }
public override async void Execute(object parameter) { OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome); dlg.Filters = new List <FileDialogFilter>() { new FileDialogFilter() { Name = "Nuget Packages (*.nupkg)", Extensions = { "nupkg" } }, new FileDialogFilter() { Name = ".NET assemblies", Extensions = { "dll", "exe", "winmd" } }, new FileDialogFilter() { Name = "All files", Extensions = { "*" } }, }; dlg.AllowMultiple = true; var filenames = await dlg.ShowAsync(MainWindow.Instance); if (filenames != null && filenames.Length > 0) { MainWindow.Instance.OpenFiles(filenames); } // var dlg = new OpenFromNuGetDialog(); //dlg.Owner = MainWindow.Instance; //if (await dlg.ShowDialog<bool>() == true) //OpenFiles(dlg.SelectedFileNames); }
public CommandLineMachineWideSettings() { var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); _settings = new Lazy <Configuration.ISettings>( () => Configuration.Settings.LoadMachineWideSettings(baseDirectory)); }
private void ListLocalResource(LocalResourceName localResourceName) { switch (localResourceName) { case LocalResourceName.HttpCache: PrintLocalResourcePath(_httpCacheResourceName, SettingsUtility.GetHttpCacheFolder()); break; case LocalResourceName.PackagesCache: PrintLocalResourcePath(_packagesCacheResourceName, MachineCache.Default?.Source); break; case LocalResourceName.GlobalPackagesFolder: PrintLocalResourcePath(_globalPackagesResourceName, SettingsUtility.GetGlobalPackagesFolder(Settings)); break; case LocalResourceName.Temp: PrintLocalResourcePath(_tempResourceName, NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp)); break; case LocalResourceName.All: PrintLocalResourcePath(_httpCacheResourceName, SettingsUtility.GetHttpCacheFolder()); PrintLocalResourcePath(_packagesCacheResourceName, MachineCache.Default?.Source); PrintLocalResourcePath(_globalPackagesResourceName, SettingsUtility.GetGlobalPackagesFolder(Settings)); PrintLocalResourcePath(_tempResourceName, NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp)); break; default: // Invalid local resource name provided. throw new CommandLineException( LocalizedResourceManager.GetString( nameof(NuGetResources.LocalsCommand_InvalidLocalResourceName))); } }
/// <summary> /// Write the dg file to a temp location if NUGET_PERSIST_NOOP_DG. /// </summary> /// <remarks>This is a noop if NUGET_PERSIST_NOOP_DG is not set to true.</remarks> private static void PersistHashedDGFileIfDebugging(DependencyGraphSpec spec, ILogger log) { if (_isPersistDGSet.Value) { string path; var envPath = Environment.GetEnvironmentVariable("NUGET_PERSIST_NOOP_DG_PATH"); if (!string.IsNullOrEmpty(envPath)) { path = envPath; Directory.CreateDirectory(Path.GetDirectoryName(path)); } else { path = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", $"{spec.GetProjectSpec(spec.Restore.FirstOrDefault()).RestoreMetadata.ProjectName}-{DateTime.Now.ToString("yyyyMMddHHmmss")}.dg"); DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(path)); } log.LogMinimal($"Persisting no-op dg to {path}"); spec.Save(path); } }
public static string GetGlobalPackagesFolder(ISettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var path = Environment.GetEnvironmentVariable(GlobalPackagesFolderEnvironmentKey); if (string.IsNullOrEmpty(path)) { // Environment variable for globalPackagesFolder is not set. path = GetValueForAddItem(settings, ConfigurationConstants.Config, ConfigurationConstants.GlobalPackagesFolder, isPath: true); } else { // Verify the path is absolute VerifyPathIsRooted(GlobalPackagesFolderEnvironmentKey, path); } if (!string.IsNullOrEmpty(path)) { path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); path = Path.GetFullPath(path); return(path); } path = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome), DefaultGlobalPackagesFolderPath); return(path); }
public MachineWideSettings() { string baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); _settings = new Lazy <IEnumerable <Settings> >( () => global::NuGet.Configuration.Settings.LoadMachineWideSettings(baseDirectory)); }
/// <summary> /// Writes the resolved NuSpec file to the package output directory. /// </summary> /// <param name="builder">The package builder</param> private void WriteResolvedNuSpecToPackageOutputDirectory(PackageBuilder builder) { var outputPath = GetOutputPath(builder, false, builder.Version); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); var resolvedNuSpecOutputPath = Path.Combine( Path.GetDirectoryName(outputPath), new VersionFolderPathResolver(outputPath).GetManifestFileName(builder.Id, builder.Version)); _packArgs.Logger.Log(PackagingLogMessage.CreateMessage(string.Format(CultureInfo.CurrentCulture, Strings.Log_PackageCommandInstallPackageToOutputPath, "NuSpec", resolvedNuSpecOutputPath), LogLevel.Minimal)); if (string.Equals(_packArgs.Path, resolvedNuSpecOutputPath, StringComparison.OrdinalIgnoreCase)) { throw new PackagingException(NuGetLogCode.NU5001, string.Format(CultureInfo.CurrentCulture, Strings.Error_WriteResolvedNuSpecOverwriteOriginal, _packArgs.Path)); } // We must use the Path.GetTempPath() which NuGetFolderPath.Temp uses as a root because writing temp files to the package directory with a guid would break some build tools caching var manifest = new Manifest(new ManifestMetadata(builder), null); var tempOutputPath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), Path.GetFileName(resolvedNuSpecOutputPath)); using (Stream stream = new FileStream(tempOutputPath, FileMode.Create)) { manifest.Save(stream); } FileUtility.Replace(tempOutputPath, resolvedNuSpecOutputPath); }
public string GetDefaultSource(string source) { var settings = Settings.LoadDefaultSettings(NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory)); var sourcesSettings = FindSourcesSettings(source, settings); return(sourcesSettings.Source ?? throw new InvalidOperationException($"A source for: {source} was not found.")); }
public static string GetDefaultDGSpecFileName() { return(Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", "nugetSpec.dg")); }
public NuGetMachineWideSettings() { string baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); _settings = new Lazy <ISettings>( () => Settings.LoadMachineWideSettings(baseDirectory)); }
public XPlatMachineWideSetting() { var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); _settings = new Lazy <IEnumerable <Settings> >( () => Configuration.Settings.LoadMachineWideSettings(baseDirectory)); }
/// <summary> /// Lists out the cache location(s) path. /// </summary> /// <param name="localResourceName">Cache resource to be listed</param> /// <throws>Thorws <code>ArgumentException</code> if the specified resource name does not match a known cache type.</throws> private void ListLocalResource(LocalResourceName localResourceName, LocalsArgs localsArgs) { switch (localResourceName) { case LocalResourceName.HttpCache: PrintLocalResourcePath(HttpCacheResourceName, SettingsUtility.GetHttpCacheFolder(), localsArgs); break; case LocalResourceName.GlobalPackagesFolder: PrintLocalResourcePath(GlobalPackagesResourceName, SettingsUtility.GetGlobalPackagesFolder(localsArgs.Settings), localsArgs); break; case LocalResourceName.Temp: PrintLocalResourcePath(TempResourceName, NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), localsArgs); break; case LocalResourceName.PluginsCache: PrintLocalResourcePath(PluginsCacheResourceName, SettingsUtility.GetPluginsCacheFolder(), localsArgs); break; case LocalResourceName.All: PrintLocalResourcePath(HttpCacheResourceName, SettingsUtility.GetHttpCacheFolder(), localsArgs); PrintLocalResourcePath(GlobalPackagesResourceName, SettingsUtility.GetGlobalPackagesFolder(localsArgs.Settings), localsArgs); PrintLocalResourcePath(TempResourceName, NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), localsArgs); PrintLocalResourcePath(PluginsCacheResourceName, SettingsUtility.GetPluginsCacheFolder(), localsArgs); break; default: // Invalid local resource name provided. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_InvalidLocalResourceName)); } }
public static string GetGlobalPackagesFolder(ISettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var path = Environment.GetEnvironmentVariable(GlobalPackagesFolderEnvironmentKey); if (string.IsNullOrEmpty(path)) { // Environment variable for globalPackagesFolder is not set. // Try and get it from nuget settings // GlobalPackagesFolder path may be relative path. If so, it will be considered relative to // the solution directory, just like the 'repositoryPath' setting path = settings.GetValue(ConfigSection, GlobalPackagesFolderKey, isPath: false); } if (!string.IsNullOrEmpty(path)) { path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); return(path); } path = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome), DefaultGlobalPackagesFolderPath); return(path); }
/// <summary> /// Write the dg file to a temp location if NUGET_PERSIST_DG. /// </summary> /// <remarks>This is a noop if NUGET_PERSIST_DG is not set to true.</remarks> public static void PersistDGFileIfDebugging(DependencyGraphSpec spec, ILogger log) { if (_isPersistDGSet.Value) { string path; var envPath = Environment.GetEnvironmentVariable("NUGET_PERSIST_DG_PATH"); if (!string.IsNullOrEmpty(envPath)) { path = envPath; Directory.CreateDirectory(Path.GetDirectoryName(path)); } else { path = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", $"{Guid.NewGuid()}.dg"); DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(path)); } log.LogMinimal( string.Format( CultureInfo.CurrentCulture, Strings.PersistDGFile, path)); spec.Save(path); } }
/// <summary> /// Validate all files in package are not traversed outside of the expected extraction path. /// Eg: file entry like ../../foo.dll can get outside of the expected extraction path. /// </summary> public async Task ValidatePackageEntriesAsync(CancellationToken token) { try { var files = await GetFilesAsync(token); var packageIdentity = await GetIdentityAsync(token); // This dummy destination is used to check if the file in package get outside of the extractionPath var dummyDestination = NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome); dummyDestination = NormalizeDirectoryPath(dummyDestination); ValidatePackageEntries(dummyDestination, files, packageIdentity); } catch (UnsafePackageEntryException) { throw; } catch (Exception e) { throw new PackagingException(string.Format( CultureInfo.CurrentCulture, Strings.ErrorUnableCheckPackageEntries), e); } }
static NuGetHelper() { // 'dotnet nuget locals global-packages --list' // SettingsUtility.GetGlobalPackagesFolder(Settings.LoadMachineWideSettings(string.Empty)); _globalPackagesPath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome), SettingsUtility.DefaultGlobalPackagesFolderPath); _runtimeFramework = Assembly.GetEntryAssembly()?.GetCustomAttribute <TargetFrameworkAttribute>()?.FrameworkName; _targetFramework = RuntimeInformation.FrameworkDescription; }
public MachineWideSettings() { _settings = new Lazy <ISettings>(() => { var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); return(global::NuGet.Configuration.Settings.LoadMachineWideSettings(baseDirectory)); }); }
public MachineWideSettings() { _settings = new Lazy <IEnumerable <NuGet.Configuration.Settings> >(() => { var folderPath = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); return(NuGet.Configuration.Settings.LoadMachineWideSettings(folderPath)); }); }
public static string GetHttpCacheFolder(ISettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } return(NuGetEnvironment.GetFolderPath(NuGetFolderPath.HttpCacheDirectory)); }
/// <summary> /// Copies test sources configuration to a test folder /// </summary> public static string CopyFuncTestConfig(string destinationFolder) { var sourceConfigFolder = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); var sourceConfigFile = Path.Combine(sourceConfigFolder, "NuGet.Core.FuncTests.Config"); var destConfigFile = Path.Combine(destinationFolder, "NuGet.Config"); File.Copy(sourceConfigFile, destConfigFile); return(destConfigFile); }
/// <summary> /// Copies test sources configuration to a test folder /// </summary> public static string CopyFuncTestConfig(string destinationFolder) { var testSettingsFolder = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); var funcTestConfigPath = Path.Combine(testSettingsFolder, TestSources.ConfigFile); var destConfigFile = Path.Combine(destinationFolder, "NuGet.Config"); File.Copy(funcTestConfigPath, destConfigFile); return(destConfigFile); }
public static string GetConfigFileRoot() { // The below environment variable is set on VSTS CI machines and the value is // equal to the root of the repository where the config files are copied as part of // a build step before the tests are run. If the environment variable is not set, the behavior // is the same as on TeamCity - this will ensure both CI's will be happy. var fullPath = Environment.GetEnvironmentVariable("NUGET_FUNCTESTS_CONFIG"); return(string.IsNullOrEmpty(fullPath) ? NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory) : fullPath); }
public static FilePath GetFileName() { string userSettingsDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); if (userSettingsDirectory != null) { return(Path.Combine(userSettingsDirectory, Settings.DefaultSettingsFileName)); } return(FilePath.Null); }
public MachineWideSettings() { _settings = Lazy.Create(LoadMachineWideSettings); IEnumerable <Settings> LoadMachineWideSettings() { var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory); return(global::NuGet.Configuration.Settings.LoadMachineWideSettings(baseDirectory)); } }
private void BuildProjectWithDotNet() { string properties = string.Empty; if (_packArgs.Properties.Any()) { foreach (var property in _packArgs.Properties) { if (property.Key.Equals(Configuration, StringComparison.OrdinalIgnoreCase)) { properties = $"-c {property.Value}"; } } } if (!string.IsNullOrEmpty(_packArgs.BasePath)) { string basePath = Path.GetFullPath(_packArgs.BasePath); properties += $" -b \"{basePath}\""; } if (!string.IsNullOrEmpty(_packArgs.Suffix)) { properties += $" --version-suffix {_packArgs.Suffix}"; } string dotnetLocation = NuGetEnvironment.GetDotNetLocation(); var processStartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = dotnetLocation, Arguments = $"build {properties}", WorkingDirectory = _packArgs.CurrentDirectory, RedirectStandardOutput = false, RedirectStandardError = false }; int result; using (var process = Process.Start(processStartInfo)) { process.WaitForExit(); result = process.ExitCode; } if (0 != result) { // If the build fails, report the error throw new Exception(String.Format(CultureInfo.CurrentCulture, Strings.Error_BuildFailed, processStartInfo.FileName, processStartInfo.Arguments)); } }
public static string ReadApiKey(string feedName) { string fullPath = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); using (Stream configStream = File.OpenRead(Path.Combine(fullPath, "NuGet.Protocol.FuncTest.config"))) { var doc = XDocument.Load(XmlReader.Create(configStream)); var element = doc.Root.Element(feedName); return(element?.Element("ApiKey")?.Value); } }
public bool ClearAll() { bool noErrors = true; noErrors &= ClearHttpCache(); noErrors &= ClearNuGetFolder(DefaultNuGetFolders.GetGlobalPackagesFolder(), "Global-packages"); noErrors &= ClearNuGetFolder(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "Temp"); Log.Info("Cache clearing operation finished"); return(noErrors); }
public void ProcessConfigFile_GetSettingsForWorkingDirectory(string emptyConfig) { ISettings settings = XPlatUtility.ProcessConfigFile(emptyConfig); var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); string baseNugetConfigPath = Path.Combine(baseDirectory, Settings.DefaultSettingsFileName); List <string> configPaths = settings.GetConfigFilePaths().ToList(); // Since this command doesn't set specific working directory itself, it's just test binary folder, // so several nuget.config including user default nuget.config'll get loaded. Assert.True(configPaths.Count > 1); // Assert user default nuget.config is loaded Assert.True(configPaths.Contains(baseNugetConfigPath)); }
public static string GetNuGetHomePluginsPath() { var nuGetHome = NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome); return(Path.Combine(nuGetHome, "plugins", #if IS_DESKTOP "netfx" #else "netcore" #endif )); }