/// <summary> /// Reads in Git's configuration files, parses them, and combines them into a single database. /// <para/> /// Returns the combined database of configuration data. /// </summary> /// <param name="directory">Optional working directory of a repository from which to read its Git local configuration.</param> /// <param name="loadLocal">Read, parse, and include Git local configuration values if `<see langword="true"/>`; otherwise do not.</param> /// <param name="loadSystem">Read, parse, and include Git system configuration values if `<see langword="true"/>`; otherwise do not.</param> public static Configuration ReadConfiuration(string directory, bool loadLocal, bool loadSystem) { if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentNullException("directory"); } if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException(directory); } ConfigurationLevel types = ConfigurationLevel.All; if (!loadLocal) { types ^= ConfigurationLevel.Local; } if (!loadSystem) { types ^= ConfigurationLevel.System; } var config = new Configuration(); config.LoadGitConfiguration(directory, types); return(config); }
public virtual IEnumerator <Entry> EnumerateEntriesByLevel(ConfigurationLevel desiredLevels) { ConfigurationLevel[] levels = new[] { ConfigurationLevel.Portable, ConfigurationLevel.System, ConfigurationLevel.Xdg, ConfigurationLevel.Global, ConfigurationLevel.Local, }; foreach (ConfigurationLevel level in levels) { // Skip levels not present in the mask. if ((desiredLevels & level) == 0) { continue; } if (_values.TryGetValue(level, out Dictionary <string, string> values)) { foreach (KeyValuePair <string, string> value in values) { yield return(new Entry(value.Key, value.Value, level)); } } } }
public override void DeleteBusinessObject(XDocument requestXml) { string key = requestXml.Root.Element("key").Value; ConfigurationLevel level = (ConfigurationLevel)Enum.Parse(typeof(ConfigurationLevel), requestXml.Root.Element("level").Value, true); this.DeleteConfiguration(key, level); }
public void SaveFrom(IConfiguration config, ConfigurationLevel level, Stream outputStream) { try { var keys = config.GetKeys(level); var properties = new Properties(); foreach (var configKey in keys) { var configValue = config.GetValue(configKey); object value; if (configValue == null || configValue.Value == null) { value = configKey.DefaultValue; } else { value = configValue.Value; } var stringValue = Convert.ToString(value, CultureInfo.InvariantCulture); properties.SetProperty(configKey.Name, stringValue); } properties.Store(outputStream, String.Empty); } catch (DatabaseConfigurationException) { throw; } catch (Exception ex) { throw new DatabaseConfigurationException("Could not save the configurations to the given stream.", ex); } }
/// <summary> /// Determines which configuration file has been found. /// </summary> public virtual bool HasConfig(ConfigurationLevel level) { using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false)) { return(handle != null); } }
private void SetUser(bool isGlobal, UserConfig config) { CheckEmailVariables(); ConfigurationLevel level = isGlobal ? ConfigurationLevel.Global : ConfigurationLevel.Local; using Repository repo = new Repository(Environment.CurrentDirectory); var emailToSet = ""; switch (config) { case UserConfig.Personal: emailToSet = personalEmail; break; case UserConfig.Work: emailToSet = workEmail; break; } repo.Config.Set("user.email", emailToSet, level); ShowUser(isGlobal); }
private async Task ParseGitConfig(ConfigurationLevel level, string configPath) { if (configPath is null) { throw new ArgumentNullException(nameof(configPath)); } if ((level & ~ConfigurationLevel.All) != 0) { throw new ArgumentOutOfRangeException(nameof(level)); } if (!Storage.FileExists(configPath)) { var inner = new FileNotFoundException(configPath); throw new ArgumentException(inner.Message, nameof(configPath), inner); } if (!_values.ContainsKey(level)) { return; } if (!Storage.FileExists(configPath)) { return; } using (var stream = Storage.FileOpen(configPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { await ParseGitConfig(Context, reader, _values[level]); } }
public static void Delete(this Configuration config, string key, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); config.Unset(key, level); }
public static IEnumerable<object> GetValues(this IConfiguration config, ConfigurationLevel level) { var keys = config.GetKeys(level); var values = keys.Select(x => config.GetValue(x)) .Where(value => value != null) .ToList(); return values.ToArray(); }
/// <summary> /// Determines which configuration file has been found. /// </summary> public virtual bool HasConfig(ConfigurationLevel level) { using (ConfigurationHandle snapshot = Snapshot()) using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { return(handle != null); } }
internal void UnsetMultivar(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete_multivar(h, key); } }
/// <summary> /// Unset all configuration values in a multivar variable (key and value). /// </summary> /// <param name="key">The key to unset.</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual bool UnsetAll(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { return(Proxy.git_config_delete_multivar(h, key)); } }
public static void Save(this IConfiguration config, ConfigurationLevel level, IConfigFormatter formatter) { if (config.Source == null) { throw new DatabaseConfigurationException("The source was not configured in the configuration."); } config.Save(config.Source, level, formatter); }
/// <summary> /// Unset a configuration variable (key and value). /// </summary> /// <param name="key">The key to unset.</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Unset(string key, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true)) { Proxy.git_config_delete(h, key); } }
/// <summary> /// Find configuration entries matching <paramref name="regexp"/>. /// </summary> /// <param name="regexp">A regular expression.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <returns>Matching entries.</returns> public virtual IEnumerable <ConfigurationEntry <string> > Find(string regexp, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true)) { return(Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList()); } }
/// <summary> /// Adds a configuration value for a multivalue key. Keys are in the form 'section.name'. /// <para> /// For example in order to add the value for this in a .git\config file: /// /// [test] /// plugin = first /// /// You would call: /// /// repo.Config.Add("test.plugin", "first"); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Add(string key, string value, ConfigurationLevel level) { Ensure.ArgumentNotNull(value, "value"); Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_add_string(h, key, value); } }
public static void ConfigureGitConfig( ConfigurationLevel level = ConfigurationLevel.Global, string file = null ) { var config = new Configuration( file, file, file ); LogManager.GetCurrentClassLogger().Info( "Installing failmerge driver to " + ( file ?? level.ToString() ) ); config.Set( "merge.failmerge.name", "fail merge driver", level ); config.Set( "merge.failmerge.driver", "false", level ); config.Set( "merge.failmerge.recursive", "binary", level ); }
public unsafe static string GetSearchPath(ConfigurationLevel level) { GitBuffer buf = new GitBuffer(); git_buf nativeBuffer = buf.NativeBuffer; Ensure.NativeSuccess(libgit2.git_libgit2_opts(git_libgit2_opt_t.GIT_OPT_GET_SEARCH_PATH, (git_config_level_t)level, nativeBuffer)); fixed(byte *bp = buf.Content) { return(Utf8Converter.FromNative(bp)); } }
public sealed override bool ContainsKey(ConfigurationLevel levels, string key) { foreach (var level in Levels) { if ((level & levels) != 0 && _values[level].ContainsKey(key)) { return(true); } } return(false); }
public virtual bool ContainsKey(ConfigurationLevel levels, string key) { foreach (ConfigurationLevel level in Levels) { if ((level & levels) != 0 && _values[level].ContainsKey(key)) { return(true); } } return(false); }
/// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get<bool>("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <param name="level">The configuration file into which the key should be searched for</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry <T> Get <T>(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false)) { if (handle == null) { return(null); } return(Proxy.git_config_get_entry <T>(handle, key)); } }
public static void Save(this IConfiguration config, IConfigurationSource source, ConfigurationLevel level, IConfigurationFormatter formatter) { try { var outputStream = source.OutputStream; if (!outputStream.CanWrite) throw new InvalidOperationException("The destination source cannot be written."); outputStream.Seek(0, SeekOrigin.Begin); formatter.SaveFrom(config, level, outputStream); outputStream.Flush(); } catch (Exception ex) { throw new DatabaseConfigurationException("Cannot save the configuration.", ex); } }
/// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Set <T>(string key, T value, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true)) { if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); } }
public XDocument DeleteConfiguration(string key, ConfigurationLevel level) { XDocument xml = XDocument.Parse(XmlName.EmptyRoot); xml.Root.Add(new XElement(XmlName.Key, key)); xml.Root.Add(new XElement(XmlName.Level, level.ToString().ToUpperInvariant())); xml.Root.Add(new XElement(XmlName.LocalTransactionId, SessionManager.VolatileElements.LocalTransactionId.ToUpperString())); xml.Root.Add(new XElement(XmlName.DeferredTransactionId, SessionManager.VolatileElements.DeferredTransactionId.ToUpperString())); xml.Root.Add(new XElement(XmlName.DatabaseId, ConfigurationMapper.Instance.DatabaseId.ToUpperString())); this.ExecuteStoredProcedure(StoredProcedure.configuration_p_deleteConfiguration, false, xml); return(xml); }
public sealed override void LoadGitConfiguration(string directory, ConfigurationLevel types) { string portableConfig = null; string systemConfig = null; string xdgConfig = null; string globalConfig = null; string localConfig = null; // read Git's four configs from lowest priority to highest, overwriting values as // higher priority configurations are parsed, storing them in a handy lookup table // find and parse Git's portable config if ((types & ConfigurationLevel.Portable) != 0 && Where.GitPortableConfig(out portableConfig)) { ParseGitConfig(ConfigurationLevel.Portable, portableConfig); } // find and parse Git's system config if ((types & ConfigurationLevel.System) != 0 && Where.GitSystemConfig(null, out systemConfig)) { ParseGitConfig(ConfigurationLevel.System, systemConfig); } // find and parse Git's Xdg config if ((types & ConfigurationLevel.Xdg) != 0 && Where.GitXdgConfig(out xdgConfig)) { ParseGitConfig(ConfigurationLevel.Xdg, xdgConfig); } // find and parse Git's global config if ((types & ConfigurationLevel.Global) != 0 && Where.GitGlobalConfig(out globalConfig)) { ParseGitConfig(ConfigurationLevel.Global, globalConfig); } // find and parse Git's local config if ((types & ConfigurationLevel.Local) != 0 && Where.GitLocalConfig(directory, out localConfig)) { ParseGitConfig(ConfigurationLevel.Local, localConfig); } Git.Trace.WriteLine($"git {types} config read, {Count} entries."); }
private void ShowUser(bool isGlobal) { ConfigurationLevel level = isGlobal ? ConfigurationLevel.Global : ConfigurationLevel.Local; using Repository repo = new Repository(Environment.CurrentDirectory); ConfigurationEntry <string> emailEntry = repo.Config.Get <string>("user.email", level); if (emailEntry == null) { Log.Red($"{level.ToString()} user is not set."); return; } Log.Green($"The {level.ToString()} user is set to {emailEntry.Value}"); }
public virtual async Task LoadGitConfiguration(string directory, ConfigurationLevel types) { string portableConfig = null; string systemConfig = null; string xdgConfig = null; string globalConfig = null; string localConfig = null; // Read Git's five configuration files from lowest priority to highest, overwriting values as higher priority configurations are parsed, storing them in a handy lookup table. // Find and parse Git's portable configuration file. if ((types & ConfigurationLevel.Portable) != 0 && Where.GitPortableConfig(out portableConfig)) { await ParseGitConfig(ConfigurationLevel.Portable, portableConfig); } // Find and parse Git's system configuration file. if ((types & ConfigurationLevel.System) != 0 && Where.GitSystemConfig(null, out systemConfig)) { await ParseGitConfig(ConfigurationLevel.System, systemConfig); } // Find and parse Git's XDG configuration file. if ((types & ConfigurationLevel.Xdg) != 0 && Where.GitXdgConfig(out xdgConfig)) { await ParseGitConfig(ConfigurationLevel.Xdg, xdgConfig); } // Find and parse Git's global configuration file. if ((types & ConfigurationLevel.Global) != 0 && Where.GitGlobalConfig(out globalConfig)) { await ParseGitConfig(ConfigurationLevel.Global, globalConfig); } // Find and parse Git's local configuration file. if ((types & ConfigurationLevel.Local) != 0 && Where.GitLocalConfig(directory, out localConfig)) { await ParseGitConfig(ConfigurationLevel.Local, localConfig); } Trace.WriteLine($"git {types} config read, {Count} entries."); }
/// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "key"></param> /// <param name = "value"></param> /// <param name = "level"></param> public void Set <T>(string key, T value, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); if (level == ConfigurationLevel.Local && !HasLocalConfig) { throw new LibGit2Exception("No local configuration file has been found. You must use ConfigurationLevel.Global when accessing configuration outside of repository."); } if (level == ConfigurationLevel.Global && !HasGlobalConfig) { throw new LibGit2Exception("No global configuration file has been found."); } if (level == ConfigurationLevel.System && !HasSystemConfig) { throw new LibGit2Exception("No system configuration file has been found."); } ConfigurationSafeHandle h; switch (level) { case ConfigurationLevel.Local: h = localHandle; break; case ConfigurationLevel.Global: h = globalHandle; break; case ConfigurationLevel.System: h = systemHandle; break; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Configuration level has an unexpected value ('{0}').", Enum.GetName(typeof(ConfigurationLevel), level)), "level"); } if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); Save(); }
private ConfigurationHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationHandle fromHandle) { ConfigurationHandle handle = null; if (fromHandle != null) { handle = Proxy.git_config_open_level(fromHandle, level); } if (handle == null && throwIfStoreHasNotBeenFound) { throw new LibGit2SharpException("No {0} configuration file has been found.", Enum.GetName(typeof(ConfigurationLevel), level)); } return(handle); }
private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound) { ConfigurationSafeHandle handle = null; if (configHandle != null) { handle = Proxy.git_config_open_level(configHandle, level); } if (handle == null && throwIfStoreHasNotBeenFound) { throw new LibGit2SharpException( string.Format(CultureInfo.InvariantCulture, "No {0} configuration file has been found.", Enum.GetName(typeof(ConfigurationLevel), level))); } return(handle); }
private void ParseGitConfig(ConfigurationLevel level, string configPath) { Debug.Assert(Enum.IsDefined(typeof(ConfigurationLevel), level), $"The `{nameof(level)}` parameter is not defined."); Debug.Assert(!String.IsNullOrWhiteSpace(configPath), $"The `{nameof(configPath)}` parameter is null or invalid."); Debug.Assert(File.Exists(configPath), $"The `{nameof(configPath)}` parameter references a non-existent file."); if (!_values.ContainsKey(level)) { return; } if (!File.Exists(configPath)) { return; } using (var sr = new StreamReader(File.OpenRead(configPath))) { ParseGitConfig(sr, _values[level]); } }
/// <inheritdoc/> public IEnumerable <string> GetKeys(ConfigurationLevel level) { var returnKeys = new Dictionary <string, string>(); if (!isRoot && Parent != null && level == ConfigurationLevel.Deep) { var configKeys = Parent.GetKeys(level); foreach (var pair in configKeys) { returnKeys[pair] = pair; } } foreach (var configKey in values.Keys) { returnKeys[configKey] = configKey; } return(returnKeys.Values.AsEnumerable()); }
private static ConfigurationEntry<string> FakeConfigurationEntry(string key, string value, ConfigurationLevel level) { return new Mock<ConfigurationEntry<string>>(key, value, level).Object; }
/// <inheritdoc/> public IEnumerable<ConfigKey> GetKeys(ConfigurationLevel level) { var returnKeys = new Dictionary<string, ConfigKey>(); if (!isRoot && Parent != null && level == ConfigurationLevel.Deep) { var configKeys = Parent.GetKeys(level); foreach (var pair in configKeys) { returnKeys[pair.Name] = pair; } } foreach (var configKey in keys) { returnKeys[configKey.Key] = configKey.Value; } return returnKeys.Values.AsEnumerable(); }