public void Update(string projectName)
        {
            try
            {
                var projectPath = Path.Combine(Folders.Projects, projectName);

                var git = new Git(projectPath);
                git.Pull();
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
        public void Post(string projectName, string configurationName, [FromBody]string value)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(configurationName) || string.IsNullOrWhiteSpace(projectName))
                    return;

                var projectPath = Path.Combine(Folders.Projects, projectName);

                var configurationPath = GetConfigurationFile(projectName, configurationName);

                var cfg = JsonConvert.DeserializeObject<Jar>(System.IO.File.ReadAllText(configurationPath));

                var box = Box.Box.Mistranslate(cfg);

                var newMachine = JsonConvert.DeserializeObject<Machine>(value);

                var machines = box.Machines.ToList();

                if (!machines.Any(x => x.Name == newMachine.Name))
                {
                    machines.Add(newMachine);

                    box.Machines = machines;

                    var jar = JsonConvert.SerializeObject(Box.Box.Mistranslate(box), Formatting.Indented);

                    System.IO.File.WriteAllText(configurationPath, jar);

                    var nameClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "name");
                    var username = nameClaim != null ? nameClaim.Value : "no name claim";
                    var emailClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "email");
                    var email = emailClaim != null ? emailClaim.Value : "no email claim";
                    var message = "Added new machine " + newMachine.Name + " in " + configurationName + " in " + projectName;

                    var git = new Git(projectPath);
                    git.Stage(new List<string>() { configurationPath });
                    git.Commit(message, username, email);
                    git.Push();
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
Beispiel #3
0
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Git git = new Git(this.repository);

                git.Checkout().SetName(radioButton1.IsChecked == true ?
                        comboBranches.SelectedValue.ToString() : txtNewBranch.Text)
                    .SetCreateBranch(radioButton2.IsChecked == true)
                    .Call();

                window.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
        public void Post(string projectName, string configurationName, [FromBody]string value)
        {
            try
            {
                var cfg = JsonConvert.DeserializeObject<Jar>(value);

                if (string.IsNullOrWhiteSpace(projectName) || string.IsNullOrWhiteSpace(configurationName))
                    throw new InvalidOperationException();

                var projectPath = Path.Combine(Folders.Projects, projectName);

                if (configurationName.EndsWith(".json", StringComparison.Ordinal) == false)
                    configurationName += ".json";

                var configurationPath = GetConfigurationFile(projectName, configurationName);

                if (System.IO.File.Exists(configurationPath))
                    throw new InvalidOperationException("There is already a configuration file: " + configurationName);

                var box = Box.Box.Mistranslate(cfg);

                var jar = JsonConvert.SerializeObject(Box.Box.Mistranslate(box), Formatting.Indented);

                System.IO.File.WriteAllText(configurationPath, jar);

                var nameClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "name");
                var username = nameClaim != null ? nameClaim.Value : "no name claim";
                var emailClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "email");
                var email = emailClaim != null ? emailClaim.Value : "no email claim";
                var message = "Added new configuration: " + cfg.Name + " in " + projectName;

                var git = new Git(projectPath);
                git.Stage(new List<string>() { configurationPath });
                git.Commit(message, username, email);
                git.Push();

                //MvcApplication.TcpServer.SendToAllClients(Encoding.UTF8.GetBytes(jar));
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
        public void Delete(string projectName, string configurationName, string referenceName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(projectName) || string.IsNullOrWhiteSpace(configurationName))
                    throw new InvalidOperationException();

                var projectPath = Path.Combine(Folders.Projects, projectName);

                if (configurationName.EndsWith(".json", StringComparison.Ordinal) == false)
                    configurationName += ".json";

                var configurationPath = GetConfigurationFile(projectName, configurationName);

                if (System.IO.File.Exists(configurationPath) == false)
                    throw new InvalidOperationException("There is no configuration file: " + configurationName);

                var cfg = JsonConvert.DeserializeObject<Jar>(System.IO.File.ReadAllText(configurationPath));

                var box = Box.Box.Mistranslate(cfg);

                var referenceForDelete = box.References.FirstOrDefault(x => x.ContainsValue(referenceName));

                if (referenceForDelete != null)
                {
                    box.References.Remove(referenceForDelete);

                    var jar = JsonConvert.SerializeObject(Box.Box.Mistranslate(box), Formatting.Indented);

                    System.IO.File.WriteAllText(configurationPath, jar);

                    var nameClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "name");
                    var username = nameClaim != null ? nameClaim.Value : "no name claim";
                    var emailClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "email");
                    var email = emailClaim != null ? emailClaim.Value : "no email claim";
                    var message = "Added new application configuration: " + cfg.Name + " in " + projectName;

                    var git = new Git(projectPath);
                    git.Stage(new List<string>() { configurationPath });
                    git.Commit(message, username, email);
                    git.Push();
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
Beispiel #6
0
        public void TestLogStreamSubFolder()
        {
            string appName      = KuduUtils.GetRandomWebsiteName("TestLogStreamFilter");
            string repoName     = "LogTester";
            string repoCloneUrl = "https://github.com/KuduApps/LogTester.git";

            TestRepository testRepository = null;
            string         localRepo      = KuduUtils.GetCachedRepositoryPath(repoName);

            if (localRepo == null)
            {
                testRepository = Git.Clone(appName, repoCloneUrl);
                localRepo      = testRepository.PhysicalPath;
            }

            ApplicationManager.Run(appName, appManager =>
            {
                // Act
                appManager.GitDeploy(localRepo);
                List <string> logFiles = new List <string>();
                List <LogStreamWaitHandle> waitHandles = new List <LogStreamWaitHandle>();
                for (int i = 0; i < 2; ++i)
                {
                    logFiles.Add(@"LogFiles\Folder" + i + "\\temp.txt");
                    //Create the directory
                    CreateLogDirectory(appManager.SiteUrl, @"LogFiles\Folder" + i);
                    RemoteLogStreamManager mgr = appManager.CreateLogStreamManager("folder" + i);
                    var waitHandle             = new LogStreamWaitHandle(mgr.GetStream().Result);
                    string line = waitHandle.WaitNextLine(10000);
                    Assert.True(!string.IsNullOrEmpty(line) && line.Contains("Welcome"), "check welcome message: " + line);
                    waitHandles.Add(waitHandle);
                }

                using (LogStreamWaitHandle waitHandle = new LogStreamWaitHandle(appManager.LogStreamManager.GetStream().Result))
                {
                    try
                    {
                        string line = waitHandle.WaitNextLine(10000);
                        Assert.True(!string.IsNullOrEmpty(line) && line.Contains("Welcome"), "check welcome message: " + line);

                        // write to folder0, we should not get any live stream for folder1 listener
                        string content = Guid.NewGuid().ToString();
                        WriteLogText(appManager.SiteUrl, logFiles[0], content);
                        line = waitHandle.WaitNextLine(10000);
                        Assert.Equal(content, line);
                        line = waitHandles[0].WaitNextLine(10000);
                        Assert.Equal(content, line);
                        line = waitHandles[1].WaitNextLine(1000);
                        Assert.True(line == null, "no more message: " + line);

                        // write to folder1, we should not get any live stream for folder0 listener
                        content = Guid.NewGuid().ToString();
                        WriteLogText(appManager.SiteUrl, logFiles[1], content);
                        line = waitHandle.WaitNextLine(10000);
                        Assert.Equal(content, line);
                        line = waitHandles[1].WaitNextLine(10000);
                        Assert.Equal(content, line);
                        line = waitHandles[0].WaitNextLine(1000);
                        Assert.True(line == null, "no more message: " + line);
                    }
                    finally
                    {
                        waitHandles[0].Dispose();
                        waitHandles[1].Dispose();
                    }
                }
            });
        }
Beispiel #7
0
 public void RevertFile(string nodeFile)
 {
     Git.Git("reset HEAD -- " + ToRelative(nodeFile));
     Git.Git("checkout -- " + ToRelative(nodeFile));
 }
        public void Delete(string projectName, string configurationName)
        {
            try
            {
                var projectPath = Path.Combine(Folders.Projects, projectName);

                var configurationPath = GetConfigurationFile(projectName, configurationName);

                if (System.IO.File.Exists(configurationPath))
                {
                    var nameClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "name");
                    var username = nameClaim != null ? nameClaim.Value : "no name claim";
                    var emailClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "email");
                    var email = emailClaim != null ? emailClaim.Value : "no email claim";
                    var message = "Deleted configuration " + configurationName + " from " + projectName;

                    var git = new Git(projectPath);
                    git.Remove(new List<string>() { configurationPath });
                    git.Stage(new List<string>() { configurationPath });
                    git.Commit(message, username, email);
                    git.Push();
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
Beispiel #9
0
        } // End Sub ListAllBranches

        // https://stackoverflow.com/questions/15822544/jgit-how-to-get-all-commits-of-a-branch-without-changes-to-the-working-direct
        public static void WalkCommits()
        {
            string     dir  = GetRepoPath();
            Git        git  = Git.Open(dir);
            Repository repo = git.GetRepository();

            RevWalk walk = new RevWalk(repo);


            System.Collections.Generic.IList <Ref> branches = git.BranchList().Call();

            // https://stackoverflow.com/questions/15822544/jgit-how-to-get-all-commits-of-a-branch-without-changes-to-the-working-direct
            foreach (Ref branch in branches)
            {
                string branchName = branch.GetName();
                System.Console.WriteLine("Commits of branch: " + branchName);
                System.Console.WriteLine("-------------------------------------");

                Sharpen.Iterable <RevCommit> commits = git.Log().All().Call();

                foreach (RevCommit commit in commits)
                {
                    bool      foundInThisBranch = false;
                    RevCommit targetCommit      = walk.ParseCommit(repo.Resolve(commit.Name));

                    foreach (System.Collections.Generic.KeyValuePair <string, Ref> e in repo.GetAllRefs())
                    {
                        if (e.Key.StartsWith(Constants.R_HEADS))
                        {
                            if (walk.IsMergedInto(targetCommit, walk.ParseCommit(e.Value.GetObjectId())))
                            {
                                string foundInBranch = e.Value.GetName();

                                if (branchName.Equals(foundInBranch))
                                {
                                    foundInThisBranch = true;
                                    break;
                                } // End if (branchName.Equals(foundInBranch))
                            }     // End if (walk.IsMergedInto(targetCommit, walk.ParseCommit(e.Value.GetObjectId())))
                        }         // End if (e.Key.StartsWith(Constants.R_HEADS))
                    }             // Next e

                    if (foundInThisBranch)
                    {
                        System.Console.WriteLine(commit.Name);
                        System.Console.WriteLine(commit.GetAuthorIdent().GetName());

                        // System.DateTime dt = new System.DateTime(commit.CommitTime);
                        System.DateTime dt = UnixTimeStampToDateTime(commit.CommitTime);

                        System.Console.WriteLine(dt);
                        System.Console.WriteLine(commit.GetFullMessage());
                    } // End if (foundInThisBranch)
                }     // Next commit
            }         // Next branch

            // Handle disposing of NGit's locks
            repo.Close();
            repo.ObjectDatabase.Close();
            repo = null;
            git  = null;
        } // End Sub
Beispiel #10
0
 public static (bool success, string output) ExecuteCommand(this Git git, string args)
 {
     return(ProcessCommand.ExecuteCommand("git", args, git.Repo.FullName));
 }
Beispiel #11
0
        public static void MergeTest(EngineContext engineContext)
        {
            // TODO: Currently hardcoded
            var db            = new FileRepository(new FilePath(@"C:\DEV\hotei_scene", Constants.DOT_GIT));
            var git           = new Git(db);
            var tree1Ref      = db.GetRef("test");
            var tree2Ref      = db.GetRef(Constants.HEAD);
            var tree1CommitId = tree1Ref.GetObjectId();
            var tree2CommitId = tree2Ref.GetObjectId();

            // Merge tree1 into current tree
            var mergeResult = git.Merge().Include(tree1CommitId).Call();

            if (mergeResult.GetMergeStatus() == MergeStatus.CONFLICTING)
            {
                foreach (var conflict in mergeResult.GetConflicts())
                {
                    if (conflict.Key.EndsWith(".hotei"))
                    {
                        // Search base tree (common ancestor), if any
                        var walk = new RevWalk(db);
                        walk.SetRevFilter(RevFilter.MERGE_BASE);
                        walk.MarkStart(walk.ParseCommit(tree1CommitId));
                        walk.MarkStart(walk.ParseCommit(tree2CommitId));
                        var baseTree = walk.Next();

                        var tw = new NameConflictTreeWalk(db);
                        tw.AddTree(new RevWalk(db).ParseTree(tree1CommitId).ToObjectId());
                        tw.AddTree(new RevWalk(db).ParseTree(tree2CommitId).ToObjectId());
                        if (baseTree != null)
                        {
                            tw.AddTree(new RevWalk(db).ParseTree(baseTree.ToObjectId()).ToObjectId());
                        }
                        tw.Filter = PathFilter.Create(conflict.Key);

                        // Should be only one iteration
                        while (tw.Next())
                        {
                            var tree0 = baseTree != null?tw.GetTree <AbstractTreeIterator>(2) : null;

                            var tree1 = tw.GetTree <AbstractTreeIterator>(0);
                            var tree2 = tw.GetTree <AbstractTreeIterator>(1);

                            // Get contents of every versions for the 3-way merge
                            var data0 = baseTree != null?LoadEntities(new MemoryStream(tw.ObjectReader.Open(tree0.EntryObjectId).GetBytes())) : null;

                            var data1 = LoadEntities(new MemoryStream(tw.ObjectReader.Open(tree1.EntryObjectId).GetBytes()));
                            var data2 = LoadEntities(new MemoryStream(tw.ObjectReader.Open(tree2.EntryObjectId).GetBytes()));

                            // Perform 3-way merge
                            var entities = new List <EntityDefinition>();
                            ThreeWayMergeOrdered.Merge(entities, data0, data1, data2, x => x.Guid, (x, y) => x == y, ResolveEntityConflicts);

                            // Save new merged file
                            var fileStream = new FileStream(new FilePath(db.WorkTree, conflict.Key), FileMode.Create, FileAccess.Write);
                            var stream     = new BinarySerializationWriter(fileStream);
                            stream.Context.Serializer = Serializer;
                            stream.SerializeClass(null, ref entities, ArchiveMode.Serialize);
                            fileStream.Close();

                            // TODO: Check if all conflicts are really resolved
                            // Add resolved file for merge commit
                            git.Add().AddFilepattern(conflict.Key).Call();
                        }
                    }
                }
            }
        }
Beispiel #12
0
    public static List <string> Commit(string key, List <int> indexes, string comment, string user)
    {
        List <string> output = new List <string>();

        output.Add("Starting job...");
        lock (_commitobj)
        {
            try
            {
                ListOfChanges changes = Get(key);
                string        gitpath = Settings.CurrentSettings.WORKGIT;
                if (!Directory.Exists(Settings.CurrentSettings.WORKGIT))
                {
                    throw new Exception("Git Directory does not exist!: " + Settings.CurrentSettings.WORKGIT);
                }
                Git git = new Git(gitpath);
                output.AddRange(git.ResetHard());
                output.AddRange(git.FetchAll());
                output.AddRange(git.Checkout(changes.Branch));
                if (git.CurrentBranch() != changes.Branch)
                {
                    output.Add("Failed to switch branch!");
                    return(Git.DiffFriendOutput(output));
                }
                output.AddRange(git.PullOrigin());
                foreach (int i in indexes)
                {
                    FileChange fc      = changes[i];
                    string     gitfile = fc.BST.Replace(@"S:\", gitpath).Replace(@"s:\", gitpath);
                    string     gitdir  = Path.GetDirectoryName(gitfile);
                    if (!Directory.Exists(gitdir))
                    {
                        Directory.CreateDirectory(gitdir);
                    }
                    output.Add("Copying file: " + gitfile + "...");
                    File.Copy(fc.NEW, gitfile, true);
                    output.AddRange(git.AddFile(gitfile));
                }
                Commit oldcommit = git.GetTopCommit();
                output.AddRange(git.CommitAll("WEB: " + comment, user));
                Commit newcommit = git.GetTopCommit();
                if (oldcommit.COMMIT == newcommit.COMMIT)
                {
                    output.Add("-No files have been commited!");
                }
                else
                {
                    output.Add(string.Format("+{0} files have been commited!", newcommit.EnumFiles().Count));
                }
                output.AddRange(git.PushCurrentBranch());
                output.AddRange(git.ResetHard());
                output.AddRange(git.Checkout("master"));
                Remove(key);
            }
            catch (Exception e)
            {
                output.Add(e.ToString());
            }
        }
        return(Git.DiffFriendOutput(output));
    }
Beispiel #13
0
 public static void StageAll()
 {
     SemVer.BumpPatch();
     Git.Run("add -A");
 }
Beispiel #14
0
 public static void Stash()
 {
     SemVer.BumpPatch();
     Git.Run("stash");
 }
Beispiel #15
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.TextBlock_Path.Text = string.Join("\n", Variables.Paths);
            DotNetCore DotNetDependency = new DotNetCore();

            if (DotNetDependency.VerifyInstallationStatus())
            {
                this.TextBlock_DotNetCore.Text = string.Join("; ", DotNetDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_DotNetCore.Text = "Not Installed";
            }

            NodeJS NodeJSDependency = new NodeJS();

            if (NodeJSDependency.VerifyInstallationStatus())
            {
                this.TextBlock_NodeJS.Text = string.Join("; ", NodeJSDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_DotNetCore.Text = "Not Installed";
            }

            Python PythonDependency = new Python();

            if (PythonDependency.VerifyInstallationStatus())
            {
                this.TextBlock_Python.Text = string.Join("; ", PythonDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_Python.Text = "Not Installed";
            }
            Flutter FlutterDependency = new Flutter();

            if (FlutterDependency.VerifyInstallationStatus())
            {
                this.TextBlock_Flutter.Text = string.Join("; ", FlutterDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_Flutter.Text = "Not Installed";
            }

            Dart DartDependency = new Dart();

            if (DartDependency.VerifyInstallationStatus())
            {
                this.TextBlock_Dart.Text = string.Join("; ", DartDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_Dart.Text = "Not Installed";
            }

            Git GitDependency = new Git();

            if (GitDependency.VerifyInstallationStatus())
            {
                this.TextBlock_Git.Text = string.Join("; ", GitDependency.GetInstalledVersions());
            }
            else
            {
                this.TextBlock_Git.Text = "Not Installed";
            }
        }
Beispiel #16
0
        public string Download(PackageInfo uri, string versionlock = null)
        {
            if (uri == null)
            {
                return(null);
            }

            var storage = DependencyInstallPath(uri);

            if (!IsDownloaded(uri))
            {
                // Clone repo to temp directory
                var dir = MkTmpdir();
                // Console.WriteLine("downloading " + uri.Package + " to " + storage + " after cloning to " + dir);
                Git.Clone(uri.DownloadUrl, dir);

                if (versionlock != null)
                {
                    // Use commit from the version lock
                    Git.Checkout(dir, versionlock);
                }
                else
                {
                    // Find commit matching version constraint
                    if (uri.Constraint != null)
                    {
                        var commit = uri.Constraint.FindSatisfying(Git, dir).FirstOrDefault();

                        // Checkout commit if exists, throw if not
                        if (commit == default(string))
                        {
                            throw new System.Data.ConstraintException($"No commits matching constraint '{uri.Constraint}' could be found.");
                        }
                        else
                        {
                            Git.Checkout(dir, commit);
                        }
                    }
                    else
                    {
                        Git.Checkout(dir, "master");                 // no version constraint, check out master
                    }
                }

                // Copy to perminant storage
                CpDir(dir, storage);
                return(storage);
            }
            else
            {
                var commit = Git.CurrentCommit(storage);

                // Ensure that we are using the locked version
                if (commit != versionlock)
                {
                    Git.Checkout(storage, commit);
                }

                // Check that the downloaded one is compatible
                // Find commit matching version constraint
                if (uri.Constraint != null)
                {
                    var contains = uri.Constraint.FindSatisfying(Git, storage).Contains(commit);
                    if (!contains)
                    {
                        throw new System.Data.ConstraintException($"One or more packages have incompatible dependency versions");
                    }
                }
                return(null);        // Null so we don't re-download it's dependencies
            }
        }
 private void UpdateSingleRepository(Git repository)
 {
     repository.Pull().SetCredentialsProvider(credentials).Call();
     gitLog.AppendLine("Pull completed.");
 }
Beispiel #18
0
        public async Task <IActionResult> Edit(long?id, [FromBody] EditInputModel model)
        {
            //データの入力チェック
            if (!ModelState.IsValid || !id.HasValue)
            {
                return(JsonBadRequest("Invalid inputs."));
            }
            //データの存在チェック
            var tenant = await tenantRepository.GetTenantWithStorageForUpdateAsync(id.Value);

            if (tenant == null)
            {
                return(JsonNotFound($"Tenant ID {id.Value} is not found."));
            }

            if (model.DefaultGitId != null && model.GitIds.Contains(model.DefaultGitId.Value) == false)
            {
                //デフォルトGitがGit一覧の中になかったらエラー
                return(JsonConflict($"Default Git ID {model.DefaultGitId.Value} does NOT exist in selected gits."));
            }
            if (model.DefaultRegistryId != null && model.RegistryIds.Contains(model.DefaultRegistryId.Value) == false)
            {
                //デフォルトレジストリがレジストリ一覧の中になかったらエラー
                return(JsonConflict($"Default Registry ID {model.DefaultRegistryId.Value} does NOT exist in selected registries."));
            }
            if (model.StorageId != null)
            {
                //データの存在チェック
                var storage = tenantRepository.GetStorage(model.StorageId.Value);
                if (storage == null)
                {
                    return(JsonNotFound($"The selected storage ID {model.StorageId.Value} is not found."));
                }

                //バケットを作成する
                await storageLogic.CreateBucketAsync(tenant, storage);
            }

            tenant.DisplayName = model.DisplayName;
            tenant.StorageId   = model.StorageId;
            tenant.AvailableInfiniteTimeNotebook = model.AvailableInfiniteTimeNotebook;

            //コンテナ管理サービス作業
            //テナントを登録
            var tenantResult = await clusterManagementLogic.RegistTenantAsync(tenant.Name);

            if (tenantResult == false)
            {
                return(JsonError(HttpStatusCode.ServiceUnavailable, "Couldn't create cluster master namespace. Please check the configuration to the connect cluster manager service."));
            }

            //テナントとGitを紐づけ
            //まずは現状のGitを取得して、そこから増減を判断する
            var currentGits = gitRepository.GetGitAll(tenant.Id).ToList();

            if (model.GitIds != null && model.GitIds.Count() > 0)
            {
                //デフォルトGitの設定(無ければ一個目)
                tenant.DefaultGitId = model.DefaultGitId == null?
                                      model.GitIds.ElementAt(0) : model.DefaultGitId.Value;

                foreach (long gitId in model.GitIds)
                {
                    Git currentGit = currentGits.FirstOrDefault(r => r.Id == gitId);
                    if (currentGit != null)
                    {
                        //以前も紐づいていたので、無視。
                        currentGits.Remove(currentGit);
                        continue;
                    }

                    //データの存在チェック
                    Git git = await gitRepository.GetByIdAsync(gitId);

                    if (git == null)
                    {
                        return(JsonNotFound($"The selected git ID {gitId} is not found."));
                    }

                    await gitRepository.AttachGitToTenantAsync(tenant, git, false);
                }
            }
            //残っているのは削除された紐づけなので、消す
            foreach (var removedGit in currentGits)
            {
                gitRepository.DetachGitFromTenant(tenant, removedGit);
            }

            //テナントとレジストリを紐づけ
            //まずは現状のレジストリを取得して、そこから増減を判断する
            var currentRegistries = registryRepository.GetRegistryAll(tenant.Id).ToList();

            if (model.RegistryIds != null && model.RegistryIds.Count() > 0)
            {
                //デフォルトレジストリの設定(無ければ一個目)
                tenant.DefaultRegistryId = model.DefaultRegistryId == null?
                                           model.RegistryIds.ElementAt(0) : model.DefaultRegistryId.Value;

                foreach (long registryId in model.RegistryIds)
                {
                    Registry currentRegistry = currentRegistries.FirstOrDefault(r => r.Id == registryId);
                    if (currentRegistry != null)
                    {
                        //以前も紐づいていたので、無視。
                        currentRegistries.Remove(currentRegistry);
                        continue;
                    }

                    //データの存在チェック
                    Registry registry = await registryRepository.GetByIdAsync(registryId);

                    if (registry == null)
                    {
                        return(JsonNotFound($"The selected registry ID {registryId} is not found."));
                    }

                    var maps = await registryRepository.AttachRegistryToTenantAsync(tenant, registry, false);

                    if (maps != null)
                    {
                        foreach (var map in maps)
                        {
                            //レジストリを登録
                            var registryResult = await clusterManagementLogic.RegistRegistryToTenantAsync(tenant.Name, map);

                            if (registryResult == false)
                            {
                                return(JsonError(HttpStatusCode.ServiceUnavailable, "Couldn't map the tenant and the registry in a cluster management service. Please check the configuration to the connect cluster manager service."));
                            }
                        }
                    }
                }
            }
            //残っているのは削除された紐づけなので、消す
            foreach (var removedRegistry in currentRegistries)
            {
                registryRepository.DetachRegistryFromTenant(tenant, removedRegistry);
            }

            // 関連するクラスタトークンをリセット
            tenantRepository.DeleteClusterToken(tenant.Id);

            tenantRepository.Update(tenant, unitOfWork);

            return(JsonOK(new IndexOutputModel(tenant)));
        }
Beispiel #19
0
        private int CreateInitialDB()
        {
            //ロール作成
            Role userRole = AddNewRecordForInit(new Role()
            {
                Name = "users", DisplayName = "User", SortOrder = 10, IsSystemRole = false
            });
            Role researcherRole = AddNewRecordForInit(new Role()
            {
                Name = "researchers", DisplayName = "Researcher", SortOrder = 20, IsSystemRole = false
            });
            Role managerRole = AddNewRecordForInit(new Role()
            {
                Name = "managers", DisplayName = "Manager", SortOrder = 30, IsSystemRole = false
            });
            Role adminRole = AddNewRecordForInit(new Role()
            {
                Name = "admins", DisplayName = "Admin", SortOrder = 100, IsSystemRole = true
            });

            //メニュー作成
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = userRole, MenuCode = Logic.MenuLogic.DataMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = userRole, MenuCode = Logic.MenuLogic.DataSetMenu.Code.ToString()
            });

            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = researcherRole, MenuCode = Logic.MenuLogic.DataMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = researcherRole, MenuCode = Logic.MenuLogic.DataSetMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = researcherRole, MenuCode = Logic.MenuLogic.PreprocessMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = researcherRole, MenuCode = Logic.MenuLogic.TrainingMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = researcherRole, MenuCode = Logic.MenuLogic.InferenceMenu.Code.ToString()
            });

            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = managerRole, MenuCode = Logic.MenuLogic.TenantSettingMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = managerRole, MenuCode = Logic.MenuLogic.TenantRoleMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = managerRole, MenuCode = Logic.MenuLogic.TenantUserMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = managerRole, MenuCode = Logic.MenuLogic.TenantMenuAccessMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = managerRole, MenuCode = Logic.MenuLogic.TenantResourceMenu.Code.ToString()
            });

            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.TenantMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.GitMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.RegistryMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.StorageMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.RoleMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.QuotaMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.UserMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.NodeMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.ResourceMenu.Code.ToString()
            });
            AddNewRecordForInit(new MenuRoleMap()
            {
                Role = adminRole, MenuCode = Logic.MenuLogic.MenuAccessMenu.Code.ToString()
            });

            //初期Git作成
            Git git = AddNewRecordForInit(new Git()
            {
                Name = "GitHub", RepositoryUrl = "https://github.com", ServiceType = GitServiceType.GitHub, ApiUrl = "https://api.github.com"
            });
            //初期レジストリ作成
            Registry registry = AddNewRecordForInit(new Registry()
            {
                Name = "official-docker-hub", Host = "registry.hub.docker.com", PortNo = 80, ServiceType = RegistryServiceType.DockerHub, ApiUrl = "https://registry.hub.docker.com/", RegistryUrl = "https://registry.hub.docker.com/"
            });

            // 初期ノードの作成
            string[] nodeNames = deployOptions.GpuNodes.Split(',');
            foreach (string nodeName in nodeNames)
            {
                AddNewRecordForInit(new Node()
                {
                    Name               = nodeName,
                    AccessLevel        = NodeAccessLevel.Public,
                    TensorBoardEnabled = true
                });
            }

            // 初期ストレージの作成
            Storage storage = AddNewRecordForInit(new Storage()
            {
                Name          = ApplicationConst.DefaultFirstStorageName,
                ServerAddress = deployOptions.ObjectStorageNode + ":" + deployOptions.ObjectStoragePort,
                AccessKey     = deployOptions.ObjectStorageAccessKey,
                SecretKey     = deployOptions.ObjectStorageSecretKey,
                NfsServer     = deployOptions.NfsStorage,
                NfsRoot       = deployOptions.NfsPath
            });

            //初期テナント作成
            Tenant tenant = AddNewRecordForInit(new Tenant()
            {
                Name              = ApplicationConst.DefaultFirstTenantName,
                DisplayName       = ApplicationConst.DefaultFirstTenantDisplayName,
                DefaultGit        = git,
                DefaultRegistryId = registry.Id,
                StorageBucket     = ApplicationConst.DefaultFirstTenantName,
                StorageId         = storage.Id
            });
            //GitとTenantの対応付け
            TenantGitMap tenantGitMap = AddNewRecordForInit(new TenantGitMap()
            {
                Tenant = tenant, Git = git
            });
            //RegistryとTenantの対応付け
            TenantRegistryMap tenantRegistryMap = AddNewRecordForInit(new TenantRegistryMap()
            {
                Tenant = tenant, Registry = registry
            });

            //初期ユーザ作成
            User user = AddNewRecordForInit(new User()
            {
                Name          = ApplicationConst.DefaultFirstAdminUserName,
                ServiceType   = AuthServiceType.Local,
                DefaultTenant = tenant,
                Password      = Util.GenerateHash(deployOptions.Password, ApplicationConst.DefaultFirstAdminUserName)
            });

            //初期ユーザの所属登録
            UserTenantMap userTenantMap = AddNewRecordForInit(new UserTenantMap()
            {
                Tenant = tenant, User = user
            });

            AddNewRecordForInit(new UserTenantGitMap()
            {
                User = user, TenantGitMap = tenantGitMap
            });
            AddNewRecordForInit(new UserTenantRegistryMap()
            {
                User = user, TenantRegistryMap = tenantRegistryMap
            });

            // ロール明細の登録

            AddNewRecordForInit(new UserRoleMap()
            {
                Role = researcherRole, User = user, TenantMap = userTenantMap
            });
            AddNewRecordForInit(new UserRoleMap()
            {
                Role = managerRole, User = user, TenantMap = userTenantMap
            });
            AddNewRecordForInit(new UserRoleMap()
            {
                Role = adminRole, User = user
            });

            // テナント系DBの初期化
            InitTenant(tenant);

            //コミット
            int result = dbContext.SaveChanges(user.Name);

            // テナント環境の生成
            return(result);
        }
