private HashSet <string> AnalyzeToolDriver(ToolComponent toolComponent, string toolDriverPointer)
        {
            var rules = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (toolComponent.Rules != null && toolComponent.Rules.Count != 0)
            {
                string rulesPointer = toolDriverPointer.AtProperty(SarifPropertyName.Rules);

                for (int i = 0; i < toolComponent.Rules.Count; i++)
                {
                    AnalyzeReportingDescriptor(toolComponent.Rules[i], rulesPointer.AtIndex(i));
                    rules.Add(toolComponent.Rules[i].Id);
                }
            }
            else
            {
                // '{0}' does not provide a 'rules' property. 'rules' contain information that helps
                // users understand why each rule fires and what the user can do to fix it.
                LogResult(
                    toolDriverPointer,
                    nameof(RuleResources.SARIF2012_ProvideRuleProperties_Note_ProvideMetadataForAllViolatedRules_Text));
            }

            return(rules);
        }
Exemple #2
0
        public override void Process(Entity entity)
        {
            HandComponent     handComponent     = entity.GetComponent <HandComponent>();
            PositionComponent positionComponent = entity.GetComponent <PositionComponent>();

            Vector2 target = handComponent.TargetPosition;

            if (handComponent.HeldTool != null)
            {
                ToolComponent toolComponent = handComponent.HeldTool.GetComponent <ToolComponent>();
                target += toolComponent.PositionFunction(handComponent.Timer);
            }

            Vector2 difference = target - positionComponent.Position;

            positionComponent.Position += difference * 10f * (float)DeltaTime.TotalSeconds;

            if (positionComponent.Depth > handComponent.TargetDepth)
            {
                positionComponent.Depth -= 200f * (float)DeltaTime.TotalSeconds;
                positionComponent.Depth  = Math.Max(positionComponent.Depth, handComponent.TargetDepth);
            }
            else if (positionComponent.Depth < handComponent.TargetDepth)
            {
                positionComponent.Depth += 300f * (float)DeltaTime.TotalSeconds;
                positionComponent.Depth  = Math.Min(positionComponent.Depth, handComponent.TargetDepth);
            }
        }
Exemple #3
0
    public override bool Perform(GameObject agent, BlackBoard bb)
    {
        if (startTime == 0)
        {
            startTime = Time.time;
        }

        if (Time.time - startTime > miningDuration)
        {
            targetWolf.WolfNum--;
            // finished hunt
            BackpackComponent backpack = (BackpackComponent)agent.GetComponent(typeof(BackpackComponent));
            backpack.numMeat += 3;
            finishHunt        = true;

            if (backpack.tool == null)
            {
                ToolComponent tool = backpack.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
                tool.use(0.5f);
                if (tool.destroyed())
                {
                    Destroy(backpack.tool);
                    backpack.tool = null;
                }
            }
        }
        return(true);
    }
Exemple #4
0
    /// <summary>
    /// 执行
    /// 如果操作成功执行则返回True,否则返回false,
    /// 如果发生了什么事,它就再也无法执行了。 在这种情况下
    /// 行动队列应清除,无法达到目标。</summary>
    /// <param name="agent"></param>
    /// <param name="bb"></param>
    /// <returns></returns>
    /// <exception cref="System.NotImplementedException"></exception>
    public override bool Perform(GameObject agent, BlackBoard bb)
    {
        if (startTime == 0)
        {
            startTime = Time.time;
        }

        if (Time.time - startTime > workDuration)
        {
            //
            Backpack backpack = (Backpack)bb.GetData("backpack");
            //增加背包中的数量
            backpack.stoneNum += 5;
            //完成
            isComplete = true;
            ToolComponent tool = backpack.tool.GetComponent <ToolComponent>();
            //减少工具耐久度
            tool.use(0.34f);
            //耐久度小于等于0销毁当前工具
            if (tool.destroyed())
            {
                Destroy(backpack.tool);
                backpack.tool = null;
            }
        }
        return(true);
    }
    public override bool perform(GameObject agent)
    {
        if (startTime == 0)
        {
            startTime = Time.time;
        }

        if (Time.time - startTime > workDuration)
        {
            // finished chopping
            BackpackComponent backpack = (BackpackComponent)agent.GetComponent(typeof(BackpackComponent));
            backpack.numFirewood += 5;
            backpack.numLogs      = 0;
            backpack.numFood--;
            chopped = true;
            ToolComponent tool = backpack.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
            tool.use(0.34f);
            if (tool.destroyed())
            {
                Destroy(backpack.tool);
                backpack.tool = null;
            }
        }
        return(true);
    }
 public void DegradeTool(ToolComponent tool)
 {
     tool.use(toolDegrade);
     if (tool.destroyed())
     {
         Destroy(inventory.tool);
         inventory.tool = null;
     }
 }
 private void AnalyzeToolDriver(ToolComponent toolComponent, string toolDriverPointer)
 {
     if (toolComponent.Rules != null)
     {
         string rulesPointer = toolDriverPointer.AtProperty(SarifPropertyName.Rules);
         for (int i = 0; i < toolComponent.Rules.Count; i++)
         {
             AnalyzeReportingDescriptor(toolComponent.Rules[i], rulesPointer.AtIndex(i));
         }
     }
 }
Exemple #8
0
    void OnThrow(InputValue inputValue)
    {
        throwing = inputValue.Get <float>() > 0.5;

        if (throwing)
        {
            if (!pickedUpTool && touchingTool && !touchingTool.pickedUpBy)
            {
                pickedUpTool            = touchingTool;
                touchingTool.pickedUpBy = this;
                repairSound             = pickedUpTool.GetComponent <AudioSource>();

                var hand = transform.Find("m_mechanic/Armature/Body/right Shoulder/right Shoulder.001/right Hand 1");
                pickedUpTool.gameObject.transform.parent = hand;
                var rb = pickedUpTool.gameObject.GetComponent <Rigidbody>();
                rb.isKinematic      = true;
                rb.detectCollisions = false;
                pickedUpTool.gameObject.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
                pickedUpTool.gameObject.transform.localRotation = new Quaternion();

                pickingUp = true;
            }
            else
            {
                throwStrength = 0.0f;

                pickingUp = false;
            }
        }
        else
        {
            if (pickedUpTool && !pickingUp)
            {
                var moveDir = GetComponent <PlayerMovement>().getMoveDir();
                if (moveDir.magnitude < 1e-5)
                {
                    moveDir = transform.rotation * Vector3.forward;
                }
                var throwDirection = new Vector3(moveDir.x, throwYDir, moveDir.z);
                var strength       = Mathf.Lerp(minThrowStrength, 1.0f, throwStrength);

                pickedUpTool.gameObject.transform.parent = null;
                var rb = pickedUpTool.gameObject.GetComponent <Rigidbody>();
                rb.isKinematic      = false;
                rb.detectCollisions = true;
                rb.velocity         = strength * throwVelocity * throwDirection;
                Physics.IgnoreCollision(GetComponent <Collider>(), pickedUpTool.GetComponent <Collider>(), true);
                ignoredTools.Add(pickedUpTool.GetComponent <Collider>());
                pickedUpTool.pickedUpBy = null;
                pickedUpTool            = null;
            }
        }
    }
Exemple #9
0
        protected bool CallDamage(InteractUsingEventArgs eventArgs, ToolComponent tool)
        {
            if (eventArgs.Target.TryGetComponent <IDamageableComponent>(out var damageable))
            {
                damageable.ChangeDamage(tool.HasQuality(ToolQuality.Welding)
                        ? DamageType.Heat
                        : DamageType.Blunt,
                                        Damage, false, eventArgs.User);

                return(true);
            }

            return(false);
        }
 protected bool CallDamage(InteractUsingEventArgs eventArgs, ToolComponent tool)
 {
     if (eventArgs.Target.TryGetComponent <DamageableComponent>(out var damageable))
     {
         if (tool.HasQuality(ToolQuality.Welding))
         {
             damageable.TakeDamage(Shared.GameObjects.DamageType.Heat, Damage, eventArgs.Using, eventArgs.User);
         }
         else
         {
             damageable.TakeDamage(Shared.GameObjects.DamageType.Brute, Damage, eventArgs.Using, eventArgs.User);
         }
         return(true);
     }
     return(false);
 }
