Skip to content

Instantly share code, notes, and snippets.

@thegamecracks
Created January 15, 2026 13:58
Show Gist options
  • Select an option

  • Save thegamecracks/519cfa3f8f2b7c3a992113442da32834 to your computer and use it in GitHub Desktop.

Select an option

Save thegamecracks/519cfa3f8f2b7c3a992113442da32834 to your computer and use it in GitHub Desktop.
Generate a .NET solution with one or more projects, in case I forget how to use dotnet
"""Generate a .NET solution with one or more projects."""
import argparse
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Self
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Suppress command output",
)
parser.add_argument(
"solution",
help="The solution directory to create",
type=Path,
)
parser.add_argument(
"projects",
nargs="+",
help="Project templates to create in format name[:template]",
type=Project.from_str,
)
args = parser.parse_args()
quiet: bool = args.quiet
solution: Path = args.solution
projects: list[Project] = args.projects
config = Config(quiet=quiet)
if solution.is_dir():
sys.exit("solution directory already exists")
solution.mkdir()
config.check_call(["dotnet", "new", "sln"], cwd=solution)
for p in projects:
config.check_call(["dotnet", "new", p.template, "-o", p.name], cwd=solution)
config.check_call(["dotnet", "sln", "add", p.name], cwd=solution)
@dataclass(kw_only=True)
class Project:
name: str
template: str
@classmethod
def from_str(cls, s: str) -> Self:
try:
name, template = s.split(":")
except ValueError:
name, template = s, "console"
return cls(name=name, template=template)
@dataclass(kw_only=True)
class Config:
quiet: bool
def check_call(
self,
args: list[str],
*,
cwd: Path | None = None,
) -> None:
print("$", " ".join(str(x) for x in args))
subprocess.check_call(
args,
cwd=cwd,
stdout=subprocess.DEVNULL if self.quiet else None,
stderr=subprocess.STDOUT if self.quiet else None,
)
if __name__ == "__main__":
main()
@thegamecracks
Copy link
Author

> py newsln.py -h
usage: newsln.py [-h] [-q] solution projects [projects ...]

Generate a .NET solution with one or more projects.

positional arguments:
  solution     The solution directory to create
  projects     Project templates to create in format name[:template]

options:
  -h, --help   show this help message and exit
  -q, --quiet  Suppress command output

> py newsln.py -q Lab2 Q1 Q2:winforms
$ dotnet new sln
$ dotnet new console -o Q1
$ dotnet sln add Q1
$ dotnet new winforms -o Q2
$ dotnet sln add Q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment