├── .github
└── workflows
│ └── build.yml
├── .gitignore
├── LICENSE
├── PulumiCSharpAnalyzer.sln
├── README.md
├── build
├── Build.fsproj
├── Files.fs
├── Program.fs
└── Tools.fs
├── package
├── Package.csproj
└── tools
│ ├── install.ps1
│ └── uninstall.ps1
├── screenshots
├── error-missing-required-properties-function-invokes.png
├── error-missing-required-properties.png
├── resource-inside-apply.png
├── roslyn-settings.png
└── vscode-warnings.png
├── src
├── PulumiAnalyzer.cs
└── PulumiCSharpAnalyzer.csproj
└── tests
├── Tests.cs
├── Tests.csproj
└── Verifiers
├── CSharpAnalyzerVerifier`1+Test.cs
├── CSharpAnalyzerVerifier`1.cs
├── CSharpCodeFixVerifier`2+Test.cs
├── CSharpCodeFixVerifier`2.cs
├── CSharpCodeRefactoringVerifier`1+Test.cs
├── CSharpCodeRefactoringVerifier`1.cs
├── CSharpVerifierHelper.cs
├── VisualBasicAnalyzerVerifier`1+Test.cs
├── VisualBasicAnalyzerVerifier`1.cs
├── VisualBasicCodeFixVerifier`2+Test.cs
├── VisualBasicCodeFixVerifier`2.cs
├── VisualBasicCodeRefactoringVerifier`1+Test.cs
└── VisualBasicCodeRefactoringVerifier`1.cs
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: build and test
2 | on:
3 | push:
4 | pull_request:
5 | branches: [ master ]
6 | paths-ignore:
7 | - 'README.md'
8 | env:
9 | DOTNET_VERSION: '6.0.x'
10 | jobs:
11 | build-and-test:
12 | name: build-and-test-${{matrix.os}}
13 | runs-on: ${{ matrix.os }}
14 | strategy:
15 | matrix:
16 | os: [ubuntu-latest, windows-latest, macOS-latest]
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Setup .NET
20 | uses: actions/setup-dotnet@v1
21 | with:
22 | dotnet-version: ${{ env.DOTNET_VERSION }}
23 | - name: Build
24 | run: dotnet run --project ./build/Build.fsproj -- build
25 | - name: Test
26 | run: dotnet run --project ./build/Build.fsproj -- test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # Tye
66 | .tye/
67 |
68 | # ASP.NET Scaffolding
69 | ScaffoldingReadMe.txt
70 |
71 | # StyleCop
72 | StyleCopReport.xml
73 |
74 | # Files built by Visual Studio
75 | *_i.c
76 | *_p.c
77 | *_h.h
78 | *.ilk
79 | *.meta
80 | *.obj
81 | *.iobj
82 | *.pch
83 | *.pdb
84 | *.ipdb
85 | *.pgc
86 | *.pgd
87 | *.rsp
88 | *.sbr
89 | *.tlb
90 | *.tli
91 | *.tlh
92 | *.tmp
93 | *.tmp_proj
94 | *_wpftmp.csproj
95 | *.log
96 | *.vspscc
97 | *.vssscc
98 | .builds
99 | *.pidb
100 | *.svclog
101 | *.scc
102 |
103 | # Chutzpah Test files
104 | _Chutzpah*
105 |
106 | # Visual C++ cache files
107 | ipch/
108 | *.aps
109 | *.ncb
110 | *.opendb
111 | *.opensdf
112 | *.sdf
113 | *.cachefile
114 | *.VC.db
115 | *.VC.VC.opendb
116 |
117 | # Visual Studio profiler
118 | *.psess
119 | *.vsp
120 | *.vspx
121 | *.sap
122 |
123 | # Visual Studio Trace Files
124 | *.e2e
125 |
126 | # TFS 2012 Local Workspace
127 | $tf/
128 |
129 | # Guidance Automation Toolkit
130 | *.gpState
131 |
132 | # ReSharper is a .NET coding add-in
133 | _ReSharper*/
134 | *.[Rr]e[Ss]harper
135 | *.DotSettings.user
136 |
137 | # TeamCity is a build add-in
138 | _TeamCity*
139 |
140 | # DotCover is a Code Coverage Tool
141 | *.dotCover
142 |
143 | # AxoCover is a Code Coverage Tool
144 | .axoCover/*
145 | !.axoCover/settings.json
146 |
147 | # Coverlet is a free, cross platform Code Coverage Tool
148 | coverage*.json
149 | coverage*.xml
150 | coverage*.info
151 |
152 | # Visual Studio code coverage results
153 | *.coverage
154 | *.coveragexml
155 |
156 | # NCrunch
157 | _NCrunch_*
158 | .*crunch*.local.xml
159 | nCrunchTemp_*
160 |
161 | # MightyMoose
162 | *.mm.*
163 | AutoTest.Net/
164 |
165 | # Web workbench (sass)
166 | .sass-cache/
167 |
168 | # Installshield output folder
169 | [Ee]xpress/
170 |
171 | # DocProject is a documentation generator add-in
172 | DocProject/buildhelp/
173 | DocProject/Help/*.HxT
174 | DocProject/Help/*.HxC
175 | DocProject/Help/*.hhc
176 | DocProject/Help/*.hhk
177 | DocProject/Help/*.hhp
178 | DocProject/Help/Html2
179 | DocProject/Help/html
180 |
181 | # Click-Once directory
182 | publish/
183 |
184 | # Publish Web Output
185 | *.[Pp]ublish.xml
186 | *.azurePubxml
187 | # Note: Comment the next line if you want to checkin your web deploy settings,
188 | # but database connection strings (with potential passwords) will be unencrypted
189 | *.pubxml
190 | *.publishproj
191 |
192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
193 | # checkin your Azure Web App publish settings, but sensitive information contained
194 | # in these scripts will be unencrypted
195 | PublishScripts/
196 |
197 | # NuGet Packages
198 | *.nupkg
199 | # NuGet Symbol Packages
200 | *.snupkg
201 | # The packages folder can be ignored because of Package Restore
202 | **/[Pp]ackages/*
203 | # except build/, which is used as an MSBuild target.
204 | !**/[Pp]ackages/build/
205 | # Uncomment if necessary however generally it will be regenerated when needed
206 | #!**/[Pp]ackages/repositories.config
207 | # NuGet v3's project.json files produces more ignorable files
208 | *.nuget.props
209 | *.nuget.targets
210 |
211 | # Microsoft Azure Build Output
212 | csx/
213 | *.build.csdef
214 |
215 | # Microsoft Azure Emulator
216 | ecf/
217 | rcf/
218 |
219 | # Windows Store app package directories and files
220 | AppPackages/
221 | BundleArtifacts/
222 | Package.StoreAssociation.xml
223 | _pkginfo.txt
224 | *.appx
225 | *.appxbundle
226 | *.appxupload
227 |
228 | # Visual Studio cache files
229 | # files ending in .cache can be ignored
230 | *.[Cc]ache
231 | # but keep track of directories ending in .cache
232 | !?*.[Cc]ache/
233 |
234 | # Others
235 | ClientBin/
236 | ~$*
237 | *~
238 | *.dbmdl
239 | *.dbproj.schemaview
240 | *.jfm
241 | *.pfx
242 | *.publishsettings
243 | orleans.codegen.cs
244 |
245 | # Including strong name files can present a security risk
246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
247 | #*.snk
248 |
249 | # Since there are multiple workflows, uncomment next line to ignore bower_components
250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
251 | #bower_components/
252 |
253 | # RIA/Silverlight projects
254 | Generated_Code/
255 |
256 | # Backup & report files from converting an old project file
257 | # to a newer Visual Studio version. Backup files are not needed,
258 | # because we have git ;-)
259 | _UpgradeReport_Files/
260 | Backup*/
261 | UpgradeLog*.XML
262 | UpgradeLog*.htm
263 | ServiceFabricBackup/
264 | *.rptproj.bak
265 |
266 | # SQL Server files
267 | *.mdf
268 | *.ldf
269 | *.ndf
270 |
271 | # Business Intelligence projects
272 | *.rdl.data
273 | *.bim.layout
274 | *.bim_*.settings
275 | *.rptproj.rsuser
276 | *- [Bb]ackup.rdl
277 | *- [Bb]ackup ([0-9]).rdl
278 | *- [Bb]ackup ([0-9][0-9]).rdl
279 |
280 | # Microsoft Fakes
281 | FakesAssemblies/
282 |
283 | # GhostDoc plugin setting file
284 | *.GhostDoc.xml
285 |
286 | # Node.js Tools for Visual Studio
287 | .ntvs_analysis.dat
288 | node_modules/
289 |
290 | # Visual Studio 6 build log
291 | *.plg
292 |
293 | # Visual Studio 6 workspace options file
294 | *.opt
295 |
296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
297 | *.vbw
298 |
299 | # Visual Studio LightSwitch build output
300 | **/*.HTMLClient/GeneratedArtifacts
301 | **/*.DesktopClient/GeneratedArtifacts
302 | **/*.DesktopClient/ModelManifest.xml
303 | **/*.Server/GeneratedArtifacts
304 | **/*.Server/ModelManifest.xml
305 | _Pvt_Extensions
306 |
307 | # Paket dependency manager
308 | .paket/paket.exe
309 | paket-files/
310 |
311 | # FAKE - F# Make
312 | .fake/
313 |
314 | # CodeRush personal settings
315 | .cr/personal
316 |
317 | # Python Tools for Visual Studio (PTVS)
318 | __pycache__/
319 | *.pyc
320 |
321 | # Cake - Uncomment if you are using it
322 | # tools/**
323 | # !tools/packages.config
324 |
325 | # Tabs Studio
326 | *.tss
327 |
328 | # Telerik's JustMock configuration file
329 | *.jmconfig
330 |
331 | # BizTalk build output
332 | *.btp.cs
333 | *.btm.cs
334 | *.odx.cs
335 | *.xsd.cs
336 |
337 | # OpenCover UI analysis results
338 | OpenCover/
339 |
340 | # Azure Stream Analytics local run output
341 | ASALocalRun/
342 |
343 | # MSBuild Binary and Structured Log
344 | *.binlog
345 |
346 | # NVidia Nsight GPU debugger configuration file
347 | *.nvuser
348 |
349 | # MFractors (Xamarin productivity tool) working folder
350 | .mfractor/
351 |
352 | # Local History for Visual Studio
353 | .localhistory/
354 |
355 | # BeatPulse healthcheck temp database
356 | healthchecksdb
357 |
358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
359 | MigrationBackup/
360 |
361 | # Ionide (cross platform F# VS Code tools) working folder
362 | .ionide/
363 |
364 | # Fody - auto-generated XML schema
365 | FodyWeavers.xsd
366 |
367 | ##
368 | ## Visual studio for Mac
369 | ##
370 |
371 |
372 | # globs
373 | Makefile.in
374 | *.userprefs
375 | *.usertasks
376 | config.make
377 | config.status
378 | aclocal.m4
379 | install-sh
380 | autom4te.cache/
381 | *.tar.gz
382 | tarballs/
383 | test-results/
384 |
385 | # Mac bundle stuff
386 | *.dmg
387 | *.app
388 |
389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
390 | # General
391 | .DS_Store
392 | .AppleDouble
393 | .LSOverride
394 |
395 | # Icon must end with two \r
396 | Icon
397 |
398 |
399 | # Thumbnails
400 | ._*
401 |
402 | # Files that might appear in the root of a volume
403 | .DocumentRevisions-V100
404 | .fseventsd
405 | .Spotlight-V100
406 | .TemporaryItems
407 | .Trashes
408 | .VolumeIcon.icns
409 | .com.apple.timemachine.donotpresent
410 |
411 | # Directories potentially created on remote AFP share
412 | .AppleDB
413 | .AppleDesktop
414 | Network Trash Folder
415 | Temporary Items
416 | .apdisk
417 |
418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
419 | # Windows thumbnail cache files
420 | Thumbs.db
421 | ehthumbs.db
422 | ehthumbs_vista.db
423 |
424 | # Dump file
425 | *.stackdump
426 |
427 | # Folder config file
428 | [Dd]esktop.ini
429 |
430 | # Recycle Bin used on file shares
431 | $RECYCLE.BIN/
432 |
433 | # Windows Installer files
434 | *.cab
435 | *.msi
436 | *.msix
437 | *.msm
438 | *.msp
439 |
440 | # Windows shortcuts
441 | *.lnk
442 |
443 | # JetBrains Rider
444 | .idea/
445 | *.sln.iml
446 |
447 | ##
448 | ## Visual Studio Code
449 | ##
450 | .vscode/*
451 | !.vscode/settings.json
452 | !.vscode/tasks.json
453 | !.vscode/launch.json
454 | !.vscode/extensions.json
455 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Zaid Ajaj
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/PulumiCSharpAnalyzer.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30114.105
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PulumiCSharpAnalyzer", "src\PulumiCSharpAnalyzer.csproj", "{E2847277-FBDF-453A-942A-1FC1234FB341}"
7 | EndProject
8 | Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Build", "build\Build.fsproj", "{94224880-8D59-48A3-8EB8-D12880130EF5}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Package", "package\Package.csproj", "{F932CF3A-2BF4-4235-9977-429775F20F43}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "tests\Tests.csproj", "{07ACF98D-F63C-4D6B-8778-F21BD61E3844}"
13 | EndProject
14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{339717ED-03C2-468A-B76B-08B5BD2FE9C8}"
15 | ProjectSection(SolutionItems) = preProject
16 | README.md = README.md
17 | EndProjectSection
18 | EndProject
19 | Global
20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
21 | Debug|Any CPU = Debug|Any CPU
22 | Release|Any CPU = Release|Any CPU
23 | EndGlobalSection
24 | GlobalSection(SolutionProperties) = preSolution
25 | HideSolutionNode = FALSE
26 | EndGlobalSection
27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
28 | {E2847277-FBDF-453A-942A-1FC1234FB341}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {E2847277-FBDF-453A-942A-1FC1234FB341}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {E2847277-FBDF-453A-942A-1FC1234FB341}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {E2847277-FBDF-453A-942A-1FC1234FB341}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {94224880-8D59-48A3-8EB8-D12880130EF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {94224880-8D59-48A3-8EB8-D12880130EF5}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {94224880-8D59-48A3-8EB8-D12880130EF5}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {94224880-8D59-48A3-8EB8-D12880130EF5}.Release|Any CPU.Build.0 = Release|Any CPU
36 | {F932CF3A-2BF4-4235-9977-429775F20F43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
37 | {F932CF3A-2BF4-4235-9977-429775F20F43}.Debug|Any CPU.Build.0 = Debug|Any CPU
38 | {F932CF3A-2BF4-4235-9977-429775F20F43}.Release|Any CPU.ActiveCfg = Release|Any CPU
39 | {F932CF3A-2BF4-4235-9977-429775F20F43}.Release|Any CPU.Build.0 = Release|Any CPU
40 | {07ACF98D-F63C-4D6B-8778-F21BD61E3844}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {07ACF98D-F63C-4D6B-8778-F21BD61E3844}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {07ACF98D-F63C-4D6B-8778-F21BD61E3844}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {07ACF98D-F63C-4D6B-8778-F21BD61E3844}.Release|Any CPU.Build.0 = Release|Any CPU
44 | EndGlobalSection
45 | EndGlobal
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PulumiCSharpAnalyzer [](https://www.nuget.org/packages/PulumiCSharpAnalyzer)
2 |
3 | Roslyn-based static code analysis for pulumi programs written in C#.
4 |
5 | - Detecting missing required resource argument properties
6 | - Detecting missing required function invoke argument properties
7 | - Detects resource creation inside `.Apply(...)` calls and reports a warning
8 |
9 | ## Install
10 |
11 | ```bash
12 | dotnet add package PulumiCSharpAnalyzer
13 | ```
14 |
15 | Which effectively adds the following package reference to your project file
16 | ```xml
17 |
18 | runtime; build; native; contentfiles; analyzers; buildtransitive
19 | all
20 |
21 | ```
22 |
23 | ### Detecting missing required resource argument properties
24 |
25 | 
26 |
27 | ### Detecting missing required function invoke argument properties
28 |
29 | 
30 |
31 | ### Detects resource creation inside `Apply(...)`
32 |
33 | 
34 |
35 | ### VS Code and OmniSharp
36 |
37 | Can't see the warnings when writing Pulumi programs in C# inside VS Code? Make sure you have roslyn analyzers enabled in the settings of OmniSharp:
38 |
39 | 
40 |
41 | Now you should see the analyzer warnings:
42 |
43 | 
44 |
45 | ### Developing the project
46 |
47 | ```bash
48 | cd ./build
49 |
50 | # build the solution
51 | dotnet run -- build
52 |
53 | # run the tets
54 | dotnet run -- test
55 |
56 | # generate a local nuget file
57 | dotnet run -- pack
58 |
59 | # publish the nuget
60 | dotnet run -- publish
61 | ```
62 |
--------------------------------------------------------------------------------
/build/Build.fsproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/build/Files.fs:
--------------------------------------------------------------------------------
1 | []
2 | module Files
3 |
4 | open System.IO
5 | open System.Linq
6 |
7 | /// Recursively tries to find the parent of a file starting from a directory
8 | let rec findParent (directory: string) (fileToFind: string) =
9 | let path = if Directory.Exists(directory) then directory else Directory.GetParent(directory).FullName
10 | let files = Directory.GetFiles(path)
11 | if files.Any(fun file -> Path.GetFileName(file).ToLower() = fileToFind.ToLower())
12 | then path
13 | else findParent (DirectoryInfo(path).Parent.FullName) fileToFind
--------------------------------------------------------------------------------
/build/Program.fs:
--------------------------------------------------------------------------------
1 | module Program
2 |
3 | open System
4 | open System.IO
5 | open System.Text
6 | open System.Xml
7 | open System.Xml.Linq
8 | open System.Net
9 | open System.Net.Http
10 | open Fake.IO
11 | open Fake.Core
12 | open System.Linq
13 |
14 |
15 | let path xs = Path.Combine(Array.ofList xs)
16 |
17 | let solutionRoot = Files.findParent __SOURCE_DIRECTORY__ "PulumiCSharpAnalyzer.sln";
18 |
19 | let src = path [ solutionRoot; "src" ]
20 |
21 | let package = path [ solutionRoot; "package" ]
22 |
23 | let tests = path [ solutionRoot; "tests" ]
24 |
25 | let build() =
26 | if Shell.Exec(Tools.dotnet, "build --configuration Release", solutionRoot) <> 0
27 | then failwith "build failed"
28 |
29 | let test() =
30 | if Shell.Exec(Tools.dotnet, "test --configuration Release", tests) <> 0
31 | then failwith "Tests failed"
32 |
33 | let clean dir =
34 | Shell.deleteDir (path [ dir; "bin" ])
35 | Shell.deleteDir (path [ dir; "obj" ])
36 |
37 | let pack() =
38 | clean package
39 | if Shell.Exec(Tools.dotnet, "build --configuration Release", package) <> 0
40 | then failwith "Pack failed"
41 |
42 | let publish() =
43 | clean package
44 | if Shell.Exec(Tools.dotnet, "build --configuration Release", package) <> 0 then
45 | failwith "Pack failed"
46 | else
47 | let nugetKey =
48 | match Environment.environVarOrNone "NUGET_KEY" with
49 | | Some nugetKey -> nugetKey
50 | | None ->
51 | printfn "The Nuget API key was not found in a NUGET_KEY environmental variable"
52 | printf "Enter NUGET_KEY: "
53 | Console.ReadLine()
54 |
55 | let nugetPath =
56 | Directory.GetFiles(path [ package; "bin"; "Release" ])
57 | |> Seq.head
58 | |> Path.GetFullPath
59 |
60 | if Shell.Exec(Tools.dotnet, sprintf "nuget push %s -s nuget.org -k %s" nugetPath nugetKey, src) <> 0
61 | then failwith "Publish failed"
62 |
63 | []
64 | let main (args: string[]) =
65 | Console.InputEncoding <- Encoding.UTF8
66 | Console.OutputEncoding <- Encoding.UTF8
67 | try
68 | match args with
69 | | [| "build" |] -> build()
70 | | [| "pack" |] -> pack()
71 | | [| "publish" |] -> test(); publish()
72 | | [| "test" |] -> test()
73 | | otherwise -> printfn $"Unknown build args %A{otherwise}"
74 | 0
75 | with ex ->
76 | printfn "%A" ex
77 | 1
78 |
--------------------------------------------------------------------------------
/build/Tools.fs:
--------------------------------------------------------------------------------
1 | []
2 | module Tools
3 |
4 | open System
5 | open System.IO
6 | open Fake.Core
7 |
8 | module CreateProcess =
9 | /// Creates a cross platfrom command from the given program and arguments.
10 | ///
11 | /// For example:
12 | ///
13 | /// ```fsharp
14 | /// CreateProcess.xplatCommand "npm" [ "install" ]
15 | /// ```
16 | ///
17 | /// Will be the following on windows
18 | ///
19 | /// ```fsharp
20 | /// CreateProcess.fromRawCommand "cmd" [ "/C"; "npm"; "install" ]
21 | /// ```
22 | /// And the following otherwise
23 | ///
24 | /// ```fsharp
25 | /// CreateProcess.fromRawCommand "npm" [ "install" ]
26 | /// ```
27 | let xplatCommand program args =
28 | let program', args' =
29 | if Environment.isWindows
30 | then "cmd", List.concat [ [ "/C"; program ]; args ]
31 | else program, args
32 |
33 | CreateProcess.fromRawCommand program' args'
34 |
35 | let executablePath (tool: string) =
36 | let locator =
37 | if Environment.isWindows
38 | then "C:\\Windows\\System32\\where.exe"
39 | else "/usr/bin/which"
40 |
41 | let locatorOutput =
42 | CreateProcess.xplatCommand locator [ tool ]
43 | |> CreateProcess.redirectOutput
44 | |> Proc.run
45 |
46 | if locatorOutput.ExitCode <> 0 then failwithf "Could not determine the executable path of '%s'" tool
47 |
48 | locatorOutput.Result.Output
49 | |> String.splitStr Environment.NewLine
50 | |> List.filter (fun path -> (Environment.isWindows && Path.HasExtension(path)) || Environment.isUnix)
51 | |> List.tryFind File.Exists
52 | |> function
53 | | Some executable -> executable
54 | | None -> failwithf "The executable paht '%s' was not found" tool
55 |
56 | let dotnet = executablePath "dotnet"
--------------------------------------------------------------------------------
/package/Package.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | false
6 | true
7 | true
8 |
9 |
10 |
11 | PulumiCSharpAnalyzer
12 | 0.1.0
13 | Zaid Ajaj
14 | https://github.com/Zaid-Ajaj/pulumi-csharp-analyzer/blob/master/LICENSE
15 | https://github.com/Zaid-Ajaj/pulumi-csharp-analyzer
16 | https://github.com/Zaid-Ajaj/pulumi-csharp-analyzer
17 | false
18 | Roslyn-based static code analysis for pulumi programs written in C#
19 | Initial release.
20 | Copyright
21 | pulumi, csharp, analyzers
22 | true
23 | true
24 |
25 | $(TargetsForTfmSpecificContentInPackage);_AddAnalyzersToOutput
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/package/tools/install.ps1:
--------------------------------------------------------------------------------
1 | param($installPath, $toolsPath, $package, $project)
2 |
3 | if($project.Object.SupportsPackageDependencyResolution)
4 | {
5 | if($project.Object.SupportsPackageDependencyResolution())
6 | {
7 | # Do not install analyzers via install.ps1, instead let the project system handle it.
8 | return
9 | }
10 | }
11 |
12 | $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve
13 |
14 | foreach($analyzersPath in $analyzersPaths)
15 | {
16 | if (Test-Path $analyzersPath)
17 | {
18 | # Install the language agnostic analyzers.
19 | foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll)
20 | {
21 | if($project.Object.AnalyzerReferences)
22 | {
23 | $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
24 | }
25 | }
26 | }
27 | }
28 |
29 | # $project.Type gives the language name like (C# or VB.NET)
30 | $languageFolder = ""
31 | if($project.Type -eq "C#")
32 | {
33 | $languageFolder = "cs"
34 | }
35 | if($project.Type -eq "VB.NET")
36 | {
37 | $languageFolder = "vb"
38 | }
39 | if($languageFolder -eq "")
40 | {
41 | return
42 | }
43 |
44 | foreach($analyzersPath in $analyzersPaths)
45 | {
46 | # Install language specific analyzers.
47 | $languageAnalyzersPath = join-path $analyzersPath $languageFolder
48 | if (Test-Path $languageAnalyzersPath)
49 | {
50 | foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll)
51 | {
52 | if($project.Object.AnalyzerReferences)
53 | {
54 | $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
55 | }
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/package/tools/uninstall.ps1:
--------------------------------------------------------------------------------
1 | param($installPath, $toolsPath, $package, $project)
2 |
3 | if($project.Object.SupportsPackageDependencyResolution)
4 | {
5 | if($project.Object.SupportsPackageDependencyResolution())
6 | {
7 | # Do not uninstall analyzers via uninstall.ps1, instead let the project system handle it.
8 | return
9 | }
10 | }
11 |
12 | $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve
13 |
14 | foreach($analyzersPath in $analyzersPaths)
15 | {
16 | # Uninstall the language agnostic analyzers.
17 | if (Test-Path $analyzersPath)
18 | {
19 | foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll)
20 | {
21 | if($project.Object.AnalyzerReferences)
22 | {
23 | $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName)
24 | }
25 | }
26 | }
27 | }
28 |
29 | # $project.Type gives the language name like (C# or VB.NET)
30 | $languageFolder = ""
31 | if($project.Type -eq "C#")
32 | {
33 | $languageFolder = "cs"
34 | }
35 | if($project.Type -eq "VB.NET")
36 | {
37 | $languageFolder = "vb"
38 | }
39 | if($languageFolder -eq "")
40 | {
41 | return
42 | }
43 |
44 | foreach($analyzersPath in $analyzersPaths)
45 | {
46 | # Uninstall language specific analyzers.
47 | $languageAnalyzersPath = join-path $analyzersPath $languageFolder
48 | if (Test-Path $languageAnalyzersPath)
49 | {
50 | foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll)
51 | {
52 | if($project.Object.AnalyzerReferences)
53 | {
54 | try
55 | {
56 | $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName)
57 | }
58 | catch
59 | {
60 |
61 | }
62 | }
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/screenshots/error-missing-required-properties-function-invokes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zaid-Ajaj/pulumi-csharp-analyzer/64c2ffcf2335e7c0e3abab7db6c0b4fd5672efa6/screenshots/error-missing-required-properties-function-invokes.png
--------------------------------------------------------------------------------
/screenshots/error-missing-required-properties.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zaid-Ajaj/pulumi-csharp-analyzer/64c2ffcf2335e7c0e3abab7db6c0b4fd5672efa6/screenshots/error-missing-required-properties.png
--------------------------------------------------------------------------------
/screenshots/resource-inside-apply.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zaid-Ajaj/pulumi-csharp-analyzer/64c2ffcf2335e7c0e3abab7db6c0b4fd5672efa6/screenshots/resource-inside-apply.png
--------------------------------------------------------------------------------
/screenshots/roslyn-settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zaid-Ajaj/pulumi-csharp-analyzer/64c2ffcf2335e7c0e3abab7db6c0b4fd5672efa6/screenshots/roslyn-settings.png
--------------------------------------------------------------------------------
/screenshots/vscode-warnings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zaid-Ajaj/pulumi-csharp-analyzer/64c2ffcf2335e7c0e3abab7db6c0b4fd5672efa6/screenshots/vscode-warnings.png
--------------------------------------------------------------------------------
/src/PulumiAnalyzer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Collections.Immutable;
3 | using System.Linq;
4 | using Microsoft.CodeAnalysis;
5 | using Microsoft.CodeAnalysis.CSharp.Syntax;
6 | using Microsoft.CodeAnalysis.Diagnostics;
7 | using Microsoft.CodeAnalysis.Operations;
8 |
9 | namespace PulumiCSharpAnalyzer
10 | {
11 | [DiagnosticAnalyzer(LanguageNames.CSharp)]
12 | public class PulumiAnalyzer : DiagnosticAnalyzer
13 | {
14 | private static readonly DiagnosticDescriptor MissingRequiredPropertyRule = new DiagnosticDescriptor(
15 | id: "MissingRequiredProperty",
16 | title: "Missing required property",
17 | messageFormat: "Missing required {0} when initializing properties of type {1}",
18 | category: "Usage",
19 | defaultSeverity: DiagnosticSeverity.Warning,
20 | isEnabledByDefault: true);
21 |
22 | private static readonly DiagnosticDescriptor ResourceCreatedInsideApplyRule = new DiagnosticDescriptor(
23 | id: "ResourceCreatedInsideApply",
24 | title: "Resource created inside Apply",
25 | messageFormat: "Resource {0} created from inside Output.Apply(...) potentially would not show up during pulumi preview phase depending on whether or not the value of the output instance is known",
26 | category: "Usage",
27 | defaultSeverity:DiagnosticSeverity.Warning,
28 | isEnabledByDefault: true
29 | );
30 |
31 | private static readonly DiagnosticDescriptor ApplyResultDiscardedRule = new DiagnosticDescriptor(
32 | id: "ApplyResultDiscarded",
33 | title: "The result of the Apply transform was ignored",
34 | messageFormat: "The result of Output.Apply(...) is discarded. Consider assigning the function call to a variable",
35 | category: "Usage",
36 | defaultSeverity:DiagnosticSeverity.Warning,
37 | isEnabledByDefault: true
38 | );
39 |
40 | public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(
41 | MissingRequiredPropertyRule,
42 | ResourceCreatedInsideApplyRule,
43 | ApplyResultDiscardedRule
44 | );
45 |
46 | public override void Initialize(AnalysisContext context)
47 | {
48 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
49 | context.EnableConcurrentExecution();
50 | context.RegisterOperationAction(AnalyzeObjectCreation, OperationKind.ObjectCreation);
51 | context.RegisterOperationAction(AnalyzeOutputApplyCall, OperationKind.Invocation);
52 | }
53 |
54 | private void AnalyzeOutputApplyCall(OperationAnalysisContext context)
55 | {
56 | var operation = (IInvocationOperation)context.Operation;
57 | var targetMethod = operation.TargetMethod;
58 | if (targetMethod.Name == "Apply")
59 | {
60 | if (targetMethod.ReceiverType != null && targetMethod.ReceiverType.Name.EndsWith("Output"))
61 | {
62 | foreach (var childOperation in operation.Descendants())
63 | {
64 | if (childOperation is IObjectCreationOperation objectCreationOperation)
65 | {
66 | if (IsResourceType(objectCreationOperation.Type))
67 | {
68 | var diagnostic = Diagnostic.Create(
69 | descriptor: ResourceCreatedInsideApplyRule,
70 | location: objectCreationOperation.Syntax.GetLocation(),
71 | messageArgs: new object[] { objectCreationOperation.Type?.Name });
72 |
73 | context.ReportDiagnostic(diagnostic);
74 | }
75 | }
76 | }
77 | }
78 | }
79 | }
80 |
81 | ///
82 | /// Detects resource argument creation and reports required properties that are not defined.
83 | ///
84 | /// The analysis context
85 | private void AnalyzeObjectCreation(OperationAnalysisContext context)
86 | {
87 | var operation = (IObjectCreationOperation)context.Operation;
88 | if (operation.Type != null)
89 | {
90 | var typeName = operation.Type.Name;
91 | if (operation.Type.BaseType != null)
92 | {
93 | var baseTypeName = operation.Type.BaseType.Name;
94 | if (baseTypeName.EndsWith("ResourceArgs") || baseTypeName.EndsWith("InvokeArgs"))
95 | {
96 | var assignedProperties = GetAssignedProperties(operation);
97 | var requiredProperties = GetRequiredProperties(operation.Type);
98 | var missingRequiredProperties = new List();
99 | foreach (var requiredProperty in requiredProperties)
100 | {
101 | if (!assignedProperties.Contains(requiredProperty)
102 | && !missingRequiredProperties.Contains(requiredProperty))
103 | {
104 | missingRequiredProperties.Add(requiredProperty);
105 | }
106 | }
107 |
108 | if (missingRequiredProperties.Any())
109 | {
110 | if (missingRequiredProperties.Count == 1)
111 | {
112 | var diagnostic = Diagnostic.Create(
113 | descriptor: MissingRequiredPropertyRule,
114 | location: operation.Syntax.GetLocation(),
115 | $"property {missingRequiredProperties[0]}",
116 | typeName);
117 |
118 | context.ReportDiagnostic(diagnostic);
119 | }
120 | else
121 | {
122 | var last = missingRequiredProperties.Last();
123 | var allButLast = missingRequiredProperties.TakeWhile(prop => prop != last);
124 | var joinedFirstProperties = string.Join(", ", allButLast);
125 | var diagnostic = Diagnostic.Create(
126 | descriptor: MissingRequiredPropertyRule,
127 | location: operation.Syntax.GetLocation(),
128 | $"properties {joinedFirstProperties} and {last}",
129 | typeName);
130 |
131 | context.ReportDiagnostic(diagnostic);
132 | }
133 | }
134 | }
135 | }
136 | }
137 | }
138 |
139 | bool IsResourceType(ITypeSymbol typeSymbol)
140 | {
141 | if (typeSymbol?.BaseType == null)
142 | {
143 | return false;
144 | }
145 |
146 | return typeSymbol.BaseType.Name.EndsWith("CustomResource");
147 | }
148 |
149 | private List GetAssignedProperties(IObjectCreationOperation objectCreation)
150 | {
151 | var result = new List();
152 | if (objectCreation.Initializer != null)
153 | {
154 | foreach (var initializer in objectCreation.Initializer.Initializers)
155 | {
156 | if (initializer is ISimpleAssignmentOperation assignmentOperation &&
157 | assignmentOperation.Target is IPropertyReferenceOperation propertyReference)
158 | {
159 | result.Add(propertyReference.Property.Name);
160 | }
161 | }
162 | }
163 |
164 | return result;
165 | }
166 |
167 | private List GetRequiredProperties(ITypeSymbol type)
168 | {
169 | var properties = new List();
170 |
171 | // Walk all the properties of this args type looking for those that have a
172 | // `[Input("name", required: true)]` arg.
173 | foreach (var member in type.GetMembers())
174 | {
175 | if (member is IPropertySymbol property)
176 | {
177 | var attributes = property.GetAttributes();
178 | foreach (var attribute in attributes)
179 | {
180 | var args = attribute.ConstructorArguments;
181 | if (args.Length >= 2 && args[1].Value is true)
182 | {
183 | properties.Add(member.Name);
184 | }
185 | }
186 | }
187 | }
188 |
189 | return properties.Distinct().ToList();
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/src/PulumiCSharpAnalyzer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | false
6 |
7 |
8 | *$(MSBuildProjectFile)*
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/tests/Tests.cs:
--------------------------------------------------------------------------------
1 | using System.Threading;
2 | using System.Threading.Tasks;
3 | using Microsoft.CodeAnalysis.Testing;
4 | using Microsoft.VisualStudio.TestTools.UnitTesting;
5 |
6 | namespace PulumiCSharpAnalyzer.Test
7 | {
8 | [TestClass]
9 | public class Tests
10 | {
11 | [TestMethod]
12 | public async Task BasicVerificationWorks_NoDiagnostics()
13 | {
14 | var tester = new CSharpAnalyzerVerifier.Test();
15 | tester.TestCode = @"
16 | using System;
17 |
18 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
19 | public sealed class InputAttribute : Attribute
20 | {
21 | internal string Name { get; }
22 | internal bool IsRequired { get; }
23 | internal bool Json { get; }
24 |
25 | public InputAttribute(string name, bool required = false, bool json = false)
26 | {
27 | Name = name;
28 | IsRequired = required;
29 | Json = json;
30 | }
31 | }
32 |
33 | class Output
34 | {
35 | public Output Apply(Func map) => null;
36 | }
37 |
38 | class Output
39 | {
40 | public static Output Create(T value) => null;
41 | }
42 |
43 | class ResourceArgs
44 | {
45 |
46 | }
47 |
48 | class CustomResource
49 | {
50 | }
51 |
52 | class StorageAccountArgs : ResourceArgs
53 | {
54 | [Input(""resourceName"", true, false)]
55 | public string ResourceName { get; set; }
56 |
57 | [Input(""version"", false, false)]
58 | public int Version { get; set; }
59 | }
60 |
61 | class StorageAccount : CustomResource
62 | {
63 |
64 | }
65 |
66 | class Program
67 | {
68 | static void Main()
69 | {
70 | var args = new StorageAccountArgs
71 | {
72 | ResourceName = ""fooBar"",
73 | Version = 42
74 | };
75 |
76 | var output = Output.Create(42);
77 | output.Apply(value =>
78 | {
79 | return 1;
80 | });
81 | }
82 | }
83 | ";
84 | await tester.RunAsync(CancellationToken.None);
85 | }
86 |
87 | [TestMethod]
88 | public async Task BasicVerificationWorks_MissingRequiredProperty()
89 | {
90 | var tester = new CSharpAnalyzerVerifier.Test();
91 | tester.TestCode = @"
92 | using System;
93 |
94 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
95 | public sealed class InputAttribute : Attribute
96 | {
97 | internal string Name { get; }
98 | internal bool IsRequired { get; }
99 | internal bool Json { get; }
100 |
101 | public InputAttribute(string name, bool required = false, bool json = false)
102 | {
103 | Name = name;
104 | IsRequired = required;
105 | Json = json;
106 | }
107 | }
108 |
109 | class ResourceArgs
110 | {
111 |
112 | }
113 |
114 | class CustomResource
115 | {
116 | }
117 |
118 | class StorageAccountArgs : ResourceArgs
119 | {
120 | [Input(""resourceName"", true, false)]
121 | public string ResourceName { get; set; }
122 |
123 | [Input(""version"", false, false)]
124 | public int Version { get; set; }
125 | }
126 |
127 | class StorageAccount : CustomResource
128 | {
129 |
130 | }
131 |
132 | class Program
133 | {
134 | static void Main()
135 | {
136 | var args = new StorageAccountArgs
137 | {
138 | Version = 42
139 | };
140 | }
141 | }
142 | ";
143 |
144 | var diagnosticResult =
145 | DiagnosticResult
146 | .CompilerWarning("MissingRequiredProperty")
147 | .WithArguments("property ResourceName", "StorageAccountArgs")
148 | .WithSpan(46, 20, 49, 10)
149 | .WithMessage("Missing required property ResourceName when initializing properties of type StorageAccountArgs");
150 |
151 | tester.ExpectedDiagnostics.Add(diagnosticResult);
152 | await tester.RunAsync(CancellationToken.None);
153 | }
154 |
155 | [TestMethod]
156 | public async Task BasicVerificationWorks_MissingMultipleRequiredProperty()
157 | {
158 | var tester = new CSharpAnalyzerVerifier.Test();
159 | tester.TestCode = @"
160 | using System;
161 |
162 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
163 | public sealed class InputAttribute : Attribute
164 | {
165 | internal string Name { get; }
166 | internal bool IsRequired { get; }
167 | internal bool Json { get; }
168 |
169 | public InputAttribute(string name, bool required = false, bool json = false)
170 | {
171 | Name = name;
172 | IsRequired = required;
173 | Json = json;
174 | }
175 | }
176 |
177 | class ResourceArgs
178 | {
179 |
180 | }
181 |
182 | class CustomResource
183 | {
184 | }
185 |
186 | class StorageAccountArgs : ResourceArgs
187 | {
188 | [Input(""resourceName"", true, false)]
189 | public string ResourceName { get; set; }
190 |
191 | [Input(""version"", true, false)]
192 | public int Version { get; set; }
193 | }
194 |
195 | class StorageAccount : CustomResource
196 | {
197 |
198 | }
199 |
200 | class Program
201 | {
202 | static void Main()
203 | {
204 | var args = new StorageAccountArgs
205 | {
206 |
207 | };
208 | }
209 | }
210 | ";
211 | var diagnosticResult =
212 | DiagnosticResult
213 | .CompilerWarning("MissingRequiredProperty")
214 | .WithArguments("properties ResourceName and Version", "StorageAccountArgs")
215 | .WithSpan(46, 20, 49, 10)
216 | .WithMessage("Missing required properties ResourceName and Version when initializing properties of type StorageAccountArgs");
217 |
218 | tester.ExpectedDiagnostics.Add(diagnosticResult);
219 | await tester.RunAsync(CancellationToken.None);
220 | }
221 |
222 | [TestMethod]
223 | public async Task BasicVerificationWorks_ResourceCreatedInsideApply()
224 | {
225 | var tester = new CSharpAnalyzerVerifier.Test();
226 | tester.TestCode = @"
227 | using System;
228 |
229 | class Output
230 | {
231 | public Output Apply(Func map) => null;
232 | }
233 |
234 | class Output
235 | {
236 | public static Output Create(T value) => null;
237 | }
238 |
239 | class ResourceArgs
240 | {
241 |
242 | }
243 |
244 | class CustomResource
245 | {
246 | }
247 |
248 | class StorageAccount : CustomResource
249 | {
250 |
251 | }
252 |
253 | class Program
254 | {
255 | static void Main()
256 | {
257 | Output.Create(42).Apply(value =>
258 | {
259 | return new StorageAccount { };
260 | });
261 | }
262 | }
263 | ";
264 | var diagnosticResult =
265 | DiagnosticResult
266 | .CompilerWarning("ResourceCreatedInsideApply")
267 | .WithArguments("StorageAccount")
268 | .WithSpan(34, 20, 34, 42)
269 | .WithMessage("Resource StorageAccount created from inside Output.Apply(...) potentially would not show up during pulumi preview phase depending on whether or not the value of the output instance is known");
270 |
271 | tester.ExpectedDiagnostics.Add(diagnosticResult);
272 | await tester.RunAsync(CancellationToken.None);
273 | }
274 |
275 | [TestMethod]
276 | public async Task BasicVerificationWorks_MissingPropertyInsideFunctionInvokeArgs()
277 | {
278 | var tester = new CSharpAnalyzerVerifier.Test();
279 | tester.TestCode = @"
280 | using System;
281 |
282 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
283 | public sealed class InputAttribute : Attribute
284 | {
285 | internal string Name { get; }
286 | internal bool IsRequired { get; }
287 | internal bool Json { get; }
288 |
289 | public InputAttribute(string name, bool required = false, bool json = false)
290 | {
291 | Name = name;
292 | IsRequired = required;
293 | Json = json;
294 | }
295 | }
296 |
297 | class Output
298 | {
299 | public Output Apply(Func map) => null;
300 | }
301 |
302 | class Output
303 | {
304 | public static Output Create(T value) => null;
305 | }
306 |
307 | class InvokeArgs
308 | {
309 |
310 | }
311 |
312 |
313 | class GetStorageAccountArgs : InvokeArgs
314 | {
315 | [Input(""resourceName"", true, false)]
316 | public string ResourceName { get; set; }
317 | }
318 |
319 | class Program
320 | {
321 | static void Main()
322 | {
323 | // missing ResourceName property initializer
324 | new GetStorageAccountArgs { };
325 | }
326 | }
327 | ";
328 | var diagnosticResult =
329 | DiagnosticResult
330 | .CompilerWarning("MissingRequiredProperty")
331 | .WithArguments("property ResourceName", "GetStorageAccountArgs")
332 | .WithSpan(46, 9, 46, 38)
333 | .WithMessage("Missing required property ResourceName when initializing properties of type GetStorageAccountArgs");
334 |
335 | tester.ExpectedDiagnostics.Add(diagnosticResult);
336 | await tester.RunAsync(CancellationToken.None);
337 | }
338 | }
339 | }
340 |
--------------------------------------------------------------------------------
/tests/Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 |
6 | true
7 | true
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpAnalyzerVerifier`1+Test.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CSharp.Testing;
2 | using Microsoft.CodeAnalysis.Diagnostics;
3 | using Microsoft.CodeAnalysis.Testing.Verifiers;
4 |
5 | namespace PulumiCSharpAnalyzer.Test
6 | {
7 | public static partial class CSharpAnalyzerVerifier
8 | where TAnalyzer : DiagnosticAnalyzer, new()
9 | {
10 | public class Test : CSharpAnalyzerTest
11 | {
12 | public Test()
13 | {
14 | SolutionTransforms.Add((solution, projectId) =>
15 | {
16 | var compilationOptions = solution.GetProject(projectId).CompilationOptions;
17 | compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
18 | compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings));
19 | solution = solution.WithProjectCompilationOptions(projectId, compilationOptions);
20 |
21 | return solution;
22 | });
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpAnalyzerVerifier`1.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp.Testing;
3 | using Microsoft.CodeAnalysis.Diagnostics;
4 | using Microsoft.CodeAnalysis.Testing;
5 | using Microsoft.CodeAnalysis.Testing.Verifiers;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 |
9 | namespace PulumiCSharpAnalyzer.Test
10 | {
11 | public static partial class CSharpAnalyzerVerifier
12 | where TAnalyzer : DiagnosticAnalyzer, new()
13 | {
14 | ///
15 | public static DiagnosticResult Diagnostic()
16 | => CSharpAnalyzerVerifier.Diagnostic();
17 |
18 | ///
19 | public static DiagnosticResult Diagnostic(string diagnosticId)
20 | => CSharpAnalyzerVerifier.Diagnostic(diagnosticId);
21 |
22 | ///
23 | public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
24 | => CSharpAnalyzerVerifier.Diagnostic(descriptor);
25 |
26 | ///
27 | public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
28 | {
29 | var test = new Test
30 | {
31 | TestCode = source,
32 | };
33 |
34 | test.ExpectedDiagnostics.AddRange(expected);
35 | await test.RunAsync(CancellationToken.None);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpCodeFixVerifier`2+Test.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Microsoft.CodeAnalysis.CodeFixes;
3 | using Microsoft.CodeAnalysis.CSharp.Testing;
4 | using Microsoft.CodeAnalysis.Diagnostics;
5 | using Microsoft.CodeAnalysis.Testing.Verifiers;
6 |
7 | namespace PulumiCSharpAnalyzer.Test
8 | {
9 | public static partial class CSharpCodeFixVerifier
10 | where TAnalyzer : DiagnosticAnalyzer, new()
11 | where TCodeFix : CodeFixProvider, new()
12 | {
13 | public class Test : CSharpCodeFixTest
14 | {
15 | public Test()
16 | {
17 | SolutionTransforms.Add((solution, projectId) =>
18 | {
19 | var compilationOptions = solution.GetProject(projectId).CompilationOptions;
20 | compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
21 | compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings));
22 | solution = solution.WithProjectCompilationOptions(projectId, compilationOptions);
23 |
24 | return solution;
25 | });
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpCodeFixVerifier`2.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CodeFixes;
3 | using Microsoft.CodeAnalysis.CSharp.Testing;
4 | using Microsoft.CodeAnalysis.Diagnostics;
5 | using Microsoft.CodeAnalysis.Testing;
6 | using Microsoft.CodeAnalysis.Testing.Verifiers;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 |
10 | namespace PulumiCSharpAnalyzer.Test
11 | {
12 | public static partial class CSharpCodeFixVerifier
13 | where TAnalyzer : DiagnosticAnalyzer, new()
14 | where TCodeFix : CodeFixProvider, new()
15 | {
16 | ///
17 | public static DiagnosticResult Diagnostic()
18 | => CSharpCodeFixVerifier.Diagnostic();
19 |
20 | ///
21 | public static DiagnosticResult Diagnostic(string diagnosticId)
22 | => CSharpCodeFixVerifier.Diagnostic(diagnosticId);
23 |
24 | ///
25 | public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
26 | => CSharpCodeFixVerifier.Diagnostic(descriptor);
27 |
28 | ///
29 | public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
30 | {
31 | var test = new Test
32 | {
33 | TestCode = source,
34 | };
35 |
36 | test.ExpectedDiagnostics.AddRange(expected);
37 | await test.RunAsync(CancellationToken.None);
38 | }
39 |
40 | ///
41 | public static async Task VerifyCodeFixAsync(string source, string fixedSource)
42 | => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
43 |
44 | ///
45 | public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
46 | => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource);
47 |
48 | ///
49 | public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource)
50 | {
51 | var test = new Test
52 | {
53 | TestCode = source,
54 | FixedCode = fixedSource,
55 | };
56 |
57 | test.ExpectedDiagnostics.AddRange(expected);
58 | await test.RunAsync(CancellationToken.None);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpCodeRefactoringVerifier`1+Test.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CodeRefactorings;
2 | using Microsoft.CodeAnalysis.CSharp.Testing;
3 | using Microsoft.CodeAnalysis.Testing.Verifiers;
4 |
5 | namespace PulumiCSharpAnalyzer.Test
6 | {
7 | public static partial class CSharpCodeRefactoringVerifier
8 | where TCodeRefactoring : CodeRefactoringProvider, new()
9 | {
10 | public class Test : CSharpCodeRefactoringTest
11 | {
12 | public Test()
13 | {
14 | SolutionTransforms.Add((solution, projectId) =>
15 | {
16 | var compilationOptions = solution.GetProject(projectId).CompilationOptions;
17 | compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
18 | compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings));
19 | solution = solution.WithProjectCompilationOptions(projectId, compilationOptions);
20 |
21 | return solution;
22 | });
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpCodeRefactoringVerifier`1.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CodeRefactorings;
2 | using Microsoft.CodeAnalysis.Testing;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 |
6 | namespace PulumiCSharpAnalyzer.Test
7 | {
8 | public static partial class CSharpCodeRefactoringVerifier
9 | where TCodeRefactoring : CodeRefactoringProvider, new()
10 | {
11 | ///
12 | public static async Task VerifyRefactoringAsync(string source, string fixedSource)
13 | {
14 | await VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
15 | }
16 |
17 | ///
18 | public static async Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
19 | {
20 | await VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
21 | }
22 |
23 | ///
24 | public static async Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource)
25 | {
26 | var test = new Test
27 | {
28 | TestCode = source,
29 | FixedCode = fixedSource,
30 | };
31 |
32 | test.ExpectedDiagnostics.AddRange(expected);
33 | await test.RunAsync(CancellationToken.None);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/tests/Verifiers/CSharpVerifierHelper.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp;
3 | using System;
4 | using System.Collections.Immutable;
5 |
6 | namespace PulumiCSharpAnalyzer.Test
7 | {
8 | internal static class CSharpVerifierHelper
9 | {
10 | ///
11 | /// By default, the compiler reports diagnostics for nullable reference types at
12 | /// , and the analyzer test framework defaults to only validating
13 | /// diagnostics at . This map contains all compiler diagnostic IDs
14 | /// related to nullability mapped to , which is then used to enable all
15 | /// of these warnings for default validation during analyzer and code fix tests.
16 | ///
17 | internal static ImmutableDictionary NullableWarnings { get; } = GetNullableWarningsFromCompiler();
18 |
19 | private static ImmutableDictionary GetNullableWarningsFromCompiler()
20 | {
21 | string[] args = { "/warnaserror:nullable" };
22 | var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory);
23 | var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions;
24 |
25 | // Workaround for https://github.com/dotnet/roslyn/issues/41610
26 | nullableWarnings = nullableWarnings
27 | .SetItem("CS8632", ReportDiagnostic.Error)
28 | .SetItem("CS8669", ReportDiagnostic.Error);
29 |
30 | return nullableWarnings;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicAnalyzerVerifier`1+Test.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.Diagnostics;
2 | using Microsoft.CodeAnalysis.Testing.Verifiers;
3 | using Microsoft.CodeAnalysis.VisualBasic.Testing;
4 |
5 | namespace PulumiCSharpAnalyzer.Test
6 | {
7 | public static partial class VisualBasicAnalyzerVerifier
8 | where TAnalyzer : DiagnosticAnalyzer, new()
9 | {
10 | public class Test : VisualBasicAnalyzerTest
11 | {
12 | public Test()
13 | {
14 | }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicAnalyzerVerifier`1.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.Diagnostics;
3 | using Microsoft.CodeAnalysis.Testing;
4 | using Microsoft.CodeAnalysis.Testing.Verifiers;
5 | using Microsoft.CodeAnalysis.VisualBasic.Testing;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 |
9 | namespace PulumiCSharpAnalyzer.Test
10 | {
11 | public static partial class VisualBasicAnalyzerVerifier
12 | where TAnalyzer : DiagnosticAnalyzer, new()
13 | {
14 | ///
15 | public static DiagnosticResult Diagnostic()
16 | => VisualBasicAnalyzerVerifier.Diagnostic();
17 |
18 | ///
19 | public static DiagnosticResult Diagnostic(string diagnosticId)
20 | => VisualBasicAnalyzerVerifier.Diagnostic(diagnosticId);
21 |
22 | ///
23 | public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
24 | => VisualBasicAnalyzerVerifier.Diagnostic(descriptor);
25 |
26 | ///
27 | public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
28 | {
29 | var test = new Test
30 | {
31 | TestCode = source,
32 | };
33 |
34 | test.ExpectedDiagnostics.AddRange(expected);
35 | await test.RunAsync(CancellationToken.None);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicCodeFixVerifier`2+Test.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CodeFixes;
2 | using Microsoft.CodeAnalysis.Diagnostics;
3 | using Microsoft.CodeAnalysis.Testing.Verifiers;
4 | using Microsoft.CodeAnalysis.VisualBasic.Testing;
5 |
6 | namespace PulumiCSharpAnalyzer.Test
7 | {
8 | public static partial class VisualBasicCodeFixVerifier
9 | where TAnalyzer : DiagnosticAnalyzer, new()
10 | where TCodeFix : CodeFixProvider, new()
11 | {
12 | public class Test : VisualBasicCodeFixTest
13 | {
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicCodeFixVerifier`2.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CodeFixes;
3 | using Microsoft.CodeAnalysis.Diagnostics;
4 | using Microsoft.CodeAnalysis.Testing;
5 | using Microsoft.CodeAnalysis.Testing.Verifiers;
6 | using Microsoft.CodeAnalysis.VisualBasic.Testing;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 |
10 | namespace PulumiCSharpAnalyzer.Test
11 | {
12 | public static partial class VisualBasicCodeFixVerifier
13 | where TAnalyzer : DiagnosticAnalyzer, new()
14 | where TCodeFix : CodeFixProvider, new()
15 | {
16 | ///
17 | public static DiagnosticResult Diagnostic()
18 | => VisualBasicCodeFixVerifier.Diagnostic();
19 |
20 | ///
21 | public static DiagnosticResult Diagnostic(string diagnosticId)
22 | => VisualBasicCodeFixVerifier.Diagnostic(diagnosticId);
23 |
24 | ///
25 | public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
26 | => VisualBasicCodeFixVerifier.Diagnostic(descriptor);
27 |
28 | ///
29 | public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
30 | {
31 | var test = new Test
32 | {
33 | TestCode = source,
34 | };
35 |
36 | test.ExpectedDiagnostics.AddRange(expected);
37 | await test.RunAsync(CancellationToken.None);
38 | }
39 |
40 | ///
41 | public static async Task VerifyCodeFixAsync(string source, string fixedSource)
42 | => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
43 |
44 | ///
45 | public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
46 | => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource);
47 |
48 | ///
49 | public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource)
50 | {
51 | var test = new Test
52 | {
53 | TestCode = source,
54 | FixedCode = fixedSource,
55 | };
56 |
57 | test.ExpectedDiagnostics.AddRange(expected);
58 | await test.RunAsync(CancellationToken.None);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicCodeRefactoringVerifier`1+Test.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CodeRefactorings;
2 | using Microsoft.CodeAnalysis.Testing.Verifiers;
3 | using Microsoft.CodeAnalysis.VisualBasic.Testing;
4 |
5 | namespace PulumiCSharpAnalyzer.Test
6 | {
7 | public static partial class VisualBasicCodeRefactoringVerifier
8 | where TCodeRefactoring : CodeRefactoringProvider, new()
9 | {
10 | public class Test : VisualBasicCodeRefactoringTest
11 | {
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/tests/Verifiers/VisualBasicCodeRefactoringVerifier`1.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CodeRefactorings;
2 | using Microsoft.CodeAnalysis.Testing;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 |
6 | namespace PulumiCSharpAnalyzer.Test
7 | {
8 | public static partial class VisualBasicCodeRefactoringVerifier
9 | where TCodeRefactoring : CodeRefactoringProvider, new()
10 | {
11 | ///
12 | public static async Task VerifyRefactoringAsync(string source, string fixedSource)
13 | {
14 | await VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
15 | }
16 |
17 | ///
18 | public static async Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
19 | {
20 | await VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
21 | }
22 |
23 | ///
24 | public static async Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource)
25 | {
26 | var test = new Test
27 | {
28 | TestCode = source,
29 | FixedCode = fixedSource,
30 | };
31 |
32 | test.ExpectedDiagnostics.AddRange(expected);
33 | await test.RunAsync(CancellationToken.None);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------