示例#1
0
        public VersionFile GetVersionInfo(VersionInfo build)
        {
            if (!Configured())
                return null;
            if (!File.Exists(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml"))
                return null;

            var fileinfo = new VersionFile();
            fileinfo.Load(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");
            return fileinfo;
        }
示例#2
0
        public bool UpdateVersionDescription(VersionInfo build, string description)
        {
            if (!Configured())
                return false;
            if (!File.Exists(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml"))
                return false;

            var fileinfo = new VersionFile();
            fileinfo.Load(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");
            fileinfo.Description = description;
            fileinfo.Save(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");

            return true;
        }
示例#3
0
        public string AddToRepository(string sourceDir, bool beta, string description)
        {
            if (!Configured())
                return "Error : Not configured";

            var build = Tools.GetFileRevision(sourceDir + @"\Yatse2.exe");
            if (build == 0)
                return "Error : Invalid source dir";

            if (Directory.Exists(_platformDir + @"\" + build))
            {
                return "Error : Build allready in repository";
            }

            Directory.CreateDirectory(_platformDir + @"\" + build);
            Directory.CreateDirectory(_platformDir + @"\" + build + @"\Files");

            var fileinfos = new Collection<FileInfo>();
            var files = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                if (file.Contains(".pdb") || file.Contains(".vshost.") || file.Contains(".application"))
                    continue;
                var fileinfo = new FileInfo
                {
                    FilePath = file.Replace(sourceDir, ""),
                    FileHash = FileHash.GetFileHashString(file)
                };
                if (!File.Exists(_platformDir + @"\" + build + @"\Files\" +
                              fileinfo.FileHash + ".dat"))
                {
                    File.Copy(file, _platformDir + @"\" + build + @"\Files\" +
                              fileinfo.FileHash + ".dat");
                }
                fileinfos.Add(fileinfo);
            }

            var versionFile = new VersionFile { Description = description, FileInfos = fileinfos };
            versionFile.Save(_repoDir + @"\xmls\Version_" + _platform + "_" + build + ".xml");

            var liste = new VersionList();
            liste.Load(_repoDir + @"\xmls\Versions_" + _platform + ".xml");
            liste.Version.Add(new VersionInfo { Beta = beta, Build = build });
            liste.Save(_repoDir + @"\xmls\Versions_" + _platform + ".xml");

            return null;
        }
        private static VersionFile ReadOwnVersionFile()
        {
            VersionFile file        = null;
            var         ownAssembly = typeof(HugsLibController).Assembly;

            foreach (var modContentPack in LoadedModManager.RunningMods)
            {
                foreach (var loadedAssembly in modContentPack.assemblies.loadedAssemblies)
                {
                    if (!loadedAssembly.Equals(ownAssembly))
                    {
                        continue;
                    }
                    file = VersionFile.TryParseVersionFile(modContentPack);
                    if (file == null)
                    {
                        Logger.Error("Missing Version.xml file");
                    }
                }
            }
            return(file);
        }
    public void IsVersionDefined_String_ConsiderAncestorFolders()
    {
        // Construct a repo where versions are defined like this:

        /*   root <- 1.0
         *      a             (inherits 1.0)
         *          b <- 1.1
         *               c    (inherits 1.1)
         */
        VersionFile.SetVersion(this.RepoPath, new Version(1, 0));
        string subDirA   = Path.Combine(this.RepoPath, "a");
        string subDirAB  = Path.Combine(subDirA, "b");
        string subDirABC = Path.Combine(subDirAB, "c");

        Directory.CreateDirectory(subDirABC);
        VersionFile.SetVersion(subDirAB, new Version(1, 1));

        Assert.True(VersionFile.IsVersionDefined(subDirABC));
        Assert.True(VersionFile.IsVersionDefined(subDirAB));
        Assert.True(VersionFile.IsVersionDefined(subDirA));
        Assert.True(VersionFile.IsVersionDefined(this.RepoPath));
    }
示例#6
0
            protected override int Invoke(InvocationContext context)
            {
                var valid = true;

                this.Logger.LogInformation("Validting module path...");
                valid &= Validate(context.Console, () => ValidateModulePath(this.FileSystem));

                this.Logger.LogInformation("Validating main Bicep file...");

                var bicepCliProxy = new BicepCliProxy(this.environmentProxy, this.processProxy, this.FileSystem, this.Logger, context.Console);
                var mainBicepFile = MainBicepFile.ReadFromFileSystem(this.FileSystem);

                // This also validates that the main Bicep file can be built without errors.
                var latestMainArmTemplateFile = MainArmTemplateFile.Generate(this.FileSystem, bicepCliProxy, mainBicepFile);
                var descriptionsValidator     = new DescriptionsValidator(this.Logger, latestMainArmTemplateFile);

                valid &= Validate(context.Console, () => mainBicepFile.ValidatedBy(descriptionsValidator));

                var testValidator       = new TestValidator(this.FileSystem, this.Logger, bicepCliProxy, latestMainArmTemplateFile);
                var jsonSchemaValidator = new JsonSchemaValidator(this.Logger);
                var diffValidator       = new DiffValidator(this.FileSystem, this.Logger, latestMainArmTemplateFile);

                this.Logger.LogInformation("Validating main Bicep test file...");
                valid &= Validate(context.Console, () => MainBicepTestFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(testValidator));

                this.Logger.LogInformation("Validating main ARM template file...");
                valid &= Validate(context.Console, () => MainArmTemplateFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(diffValidator));

                this.Logger.LogInformation("Validating metadata file...");
                valid &= Validate(context.Console, () => MetadataFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(jsonSchemaValidator));

                this.Logger.LogInformation("Validating README file...");
                valid &= Validate(context.Console, () => ReadmeFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(diffValidator));

                this.Logger.LogInformation("Validating version file...");
                valid &= Validate(context.Console, () => VersionFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(jsonSchemaValidator, diffValidator));

                return(valid ? 0 : 1);
            }
示例#7
0
    public void PrepareRelease_ResetsVersionHeightOffset()
    {
        // create and configure repository
        this.InitializeSourceControl();

        var initialVersionOptions = new VersionOptions()
        {
            Version             = SemanticVersion.Parse("1.0-beta"),
            VersionHeightOffset = 5,
        };

        var expectedReleaseVersionOptions = new VersionOptions()
        {
            Version             = SemanticVersion.Parse("1.0"),
            VersionHeightOffset = 5,
        };

        var expectedMainVersionOptions = new VersionOptions()
        {
            Version = SemanticVersion.Parse("1.1-alpha"),
        };

        // create version.json
        this.WriteVersionFile(initialVersionOptions);

        var tipBeforePrepareRelease = this.Repo.Head.Tip;

        var releaseManager = new ReleaseManager();

        releaseManager.PrepareRelease(this.RepoPath);

        var newVersion = VersionFile.GetVersion(this.RepoPath);

        Assert.Equal(expectedMainVersionOptions, newVersion);

        var releaseVersion = VersionFile.GetVersion(this.Repo.Branches["v1.0"].Tip);

        Assert.Equal(expectedReleaseVersionOptions, releaseVersion);
    }
        private string ListActiveMods()
        {
            var builder = new StringBuilder();

            builder.Append("Loaded mods:\n");
            foreach (var modContentPack in LoadedModManager.RunningMods)
            {
                builder.Append(modContentPack.Name);
                var versionFile = VersionFile.TryParseVersionFile(modContentPack);
                if (versionFile != null && versionFile.OverrideVersion != null)
                {
                    builder.AppendFormat("[{0}]: ", versionFile.OverrideVersion);
                }
                else
                {
                    builder.Append(": ");
                }
                var firstAssembly = true;
                var anyAssemblies = false;
                foreach (var loadedAssembly in modContentPack.assemblies.loadedAssemblies)
                {
                    if (!firstAssembly)
                    {
                        builder.Append(", ");
                    }
                    firstAssembly = false;
                    builder.Append(loadedAssembly.GetName().Name);
                    builder.AppendFormat("({0})", loadedAssembly.GetName().Version);
                    anyAssemblies = true;
                }
                if (!anyAssemblies)
                {
                    builder.Append("(no assemblies)");
                }
                builder.Append("\n");
            }
            return(builder.ToString());
        }
    public void SetVersion_PathFilters_InheritOverride()
    {
        this.InitializeSourceControl();

        var rootVersionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            PathFilters = new []
            {
                new FilterPath("./root-file.txt", ""),
                new FilterPath("/absolute", ""),
            }
        };

        VersionFile.SetVersion(this.RepoPath, rootVersionOptions);

        var versionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            Inherit     = true,
            PathFilters = new []
            {
                new FilterPath("./project-file.txt", "quux"),
                new FilterPath("/absolute", "quux"),
            }
        };
        var projectDirectory = Path.Combine(this.RepoPath, "quux");

        VersionFile.SetVersion(projectDirectory, versionOptions);

        var expected = versionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        var actualVersionOptions = VersionFile.GetVersion(projectDirectory);
        var actual = actualVersionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        Assert.Equal(expected, actual);
    }
    public void SetVersion_PathFilters_DifferentRelativePaths()
    {
        this.InitializeSourceControl();

        var versionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            PathFilters = new []
            {
                new FilterPath("./foo", "bar"),
                new FilterPath("/absolute", "bar"),
            }
        };
        var expected = versionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        var projectDirectory = Path.Combine(this.RepoPath, "quux");

        VersionFile.SetVersion(projectDirectory, versionOptions);

        var actualVersionOptions = VersionFile.GetVersion(projectDirectory);
        var actual = actualVersionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        Assert.Equal(expected, actual);
    }
    public void GetVersion_String_FindsNearestFileInAncestorDirectories()
    {
        // Construct a repo where versions are defined like this:

        /*   root <- 1.0
         *      a             (inherits 1.0)
         *          b <- 1.1
         *               c    (inherits 1.1)
         */
        VersionFile.SetVersion(this.RepoPath, new Version(1, 0));
        string subDirA   = Path.Combine(this.RepoPath, "a");
        string subDirAB  = Path.Combine(subDirA, "b");
        string subDirABC = Path.Combine(subDirAB, "c");

        Directory.CreateDirectory(subDirABC);
        VersionFile.SetVersion(subDirAB, new Version(1, 1));
        this.InitializeSourceControl();
        var commit = this.Repo.Head.Commits.First();

        AssertPathHasVersion(commit, subDirABC, new Version(1, 1));
        AssertPathHasVersion(commit, subDirAB, new Version(1, 1));
        AssertPathHasVersion(commit, subDirA, new Version(1, 0));
        AssertPathHasVersion(commit, this.RepoPath, new Version(1, 0));
    }
示例#12
0
        public void Validate(VersionFile file)
        {
            var latestVersionFile = VersionFile.Generate(this.fileSystem);

            this.Validate(file.Path, file.Content, latestVersionFile.Content);
        }
示例#13
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string();
            tokens["AlterDatabaseFolderName"]  = AlterDatabaseFolderName.to_string();
            tokens["Baseline"] = Baseline.to_string();
            tokens["BeforeMigrationFolderName"]  = BeforeMigrationFolderName.to_string();
            tokens["CommandTimeout"]             = CommandTimeout.to_string();
            tokens["CommandTimeoutAdmin"]        = CommandTimeoutAdmin.to_string();
            tokens["ConfigurationFile"]          = ConfigurationFile.to_string();
            tokens["ConnectionString"]           = ConnectionString.to_string();
            tokens["ConnectionStringAdmin"]      = ConnectionStringAdmin.to_string();
            tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string();
            tokens["DatabaseName"]             = DatabaseName.to_string();
            tokens["DatabaseType"]             = DatabaseType.to_string();
            tokens["Debug"]                    = Debug.to_string();
            tokens["DisableOutput"]            = DisableOutput.to_string();
            tokens["DisableTokenReplacement"]  = DisableTokenReplacement.to_string();
            tokens["DoNotAlterDatabase"]       = DoNotAlterDatabase.to_string();
            tokens["DoNotCreateDatabase"]      = DoNotCreateDatabase.to_string();
            tokens["DoNotStoreScriptsRunText"] = DoNotStoreScriptsRunText.to_string();
            tokens["DownFolderName"]           = DownFolderName.to_string();
            tokens["Drop"]                                     = Drop.to_string();
            tokens["DryRun"]                                   = DryRun.to_string();
            tokens["EnvironmentName"]                          = string.Join(",", EnvironmentNames);
            tokens["EnvironmentNames"]                         = string.Join(",", EnvironmentNames);
            tokens["FunctionsFolderName"]                      = FunctionsFolderName.to_string();
            tokens["IndexesFolderName"]                        = IndexesFolderName.to_string();
            tokens["Initialize"]                               = Initialize.to_string();
            tokens["OutputPath"]                               = OutputPath.to_string();
            tokens["PermissionsFolderName"]                    = PermissionsFolderName.to_string();
            tokens["RecoveryMode"]                             = RecoveryMode.to_string();
            tokens["RepositoryPath"]                           = RepositoryPath.to_string();
            tokens["Restore"]                                  = Restore.to_string();
            tokens["RestoreCustomOptions"]                     = RestoreCustomOptions.to_string();
            tokens["RestoreFromPath"]                          = RestoreFromPath.to_string();
            tokens["RestoreTimeout"]                           = RestoreTimeout.to_string();
            tokens["RunAfterCreateDatabaseFolderName"]         = RunAfterCreateDatabaseFolderName.to_string();
            tokens["RunAfterOtherAnyTimeScriptsFolderName"]    = RunAfterOtherAnyTimeScriptsFolderName.to_string();
            tokens["RunAllAnyTimeScripts"]                     = RunAllAnyTimeScripts.to_string();
            tokens["RunBeforeUpFolderName"]                    = RunBeforeUpFolderName.to_string();
            tokens["RunFirstAfterUpFolderName"]                = RunFirstAfterUpFolderName.to_string();
            tokens["SchemaName"]                               = SchemaName.to_string();
            tokens["ScriptsRunErrorsTableName"]                = ScriptsRunErrorsTableName.to_string();
            tokens["ScriptsRunTableName"]                      = ScriptsRunTableName.to_string();
            tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string();
            tokens["ServerName"]                               = ServerName.to_string();
            tokens["Silent"]                                   = Silent.to_string();
            tokens["SprocsFolderName"]                         = SprocsFolderName.to_string();
            tokens["SqlFilesDirectory"]                        = SqlFilesDirectory.to_string();
            tokens["TriggersFolderName"]                       = TriggersFolderName.to_string();
            tokens["UpFolderName"]                             = UpFolderName.to_string();
            tokens["Version"]                                  = Version.to_string();
            tokens["VersionFile"]                              = VersionFile.to_string();
            tokens["VersionTableName"]                         = VersionTableName.to_string();
            tokens["VersionXPath"]                             = VersionXPath.to_string();
            tokens["ViewsFolderName"]                          = ViewsFolderName.to_string();
            tokens["WarnAndIgnoreOnOneTimeScriptChanges"]      = WarnAndIgnoreOnOneTimeScriptChanges.to_string();
            tokens["WarnOnOneTimeScriptChanges"]               = WarnOnOneTimeScriptChanges.to_string();
            tokens["WithTransaction"]                          = WithTransaction.to_string();

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
 public void GetVersion_String_MissingFile()
 {
     Assert.Null(VersionFile.GetVersion(this.RepoPath));
 }
 public void IsVersionDefined_Commit_Null()
 {
     Assert.False(VersionFile.IsVersionDefined((Commit)null));
 }
示例#16
0
        public VersionFile GetVersionInfo(VersionInfo build)
        {
            if (!Configured())
                return null;

            if (!DownloadFile(_repository + @"/Download/" + _platform + @"/" + build.Build + @"/Version" , "Version_" + _platform + "_" + build.Build + ".xml"))
                return null;

            var fileinfo = new VersionFile();
            fileinfo.Load(_tempDirectory + @"\Version_" + _platform + "_" + build.Build + ".xml");
            Log("Get Version Info : Build : " + build.Build);
            return fileinfo;
        }
示例#17
0
    IEnumerator CheckHotUpdateAsync()
    {
        WWW www = new WWW(FormatUrl(serverUrl, GetRouteRoot() + "files.txt"));

        yield return(www);

        if (!string.IsNullOrEmpty(www.error))
        {
            hotUI.HOT_CheckHotUpdateError(www.error, this);

            www.Dispose();
            www = null;
        }
        else
        {
            //对比文件是否需要更新
            var serverFileInfos = VersionFile.ReadFileInfo(www.text);

            // 清空更新文件列表
            updateVersionFileList.Clear();
            updateVersionFileCount        = 0;
            currentUpdateVersionFileIndex = 0;

            for (int i = 0; i < serverFileInfos.Length; i++)
            {
                var fileInfo = serverFileInfos[i];
                // 本地文件路径
                var localFilePath = fileInfo.DataLocalPath;

                // 文件夹是否存在
                var localFileDir = Path.GetDirectoryName(localFilePath);
                if (!Directory.Exists(localFileDir))
                {
                    Directory.CreateDirectory(localFileDir);
                }

                // 文件服务器地址
                var fileUrl = FormatUrl(serverUrl, GetRouteRoot() + fileInfo.WebPath);

                if (!File.Exists(localFilePath))
                {
                    // 文件不存在,需要更新
                    updateVersionFileList.Add(fileInfo);

                    // 删除本地文件,等待更新
                    updateSize += fileInfo.Size;
                }
                else
                {
                    string serverFileHash = fileInfo.Hash.Trim();
                    string localMd5       = Util.md5file(localFilePath);
                    if (!serverFileHash.Equals(localMd5))
                    {
                        updateVersionFileList.Add(fileInfo);

                        updateSize += fileInfo.Size;

                        // 删除本地文件, 等待更新
                        File.Delete(localFilePath);
                    }
                }
            }
        }

        updateVersionFileCount        = updateVersionFileList.Count;
        currentUpdateVersionFileIndex = 0;

        if (updateVersionFileCount > 0)
        {
            // 需要更新
            hotUI.HOT_CheckUpdateSure(() =>
            {
                DownloadHot();
            }, () => {
                Application.Quit();
            },
                                      this);
        }
    }
示例#18
0
        public void Validate_ValidVersionFile_Succeeds()
        {
            var fileToValidate = VersionFile.ReadFromFileSystem(this.fileSystem);

            Invoking(() => this.sut.Validate(fileToValidate)).Should().NotThrow();
        }
示例#19
0
 public void Validate(VersionFile file) => this.Validate(file.Path, JsonSchemaManager.VersionFileSchema, file.RootElement);
示例#20
0
    public static void BuildHotPackage(List <HotObject> hotList)
    {
        // 把hot 转成字典 用于后面查询
        var hotDic = new Dictionary <string, bool>();

        for (int i = 0; i < hotList.Count; i++)
        {
            hotDic.Add(hotList[i].package, true);
        }

        // 版本路径
        string versionPath = GetVersionBundlePath();

        // hot 路径
        var hotPath = Replace(string.Format("{0}{1}{2}", versionPath, Path.DirectorySeparatorChar, "hot"));
        // hot vesion
        var hotVersionPath = Replace(string.Format("{0}{1}{2}", hotPath, Path.DirectorySeparatorChar, VersionInfo.BundleVersion));
        // hot file
        var hotFilePath = Replace(string.Format("{0}{1}{2}", hotPath, Path.DirectorySeparatorChar, "files.txt"));

        // res 路径
        var resPath = Replace(string.Format("{0}{1}{2}", versionPath, Path.DirectorySeparatorChar, "bundle"));
        // res version
        var resVersionPath = Replace(string.Format("{0}{1}{2}", versionPath, Path.DirectorySeparatorChar, VersionInfo.BundleVersion));
        // res file
        var resFilePath = Replace(string.Format("{0}{1}{2}", versionPath, Path.DirectorySeparatorChar, "files.txt"));

        // 线上file.txt路径
        var liveFilePath = "E:/work2/package/android/file.txt";

        // 清理目录
        ClearDirectory(hotPath);

        // hot new files context dic
        var hotNewFilesContextDic = new Dictionary <string, VersionFile>();
        // hot files context list
        var hotFilesPathContextList = new List <VersionFile>();

        // res files.txt 内容
        var resFiles = ReadFileInfo(File.ReadAllText(resFilePath));

        for (int i = 0; i < resFilePath.Length; i++)
        {
            if (hotDic.ContainsKey(resFiles[i].Path))
            {
                hotNewFilesContextDic.Add(resFiles[i].Path, resFiles[i]);
            }
        }

        // live files.txt 内容
        var liveFiles = ReadFileInfo(File.ReadAllText(liveFilePath));

        for (int i = 0; i < liveFilePath.Length; i++)
        {
            if (hotDic.ContainsKey(resFiles[i].Path))
            {
                hotFilesPathContextList.Add(hotNewFilesContextDic[resFiles[i].Path]);
                RGLog.Debug("hot file -> " + resFiles[i]);
            }
            else
            {
                hotFilesPathContextList.Add(liveFiles[i]);
            }
        }

        // hot files 文件写入
        var hotFs = new FileStream(hotFilePath, FileMode.CreateNew);
        var hotSw = new StreamWriter(hotFs);

        for (int i = 0; i < hotFilesPathContextList.Count; i++)
        {
            VersionFile verfile = hotFilesPathContextList[i];
            hotSw.WriteLine(verfile);
        }
        hotSw.Close();
        hotFs.Close();

        // copy 需要热更的文件到hot目录下
        for (int i = 0; i < hotFilesPathContextList.Count; i++)
        {
            if (hotDic.ContainsKey(hotFilesPathContextList[i].Path))
            {
                var rf = Replace(string.Format("{0}{1}{2}", resVersionPath, Path.DirectorySeparatorChar, hotFilesPathContextList[i].Path));
                var tf = Replace(string.Format("{0}{1}{2}", hotVersionPath, Path.DirectorySeparatorChar, hotFilesPathContextList[i].Path));

                string dir = Path.GetDirectoryName(tf);
                Directory.CreateDirectory(dir);

                File.Copy(rf, tf);
                RGLog.Debug("copy hot file -> " + hotFilesPathContextList[i].Path);
            }
        }

        RGLog.Debug("热更资源构建完毕");
    }
示例#21
0
    public void PrepareRelease_JsonOutput()
    {
        // create and configure repository
        this.InitializeSourceControl();

        // create version.json
        var versionOptions = new VersionOptions()
        {
            Version = SemanticVersion.Parse("1.0"),
            Release = new ReleaseOptions()
            {
                BranchName       = "v{version}",
                VersionIncrement = ReleaseVersionIncrement.Minor
            }
        };

        this.WriteVersionFile(versionOptions);

        var currentBranchName = this.Repo.Head.FriendlyName;
        var releaseBranchName = "v1.0";

        // run release preparation
        var stdout         = new StringWriter();
        var releaseManager = new ReleaseManager(stdout);

        releaseManager.PrepareRelease(this.RepoPath, outputMode: ReleaseManager.ReleaseManagerOutputMode.Json);


        // Expected output:
        // {
        //     "CurrentBranch" : {
        //         "Name" : "<NAME-OF-CURRENT-BRANCH>",
        //         "Commit" : "<HEAD-COMMIT-OF-CURRENT-BRANCH>",
        //         "Version" : "<UPDATED-VERSION-ON-CURRENT-BRANCH>",
        //     },
        //     "NewBranch" : {
        //         "Name" : "<NAME-OF-CREATED-BRANCH>",
        //         "Commit" : "<HEAD-COMMIT-OF-CREATED-BRANCH>",
        //         "Version" : "<VERSION-ON-CREATED-BRANCH>",
        //     }
        // }

        var jsonOutput = JObject.Parse(stdout.ToString());

        // check "CurrentBranch" output
        {
            var expectedCommitId = this.Repo.Branches[currentBranchName].Tip.Sha;
            var expectedVersion  = VersionFile.GetVersion(this.Repo.Branches[currentBranchName].Tip).Version.ToString();

            var currentBranchOutput = jsonOutput.Property("CurrentBranch")?.Value as JObject;
            Assert.NotNull(currentBranchOutput);

            Assert.Equal(currentBranchName, currentBranchOutput.GetValue("Name")?.ToString());
            Assert.Equal(expectedCommitId, currentBranchOutput.GetValue("Commit")?.ToString());
            Assert.Equal(expectedVersion, currentBranchOutput.GetValue("Version")?.ToString());
        }

        // Check "NewBranch" output
        {
            var expectedCommitId = this.Repo.Branches[releaseBranchName].Tip.Sha;
            var expectedVersion  = VersionFile.GetVersion(this.Repo.Branches[releaseBranchName].Tip).Version.ToString();

            var newBranchOutput = jsonOutput.Property("NewBranch")?.Value as JObject;
            Assert.NotNull(newBranchOutput);

            Assert.Equal(releaseBranchName, newBranchOutput.GetValue("Name")?.ToString());
            Assert.Equal(expectedCommitId, newBranchOutput.GetValue("Commit")?.ToString());
            Assert.Equal(expectedVersion, newBranchOutput.GetValue("Version")?.ToString());
        }
    }
示例#22
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { nameof(AccessToken), AccessToken.to_string() },
                { nameof(AfterMigrationFolderName), AfterMigrationFolderName.to_string() },
                { nameof(AlterDatabaseFolderName), AlterDatabaseFolderName.to_string() },
                { nameof(Baseline), Baseline.to_string() },
                { nameof(BeforeMigrationFolderName), BeforeMigrationFolderName.to_string() },
                { nameof(CommandTimeout), CommandTimeout.to_string() },
                { nameof(CommandTimeoutAdmin), CommandTimeoutAdmin.to_string() },
                { nameof(ConfigurationFile), ConfigurationFile.to_string() },
                { nameof(ConnectionString), ConnectionString.to_string() },
                { nameof(ConnectionStringAdmin), ConnectionStringAdmin.to_string() },
                { nameof(CreateDatabaseCustomScript), CreateDatabaseCustomScript.to_string() },
                { nameof(DatabaseName), DatabaseName.to_string() },
                { nameof(DatabaseType), DatabaseType.to_string() },
                { nameof(Debug), Debug.to_string() },
                { nameof(DisableOutput), DisableOutput.to_string() },
                { nameof(DisableTokenReplacement), DisableTokenReplacement.to_string() },
                { nameof(DoNotAlterDatabase), DoNotAlterDatabase.to_string() },
                { nameof(DoNotCreateDatabase), DoNotCreateDatabase.to_string() },
                { nameof(DoNotStoreScriptsRunText), DoNotStoreScriptsRunText.to_string() },
                { nameof(DownFolderName), DownFolderName.to_string() },
                { nameof(Drop), Drop.to_string() },
                { nameof(DryRun), DryRun.to_string() },
#pragma warning disable 618
                { nameof(EnvironmentName), string.Join(",", EnvironmentNames) },
#pragma warning restore 618
                { nameof(EnvironmentNames), string.Join(",", EnvironmentNames) },
                { nameof(FunctionsFolderName), FunctionsFolderName.to_string() },
                { nameof(IndexesFolderName), IndexesFolderName.to_string() },
                { nameof(Initialize), Initialize.to_string() },
                { nameof(OutputPath), OutputPath.to_string() },
                { nameof(PermissionsFolderName), PermissionsFolderName.to_string() },
                { nameof(RecoveryMode), RecoveryMode.to_string() },
                { nameof(RepositoryPath), RepositoryPath.to_string() },
                { nameof(Restore), Restore.to_string() },
                { nameof(RestoreCustomOptions), RestoreCustomOptions.to_string() },
                { nameof(RestoreFromPath), RestoreFromPath.to_string() },
                { nameof(RestoreTimeout), RestoreTimeout.to_string() },
                { nameof(RunAfterCreateDatabaseFolderName), RunAfterCreateDatabaseFolderName.to_string() },
                { nameof(RunAfterOtherAnyTimeScriptsFolderName), RunAfterOtherAnyTimeScriptsFolderName.to_string() },
                { nameof(RunAllAnyTimeScripts), RunAllAnyTimeScripts.to_string() },
                { nameof(RunBeforeUpFolderName), RunBeforeUpFolderName.to_string() },
                { nameof(RunFirstAfterUpFolderName), RunFirstAfterUpFolderName.to_string() },
                { nameof(SchemaName), SchemaName.to_string() },
                { nameof(ScriptsRunErrorsTableName), ScriptsRunErrorsTableName.to_string() },
                { nameof(ScriptsRunTableName), ScriptsRunTableName.to_string() },
                { nameof(SearchAllSubdirectoriesInsteadOfTraverse), SearchAllSubdirectoriesInsteadOfTraverse.to_string() },
                { nameof(ServerName), ServerName.to_string() },
                { nameof(Silent), Silent.to_string() },
                { nameof(SprocsFolderName), SprocsFolderName.to_string() },
                { nameof(SqlFilesDirectory), SqlFilesDirectory.to_string() },
                { nameof(TriggersFolderName), TriggersFolderName.to_string() },
                { nameof(UpFolderName), UpFolderName.to_string() },
                { nameof(Version), Version.to_string() },
                { nameof(VersionFile), VersionFile.to_string() },
                { nameof(VersionTableName), VersionTableName.to_string() },
                { nameof(VersionXPath), VersionXPath.to_string() },
                { nameof(ViewsFolderName), ViewsFolderName.to_string() },
                { nameof(WarnAndIgnoreOnOneTimeScriptChanges), WarnAndIgnoreOnOneTimeScriptChanges.to_string() },
                { nameof(WarnOnOneTimeScriptChanges), WarnOnOneTimeScriptChanges.to_string() },
                { nameof(WithTransaction), WithTransaction.to_string() },
            };

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
示例#23
0
        private static ExitCodes OnInstallCommand(string versionJsonRoot, string version)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return(ExitCodes.InvalidVersionSpec);
            }

            var options = new VersionOptions
            {
                Version = semver,
                PublicReleaseRefSpec = new string[]
                {
                    @"^refs/heads/master$",
                    @"^refs/heads/v\d+(?:\.\d+)?$",
                },
                CloudBuild = new VersionOptions.CloudBuildOptions
                {
                    BuildNumber = new VersionOptions.CloudBuildNumberOptions
                    {
                        Enabled = true,
                    },
                },
            };
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(versionJsonRoot);

            if (!Directory.Exists(searchPath))
            {
                Console.Error.WriteLine("\"{0}\" is not an existing directory.", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            var repository = GitExtensions.OpenGitRepo(searchPath);

            if (repository == null)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            if (string.IsNullOrEmpty(versionJsonRoot))
            {
                versionJsonRoot = repository.Info.WorkingDirectory;
            }

            var existingOptions = VersionFile.GetVersion(versionJsonRoot);

            if (existingOptions != null)
            {
                if (!string.IsNullOrEmpty(version))
                {
                    var setVersionExitCode = OnSetVersionCommand(versionJsonRoot, version);
                    if (setVersionExitCode != ExitCodes.OK)
                    {
                        return(setVersionExitCode);
                    }
                }
            }
            else
            {
                string versionJsonPath = VersionFile.SetVersion(versionJsonRoot, options);
                LibGit2Sharp.Commands.Stage(repository, versionJsonPath);
            }

            // Create/update the Directory.Build.props file in the directory of the version.json file to add the NB.GV package.
            string directoryBuildPropsPath = Path.Combine(versionJsonRoot, "Directory.Build.props");

            MSBuild.Project propsFile;
            if (File.Exists(directoryBuildPropsPath))
            {
                propsFile = new MSBuild.Project(directoryBuildPropsPath);
            }
            else
            {
                propsFile = new MSBuild.Project();
            }

            const string PackageReferenceItemType = "PackageReference";
            const string PackageId = "Nerdbank.GitVersioning";

            if (!propsFile.GetItemsByEvaluatedInclude(PackageId).Any(i => i.ItemType == "PackageReference"))
            {
                string packageVersion = GetLatestPackageVersionAsync(PackageId).GetAwaiter().GetResult();
                propsFile.AddItem(
                    PackageReferenceItemType,
                    PackageId,
                    new Dictionary <string, string>
                {
                    { "Version", packageVersion },     // TODO: use the latest version... somehow...
                    { "PrivateAssets", "all" },
                });

                propsFile.Save(directoryBuildPropsPath);
            }

            LibGit2Sharp.Commands.Stage(repository, directoryBuildPropsPath);

            return(ExitCodes.OK);
        }
示例#24
0
 public WorkingVersions(VersionFile current, VersionFile latest)
 {
     Current = current;
     Latest  = latest;
 }
示例#25
0
    public static void BuileFileIndex()
    {
        string buildVersion = "0.0.1";

        List <string> _files = new List <string>();

        string resPath = _exportPath;

        if (!Directory.Exists(resPath))
        {
            Directory.CreateDirectory(resPath);
        }

        string newFilePath = string.Format("{0}{1}", resPath, "/files.txt");

        if (File.Exists(newFilePath))
        {
            File.Delete(newFilePath);
        }

        string[] allFiles = Directory.GetFiles(resPath, "*.*", SearchOption.AllDirectories);
        _files.AddRange(allFiles);

        var fs = new FileStream(newFilePath, FileMode.CreateNew);
        var sw = new StreamWriter(fs);

        for (int i = 0; i < _files.Count; i++)
        {
            string file = _files[i];
            if (file.EndsWith(".DS_Store"))
            {
                continue;
            }
            if (file.EndsWith("StreamingAssets"))
            {
                continue;
            }

            string ext = Path.GetExtension(file);
            if (ext.EndsWith(".meta"))
            {
                continue;
            }
            if (ext.EndsWith(".txt"))
            {
                continue;
            }
            if (ext.EndsWith(".manifest"))
            {
                continue;
            }
            if (ext.EndsWith(".mp4"))
            {
                continue;
            }
            if (ext.EndsWith(".zip"))
            {
                continue;
            }

            var verfile = new VersionFile();
            verfile.Path = file.Replace(resPath + Path.DirectorySeparatorChar, string.Empty)
                           .Replace(Path.DirectorySeparatorChar, '/');
            verfile.Hash    = Util.md5file(file);
            verfile.Version = buildVersion;
            FileInfo fileInfo = new FileInfo(file);
            verfile.Size = fileInfo.Length;
            sw.WriteLine(verfile);
        }
        sw.Close();
        fs.Close();
        sw.Dispose();
        fs.Dispose();
        RGLog.Debug(" Build File Index ");
    }
示例#26
0
        private void DownloadRes(string url, string dataPath, System.Object obj)
        {
            try
            {
                if (obj == null)
                {
                    throw new System.Exception("download param is null");
                }

                int index = (int)obj;
                if (index < 0 || index >= versionInfo.Files.Count)
                {
                    throw new System.Exception("download error 1");
                }

                VersionFile vf = versionInfo.Files[index];

                string guid = vf.Guid;

                GameUtils.StringBuilderClear();

                GameUtils.stringBuilder.Append(GetLocalAssetPath());
                GameUtils.stringBuilder.Append(guid);

                string path = GameUtils.stringBuilder.ToString();
                {
                    string md5Str;

                    bool re = false;
                    using (FileStream fs = File.OpenRead(dataPath))
                    {
                        if (Config.Detail_Debug_Log())
                        {
                            Debugger.Log("res update down load res data->" + fs.Length);
                        }
                        re = UnZipData(fs, path, out md5Str);
                    }

                    File.Delete(dataPath);
#if UNITY_IPHONE
                    if (re)
                    {
                        if (Application.platform == RuntimePlatform.IPhonePlayer)
                        {
                            UnityEngine.iOS.Device.SetNoBackupFlag(GameUtils.stringBuilder.ToString());
                        }
                        //iPhone.SetNoBackupFlag(GameUtils.stringBuilder.ToString());
                    }
#endif

                    {
                        if (!re)
                        {
                            Debugger.LogError("data is null, reload");
                            WwwWorkpool.instance.AddWork(url, -1, DownloadRes, index, false);
                            return;
                        }

                        if (md5Str != vf.Md5)
                        {
                            WwwWorkpool.instance.AddWork(url, -1, DownloadRes, index, false);
                        }
                        else
                        {
                            curNum++;
                            curSize    += vf.Size;
                            curFileSize = 0;
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                //#if UNITY_EDITOR
                Debugger.LogError(e.ToString());
                //#endif
            }
        }
 public void IsVersionDefined_String_NullOrEmpty()
 {
     Assert.Throws <ArgumentNullException>(() => VersionFile.IsVersionDefined((string)null));
     Assert.Throws <ArgumentException>(() => VersionFile.IsVersionDefined(string.Empty));
 }
        public override bool Execute()
        {
            try
            {
                Version        typedVersion;
                VersionOptions versionOptions;
                using (var git = this.OpenGitRepo())
                {
                    var repoRoot = git?.Info?.WorkingDirectory?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    var relativeRepoProjectDirectory = !string.IsNullOrWhiteSpace(repoRoot)
                        ? Environment.CurrentDirectory.Substring(repoRoot.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
                        : null;

                    var commit = git?.Head.Commits.FirstOrDefault();
                    this.GitCommitId      = commit?.Id.Sha ?? string.Empty;
                    this.GitVersionHeight = git?.GetVersionHeight(relativeRepoProjectDirectory) ?? 0;
                    if (string.IsNullOrEmpty(this.BuildingRef))
                    {
                        this.BuildingRef = git?.Head.CanonicalName;
                    }

                    versionOptions =
                        VersionFile.GetVersion(git, Environment.CurrentDirectory) ??
                        VersionFile.GetVersion(Environment.CurrentDirectory);

                    this.PublicRelease = string.Equals(this.DefaultPublicRelease, "true", StringComparison.OrdinalIgnoreCase);
                    if (string.IsNullOrEmpty(this.DefaultPublicRelease))
                    {
                        if (!string.IsNullOrEmpty(this.BuildingRef) && versionOptions?.PublicReleaseRefSpec?.Length > 0)
                        {
                            this.PublicRelease = versionOptions.PublicReleaseRefSpec.Any(
                                expr => Regex.IsMatch(this.BuildingRef, expr));
                        }
                    }

                    this.PrereleaseVersion = versionOptions?.Version.Prerelease ?? string.Empty;

                    // Override the typedVersion with the special build number and revision components, when available.
                    typedVersion = git?.GetIdAsVersion(relativeRepoProjectDirectory, this.GitVersionHeight) ?? versionOptions?.Version.Version;
                }

                typedVersion = typedVersion ?? new Version();
                var typedVersionWithoutRevision = typedVersion.Build >= 0
                    ? new Version(typedVersion.Major, typedVersion.Minor, typedVersion.Build)
                    : new Version(typedVersion.Major, typedVersion.Minor);
                this.SimpleVersion = typedVersionWithoutRevision.ToString();
                var majorMinorVersion = new Version(typedVersion.Major, typedVersion.Minor);
                this.MajorMinorVersion = majorMinorVersion.ToString();
                Version assemblyVersion = GetAssemblyVersion(typedVersion, versionOptions);
                this.AssemblyVersion = assemblyVersion.ToStringSafe(4);
                this.BuildNumber     = Math.Max(0, typedVersion.Build);
                this.Version         = typedVersion.ToString();

                this.SetCloudBuildVersionVars = versionOptions?.CloudBuild?.SetVersionVariables
                                                ?? (new VersionOptions.CloudBuildOptions()).SetVersionVariables;

                var buildMetadata = this.BuildMetadata?.ToList() ?? new List <string>();
                if (!string.IsNullOrEmpty(this.GitCommitId))
                {
                    buildMetadata.Insert(0, $"g{this.GitCommitId.Substring(0, 10)}");
                }

                this.BuildMetadataFragment = FormatBuildMetadata(buildMetadata);

                var buildNumber = versionOptions?.CloudBuild?.BuildNumber ?? new VersionOptions.CloudBuildNumberOptions();
                if (buildNumber.Enabled)
                {
                    var  commitIdOptions   = buildNumber.IncludeCommitId ?? new VersionOptions.CloudBuildNumberCommitIdOptions();
                    bool includeCommitInfo = commitIdOptions.When == VersionOptions.CloudBuildNumberCommitWhen.Always ||
                                             (commitIdOptions.When == VersionOptions.CloudBuildNumberCommitWhen.NonPublicReleaseOnly && !this.PublicRelease);
                    bool    commitIdInRevision      = includeCommitInfo && commitIdOptions.Where == VersionOptions.CloudBuildNumberCommitWhere.FourthVersionComponent;
                    bool    commitIdInBuildMetadata = includeCommitInfo && commitIdOptions.Where == VersionOptions.CloudBuildNumberCommitWhere.BuildMetadata;
                    Version buildNumberVersion      = commitIdInRevision ? typedVersion : typedVersionWithoutRevision;
                    string  buildNumberMetadata     = FormatBuildMetadata(commitIdInBuildMetadata ? (IEnumerable <string>)buildMetadata : this.BuildMetadata);
                    this.CloudBuildNumber = buildNumberVersion + this.PrereleaseVersion + buildNumberMetadata;
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Log.LogErrorFromException(ex);
                return(false);
            }

            return(true);
        }
    public void VersionJson_Inheritance(bool commitInSourceControl, bool bareRepo)
    {
        if (commitInSourceControl)
        {
            this.InitializeSourceControl();
        }

        VersionOptions level1, level2, level3, level2NoInherit, level2InheritButResetVersion;

        this.WriteVersionFile(
            level1 = new VersionOptions
        {
            Version         = SemanticVersion.Parse("14.2"),
            AssemblyVersion = new VersionOptions.AssemblyVersionOptions {
                Precision = VersionOptions.VersionPrecision.Major
            },
        });
        this.WriteVersionFile(
            level2 = new VersionOptions
        {
            Inherit         = true,
            AssemblyVersion = new VersionOptions.AssemblyVersionOptions {
                Precision = VersionOptions.VersionPrecision.Minor
            },
        },
            "foo");
        this.WriteVersionFile(
            level3 = new VersionOptions
        {
            Inherit             = true,
            VersionHeightOffset = 1,
        },
            @"foo\bar");
        this.WriteVersionFile(
            level2NoInherit = new VersionOptions
        {
            Version = SemanticVersion.Parse("10.1"),
        },
            @"noInherit");
        this.WriteVersionFile(
            level2InheritButResetVersion = new VersionOptions
        {
            Inherit = true,
            Version = SemanticVersion.Parse("8.2"),
        },
            @"inheritWithVersion");

        Repository operatingRepo = this.Repo;

        if (bareRepo)
        {
            operatingRepo = new Repository(
                Repository.Clone(this.RepoPath, this.CreateDirectoryForNewRepo(), new CloneOptions {
                IsBare = true
            }));
        }

        using (operatingRepo)
        {
            VersionOptions GetOption(string path) => commitInSourceControl?VersionFile.GetVersion(operatingRepo, path) : VersionFile.GetVersion(Path.Combine(this.RepoPath, path));

            var level1Options = GetOption(string.Empty);
            Assert.False(level1Options.Inherit);

            var level2Options = GetOption("foo");
            Assert.Equal(level1.Version.Version.Major, level2Options.Version.Version.Major);
            Assert.Equal(level1.Version.Version.Minor, level2Options.Version.Version.Minor);
            Assert.Equal(level2.AssemblyVersion.Precision, level2Options.AssemblyVersion.Precision);
            Assert.True(level2Options.Inherit);

            var level3Options = GetOption(@"foo\bar");
            Assert.Equal(level1.Version.Version.Major, level3Options.Version.Version.Major);
            Assert.Equal(level1.Version.Version.Minor, level3Options.Version.Version.Minor);
            Assert.Equal(level2.AssemblyVersion.Precision, level3Options.AssemblyVersion.Precision);
            Assert.Equal(level2.AssemblyVersion.Precision, level3Options.AssemblyVersion.Precision);
            Assert.Equal(level3.VersionHeightOffset, level3Options.VersionHeightOffset);
            Assert.True(level3Options.Inherit);

            var level2NoInheritOptions = GetOption("noInherit");
            Assert.Equal(level2NoInherit.Version, level2NoInheritOptions.Version);
            Assert.Equal(VersionOptions.DefaultVersionPrecision, level2NoInheritOptions.AssemblyVersionOrDefault.PrecisionOrDefault);
            Assert.False(level2NoInheritOptions.Inherit);

            var level2InheritButResetVersionOptions = GetOption("inheritWithVersion");
            Assert.Equal(level2InheritButResetVersion.Version, level2InheritButResetVersionOptions.Version);
            Assert.True(level2InheritButResetVersionOptions.Inherit);

            if (commitInSourceControl)
            {
                int totalCommits = operatingRepo.Head.Commits.Count();

                // The version height should be the same for all those that inherit the version from the base,
                // even though the inheriting files were introduced in successive commits.
                Assert.Equal(totalCommits, operatingRepo.GetVersionHeight());
                Assert.Equal(totalCommits, operatingRepo.GetVersionHeight("foo"));
                Assert.Equal(totalCommits, operatingRepo.GetVersionHeight(@"foo\bar"));

                // These either don't inherit, or inherit but reset versions, so the commits were reset.
                Assert.Equal(2, operatingRepo.GetVersionHeight("noInherit"));
                Assert.Equal(1, operatingRepo.GetVersionHeight("inheritWithVersion"));
            }
        }
    }
 public void Setup()
 {
     _versionFileKey = Guid.NewGuid().ToString();
     _versionFile = new VersionFile(_versionFileKey);
 }
    public void PrepareRelease_Master(
        // data for initial setup (version and release options configured in version.json)
        string initialVersion,
        string releaseOptionsBranchName,
        ReleaseVersionIncrement?releaseOptionsVersionIncrement,
        string releaseOptionsFirstUnstableTag,
        // arguments passed to PrepareRelease()
        string releaseUnstableTag,
        string nextVersion,
        ReleaseVersionIncrement?parameterVersionIncrement,
        // expected versions and branch name after running PrepareRelease()
        string expectedBranchName,
        string resultingReleaseVersion,
        string resultingMainVersion)
    {
        // create and configure repository
        this.InitializeSourceControl();
        this.Repo.Config.Set("user.name", this.Signer.Name, ConfigurationLevel.Local);
        this.Repo.Config.Set("user.email", this.Signer.Email, ConfigurationLevel.Local);

        // create version.json
        var initialVersionOptions = new VersionOptions()
        {
            Version = SemanticVersion.Parse(initialVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        this.WriteVersionFile(initialVersionOptions);

        var expectedVersionOptionsReleaseBranch = new VersionOptions()
        {
            Version = SemanticVersion.Parse(resultingReleaseVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        var expectedVersionOptionsCurrentBrach = new VersionOptions()
        {
            Version = SemanticVersion.Parse(resultingMainVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        var initialBranchName       = this.Repo.Head.FriendlyName;
        var tipBeforePrepareRelease = this.Repo.Head.Tip;

        // prepare release
        var releaseManager = new ReleaseManager();

        releaseManager.PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion == null ? null : Version.Parse(nextVersion)), parameterVersionIncrement);

        // check if a branch was created
        Assert.Contains(this.Repo.Branches, branch => branch.FriendlyName == expectedBranchName);

        // PrepareRelease should switch back to the initial branch
        Assert.Equal(initialBranchName, this.Repo.Head.FriendlyName);

        // check if release branch contains a new commit
        // parent of new commit must be the commit before preparing the release
        var releaseBranch = this.Repo.Branches[expectedBranchName];

        {
            // If the original branch had no -prerelease tag, the release branch has no commit to author.
            if (string.IsNullOrEmpty(initialVersionOptions.Version.Prerelease))
            {
                Assert.Equal(releaseBranch.Tip.Id, tipBeforePrepareRelease.Id);
            }
            else
            {
                Assert.NotEqual(releaseBranch.Tip.Id, tipBeforePrepareRelease.Id);
                Assert.Equal(releaseBranch.Tip.Parents.Single().Id, tipBeforePrepareRelease.Id);
            }
        }

        if (string.IsNullOrEmpty(initialVersionOptions.Version.Prerelease))
        {
            // Verify that one commit was authored.
            var incrementCommit = this.Repo.Head.Tip;
            Assert.Single(incrementCommit.Parents);
            Assert.Equal(tipBeforePrepareRelease.Id, incrementCommit.Parents.Single().Id);
        }
        else
        {
            // check if current branch contains new commits
            // - one commit that updates the version (parent must be the commit before preparing the release)
            // - one commit merging the release branch back to master and resolving the conflict
            var mergeCommit = this.Repo.Head.Tip;
            Assert.Equal(2, mergeCommit.Parents.Count());
            Assert.Equal(releaseBranch.Tip.Id, mergeCommit.Parents.Skip(1).First().Id);

            var updateVersionCommit = mergeCommit.Parents.First();
            Assert.Single(updateVersionCommit.Parents);
            Assert.Equal(tipBeforePrepareRelease.Id, updateVersionCommit.Parents.First().Id);
        }

        // check version on release branch
        {
            var releaseBranchVersion = VersionFile.GetVersion(releaseBranch.Tip);
            Assert.Equal(expectedVersionOptionsReleaseBranch, releaseBranchVersion);
        }

        // check version on master branch
        {
            var currentBranchVersion = VersionFile.GetVersion(this.Repo.Head.Tip);
            Assert.Equal(expectedVersionOptionsCurrentBrach, currentBranchVersion);
        }
    }
示例#32
0
        private static ExitCodes OnInstallCommand(string versionJsonRoot, string version, IReadOnlyList <string> sources)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return(ExitCodes.InvalidVersionSpec);
            }

            var options = new VersionOptions
            {
                Version = semver,
                PublicReleaseRefSpec = new string[]
                {
                    @"^refs/heads/master$",
                    @"^refs/heads/v\d+(?:\.\d+)?$",
                },
                CloudBuild = new VersionOptions.CloudBuildOptions
                {
                    BuildNumber = new VersionOptions.CloudBuildNumberOptions
                    {
                        Enabled = true,
                    },
                },
            };
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(versionJsonRoot);

            if (!Directory.Exists(searchPath))
            {
                Console.Error.WriteLine("\"{0}\" is not an existing directory.", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            var repository = GitExtensions.OpenGitRepo(searchPath);

            if (repository == null)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            if (string.IsNullOrEmpty(versionJsonRoot))
            {
                versionJsonRoot = repository.Info.WorkingDirectory;
            }

            var existingOptions = VersionFile.GetVersion(versionJsonRoot);

            if (existingOptions != null)
            {
                if (!string.IsNullOrEmpty(version))
                {
                    var setVersionExitCode = OnSetVersionCommand(versionJsonRoot, version);
                    if (setVersionExitCode != ExitCodes.OK)
                    {
                        return(setVersionExitCode);
                    }
                }
            }
            else
            {
                string versionJsonPath = VersionFile.SetVersion(versionJsonRoot, options);
                LibGit2Sharp.Commands.Stage(repository, versionJsonPath);
            }

            // Create/update the Directory.Build.props file in the directory of the version.json file to add the NB.GV package.
            string directoryBuildPropsPath = Path.Combine(versionJsonRoot, "Directory.Build.props");

            MSBuild.Project propsFile;
            if (File.Exists(directoryBuildPropsPath))
            {
                propsFile = new MSBuild.Project(directoryBuildPropsPath);
            }
            else
            {
                propsFile = new MSBuild.Project();
            }

            const string PackageReferenceItemType = "PackageReference";

            if (!propsFile.GetItemsByEvaluatedInclude(PackageId).Any(i => i.ItemType == "PackageReference"))
            {
                // Validate given sources
                foreach (var source in sources)
                {
                    if (!Uri.TryCreate(source, UriKind.Absolute, out var _))
                    {
                        Console.Error.WriteLine($"\"{source}\" is not a valid NuGet package source.");
                        return(ExitCodes.InvalidNuGetPackageSource);
                    }
                }

                string packageVersion = GetLatestPackageVersionAsync(PackageId, versionJsonRoot, sources).GetAwaiter().GetResult();
                if (string.IsNullOrEmpty(packageVersion))
                {
                    string verifyPhrase = sources.Any()
                        ? "Please verify the given 'source' option(s)."
                        : "Please verify the package sources in the NuGet.Config files.";
                    Console.Error.WriteLine($"Latest stable version of the {PackageId} package could not be determined. " + verifyPhrase);
                    return(ExitCodes.PackageIdNotFound);
                }

                propsFile.AddItem(
                    PackageReferenceItemType,
                    PackageId,
                    new Dictionary <string, string>
                {
                    { "Version", packageVersion },
                    { "PrivateAssets", "all" },
                });

                propsFile.Save(directoryBuildPropsPath);
            }

            LibGit2Sharp.Commands.Stage(repository, directoryBuildPropsPath);

            return(ExitCodes.OK);
        }