Beispiel #20
0
        public async Task Test_Pop_Stash_Without_Stash_Throws()
        {
            string dir = await InitRepo();

            await Assert.ThrowsExceptionAsync <StashEmptyGitException>(async() => await Git.PopStash(dir));
        }
Beispiel #21
0
 /// <summary>
 /// Disposes the LibGit2Sharp repository.
 /// </summary>
 public void Dispose() => Git.Dispose();
Beispiel #22
0
        } // End Function GetRepoPath

        // https://github.com/mono/ngit/commits/master
        public static void GetCommitsByBranch(string branchName)
        {
            // D:\Stefan.Steiger\Documents\Visual Studio 2013\Projects
            string dir = GetRepoPath();

            System.Console.WriteLine(dir);
            // dir = "https://github.com/mono/ngit.git";


            // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListRemoteRepository.java
            // https://stackoverflow.com/questions/13667988/how-to-use-ls-remote-in-ngit
            // git.LsRemote();


            Git        git  = Git.Open(dir);
            Repository repo = git.GetRepository();

            ObjectId branchOid = repo.Resolve(branchName);

            System.Console.WriteLine("Commits of branch: '{0}' ({1})", branchName, branchOid);
            System.Console.WriteLine("-------------------------------------");


            Sharpen.Iterable <RevCommit> commits = git.Log().Add(branchOid).Call();

            int count = 0;

            RevCommit laterCommit = null;

            // Note: Apparently sorted DESCENDING by COMMIT DATE
            foreach (RevCommit earlierCommit in commits)
            {
                System.Console.WriteLine(earlierCommit.Name);
                System.Console.WriteLine(earlierCommit.GetAuthorIdent().GetName());

                System.DateTime dt = UnixTimeStampToDateTime(earlierCommit.CommitTime);
                System.Console.WriteLine(dt);

                System.Console.WriteLine(earlierCommit.GetFullMessage());

                if (laterCommit != null)
                {
                    GetChanges(git, repo, earlierCommit, laterCommit);
                } // End if (laterCommit != null)

                // https://github.com/gitblit/gitblit/blob/master/src/main/java/com/gitblit/utils/JGitUtils.java#L718
                laterCommit = earlierCommit;
                count++;
            } // Next earlierCommit

            System.Console.WriteLine(count);


            // Handle disposing of NGit's locks
            repo.Close();
            repo.ObjectDatabase.Close();
            repo = null;
            git  = null;

            // https://github.com/mono/ngit/blob/master/NGit/NGit.Revwalk/RevWalkUtils.cs
        } // End Sub GetCommitsByBranch
