'Calculate cyclomatic complexity from file in different programming language via script

I am working on writing a script that outputs information about my written source code. So far, I am analysing the code with Python scripts that I have written. There is a Test.cs class which is used for this analysis.
Now I want to calculate the cyclomatic complexity from Test.cs.

Currently I am working on Visual Studio Code. I am aware that Visual Studio offers such a functionality and there are also packages that I can use for this.

However, I wanted to find out whether it is possible

  • a.) to write a Python script which can analyse my Test.cs class or
  • b.) to create a C# project to analyse the corresponding Test.cs class and if so, how can I pass the value for my script?

Because I would like to output and evaluate this value separately for the user.


Also I found this interesting documentation:

https://docs.microsoft.com/en-us/visualstudio/code-quality/how-to-generate-code-metrics-data?view=vs-2022#metricsexe

But here it is not clear to me how I could build and call up the Metrics.exe accordingly.


Or are there other approaches I could pursue?

I look forward to your feedback.



Solution 1:[1]

The easiest method is probably to call and parse the output of Metrics.exe.

If you don't provide /out, it will print to stdout, so you can capture it in Python.

I don't use Windows, so I can't test this, but something along the lines of this should work:

import subprocess
import xml.etree.ElementTree as ET

o = subprocess.run("Metrics.exe", "/project:ConsoleApp20.csproj", capture_output=True, check=True, text=True)
root = ET.fromstring(o.stdout)
print(root)

From there, just select the metrics you're looking for.

Solution 2:[2]

You need to stopPropagation for the event when element three is clicked so that it doesn't bubble up to the parent (box) element.

document.getElementById('box').addEventListener('click', () => 
  alert('triggered')
);

document.getElementById('box_child_three').addEventListener('click', e => 
  e.stopPropagation()
);
<div id="box">
  <div id="box_child_one">one</div>
  <div id="box_child_two">two</div>
  <div id="box_child_three">three</div>
</div>

Solution 3:[3]

<div id="box">
    <div id="box_child_one" trigger></div>
    <div id="box_child_two" trigger></div>
    <div id="box_child_three"></div>
</div>

<script>
document.querySelector('#box').onclick = function(e){
  if(e.target.hasAttribute('trigger')){
    alert('event fired')
  }
}
</script>

I'd go for this. As you are now no longer relying on an id to carry this out making it more re-usable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AlexApps99
Solution 2 Tom
Solution 3 anotherRandomGuy