Exemple #11
0
        /// <summary>
        /// Builds a SARIF log object with the stored results
        /// </summary>
        /// <returns></returns>
        public SarifLog BuildSingleRunSarifLog()
        {
            Tool thisTool = new()
            {
                Driver = new ToolComponent
                {
                    Name         = AssemblyName,
                    Version      = Version,
                    Organization = Company,
                    Product      = "OSSGadget (https://github.com/Microsoft/OSSGadget)",
                }
            };

            SarifLog sarifLog = new()
            {
                Runs = new List <Run>()
                {
                    new Run()
                    {
                        Tool    = thisTool,
                        Results = sarifResults
                    }
                },
                Version = currentSarifVersion
            };

            return(sarifLog);
        }

        /// <summary>
        /// Gets the string representation of the sarif
        /// </summary>
        /// <returns></returns>
        public string GetOutput()
        {
            SarifLog completedSarif = BuildSingleRunSarifLog();

            using MemoryStream ms = new();
            StreamWriter sw = new(ms, System.Text.Encoding.UTF8, -1, true);
            StreamReader sr = new(ms);

            completedSarif.Save(sw);
            ms.Position = 0;

            return(sr.ReadToEnd());
        }
Exemple #12
0
    void OnTriggerExit(Collider other)
    {
        var tool = other.GetComponent <ToolComponent>();

        if (tool && touchingTool == tool)
        {
            touchingTool = null;
        }

        if (other.transform.parent)
        {
            var machine = other.transform.parent.GetComponent <MachineComponent>();
            if (machine && touchingMachine == machine)
            {
                touchingMachine = null;
            }
        }
    }
Exemple #13
0
    void OnTriggerEnter(Collider other)
    {
        var tool = other.GetComponent <ToolComponent>();

        if (tool)
        {
            touchingTool = tool;
        }

        if (other.transform.parent)
        {
            var machine = other.transform.parent.GetComponent <MachineComponent>();
            if (machine)
            {
                touchingMachine = machine;
            }
        }
    }
Exemple #14
0
        internal Tool CreateTool(ToolVersionOne v1Tool)
        {
            Tool tool = null;

            if (v1Tool != null)
            {
                // The SARIF v1 spec does not specify a format for tool.fileVersion (although on the
                // Windows platform, the spec anticipated that it would be of the form n.n.n.n where
                // each n is one or more decimal digits).
                //
                // The SARIF v2 spec is more prescriptive: it defines a property toolComponent.dottedQuadFileVersion
                // with exactly that format. So if the v1 file contained a tool.fileVersion in any other
                // format, the best we can do is put it in the property bag.
                string dottedQuadFileVersion = null;

                if (v1Tool.FileVersion != null &&
                    s_dottedQuadFileVersionRegex.IsMatch(v1Tool.FileVersion))
                {
                    dottedQuadFileVersion = v1Tool.FileVersion;
                }

                var driver = new ToolComponent
                {
                    DottedQuadFileVersion = dottedQuadFileVersion,
                    FullName        = v1Tool.FullName,
                    Name            = v1Tool.Name,
                    Properties      = v1Tool.Properties,
                    SemanticVersion = v1Tool.SemanticVersion,
                    Version         = v1Tool.Version
                };

                if (dottedQuadFileVersion == null && v1Tool.FileVersion != null)
                {
                    driver.SetProperty("sarifv1/toolFileVersion", v1Tool.FileVersion);
                }

                tool = new Tool
                {
                    Driver = driver
                };
            }

            return(tool);
        }