Beispiel #23
0
 public void StartUpdateFileStatus(string path)
 {
     Git.UpdateFileStatusAsync(path);
 }
Beispiel #24
0
        } // End Function GetDiff

        // https://stackoverflow.com/questions/13537734/how-to-use-jgit-to-get-list-of-changed-files
        // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowChangedFilesBetweenCommits.java
        public static void GetChanges(Git git, Repository repo, RevCommit oldCommit, RevCommit newCommit)
        {
            System.Console.WriteLine("Printing diff between commit: " + oldCommit.ToString() + " and " + newCommit.ToString());
            ObjectReader reader = repo.NewObjectReader();

            // prepare the two iterators to compute the diff between
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();

            oldTreeIter.Reset(reader, oldCommit.Tree.Id);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();

            newTreeIter.Reset(reader, newCommit.Tree.Id);

            // DiffStatFormatter df = new DiffStatFormatter(newCommit.Name, repo);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                DiffFormatter diffFormatter = new DiffFormatter(ms);
                diffFormatter.SetRepository(repo);

                int entryCount = 0;
                foreach (DiffEntry entry in diffFormatter.Scan(oldCommit, newCommit))
                {
                    string pathToUse = null;

                    TreeWalk treeWalk = new TreeWalk(repo);
                    treeWalk.Recursive = true;

                    if (entry.GetChangeType() == DiffEntry.ChangeType.DELETE)
                    {
                        treeWalk.AddTree(oldCommit.Tree);
                        pathToUse = entry.GetOldPath();
                    }
                    else
                    {
                        treeWalk.AddTree(newCommit.Tree);
                        pathToUse = entry.GetNewPath();
                    }

                    treeWalk.Filter = PathFilter.Create(pathToUse);

                    if (!treeWalk.Next())
                    {
                        throw new System.Exception("Did not find expected file '" + pathToUse + "'");
                    }

                    ObjectId     objectId = treeWalk.GetObjectId(0);
                    ObjectLoader loader   = repo.Open(objectId);

                    string strModifiedFile = ReadFile(loader);
                    System.Console.WriteLine(strModifiedFile);

                    //////////////
                    // https://stackoverflow.com/questions/27361538/how-to-show-changes-between-commits-with-jgit
                    diffFormatter.Format(diffFormatter.ToFileHeader(entry));

                    string diff = GetDiff(repo, entry);
                    System.Console.WriteLine(diff);

                    entryCount++;
                } // Next entry

                System.Console.WriteLine(entryCount);

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms))
                {
                    string strAllDiffs = sr.ReadToEnd();
                    System.Console.WriteLine(strAllDiffs);
                } // End Using sr
            }     // End Using ms


            System.Collections.Generic.IList <DiffEntry> diffs = git.Diff()
                                                                 .SetNewTree(newTreeIter)
                                                                 .SetOldTree(oldTreeIter)
                                                                 .Call();

            foreach (DiffEntry entry in diffs)
            {
                System.Console.WriteLine("Entry: " + entry);
                System.Console.WriteLine("Entry: " + entry.GetChangeType());
            } // Next entry

            System.Console.WriteLine("Done");
        } // End Sub GetChanges
 public void MergeFrom(EstafetteTrigger other)
 {
     if (other == null)
     {
         return;
     }
     if (other.pipeline_ != null)
     {
         if (pipeline_ == null)
         {
             Pipeline = new global::Estafette.Ci.Manifest.V1.EstafettePipelineTrigger();
         }
         Pipeline.MergeFrom(other.Pipeline);
     }
     if (other.release_ != null)
     {
         if (release_ == null)
         {
             Release = new global::Estafette.Ci.Manifest.V1.EstafetteReleaseTrigger();
         }
         Release.MergeFrom(other.Release);
     }
     if (other.git_ != null)
     {
         if (git_ == null)
         {
             Git = new global::Estafette.Ci.Manifest.V1.EstafetteGitTrigger();
         }
         Git.MergeFrom(other.Git);
     }
     if (other.docker_ != null)
     {
         if (docker_ == null)
         {
             Docker = new global::Estafette.Ci.Manifest.V1.EstafetteDockerTrigger();
         }
         Docker.MergeFrom(other.Docker);
     }
     if (other.cron_ != null)
     {
         if (cron_ == null)
         {
             Cron = new global::Estafette.Ci.Manifest.V1.EstafetteCronTrigger();
         }
         Cron.MergeFrom(other.Cron);
     }
     if (other.pubSub_ != null)
     {
         if (pubSub_ == null)
         {
             PubSub = new global::Estafette.Ci.Manifest.V1.EstafettePubSubTrigger();
         }
         PubSub.MergeFrom(other.PubSub);
     }
     if (other.buildAction_ != null)
     {
         if (buildAction_ == null)
         {
             BuildAction = new global::Estafette.Ci.Manifest.V1.EstafetteTriggerBuildAction();
         }
         BuildAction.MergeFrom(other.BuildAction);
     }
     if (other.releaseAction_ != null)
     {
         if (releaseAction_ == null)
         {
             ReleaseAction = new global::Estafette.Ci.Manifest.V1.EstafetteTriggerReleaseAction();
         }
         ReleaseAction.MergeFrom(other.ReleaseAction);
     }
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
 private RepoWrapper GetRepository()
 {
     return(new RepoWrapper(Git.Open(new FilePath(directory.FullName)).GetRepository() as FileRepository));
 }
        public void Api_can_read_the_latest_git_commit_from_a_solution_in_git(CraneRunner craneRunner, RunResult result, CraneTestContext craneTestContext,
                                                                              ISolutionContext solutionContext, string projectDir, Git git, ISourceControlInformation sourceControlInformation,
                                                                              ICraneApi craneApi)
        {
            "Given I have my own private copy of the crane console"
            ._(() => craneTestContext = ServiceLocator.Resolve <CraneTestContext>());

            "And I have a run context"
            ._(() => craneRunner = new CraneRunner());

            "And I have run crane init ServiceStack"
            ._(() => result = craneRunner.Command(craneTestContext.BuildOutputDirectory, "crane init ServiceStack"));

            "And I initialize that as a git repository"
            ._(() =>
            {
                projectDir = Path.Combine(craneTestContext.BuildOutputDirectory, "ServiceStack");
                git        = ServiceLocator.Resolve <Git>();
                git.Run("init", projectDir).ErrorOutput.Should().BeEmpty();
                git.Run("config user.email [email protected]", projectDir).ErrorOutput.Should().BeEmpty();
            });

            "And I have a previous commit"
            ._(() =>
            {
                git.Run("add -A", projectDir).ErrorOutput.Should().BeEmpty();
                git.Run("config user.email [email protected]", projectDir).ErrorOutput.Should().BeEmpty();
                git.Run("commit -m \"First commit of ServiceStack\"", projectDir).ErrorOutput.Should().BeEmpty();
            });


            "And I have the solution context using the api"
            ._(() =>
            {
                craneApi        = ServiceLocator.Resolve <ICraneApi>();
                solutionContext = craneApi.GetSolutionContext(projectDir);
            });
            "When I get the source information using the api"
            ._(() => sourceControlInformation = craneApi.GetSourceControlInformation(solutionContext));

            "It should set the provider name to git"
            ._(() => sourceControlInformation.ProviderName.Should().Be("git"));

            "It should return the latest commit message as 'First commit of ServiceStack'"
            ._(() => sourceControlInformation.LastCommitMessage.Should().Contain("First commit of ServiceStack"))
            .Teardown(() => craneTestContext.TearDown());
        }
Beispiel #28
0
 private void SetupGit(IFileSystem filesystem, IFileDirectoryDeleter fileDirectoryDeleter)
 {
     git                  = new Git((IHistoryParser)mockHistoryParser.MockInstance, (ProcessExecutor)mockProcessExecutor.MockInstance, filesystem, fileDirectoryDeleter);
     git.Repository       = @"xyz.git";
     git.WorkingDirectory = DefaultWorkingDirectory;
 }
        public void Setup()
        {
            repo = Util.InitTestRepo();

            git = new Git(Util.GetFullPath("test_repo"));
        }
 protected override StatusViewModel CreateStatusViewModel(IRepositoryService repositoryService, IFileIconService iconService, Git.Status s)
 {
     var status = base.CreateStatusViewModel(repositoryService, iconService, s);
     status.ProjectName = _solutionService.GetNameOfParentProject(s.FilePath);
     return status;
 }
Beispiel #31
0
    public override bool Run(string[] args)
    {
        Console.WriteLine("");
        Console.WriteLine("Starting a full release cycle.");
        Console.WriteLine("");

        var packageName = ""; // Empty means all

        if (Arguments.KeylessArguments.Length > 0)
        {
            packageName = Arguments.KeylessArguments[0];
        }

        var version = "";

        if (Arguments.ContainsAny("version"))
        {
            version = Arguments["version"];
        }

        // Clone (using git) from the project to another tmp directory
        var tmpDir = CloneToTmpDirectory();

        // Grab any files required to continue
        GrabFiles(tmpDir);

        // Move to the tmp directory
        Relocate(tmpDir);

        // Create any missing file nodes (*.node files)
        CreateNodes();

        if (!String.IsNullOrEmpty(version))
        {
            ExecuteScript("SetVersion", version);
        }
        else
        {
            ExecuteScript("IdentifyVersion");
        }

        Nodes.Refresh();

        // Increment the 3rd position of the version for each publishing cycle
        IncrementVersion(3);

        // Build and package the cloned source code (the package script will trigger build cycle if necessary)
        if (!String.IsNullOrEmpty(packageName))
        {
            ExecuteScript("CyclePackage", packageName, "-skipincrement");
        }
        else
        {
            ExecuteScript("CyclePackage", "-skipincrement");
        }

        // Commit the file version information to source control
        ExecuteScript("CommitVersion");

        // Return the created packages back to the original project /pkg/ directory
        ReturnPackages();

        var branch = "master";

        if (CurrentNode.Properties.ContainsKey("Branch"))
        {
            branch = CurrentNode.Properties["Branch"];
        }

        // TODO: Make the remotes configurable
        Git.Push("origin", branch, "-f");

        if (!IsError)
        {
            // Publish files
            ExecuteScript("Publish", packageName);
        }

        return(!IsError);
    }
Beispiel #32
0
        private static void UpdateGit(string directory)
        {
            var git = new Git(new DirectoryInfo(directory));

            git.FetchAll();
        }
Beispiel #33
0
        public async Task Execute()
        {
            Git.CheckVersion();
            Logger.Write(
                $"Make sure Lat & Lng is right. Exit Program if not! Lat: {_client.CurrentLat} Lng: {_client.CurrentLng}",
                LogLevel.Warning);
            Thread.Sleep(3000);
            Logger.Write($"Logging in via: {_clientSettings.AuthType}");

            while (true)
            {
                try
                {
                    if (_clientSettings.AuthType == AuthType.Ptc)
                    {
                        await _client.DoPtcLogin(_clientSettings.PtcUsername, _clientSettings.PtcPassword);
                    }
                    else if (_clientSettings.AuthType == AuthType.Google)
                    {
                        _client.DoGoogleLogin("", "");
                    }

                    await _client.SetServer();

                    await PostLoginExecute();
                }
                catch (AccessTokenExpiredException)
                {
                    Logger.Write("Access token expired");
                }
                catch (TaskCanceledException)
                {
                    Logger.Write("Task Canceled Exception - Restarting", LogLevel.Error);
                    await Execute();
                }
                catch (UriFormatException)
                {
                    Logger.Write("UriFormatException - Restarting", LogLevel.Error);
                    await Execute();
                }
                catch (ArgumentOutOfRangeException)
                {
                    Logger.Write("ArgumentOutOfRangeException - Restarting", LogLevel.Error);
                    await Execute();
                }
                catch (ArgumentNullException)
                {
                    Logger.Write("ArgumentNullException - Restarting", LogLevel.Error);
                    await Execute();
                }
                catch (NullReferenceException)
                {
                    Logger.Write("NullReferenceException - Restarting", LogLevel.Error);
                    await Execute();
                }
                catch (InvalidResponseException e)
                {
                    Logger.Write("InvalidResponseException - Restarting", LogLevel.Error);
                    Logger.Write("err: " + e);
                    await Execute();
                }
                catch (AggregateException)
                {
                    Logger.Write("AggregateException - Restarting", LogLevel.Error);
                    await Execute();
                }
                await Task.Delay(10000);
            }
        }
        public void Delete(string projectName, string configurationName, string key)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(configurationName) || string.IsNullOrWhiteSpace(projectName))
                    return;

                var projectPath = Path.Combine(Folders.Projects, projectName);

                var configurationPath = GetConfigurationFile(projectName, configurationName);

                var cfg = JsonConvert.DeserializeObject<Jar>(System.IO.File.ReadAllText(configurationPath));

                var box = Box.Box.Mistranslate(cfg);

                var defaults = box.Defaults.AsDictionary();

                if (defaults.ContainsKey(key))
                {
                    defaults.Remove(key);

                    box.Defaults = new Configuration(box.Defaults.Name, defaults);

                    foreach (var cluster in box.Clusters)
                    {
                        cluster.DeleteKey(key);
                    }

                    foreach (var machine in box.Machines)
                    {
                        machine.DeleteKey(key);
                    }

                    var jar = JsonConvert.SerializeObject(Box.Box.Mistranslate(box));

                    System.IO.File.WriteAllText(configurationPath, jar);

                    var nameClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "name");
                    var username = nameClaim != null ? nameClaim.Value : "no name claim";
                    var emailClaim = ClaimsPrincipal.Current.Identities.First().Claims.SingleOrDefault(x => x.Type == "email");
                    var email = emailClaim != null ? emailClaim.Value : "no email claim";
                    var message = "Removed setting " + key + " from " + configurationName + " in " + projectName;

                    var git = new Git(projectPath);
                    git.Stage(new List<string>() { configurationPath });
                    git.Commit(message, username, email);
                    git.Push();
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                throw;
            }
        }
