public static IServiceCollection AddDapperApplicationBuilder(this IServiceCollection services) { services.AddTransient(provider => { var conn = provider.GetService<SqlConnection>(); var userStore = new UserStore(conn); var repo = new RepositoryOptions<User> { UserStore = userStore, UserEmailStore = new UserEmailStore(conn), UserLockoutStore = new UserLockoutStore(conn), UserLoginStore = new UserLoginStore(conn), UserPasswordStore = new UserPasswordStore(conn), UserPropertyStore = new UserPropertyStore(conn), UserRoleStore = new UserRoleStore(conn), UserTokenStore = new UserUpdateTokenStore(conn) }; return new UserManager<User>(repo, provider.GetService<IEmailService>(), provider.GetService<ILogger<UserManager<User>>>(), TimeSpan.FromDays(1)); }); services.AddTransient( provider => { var manager = provider.GetService<UserManager<User>>(); return new LoginManager<User>(provider.GetService<UserManager<User>>(), provider.GetService<ILogger<LoginManager<User>>>(), new LoginManagerOptions<User> { ClaimsProvider = new ClaimsProvider<User>(manager, new ClaimTypesOptions()) }); }); return services; }
public void CanOpenABareRepoAsIfItWasAStandardOneWithANonExisitingIndexFile() { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var repo = new Repository(BareTestRepoPath, options)) { var st = repo.Index.RetrieveStatus("1/branch_file.txt"); Assert.Equal(FileStatus.Removed, st); } }
public void CanOpenABareRepoWithOptions() { var options = new RepositoryOptions { GlobalConfigurationLocation = null }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { Assert.True(repo.Info.IsBare); } }
public void CanOpenABareRepoAsIfItWasAStandardOne() { File.Copy(Path.Combine(StandardTestRepoPath, "index"), newIndex); var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var repo = new Repository(BareTestRepoPath, options)) { var st = repo.Index.RetrieveStatus("1/branch_file.txt"); Assert.Equal(FileStatus.Missing, st); } }
public void CanEnumerateGlobalConfig() { string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(StandardTestRepoPath, options)) { var entry = repo.Config.FirstOrDefault<ConfigurationEntry<string>>(e => e.Key == "user.name"); Assert.NotNull(entry); Assert.Equal(Constants.Signature.Name, entry.Value); } }
public void CanFindInGlobalConfig() { string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(StandardTestRepoPath, options)) { var matches = repo.Config.Find(@"\.name", ConfigurationLevel.Global); Assert.NotNull(matches); Assert.Equal(new[] { "user.name" }, matches.Select(m => m.Key).ToArray()); } }
/// <inheritdoc/> public DefaultCosmosClientProvider( CosmosClientOptions cosmosClientOptions, IOptions <RepositoryOptions> options) { _cosmosClientOptions = cosmosClientOptions ?? throw new ArgumentNullException( nameof(cosmosClientOptions), "Cosmos Client options are required."); _options = options?.Value ?? throw new ArgumentNullException( nameof(options), "Repository options are required."); _lazyCosmosClient = new Lazy <CosmosClient>( () => new CosmosClient(_options.CosmosConnectionString, _cosmosClientOptions)); }
public void CanOpenABareRepoAsIfItWasAStandardOne() { File.Copy(Path.Combine(StandardTestRepoPath, "index"), newIndex); var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { var st = repo.RetrieveStatus("1/branch_file.txt"); Assert.Equal(FileStatus.DeletedFromWorkdir, st); } }
public void CanEnumerateGlobalConfig() { string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path, options)) { var entry = repo.Config.FirstOrDefault <ConfigurationEntry <string> >(e => e.Key == "user.name"); Assert.NotNull(entry); Assert.Equal(Constants.Signature.Name, entry.Value); } }
private static RepositoryOptions configureTemporaryRepository(string baseRepositoryPath, string repoName) { removeTemporaryRepository(baseRepositoryPath, repoName); var tempPath = Path.Combine(Path.GetDirectoryName(baseRepositoryPath), repoName); string tempIndex = Path.Combine(tempPath, "tmp_idx"); Directory.CreateDirectory(tempPath); var repoOpts = new RepositoryOptions { WorkingDirectoryPath = tempPath, IndexPath = tempIndex }; return(repoOpts); }
public void CanProvideADifferentWorkDirToAStandardRepo() { var path1 = CloneStandardTestRepo(); using (var repo = new Repository(path1)) { Assert.Equal(FileStatus.Unaltered, repo.Index.RetrieveStatus("1/branch_file.txt")); } var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir }; var path2 = CloneStandardTestRepo(); using (var repo = new Repository(path2, options)) { Assert.Equal(FileStatus.Missing, repo.Index.RetrieveStatus("1/branch_file.txt")); } }
public DefaultCosmosContainerProvider( ICosmosClientProvider cosmosClientProvider, ICosmosPartitionKeyPathProvider cosmosPartitionKeyPathProvider, ICosmosContainerNameProvider cosmosContainerNameProvider, IOptions <RepositoryOptions> options, ILogger <DefaultCosmosContainerProvider <TItem> > logger) { _cosmosClientProvider = cosmosClientProvider ?? throw new ArgumentNullException( nameof(cosmosClientProvider), "Cosmos client provider is required."); _cosmosPartitionKeyPathProvider = cosmosPartitionKeyPathProvider ?? throw new ArgumentNullException( nameof(cosmosPartitionKeyPathProvider), "Cosmos partition key name provider is required."); _cosmosContainerNameProvider = cosmosContainerNameProvider ?? throw new ArgumentNullException( nameof(cosmosContainerNameProvider), "Cosmos container name provider is required."); _options = options?.Value ?? throw new ArgumentNullException( nameof(options), "Repository options are required."); _logger = logger ?? throw new ArgumentNullException($"The {nameof(logger)} is required."); if (_options.CosmosConnectionString is null) { throw new ArgumentNullException($"The {nameof(_options.CosmosConnectionString)} is required."); } if (_options.ContainerPerItemType is false) { if (_options.DatabaseId is null) { throw new ArgumentNullException( $"The {nameof(_options.DatabaseId)} is required when container per item type is false."); } if (_options.ContainerId is null) { throw new ArgumentNullException( $"The {nameof(_options.ContainerId)} is required when container per item type is false."); } } _lazyContainer = new Lazy <Task <Container> >(async() => await GetContainerValueFactoryAsync()); _cosmosContainerNameProvider = cosmosContainerNameProvider; }
public void CannotBuildAProperSignatureFromConfigWhenFullIdentityCannotBeFoundInTheConfig(string name, string email) { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(name, email); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { Assert.Equal(name, repo.Config.GetValueOrDefault <string>("user.name")); Assert.Equal(email, repo.Config.GetValueOrDefault <string>("user.email")); Signature signature = repo.Config.BuildSignature(DateTimeOffset.Now); Assert.Null(signature); } }
public RepositoryReadInfrastructure(IDbContextFactory _factory, IRepositoryInfrastructureBase <TDbContext> _infrastructureBase, RepositoryOptions <TDbContext> _unitOfWorkOptions) { factory = _factory; infrastructureBase = _infrastructureBase; unitOfWorkOptions = _unitOfWorkOptions; //验证是否开启了事务 如果开启了事务 就获取主库的连接 //或者没有开启读写分离 直接使用 主库的数据 if (_unitOfWorkOptions.IsBeginTran || !_unitOfWorkOptions.IsOpenMasterSlave) { slaveDbContext = _factory.GetMaster <TDbContext>(); IsMaster = true; } else { slaveDbContext = _factory.GetSlave <TDbContext>(); _infrastructureBase.SwitchSlaveAsync(slaveDbContext).ConfigureAwait(false).GetAwaiter().GetResult(); } }
/// <summary> /// 构造注入 /// </summary> /// <param name="_options"></param> /// <param name="_service"></param> public BaseRepository(IServiceProvider _service, RepositoryOptions <TDbContext> _unitOfWorkOptions, IDbContextFactory _repositoryFactory, IRepositoryMediator <TDbContext> _repositoryMediator, IEFOptionsFactory eFOptionsFactory) { unitOfWorkOptions = _unitOfWorkOptions; //获取上下文类型 unitOfWorkOptions.DbContextType = typeof(TDbContext); //获取ef的配置信息 var dbInfo = eFOptionsFactory.Get <TDbContext>(); unitOfWorkOptions.WriteReadConnectionString = dbInfo?.WriteReadConnectionString; //是否开启读写分离操作 unitOfWorkOptions.IsOpenMasterSlave = dbInfo.IsOpenMasterSlave; //获取上下文 var _dbContext = _service.GetService(unitOfWorkOptions.DbContextType) as DbContext; //设置上下文工厂 _repositoryFactory.Set(unitOfWorkOptions?.DbContextType, _dbContext); repositoryMediator = _repositoryMediator; }
public void CanProvideADifferentWorkDirToAStandardRepo() { var scd = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath); using (var repo = new Repository(scd.DirectoryPath)) { Assert.Equal(FileStatus.Unaltered, repo.Index.RetrieveStatus("1/branch_file.txt")); } var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir }; scd = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath); using (var repo = new Repository(scd.DirectoryPath, options)) { Assert.Equal(FileStatus.Missing, repo.Index.RetrieveStatus("1/branch_file.txt")); } }
/// <summary> /// Adds the repository factory to the service collection. /// </summary> /// <typeparam name="TEntity">Entity type of the repository.</typeparam> /// <typeparam name="TFactory">Factory type for the repository factory. Default is <see cref="RepositoryFactory{TEntity,TRepo}"></see>/></typeparam> /// <typeparam name="TRepo"></typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services.</param> /// <param name="optionsAction">Action for the repository options.</param> /// <returns><see cref="RepositoryBuilder{TEntity}"/> for configuring options for the repository if they are not provided already.</returns> public static RepositoryBuilder <TEntity> AddRepository <TEntity, TFactory, TRepo>( this IServiceCollection services, Action <RepositoryOptions <TEntity> > optionsAction = null) where TEntity : class where TFactory : class, IRepositoryFactory <TEntity, TRepo> where TRepo : IRepository <TEntity> { var repoOptions = new RepositoryOptions <TEntity>(); optionsAction?.Invoke(repoOptions); services.TryAddSingleton <IRepositoryFactory <TEntity, TRepo>, TFactory>(); services.Configure <RepositoryOptions <TEntity> >(options => { options.SaveChangesOnDispose = true; }); return(new RepositoryBuilder <TEntity>(services)); }
public void CorrectlyEncodesAndDecodesInput() { const string decodedInput = "This is a substitution cipher"; const string encodedInput = "Guvf vf n fhofgvghgvba pvcure"; var attributes = new List <FilterAttributeEntry> { new FilterAttributeEntry("rot13") }; var filter = new SubstitutionCipherFilter("cipher-filter", attributes); var filterRegistration = GlobalSettings.RegisterFilter(filter); string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".rot13"; string configPath = CreateConfigurationWithDummyUser(Constants.Identity); var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, repositoryOptions)) { CreateAttributesFile(repo, "*.rot13 filter=rot13"); var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); var textDetected = blob.GetContentText(); Assert.Equal(encodedInput, textDetected); Assert.Equal(1, filter.CleanCalledCount); Assert.Equal(0, filter.SmudgeCalledCount); var branch = repo.CreateBranch("delete-files"); repo.Checkout(branch.FriendlyName); DeleteFile(repo, fileName); repo.Checkout("master"); var fileContents = ReadTextFromFile(repo, fileName); Assert.Equal(1, filter.SmudgeCalledCount); Assert.Equal(decodedInput, fileContents); } GlobalSettings.DeregisterFilter(filterRegistration); }
public void CommitWithInvalidSignatureConfigThrows(string name, string email) { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(name, email); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { Assert.Equal(name, repo.Config.GetValueOrDefault <string>("user.name")); Assert.Equal(email, repo.Config.GetValueOrDefault <string>("user.email")); Assert.Throws <LibGit2SharpException>( () => repo.Commit("Initial egotistic commit", new CommitOptions { AllowEmptyCommit = true })); } }
private string MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(string workingDirectoryPath) { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var sneakyRepo = new Repository(workingDirectoryPath, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, Path.GetFullPath(sneakyRepo.Info.WorkingDirectory)); sneakyRepo.Reset(ResetOptions.Mixed, sneakyRepo.Head.Tip.Sha); var filepath = Path.Combine(sneakyRepo.Info.WorkingDirectory, "zomg.txt"); File.WriteAllText(filepath, "I'm being sneaked in!\n"); sneakyRepo.Index.Stage(filepath); return(sneakyRepo.Commit("Tadaaaa!", DummySignature, DummySignature).Sha); } }
private string MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(string workingDirectoryPath) { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var sneakyRepo = new Repository(workingDirectoryPath, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, Path.GetFullPath(sneakyRepo.Info.WorkingDirectory)); sneakyRepo.Reset(ResetMode.Mixed, sneakyRepo.Head.Tip.Sha); const string filename = "zomg.txt"; Touch(sneakyRepo.Info.WorkingDirectory, filename, "I'm being sneaked in!\n"); sneakyRepo.Index.Stage(filename); return(sneakyRepo.Commit("Tadaaaa!", Constants.Signature, Constants.Signature).Sha); } }
private RepositoryOptions BuildFakeSystemConfigFilemodeOption( SelfCleaningDirectory scd, bool value) { Directory.CreateDirectory(scd.DirectoryPath); var options = new RepositoryOptions { SystemConfigurationLocation = Path.Combine( scd.RootedDirectoryPath, "fake-system.config") }; StringBuilder sb = new StringBuilder() .AppendFormat("[core]{0}", Environment.NewLine) .AppendFormat("filemode = {1}{0}", Environment.NewLine, value); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); return(options); }
private void connectSynchronization(RepositoryOptions ro) { try { String syncIt = "[" + ro.LastUsername + "].SyncItem"; String fieldSt = "[" + ro.LastUsername + "].FieldState"; MappingDictionary.Mapping.Add(typeof(SyncItem), syncIt); MappingDictionary.Mapping.Add(typeof(FieldState), fieldSt); Synchronization.RegisterType(typeof(SyncItem)); Synchronization.RegisterType(typeof(FieldState)); Synchronization.Activate(); State |= ConnectionState.ConnectedToSynchronization; } catch// (Exception syncDBEx) { Synchronization = null; MappingDictionary.Mapping.Clear(); State &= ~ConnectionState.ConnectedToSynchronization; } }
/** * Baut Verbindungen auf und aktualisiert die Anzeige */ private void buttonConnectToRepository_Click(object sender, RoutedEventArgs e) { ILanguage lf = OptionsAccess.Language; RepositoryOptions ro = OptionsAccess.RepositoryOptions; this.buttonConnectToRepository.IsEnabled = false; //Wartecursor anzeigen Cursor defaultCursor = this.Cursor; this.Cursor = Cursors.Wait; if (State.CheckForFlags(ConnectionsAccess.ConnectionState.RepositoryConnected, false)) { ConnectionsAccess.Instance.disconnectFromRepository(); } else { //Passwort abhängig von den Sichtbarkeitseinstellungen abrufen string password = (textBoxPassword.Visibility == Visibility.Visible) ? textBoxPassword.Password : textBoxPasswordVisible.Text; ConnectionsAccess.Instance.connectToRepository(OptionsAccess.RepositoryOptions, textBoxUsername.Text, password); if (!State.hasFlags(ConnectionsAccess.ConnectionState.RepositoryConnected)) { (new MessageBoxWindow(960, 960, 961, 962)).ShowDialog(); } } this.Cursor = defaultCursor; if (State.CheckForFlags(ConnectionsAccess.ConnectionState.RepositoryConnected, false)) { this.buttonConnectToRepository.Content = lf.getLanguageString(933); } else { this.buttonConnectToRepository.Content = lf.getLanguageString(932); } this.buttonConnectToRepository.IsEnabled = true; HasNext = State.hasFlags(ConnectionsAccess.ConnectionState.FullyConnected); }
public void CanAccessConfigurationWithoutARepository(Func <string, string> localConfigurationPathProvider) { var path = SandboxStandardTestRepoGitDir(); string globalConfigPath = CreateConfigurationWithDummyUser(Constants.Identity); var options = new RepositoryOptions { GlobalConfigurationLocation = globalConfigPath }; using (var repo = new Repository(path, options)) { repo.Config.Set("my.key", "local"); repo.Config.Set("my.key", "mouse", ConfigurationLevel.Global); } using (var config = Configuration.BuildFrom(localConfigurationPathProvider(path), globalConfigPath)) { Assert.Equal("local", config.Get <string>("my.key").Value); Assert.Equal("mouse", config.Get <string>("my.key", ConfigurationLevel.Global).Value); } }
public void CanProvideADifferentIndexToAStandardRepo() { var path1 = CloneStandardTestRepo(); using (var repo = new Repository(path1)) { Assert.Equal(FileStatus.Untracked, repo.Index.RetrieveStatus("new_untracked_file.txt")); repo.Index.Stage("new_untracked_file.txt"); Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus("new_untracked_file.txt")); File.Copy(Path.Combine(repo.Info.Path, "index"), newIndex); } var options = new RepositoryOptions { IndexPath = newIndex }; var path2 = CloneStandardTestRepo(); using (var repo = new Repository(path2, options)) { Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus("new_untracked_file.txt")); } }
public void CanAddANoteWithSignatureFromConfig() { string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; string path = CloneBareTestRepo(); using (var repo = new Repository(path, options)) { var commit = repo.Lookup <Commit>("9fd738e8f7967c078dceed8190330fc8648ee56a"); var note = repo.Notes.Add(commit.Id, "I'm batman!\n", "batmobile"); var newNote = commit.Notes.Single(); Assert.Equal(note, newNote); Assert.Equal("I'm batman!\n", newNote.Message); Assert.Equal("batmobile", newNote.Namespace); AssertCommitSignaturesAre(repo.Lookup <Commit>("refs/notes/batmobile"), Constants.Signature); } }
/** * Aktualisiert die Optionen in der Ansicht */ private void UpdateRepositoryOptionsView() { RepositoryOptions ro = OptionsAccess.RepositoryOptions; ComboBoxItem cbiName = new ComboBoxItem(); cbiName.Content = ro.ConnectionName; this.comboBoxConnectionName.Items.Clear(); this.comboBoxConnectionName.Items.Add(cbiName); this.comboBoxConnectionName.SelectedItem = cbiName; if (ro.SqlAuthentification == true) { this.radioButtonSQL.IsChecked = true; this.radioButtonWindows.IsChecked = false; } else { this.radioButtonSQL.IsChecked = false; this.radioButtonWindows.IsChecked = true; } this.textBoxIPAddress.Text = ro.IPAddress; this.textBoxIPPort.Text = ro.IPPort; ComboBoxItem cbiCatalog = new ComboBoxItem(); cbiCatalog.Content = ro.InitialCatalog; this.comboBoxCatalog.Items.Clear(); this.comboBoxCatalog.Items.Add(cbiCatalog); this.comboBoxCatalog.SelectedItem = cbiCatalog; ComboBoxItem cbiTaxonCatalog = new ComboBoxItem(); cbiTaxonCatalog.Content = ro.TaxonNamesInitialCatalog; this.comboBoxTaxonCatalog.Items.Clear(); this.comboBoxTaxonCatalog.Items.Add(cbiTaxonCatalog); this.comboBoxTaxonCatalog.SelectedItem = cbiTaxonCatalog; }
/** * Speichert die Optionen ab */ private void SaveRepositoryOptions() { RepositoryOptions ro = OptionsAccess.RepositoryOptions; ro.ConnectionName = (string)((ComboBoxItem)this.comboBoxConnectionName.SelectedItem).Content; if (this.radioButtonSQL.IsChecked == null || this.radioButtonSQL.IsChecked == false) { ro.SqlAuthentification = false; } else { ro.SqlAuthentification = true; } ro.IPAddress = this.textBoxIPAddress.Text; ro.IPPort = this.textBoxIPPort.Text; ro.InitialCatalog = this.comboBoxCatalog.Text; ro.TaxonNamesInitialCatalog = this.comboBoxTaxonCatalog.Text; OptionsAccess.RepositoryOptions = ro; DialogResult = true; }
public void CanProvideDifferentConfigurationFilesToARepository() { string globalLocation = Path.Combine(newWorkdir, "my-global-config"); string xdgLocation = Path.Combine(newWorkdir, "my-xdg-config"); string systemLocation = Path.Combine(newWorkdir, "my-system-config"); const string name = "Adam 'aroben' Roben"; const string email = "*****@*****.**"; StringBuilder sb = new StringBuilder() .AppendLine("[user]") .AppendFormat("name = {0}{1}", name, Environment.NewLine) .AppendFormat("email = {0}{1}", email, Environment.NewLine); File.WriteAllText(globalLocation, sb.ToString()); File.WriteAllText(systemLocation, string.Empty); File.WriteAllText(xdgLocation, string.Empty); var options = new RepositoryOptions { GlobalConfigurationLocation = globalLocation, XdgConfigurationLocation = xdgLocation, SystemConfigurationLocation = systemLocation, }; string path = SandboxBareTestRepo(); using (var repo = new Repository(path, options)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.Global)); Assert.Equal(name, repo.Config.Get <string>("user.name").Value); Assert.Equal(email, repo.Config.Get <string>("user.email").Value); repo.Config.Set("xdg.setting", "https://twitter.com/libgit2sharp", ConfigurationLevel.Xdg); repo.Config.Set("help.link", "https://twitter.com/xpaulbettsx/status/205761932626636800", ConfigurationLevel.System); } AssertValueInConfigFile(systemLocation, "xpaulbettsx"); }
public void CanRemoveANoteWithSignatureFromConfig() { string configPath = CreateConfigurationWithDummyUser(Constants.Signature); RepositoryOptions options = new RepositoryOptions() { GlobalConfigurationLocation = configPath }; string path = CloneBareTestRepo(); using (var repo = new Repository(path, options)) { var commit = repo.Lookup <Commit>("8496071c1b46c854b31185ea97743be6a8774479"); var notes = repo.Notes[commit.Id]; Assert.NotEmpty(notes); repo.Notes.Remove(commit.Id, repo.Notes.DefaultNamespace); Assert.Empty(notes); AssertCommitSignaturesAre(repo.Lookup <Commit>("refs/notes/" + repo.Notes.DefaultNamespace), Constants.Signature); } }
public void CanProvideADifferentIndexToAStandardRepo() { var scd = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath); using (var repo = new Repository(scd.DirectoryPath)) { Assert.Equal(FileStatus.Untracked, repo.Index.RetrieveStatus("new_untracked_file.txt")); repo.Index.Stage("new_untracked_file.txt"); Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus("new_untracked_file.txt")); File.Copy(Path.Combine(repo.Info.Path, "index"), newIndex); } var options = new RepositoryOptions { IndexPath = newIndex }; scd = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath); using (var repo = new Repository(scd.DirectoryPath, options)) { Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus("new_untracked_file.txt")); } }
public Repo(string path, RepoOptions options = null) { if (options == null) { options = new RepoOptions(); } if (!Repository.IsValid(path)) { Repository.Init(path, true); } var repositoryOptions = new RepositoryOptions() { }; _repo = new Repository(path, repositoryOptions); if (!string.IsNullOrEmpty(options.RemoteName)) { _repo.Network.Remotes.Add(options.RemoteName, options.RemoteUrl); } _branchName = options.Branch ?? "master"; }
public async Task UpgradeAsync(RepositoryOptions options, CancellationToken cancel = default) { var path = Path.Combine(options.Folder, "pins"); var folder = new DirectoryInfo(path); if (!folder.Exists) { return; } var store = new FileStore <Cid, Pin1> { Folder = path, NameToKey = (cid) => cid.Hash.ToBase32(), KeyToName = (key) => new MultiHash(key.FromBase32()) }; var files = folder.EnumerateFiles().Where(fi => fi.Length == 0); foreach (var fi in files) { try { var cid = Cid.Decode(fi.Name); await store.PutAsync(cid, new Pin1 { Id = cid }, cancel).ConfigureAwait(false); File.Delete(fi.FullName); } catch { // ignored } } }
public void SmudgeIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int smudgeCount) { const string decodedInput = "This is a substitution cipher"; var filterForAttributes = new List <FilterAttributeEntry> { new FilterAttributeEntry(filterAttribute) }; var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes); var filterRegistration = GlobalSettings.RegisterFilter(filter); string repoPath = InitNewRepository(); string fileName = Guid.NewGuid() + ".txt"; string configPath = CreateConfigurationWithDummyUser(Constants.Identity); var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, repositoryOptions)) { CreateAttributesFile(repo, attributeEntry); CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput); var branch = repo.CreateBranch("delete-files"); repo.Checkout(branch.FriendlyName); DeleteFile(repo, fileName); repo.Checkout("master"); Assert.Equal(smudgeCount, filter.SmudgeCalledCount); } GlobalSettings.DeregisterFilter(filterRegistration); }
public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = BuildFakeRepositoryOptions(scd, options); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(options.XdgConfigurationLocation, sb.ToString()); return(options); }
public void CanCommitOnBareRepository() { string repoPath = InitNewRepository(true); SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string workPath = Path.Combine(scd.RootedDirectoryPath, "work"); Directory.CreateDirectory(workPath); var repositoryOptions = new RepositoryOptions { WorkingDirectoryPath = workPath, IndexPath = Path.Combine(scd.RootedDirectoryPath, "index") }; using (var repo = new Repository(repoPath, repositoryOptions)) { const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Stage(relativeFilepath); Assert.NotNull(repo.Commit("Initial commit", Constants.Signature, Constants.Signature)); Assert.Equal(1, repo.Head.Commits.Count()); Assert.Equal(1, repo.Commits.Count()); } }
private void button2_Click(object sender, EventArgs e) { myBroker = new SimpleBlockBroker(); RepositoryOptions opt = new RepositoryOptions(); opt.Folder = txtBlocksFolder.Text; myBroker.SetupBroker(opt); innerWeb = new BlockWeb(txtWebId.Text, myBroker); //innerWeb.AddBlock(BlockHandle.New("DummyBlock")); //string logger = innerWeb.AddBlock(BlockHandle.New("Logger")); //string formBuilder = innerWeb.AddBlock(BlockHandle.New("FormBuilder")); //innerWeb[formBuilder].ProcessRequest("BuildForm", "frmLog"); //innerWeb[logger]["ContainerControl"].AttachEndPoint(formBuilder, "GetForm", new object[] { "frmLog" }); //innerWeb[formBuilder].ProcessRequest("ShowForm", "frmLog"); //innerWeb[EventCode.LogWebEvent].AttachEndPoint(logger, "Log"); txtBlocksFolder.Enabled = false; txtWebId.Enabled = false; button1.Enabled = false; button2.Enabled = false; lblWebAddress.Text= innerWeb.Address; cmdRefresh.Enabled = true; cmdShutdown.Enabled = true; button2.Enabled = false; startTime = DateTime.Now; timer1.Enabled = true; MessageBox.Show("BlockWeb is Started!"); //innerWeb[logger].ProcessRequest("Log", LogType.General, "BlockWeb is Started!"); }
private static ServiceProvider GetProviderConfiguredServicesFromTenantContext(string tenantHost = "http://domain.tenant.one.com") { var services = new ServiceCollection(); var options = new RepositoryOptions(); options .EnabledInMemory() .EnabledLogging(); services.AddLogging(); services.AddDbContext <TenantDbContext>(options.Builder()); services.AddContext <MultiTenantContext>(options => { options .EnabledInMemory() .EnabledLogging(); }); services.AddRepository <ITestTenantReadRepository, TestTenantReadRepository>(new[] { "Optsol.Components.Test.Utils" }); services.AddSingleton <IHttpContextAccessor>(x => new HttpContextAccessorTest(tenantHost)); services.AddSingleton <ITenantProvider, DataBaseTenantProvider>(); return(services.BuildServiceProvider()); }
private RepositoryOptions BuildFakeSystemConfigFilemodeOption( SelfCleaningDirectory scd, bool value) { Directory.CreateDirectory(scd.DirectoryPath); var options = new RepositoryOptions { SystemConfigurationLocation = Path.Combine( scd.RootedDirectoryPath, "fake-system.config") }; StringBuilder sb = new StringBuilder() .AppendFormat("[core]{0}", Environment.NewLine) .AppendFormat("filemode = {1}{0}", Environment.NewLine, value); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); return options; }
public void CanProvideADifferentIndexToAStandardRepo() { var path1 = SandboxStandardTestRepo(); using (var repo = new Repository(path1)) { Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus("new_untracked_file.txt")); Commands.Stage(repo, "new_untracked_file.txt"); Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus("new_untracked_file.txt")); File.Copy(Path.Combine(repo.Info.Path, "index"), newIndex); } var options = new RepositoryOptions { IndexPath = newIndex }; var path2 = SandboxStandardTestRepo(); using (var repo = new Repository(path2, options)) { Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus("new_untracked_file.txt")); } }
public void OpeningARepoWithAnEmptyRepositoryOptionsThrows() { var options = new RepositoryOptions(); Repository repo; Assert.Throws<ArgumentException>(() => repo = new Repository(BareTestRepoPath, options)); Assert.Throws<ArgumentException>(() => repo = new Repository(StandardTestRepoPath, options)); }
private string MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(string workingDirectoryPath) { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var sneakyRepo = new Repository(workingDirectoryPath, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, Path.GetFullPath(sneakyRepo.Info.WorkingDirectory)); sneakyRepo.Reset(ResetMode.Mixed, sneakyRepo.Head.Tip.Sha); const string filename = "zomg.txt"; Touch(sneakyRepo.Info.WorkingDirectory, filename, "I'm being sneaked in!\n"); sneakyRepo.Index.Stage(filename); return sneakyRepo.Commit("Tadaaaa!", Constants.Signature, Constants.Signature).Sha; } }
public void CanProvideDifferentConfigurationFilesToARepository() { string globalLocation = Path.Combine(newWorkdir, "my-global-config"); string xdgLocation = Path.Combine(newWorkdir, "my-xdg-config"); string systemLocation = Path.Combine(newWorkdir, "my-system-config"); const string name = "Adam 'aroben' Roben"; const string email = "*****@*****.**"; StringBuilder sb = new StringBuilder() .AppendLine("[user]") .AppendFormat("name = {0}{1}", name, Environment.NewLine) .AppendFormat("email = {0}{1}", email, Environment.NewLine); File.WriteAllText(globalLocation, sb.ToString()); File.WriteAllText(systemLocation, string.Empty); File.WriteAllText(xdgLocation, string.Empty); var options = new RepositoryOptions { GlobalConfigurationLocation = globalLocation, XdgConfigurationLocation = xdgLocation, SystemConfigurationLocation = systemLocation, }; using (var repo = new Repository(BareTestRepoPath, options)) { Assert.True(repo.Config.HasConfig(ConfigurationLevel.Global)); Assert.Equal(name, repo.Config.Get<string>("user.name").Value); Assert.Equal(email, repo.Config.Get<string>("user.email").Value); repo.Config.Set("xdg.setting", "https://twitter.com/libgit2sharp", ConfigurationLevel.Xdg); repo.Config.Set("help.link", "https://twitter.com/xpaulbettsx/status/205761932626636800", ConfigurationLevel.System); } AssertValueInConfigFile(systemLocation, "xpaulbettsx"); }
public void CanProvideDifferentWorkingDirOnClone() { string url = "https://github.com/libgit2/TestGitRepository"; var scd = BuildSelfCleaningDirectory(); var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir }; using (var repo = Repository.Clone(url, scd.DirectoryPath, false, true, null, null, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, repo.Info.WorkingDirectory); } }
public void CanProvideDifferentWorkingDirOnInit() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var options = new RepositoryOptions {WorkingDirectoryPath = newWorkdir}; using (var repo = Repository.Init(scd.DirectoryPath, false, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, repo.Info.WorkingDirectory); } }
private string MeanwhileInAnotherDimensionAnEvilMastermindIsAtWork(string workingDirectoryPath) { var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex }; using (var sneakyRepo = new Repository(workingDirectoryPath, options)) { Assert.Equal(Path.GetFullPath(newWorkdir) + Path.DirectorySeparatorChar, Path.GetFullPath(sneakyRepo.Info.WorkingDirectory)); sneakyRepo.Reset(ResetOptions.Mixed, sneakyRepo.Head.Tip.Sha); var filepath = Path.Combine(sneakyRepo.Info.WorkingDirectory, "zomg.txt"); File.WriteAllText(filepath, "I'm being sneaked in!\n"); sneakyRepo.Index.Stage(filepath); return sneakyRepo.Commit("Tadaaaa!", DummySignature, DummySignature).Sha; } }
public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = BuildFakeRepositoryOptions(scd, options); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(options.XdgConfigurationLocation, sb.ToString()); return options; }
protected Repository InitIsolatedRepository(string path = null, bool isBare = false, RepositoryOptions options = null) { path = path ?? InitNewRepository(isBare); options = BuildFakeConfigs(BuildSelfCleaningDirectory(), options); return new Repository(path, options); }
private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = options ?? new RepositoryOptions(); string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); options.GlobalConfigurationLocation = Path.Combine(confs, "my-global-config"); options.XdgConfigurationLocation = Path.Combine(confs, "my-xdg-config"); options.SystemConfigurationLocation = Path.Combine(confs, "my-system-config"); return options; }
public void SetupBroker(RepositoryOptions options) { if (options == null) { options = new RepositoryOptions(); (options as RepositoryOptions).Folder = "."; } folder = (options as RepositoryOptions).Folder; loader.SetGeneralLibrariesPath((options as RepositoryOptions).GeneralLibrariesPath, null); }
public void CanCommitWithSignatureFromConfig() { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null"); repo.Index.Stage(relativeFilepath); File.AppendAllText(filePath, "token\n"); repo.Index.Stage(relativeFilepath); Assert.Null(repo.Head[relativeFilepath]); Commit commit = repo.Commit("Initial egotistic commit"); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n"); AssertBlobContent(commit[relativeFilepath], "nulltoken\n"); AssertCommitSignaturesAre(commit, Constants.Signature); } }
public void CommitWithInvalidSignatureConfigThrows(string name, string email) { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(name, email); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { Assert.Equal(name, repo.Config.GetValueOrDefault<string>("user.name")); Assert.Equal(email, repo.Config.GetValueOrDefault<string>("user.email")); Assert.Throws<LibGit2SharpException>( () => repo.Commit("Initial egotistic commit", new CommitOptions { AllowEmptyCommit = true })); } }