Exemple #15
0
    public override bool perform(GameObject agent)
    {
        // check inventory first
        if (inventory.numLogs <= 0)
        {
            return(false);
        }

        if (tool == null)
        {
            tool = inventory.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
        }

        if (startTime == 0)
        {
            startTime = Time.time;
            inventory.DetermineMood();
        }

        // run animation while action continues
        if (!chopped)
        {
            animator.SetTrigger("cut");
        }

        if (Time.time - startTime > workDuration)
        {
            // finished chopping
            chopped = true;
            // reset animation trigger
            animator.ResetTrigger("cut");
            // update stats
            inventory.hydration -= inventory.MoodModifier(hydrationConsumed);
            inventory.energy    -= inventory.MoodModifier(energyConsumed);
            //inventory.numLogs -= WorkMoodActionsConsume(logsConsumed);
            inventory.numLogs -= inventory.MoodModifier(logsConsumed);
            //inventory.numFirewood += WorkMoodActionsCreate(firewoodCreated);
            inventory.numFirewood += inventory.MoodModifier(firewoodCreated);
            // tool degrades as used
            DegradeTool(tool);
        }
        return(true);
    }
        private void Visit(ToolComponent toolComponent, string toolComponentPointer)
        {
            Analyze(toolComponent, toolComponentPointer);

            if (toolComponent.AssociatedComponent != null)
            {
                Visit(toolComponent.AssociatedComponent, toolComponentPointer.AtProperty(SarifPropertyName.AssociatedComponent));
            }

            if (toolComponent.Notifications != null)
            {
                Context.CurrentReportingDescriptorKind = SarifValidationContext.ReportingDescriptorKind.Notification;
                try
                {
                    string notificationsPointer = toolComponentPointer.AtProperty(SarifPropertyName.Notifications);
                    for (int i = 0; i < toolComponent.Notifications.Count; ++i)
                    {
                        Visit(toolComponent.Notifications[i], notificationsPointer.AtIndex(i));
                    }
                }
                finally
                {
                    Context.CurrentReportingDescriptorKind = SarifValidationContext.ReportingDescriptorKind.None;
                }
            }

            if (toolComponent.Rules != null)
            {
                Context.CurrentReportingDescriptorKind = SarifValidationContext.ReportingDescriptorKind.Rule;
                try
                {
                    string rulesPointer = toolComponentPointer.AtProperty(SarifPropertyName.Rules);
                    for (int i = 0; i < toolComponent.Rules.Count; ++i)
                    {
                        Visit(toolComponent.Rules[i], rulesPointer.AtIndex(i));
                    }
                }
                finally
                {
                    Context.CurrentReportingDescriptorKind = SarifValidationContext.ReportingDescriptorKind.None;
                }
            }
        }
        private void AnalyzeToolDriver(ToolComponent toolComponent, string toolDriverPointer)
        {
            if (!string.IsNullOrEmpty(toolComponent.Name))
            {
                const int MaxWords  = 3;
                int       wordCount = toolComponent.Name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;
                if (wordCount > MaxWords)
                {
                    string driverNamePointer = toolDriverPointer.AtProperty(SarifPropertyName.Name);

                    // {0}: The tool name '{1}' contains {2} words, which is more than the recommended
                    // maximum of {3} words. A short tool name is easy to remember and fits into a
                    // narrow column when displaying a list of results. If you need to provide more
                    // information about your tool, use the 'fullName' property.
                    LogResult(
                        driverNamePointer,
                        nameof(RuleResources.SARIF2005_ProvideToolProperties_Warning_ProvideConciseToolName_Text),
                        toolComponent.Name,
                        wordCount.ToString(),
                        MaxWords.ToString());
                }
            }

            if (string.IsNullOrWhiteSpace(toolComponent.Version) && string.IsNullOrWhiteSpace(toolComponent.SemanticVersion))
            {
                // {0}: The tool '{1}' provides neither a 'version' property nor a 'semanticVersion'
                // property. Providing a version enables the log file consumer to determine whether
                // the file was produced by an up to date version, and to avoid accidentally comparing
                // log files produced by different tool versions.
                LogResult(
                    toolDriverPointer,
                    nameof(RuleResources.SARIF2005_ProvideToolProperties_Warning_ProvideToolVersion_Text),
                    toolComponent.Name);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toolComponent.Version))
                {
                    AnalyzeVersion(toolComponent.Name, toolComponent.Version, toolDriverPointer.AtProperty(SarifPropertyName.Version));
                }
            }
        }