Beispiel #35
0
 /// <summary>
 /// Checkout a branch or SHA.
 /// </summary>
 /// <param name="localRepository">The local Git repository.</param>
 /// <param name="branch">The branch or SHA you want to check out.</param>
 public void CheckoutBranch(string localRepository, string branch)
 {
     Git.Open(localRepository).Checkout().SetName(branch).Call();
 }
Beispiel #36
0
        public async Task <IActionResult> CreateForTenant([FromBody] CreateInputModel model, [FromServices] INodeRepository nodeRepository)
        {
            //データの入力チェック
            if (!ModelState.IsValid)
            {
                return(JsonBadRequest("Invalid inputs."));
            }

            if (model.TenantName.StartsWith(containerManageOptions.KqiNamespacePrefix) || model.TenantName.StartsWith(containerManageOptions.KubernetesNamespacePrefix))
            {
                // KqiNamespacePrefix または KubernetesNamespacePrefix で始まるテナント名は許可しないためエラー
                return(JsonBadRequest($"Invalid inputs. 'TenantName' cannot start with '{ containerManageOptions.KqiNamespacePrefix }' or '{ containerManageOptions.KubernetesNamespacePrefix }'."));
            }

            Tenant tenant = tenantRepository.GetFromTenantName(model.TenantName);

            if (tenant != null)
            {
                //テナント名の重複があるのでエラー
                return(JsonConflict($"Tenant {model.TenantName} already exists: ID = {tenant.Id}"));
            }
            if (model.DefaultGitId != null && model.GitIds.Contains(model.DefaultGitId.Value) == false)
            {
                //デフォルトGitがGit一覧の中になかったらエラー
                return(JsonConflict($"Default Git ID {model.DefaultGitId.Value} does NOT exist in selected gits."));
            }
            if (model.DefaultRegistryId != null && model.RegistryIds.Contains(model.DefaultRegistryId.Value) == false)
            {
                //デフォルトレジストリがレジストリ一覧の中になかったらエラー
                return(JsonConflict($"Default Registry ID {model.DefaultRegistryId.Value} does NOT exist in selected registries."));
            }

            tenant = new Tenant()
            {
                Name          = model.TenantName,
                DisplayName   = model.DisplayName,
                StorageBucket = model.TenantName,
                StorageId     = model.StorageId,
                AvailableInfiniteTimeNotebook = model.AvailableInfiniteTimeNotebook
            };

            Git git = null;

            if (model.GitIds != null && model.GitIds.Count() > 0)
            {
                //デフォルトGitの設定(無ければ一個目)
                tenant.DefaultGitId = model.DefaultGitId == null?
                                      model.GitIds.ElementAt(0) : model.DefaultGitId.Value;

                foreach (long gitId in model.GitIds)
                {
                    //データの存在チェック
                    git = await gitRepository.GetByIdAsync(gitId);

                    if (git == null)
                    {
                        return(JsonNotFound($"The selected git ID {gitId} is not found."));
                    }
                    await gitRepository.AttachGitToTenantAsync(tenant, git, true);
                }
            }
            Registry registry = null;

            if (model.RegistryIds != null && model.RegistryIds.Count() > 0)
            {
                //デフォルトレジストリの設定(無ければ一個目)
                tenant.DefaultRegistryId = model.DefaultRegistryId == null?
                                           model.RegistryIds.ElementAt(0) : model.DefaultRegistryId.Value;

                foreach (long registryId in model.RegistryIds)
                {
                    //データの存在チェック
                    registry = await registryRepository.GetByIdAsync(registryId);

                    if (registry == null)
                    {
                        return(JsonNotFound($"The selected registry ID {registryId} is not found."));
                    }
                    await registryRepository.AttachRegistryToTenantAsync(tenant, registry, true);
                }
            }

            //データの存在チェック
            var storage = tenantRepository.GetStorage(model.StorageId.Value);

            if (storage == null)
            {
                return(JsonNotFound($"The selected storage ID {model.StorageId.Value} is not found."));
            }

            //ObjectStorage に バケットを作成する
            bool isCreated = await storageLogic.CreateBucketAsync(tenant, storage);

            if (!isCreated)
            {
                // 既にバケットが存在していたならエラーとする
                return(JsonNotFound($"Can not create because [{tenant.Name}] exists in the NFS server. Please delete it from the NFS server."));
            }

            tenantRepository.AddTenant(tenant);

            //コンテナ管理サービス作業
            //テナントを登録
            var tenantResult = await clusterManagementLogic.RegistTenantAsync(tenant.Name);

            if (tenantResult == false)
            {
                return(JsonError(HttpStatusCode.ServiceUnavailable, "Couldn't create cluster master namespace. Please check the configuration to the connect cluster manager service."));
            }

            // アクセスレベルが "Public" のノードにアサイン
            var nodes = nodeRepository.GetAll().Where(n => n.AccessLevel == NodeAccessLevel.Public);

            foreach (Node node in nodes)
            {
                await clusterManagementLogic.UpdateTenantEnabledLabelAsync(node.Name, tenant.Name, true);
            }

            //初期データ投入処理
            commonDiLogic.InitializeTenant(tenant);

            unitOfWork.Commit();
            tenantRepository.Refresh();
            roleRepository.Refresh();

            var result = new IndexOutputModel(tenant);

            return(JsonOK(result));
        }
Beispiel #37
0
        public void DefaultValuesTest()
        {
            var instance = new Git();

            Assert.IsNull(instance.WorkingDirectory);
        }