Exemple #18
0
        static void AddReferenceToProject(IProject project, AssemblyName referenceName)
        {
            LoggingService.Warn("Adding reference to project: " + referenceName.FullName);
            ReferenceProjectItem reference     = new ReferenceProjectItem(project, "Reference");
            ToolComponent        toolComponent = ToolboxProvider.ComponentLibraryLoader.GetToolComponent(referenceName.FullName);

            if (toolComponent == null || toolComponent.HintPath == null)
            {
                reference.Include = referenceName.FullName;
                LoggingService.Debug("Added GAC reference to project: " + reference.Include);
            }
            else
            {
                reference.Include  = referenceName.FullName;
                reference.HintPath = FileUtility.GetRelativePath(project.Directory, toolComponent.FileName);
                LoggingService.Debug("Added assembly reference to project: " + reference.Include);
            }
            ProjectService.AddProjectItem(project, reference);
            project.Save();
        }
        private ToolComponent CreateToolComponent(string name, int rulesCount, FailureLevel failureLevel)
        {
            ToolComponent toolComponent = new ToolComponent();

            toolComponent.Name  = name;
            toolComponent.Rules = new ReportingDescriptor[rulesCount];
            for (int i = 0; i < rulesCount; i++)
            {
                toolComponent.Rules[i] = new ReportingDescriptor
                {
                    Id = $"TEST{i}",
                    DefaultConfiguration = new ReportingConfiguration
                    {
                        Level = failureLevel
                    }
                };
            }

            return(toolComponent);
        }
Exemple #20
0
        private void Visit(ToolComponent toolComponent, string toolComponentPointer)
        {
            Analyze(toolComponent, toolComponentPointer);

            if (toolComponent.Notifications != null)
            {
                string notificationsPointer = toolComponentPointer.AtProperty(SarifPropertyName.Notifications);
                for (int i = 0; i < toolComponent.Notifications.Count; ++i)
                {
                    Visit(toolComponent.Notifications[i], notificationsPointer.AtIndex(i));
                }
            }

            if (toolComponent.Rules != null)
            {
                string rulesPointer = toolComponentPointer.AtProperty(SarifPropertyName.Rules);
                for (int i = 0; i < toolComponent.Rules.Count; ++i)
                {
                    Visit(toolComponent.Rules[i], rulesPointer.AtIndex(i));
                }
            }
        }
    public override bool perform(GameObject agent)
    {
        if (tool == null)
        {
            tool = inventory.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
        }

        if (startTime == 0 && closest.engaged == false)
        {
            closest.engaged = true;
            startTime       = Time.time;
            inventory.DetermineMood();
        }
        else if (startTime == 0 && closest.engaged == true)
        {
            return(false);
        }

        if (!mined)
        {
            animator.SetTrigger("mine");
        }

        if (Time.time - startTime > workDuration)
        {
            // finished mining
            mined           = true;
            closest.engaged = false;
            animator.ResetTrigger("mine");
            inventory.hydration  -= inventory.MoodModifier(hydrationConsumed);
            inventory.energy     -= inventory.MoodModifier(energyConsumed);
            inventory.numOre     += inventory.MoodModifier(oreCreated);
            closest.rockResource -= 1;

            DegradeTool(tool);
        }
        return(true);
    }
    public override bool perform(GameObject agent)
    {
        if (tool == null)
        {
            tool = inventory.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
        }

        if (startTime == 0 && closest.engaged == false)
        {
            closest.engaged = true;
            startTime       = Time.time;
            inventory.DetermineMood();
        }
        else if (startTime == 0 && closest.engaged == true)
        {
            return(false);
        }

        if (!farmed)
        {
            animator.SetTrigger("forge");
        }                                                      // forge animation resembles farming

        if (Time.time - startTime > farmingDuration)
        {
            // finished farming
            farmed          = true;
            closest.engaged = false;
            animator.ResetTrigger("forge");
            inventory.hydration  -= inventory.MoodModifier(hydrationConsumed);
            inventory.energy     -= inventory.MoodModifier(energyConsumed);
            inventory.numRawFood += inventory.MoodModifier(rawfoodCreated);
            closest.farmResource -= 1;

            DegradeTool(tool);
        }
        return(true);
    }
    public override bool perform(GameObject agent)
    {
        if (startTime == 0)
        {
            startTime = Time.time;
        }

        if (Time.time - startTime > miningDuration)
        {
            // finished mining
            BackpackComponent backpack = (BackpackComponent)agent.GetComponent(typeof(BackpackComponent));
            backpack.numOre += 2;
            mined            = true;
            ToolComponent tool = backpack.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
            tool.use(0.5f);
            if (tool.destroyed())
            {
                Destroy(backpack.tool);
                backpack.tool = null;
            }
        }
        return(true);
    }
Exemple #24
0
    public override bool Perform(GameObject agent)
    {
        if (_startTime == 0)
        {
            _startTime = Time.time;
        }

        if ((Time.time - _startTime) > workDuration)
        {
            // finished chopping
            BackpackComponent backpack = agent.GetComponent <BackpackComponent>();
            backpack.numLogs += 1;
            _chopped          = true;
            ToolComponent tool = backpack.tool.GetComponent <ToolComponent>();
            tool.Use(0.34f);
            if (tool.IsDestroyed())
            {
                Destroy(backpack.tool);
                backpack.tool = null;
            }
        }
        return(true);
    }
Exemple #25
0
    public override bool perform(GameObject agent)
    {
        if (inventory.numRawFood <= 0)
        {
            return(false);
        }

        if (tool == null)
        {
            tool = inventory.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
        }

        if (startTime == 0)
        {
            startTime = Time.time;
            inventory.DetermineMood();
        }

        if (!cooked)
        {
            animator.SetTrigger("cut");
        }

        if (Time.time - startTime > workDuration)
        {
            // finished cooking
            cooked = true;
            animator.ResetTrigger("cut");
            inventory.hydration -= inventory.MoodModifier(hydrationConsumed);
            //stats.energy -= energyConsumed; // unused as cook eats while working
            inventory.numRawFood  -= inventory.MoodModifier(rawfoodConsumed);
            inventory.numFirewood -= inventory.MoodModifier(firewoodConsumed);

            DegradeTool(tool);
        }
        return(true);
    }
Exemple #26
0
 protected override void Analyze(ToolComponent toolComponent, string toolComponentPointer)
 {
     AnalyzeUri(toolComponent.DownloadUri, toolComponentPointer.AtProperty(SarifPropertyName.DownloadUri));
 }
Exemple #27
0
        protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter)
        {
            string v2LogText = GetResourceText(inputResourceName);

            string inputLogDirectory = this.OutputFolderPath;
            string inputLogFileName  = Path.GetFileName(inputResourceName);
            string inputLogFilePath  = Path.Combine(this.OutputFolderPath, inputLogFileName);

            string actualLogFilePath = Guid.NewGuid().ToString();

            string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1];

            // All SARIF rule prefixes require update to current release.
            // All rules with JSON prefix are low level syntax/deserialization checks.
            // We can't transform these test inputs as that operation fixes up erros in the file.
            bool updateInputsToCurrentSarif = ruleUnderTest.StartsWith("SARIF") ? true : false;

            var validateOptions = new ValidateOptions
            {
                SarifOutputVersion   = SarifVersion.Current,
                TargetFileSpecifiers = new[] { inputLogFilePath },
                OutputFilePath       = actualLogFilePath,
                Quiet = true,
                UpdateInputsToCurrentSarif = updateInputsToCurrentSarif,
                PrettyPrint = true,
                Optimize    = true
            };

            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true);
            mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]);
            mockFileSystem.Setup(x => x.GetFilesInDirectory(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath });
            mockFileSystem.Setup(x => x.ReadAllText(inputLogFilePath)).Returns(v2LogText);
            mockFileSystem.Setup(x => x.ReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path));
            mockFileSystem.Setup(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>()));

            var validateCommand = new ValidateCommand(mockFileSystem.Object);

            int returnCode = validateCommand.Run(validateOptions);

            if (validateCommand.ExecutionException != null)
            {
                Console.WriteLine(validateCommand.ExecutionException.ToString());
            }

            returnCode.Should().Be(0);

            SarifLog actualLog = JsonConvert.DeserializeObject <SarifLog>(File.ReadAllText(actualLogFilePath));

            // First, we'll strip any validation results that don't originate with the rule under test
            var newResults = new List <Result>();

            foreach (Result result in actualLog.Runs[0].Results)
            {
                if (result.RuleId == ruleUnderTest)
                {
                    newResults.Add(result);
                }
            }

            // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data.
            var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties);

            removeTimestampsVisitor.Visit(actualLog);

            // Finally, we'll elide non-deterministic build root details
            var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory));

            rebaseUrisVisitor.Visit(actualLog);

            // There are differences in log file output depending on whether we are invoking xunit
            // from within Visual Studio or at the command-line via xunit.exe. We elide these differences.

            ToolComponent driver = actualLog.Runs[0].Tool.Driver;

            driver.Name                  = "SARIF Functional Testing";
            driver.Version               = null;
            driver.FullName              = null;
            driver.SemanticVersion       = null;
            driver.DottedQuadFileVersion = null;
            driver.Product               = null;
            driver.Organization          = null;
            driver.Properties?.Clear();
            actualLog.Runs[0].OriginalUriBaseIds = null;

            return(JsonConvert.SerializeObject(actualLog, Formatting.Indented));
        }
Exemple #28
0
        protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter)
        {
            string v2LogText = GetResourceText(inputResourceName);

            string inputLogDirectory = this.OutputFolderPath;
            string inputLogFileName  = Path.GetFileName(inputResourceName);
            string inputLogFilePath  = Path.Combine(this.OutputFolderPath, inputLogFileName);

            string actualLogFilePath = Guid.NewGuid().ToString();

            string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1];

            // All SARIF rule prefixes require update to current release.
            // All rules with JSON prefix are low level syntax/deserialization checks.
            // We can't transform these test inputs as that operation fixes up errors in the file.
            // Also, don't transform the tests for SARIF1011 or SARIF2008, because these rules
            // examine the actual contents of the $schema property.

            string[] shouldNotTransform = { "SARIF1011", "SARIF2008" };

            bool updateInputsToCurrentSarif = IsSarifRule(ruleUnderTest) &&
                                              !shouldNotTransform.Contains(ruleUnderTest);

            var validateOptions = new ValidateOptions
            {
                SarifOutputVersion   = SarifVersion.Current,
                TargetFileSpecifiers = new[] { inputLogFilePath },
                OutputFilePath       = actualLogFilePath,
                Quiet = true,
                UpdateInputsToCurrentSarif = updateInputsToCurrentSarif,
                PrettyPrint = true,
                Optimize    = true,
                Kind        = new List <ResultKind> {
                    ResultKind.Fail
                },
                Level = new List <FailureLevel> {
                    FailureLevel.Error, FailureLevel.Warning, FailureLevel.Note, FailureLevel.None
                },
            };

            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true);
            mockFileSystem.Setup(x => x.DirectoryGetDirectories(It.IsAny <string>())).Returns(new string[0]);
            mockFileSystem.Setup(x => x.DirectoryGetFiles(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath });
            mockFileSystem.Setup(x => x.FileReadAllText(inputLogFilePath)).Returns(v2LogText);
            mockFileSystem.Setup(x => x.FileReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path));
            mockFileSystem.Setup(x => x.FileWriteAllText(It.IsAny <string>(), It.IsAny <string>()));

            // Some rules are disabled by default, so create a configuration file that explicitly
            // enables the rule under test.
            using (TempFile configFile = CreateTempConfigFile(ruleUnderTest, parameter))
            {
                validateOptions.ConfigurationFilePath = configFile.Name;
                mockFileSystem.Setup(x => x.FileExists(validateOptions.ConfigurationFilePath)).Returns(true);

                var validateCommand = new ValidateCommand(mockFileSystem.Object);

                int returnCode = validateCommand.Run(validateOptions);

                if (validateCommand.ExecutionException != null)
                {
                    Console.WriteLine(validateCommand.ExecutionException.ToString());
                }

                returnCode.Should().Be(0);
            }

            string   actualLogFileContents = File.ReadAllText(actualLogFilePath);
            SarifLog actualLog             = JsonConvert.DeserializeObject <SarifLog>(actualLogFileContents);
            Run      run = actualLog.Runs[0];

            // First, we'll strip any validation results that don't originate with the rule under test.
            // But leave the results that originate from JSchema! Also, be careful because output files
            // from "valid" test cases don't have any results.
            run.Results = run.Results
                          ?.Where(r => IsRelevant(r.RuleId, ruleUnderTest))
                          ?.ToList();

            // Next, remove any rule metadata for those rules. The output files from "valid" test
            // cases don't have any rules.
            run.Tool.Driver.Rules = run.Tool.Driver.Rules
                                    ?.Where(r => IsRelevant(r.Id, ruleUnderTest))
                                    ?.ToList();

            // Since there's only one rule in the metadata, the ruleIndex for all remaining results
            // must be 0.
            foreach (Result result in run.Results)
            {
                result.RuleIndex = 0;
            }

            // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data.
            var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties);

            removeTimestampsVisitor.Visit(actualLog);

            // Finally, we'll elide non-deterministic build root details
            var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory));

            rebaseUrisVisitor.Visit(actualLog);

            // There are differences in log file output depending on whether we are invoking xunit
            // from within Visual Studio or at the command-line via xunit.exe. We elide these differences.

            ToolComponent driver = actualLog.Runs[0].Tool.Driver;

            driver.Name                  = "SARIF Functional Testing";
            driver.Version               = null;
            driver.FullName              = null;
            driver.SemanticVersion       = null;
            driver.DottedQuadFileVersion = null;
            driver.Product               = null;
            driver.Organization          = null;
            driver.Properties?.Clear();
            actualLog.Runs[0].OriginalUriBaseIds = null;

            return(JsonConvert.SerializeObject(actualLog, Formatting.Indented));
        }
 protected virtual void Analyze(ToolComponent toolComponent, string toolComponentPointer)
 {
 }
        private void AnalyzeToolDriver(ToolComponent toolComponent, string toolDriverPointer)
        {
            if (!string.IsNullOrEmpty(toolComponent.Name))
            {
                const int MaxWords  = 3;
                int       wordCount = toolComponent.Name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;
                if (wordCount > MaxWords)
                {
                    string driverNamePointer = toolDriverPointer.AtProperty(SarifPropertyName.Name);

                    // {0}: The tool name '{1}' contains {2} words, which is more than the recommended
                    // maximum of {3} words. A short tool name is easy to remember and fits into a
                    // narrow column when displaying a list of results. If you need to provide more
                    // information about your tool, use the 'fullName' property.
                    LogResult(
                        driverNamePointer,
                        nameof(RuleResources.SARIF2005_ProvideToolProperties_Warning_ProvideConciseToolName_Text),
                        toolComponent.Name,
                        wordCount.ToString(),
                        MaxWords.ToString());
                }
            }

            bool informationUriRequired = this.Context.Policy.GetProperty(InformationUriRequired);

            if (informationUriRequired && toolComponent.InformationUri == null)
            {
                // {0}: The tool '{1}' does not provide 'informationUri'. This property helps the
                // developer responsible for addessing a result by providing a way to learn more
                // about the tool.
                LogResult(
                    toolDriverPointer,
                    nameof(RuleResources.SARIF2005_ProvideToolProperties_Warning_ProvideToolnformationUri_Text),
                    toolComponent.Name);
            }

            StringSet acceptableVersionProperties = this.Context.Policy.GetProperty(AcceptableVersionProperties);
            bool      toolDriverProvidesVersion   = false;

            toolDriverProvidesVersion |= acceptableVersionProperties.Contains(nameof(toolComponent.Version)) && !string.IsNullOrWhiteSpace(toolComponent.Version);
            toolDriverProvidesVersion |= acceptableVersionProperties.Contains(nameof(toolComponent.SemanticVersion)) && !string.IsNullOrWhiteSpace(toolComponent.SemanticVersion);
            toolDriverProvidesVersion |= acceptableVersionProperties.Contains(nameof(toolComponent.DottedQuadFileVersion)) && !string.IsNullOrWhiteSpace(toolComponent.DottedQuadFileVersion);

            if (!toolDriverProvidesVersion)
            {
                // {0}: The tool '{1}' does not provide any of the version-related properties {2}.
                // Providing version information enables the log file consumer to determine whether
                // the file was produced by an up to date version, and to avoid accidentally
                // comparing log files produced by different tool versions.
                LogResult(
                    toolDriverPointer,
                    nameof(RuleResources.SARIF2005_ProvideToolProperties_Warning_ProvideToolVersion_Text),
                    toolComponent.Name,
                    $"'{string.Join("', '", acceptableVersionProperties.Select(ToCamelCase))}'");
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toolComponent.Version))
                {
                    AnalyzeVersion(toolComponent.Name, toolComponent.Version, toolDriverPointer.AtProperty(SarifPropertyName.Version));
                }
            }
        }