feat: Initial commit

This commit is contained in:
Sam Therapy 2023-05-13 20:10:14 +02:00
commit b3fa862f39
Signed by: sam
GPG Key ID: 4D8B07C18F31ACBD
33 changed files with 3044 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

60
.github/workflows/build-test.yaml vendored Normal file
View File

@ -0,0 +1,60 @@
name: Build
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
operating-system: ["windows", "macos", "ubuntu"]
dotnet-version: ["7.0.x"]
runs-on: ${{ matrix.operating-system }}-latest
steps:
- uses: actions/checkout@v3
- name: Setup .NET Core SDK ${{ matrix.dotnet-version }}
uses: actions/setup-dotnet@v3
with:
dotnet-version: ${{ matrix.dotnet-version }}
- uses: actions/cache@v3
with:
path: ~/.nuget/packages
# Look to see if there is a cache hit for the corresponding requirements file
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Install dependencies
run: dotnet restore
- name: Build
run: dotnet build --configuration Release --no-restore
- name: Test
run: dotnet test --no-restore --verbosity normal
publish:
needs: build
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v3
- uses: actions/cache@v3
with:
path: ~/.nuget/packages
# Look to see if there is a cache hit for the corresponding requirements file
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Install dependencies
run: dotnet restore
- name: Build the package
run: dotnet build --configuration Release --no-restore -p:SymbolPackageFormat=symbols.nupkg
- name: Publish the package
run: dotnet nuget push src/Xdg.Directories/bin/Release/*.symbols.nupkg -s https://nuget.pkg.github.com/SamTherapy/index.json -k ${{ secrets.GITHUB_TOKEN }}

68
.github/workflows/codeql.yml vendored Normal file
View File

@ -0,0 +1,68 @@
# CodeQL Code Scanning
# Analyses your code for security vulnerabilities and coding errors.
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository. You may wish to alter this file to override
# the set of languages analyzed, or to provide custom queries or build logic.
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/about-code-scanning
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: "0 8 * * 4"
workflow_dispatch:
jobs:
analyze:
name: Analyze
permissions:
actions: read
contents: read
security-events: write
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: ["csharp"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3.5.2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

366
.gitignore vendored Normal file
View File

@ -0,0 +1,366 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Visual Studio Code files
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

52
GNUmakefile Normal file
View File

@ -0,0 +1,52 @@
NETVERSION ?= net7.0
PUBFLAGS ?= --framework $(NETVERSION) -c Release -p GeneratePackageOnBuild=false -p PublishAot=true -p AssemblyName=libxdg
ifeq ($(OS),Windows_NT)
OSFLAG += win
ifeq ($(PROCESSOR_ARCHITEW6432),AMD64)
:= $(OSFLAG)-x64
else
ifeq ($(PROCESSOR_ARCHITECTURE),AMD64)
:= $(OSFLAG)-x64
endif
ifeq ($(PROCESSOR_ARCHITECTURE),x86)
:= $(OSFLAG)-x86
endif
endif
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
OSFLAG += linux
endif
ifeq ($(UNAME_S),Darwin)
OSFLAG += osx
endif
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_M),x86_64)
OSFLAG := $(OSFLAG)-x64
endif
ifeq ($(UNAME_M),x86)
OSFLAG := $(OSFLAG)-x86
endif
ifeq ($(UNAME_M),arm64)
OSFLAG := $(OSFLAG)-arm64
endif
ifeq ($(UNAME_M),arm)
OSFLAG := $(OSFLAG)-arm
endif
endif
PUBFLAGS += -r $(OSFLAG)
publish: src/Xdg.Directories/bin/Release/$(NETVERSION)/$(OSFLAG)/publish
src/Xdg.Directories/bin/Release/$(NETVERSION)/$(OSFLAG)/publish:
dotnet publish ./src/Xdg.Directories $(PUBFLAGS)
.PHONY: install
install: publish
make NETVERSION=$(NETVERSION) -C src/Xdg.Directories install
.PHONY: uninstall
uninstall:
make -C src/Xdg.Directories uninstall

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Xdg.Net Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

6
README.md Normal file
View File

@ -0,0 +1,6 @@
# Xdg
----
[![Build](https://github.com/SamTherapy/Xdg.Net/actions/workflows/build-test.yaml/badge.svg)](https://github.com/SamTherapy/Xdg.Net/actions/workflows/build-test.yaml)
[![CodeQL](https://github.com/SamTherapy/Xdg.Net/actions/workflows/codeql.yml/badge.svg)](https://github.com/SamTherapy/Xdg.Net/actions/workflows/codeql.yml)
A .NET implementation of the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html).

37
Xdg.Net.sln Normal file
View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33627.172
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Xdg.Directories", "src\Xdg.Directories\Xdg.Directories.csproj", "{D644CF8D-B8EB-4581-B075-9FD62BB5709A}"
EndProject
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Xdg.Benchmarks", "src\Xdg.Benchmarks\Xdg.Benchmarks.fsproj", "{AEC4CC3D-E753-4D96-B8E8-B39B41EC0871}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Xdg.Testing", "src\Xdg.Testing\Xdg.Testing.csproj", "{F5B4B166-F5F9-4D47-B426-CDA907C8B3E5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D644CF8D-B8EB-4581-B075-9FD62BB5709A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D644CF8D-B8EB-4581-B075-9FD62BB5709A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D644CF8D-B8EB-4581-B075-9FD62BB5709A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D644CF8D-B8EB-4581-B075-9FD62BB5709A}.Release|Any CPU.Build.0 = Release|Any CPU
{AEC4CC3D-E753-4D96-B8E8-B39B41EC0871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AEC4CC3D-E753-4D96-B8E8-B39B41EC0871}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AEC4CC3D-E753-4D96-B8E8-B39B41EC0871}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AEC4CC3D-E753-4D96-B8E8-B39B41EC0871}.Release|Any CPU.Build.0 = Release|Any CPU
{F5B4B166-F5F9-4D47-B426-CDA907C8B3E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F5B4B166-F5F9-4D47-B426-CDA907C8B3E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F5B4B166-F5F9-4D47-B426-CDA907C8B3E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F5B4B166-F5F9-4D47-B426-CDA907C8B3E5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6625754A-B79C-48B3-9B84-B7CF536AF30C}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,56 @@
open BenchmarkDotNet.Attributes
open BenchmarkDotNet.Running
open BenchmarkDotNet.Jobs
open Xdg.Directories;
[<MemoryDiagnoser>]
[<SimpleJob(RuntimeMoniker.Net462)>]
//[<SimpleJob(RuntimeMoniker.Mono)>]
[<SimpleJob(RuntimeMoniker.Net70, baseline = true)>]
[<SimpleJob(RuntimeMoniker.NativeAot70)>]
type Benchmarks() =
// Base Directory
[<Benchmark>]
member _.DataHome () = BaseDirectory.DataHome
[<Benchmark>]
member _.ConfigHome () = BaseDirectory.ConfigHome
[<Benchmark>]
member _.StateHome () = BaseDirectory.StateHome
[<Benchmark>]
member _.BinHome () = BaseDirectory.BinHome
[<Benchmark>]
member _.DataDirs () = BaseDirectory.DataDirs
[<Benchmark>]
member _.ConfigDirs () = BaseDirectory.ConfigDirs
[<Benchmark>]
member _.CacheHome () = BaseDirectory.CacheHome
[<Benchmark>]
member _.RuntimeDir() = BaseDirectory.RuntimeDir
// User Directories
[<Benchmark>]
member _.DesktopDir () = UserDirectory.DesktopDir
[<Benchmark>]
member _.DownloadDir () = UserDirectory.DownloadDir
[<Benchmark>]
member _.DocumentsDir () = UserDirectory.DocumentsDir
[<Benchmark>]
member _.MusicDir () = UserDirectory.MusicDir
[<Benchmark>]
member _.PicturesDir () = UserDirectory.PicturesDir
[<Benchmark>]
member _.VideosDir () = UserDirectory.VideosDir
[<Benchmark>]
member _.TemplatesDir () = UserDirectory.TemplatesDir
[<Benchmark>]
member _.PublicDir () = UserDirectory.PublicDir
// Other
[<Benchmark>]
member _.Home () = Other.Home
[<Benchmark>]
member _.Applications () = Other.Applications
[<Benchmark>]
member _.Fonts () = Other.Fonts
BenchmarkRunner.Run<Benchmarks>() |> ignore

View File

@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net7.0;net48</TargetFrameworks>
<IsPackable>false</IsPackable>
<IsPublishable>false</IsPublishable>
<RunAnalyzersDuringBuild>True</RunAnalyzersDuringBuild>
<RunAnalyzersDuringLiveAnalysis>True</RunAnalyzersDuringLiveAnalysis>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<EnableNETAnalyzers>True</EnableNETAnalyzers>
<AnalysisLevel>latest-all</AnalysisLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net7.0|AnyCPU'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net7.0|AnyCPU'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net462|AnyCPU'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net462|AnyCPU'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Xdg.Directories\Xdg.Directories.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,122 @@
namespace Xdg.Directories;
/// <include file='docs/BaseDirectory.xml' path='docs/BaseDirectory'/>
public static class BaseDirectory
{
/// <include file='docs/BaseDirectory.xml' path='docs/DataHome'/>
public static string DataHome
{
get =>
Helpers.OS(
"XDG_DATA_HOME",
GetEnvironmentVariable("LOCALAPPDATA")
?? GetFolderPath(SpecialFolder.LocalApplicationData),
$"{Other.Home}/Library/Application Support",
$"{Other.Home}/.local/share"
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/ConfigHome'/>
public static string ConfigHome
{
get =>
Helpers.OS(
"XDG_CONFIG_HOME",
GetEnvironmentVariable("LOCALAPPDATA")
?? GetFolderPath(SpecialFolder.LocalApplicationData),
$"{Other.Home}/Library/Application Support",
$"{Other.Home}/.config"
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/StateHome'/>
public static string StateHome
{
get =>
Helpers.OS(
"XDG_STATE_HOME",
GetEnvironmentVariable("LOCALAPPDATA")
?? GetFolderPath(SpecialFolder.LocalApplicationData),
$"{Other.Home}/Library/Application Support",
$"{Other.Home}/.local/state"
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/BinHome'/>
public static string? BinHome
{
get => Helpers.OS("XDG_BIN_HOME", null, null, $"{Other.Home}/.local/bin")!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/DataDirs'/>
public static IList<string> DataDirs
{
get =>
Helpers.OS(
"XDG_DATA_DIRS",
new string[]
{
Helpers.AorB(
GetFolderPath(SpecialFolder.ApplicationData),
GetEnvironmentVariable("APPDATA")!
),
GetEnvironmentVariable("PROGRAMDATA")
?? GetFolderPath(SpecialFolder.CommonApplicationData)
},
new string[] { "/Library/Application Support" },
new string[] { "/usr/local/share", "/usr/share" }
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/ConfigDirs'/>
public static IList<string> ConfigDirs
{
get =>
Helpers.OS(
"XDG_CONFIG_DIRS",
new string[]
{
GetEnvironmentVariable("PROGRAMDATA")
?? GetFolderPath(SpecialFolder.CommonApplicationData),
Helpers.AorB(
GetFolderPath(SpecialFolder.ApplicationData),
GetEnvironmentVariable("APPDATA")!
)
},
new string[]
{
$"{Other.Home}/Library/Preferences",
"/Library/Application Support",
"/Library/Preferences"
},
new string[] { "/etc/xdg" }
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/CacheHome'/>
public static string CacheHome
{
get =>
Helpers.OS(
"XDG_CACHE_HOME",
GetEnvironmentVariable("LOCALAPPDATA") is not null
? $"{GetEnvironmentVariable("LOCALAPPDATA")}\\cache"
: $"{GetFolderPath(SpecialFolder.LocalApplicationData)}\\cache",
$"{Other.Home}/Library/Caches",
$"{Other.Home}/.cache"
)!;
}
/// <include file='docs/BaseDirectory.xml' path='docs/RuntimeDir'/>
public static string RuntimeDir
{
get =>
Helpers.OS(
"XDG_RUNTIME_DIR",
GetEnvironmentVariable("LOCALAPPDATA")
?? GetFolderPath(SpecialFolder.LocalApplicationData),
$"{Other.Home}/Library/Application Support",
$"/run/user/{GetEnvironmentVariable("UID")}"
)!;
}
}

View File

@ -0,0 +1,90 @@
#if NET7_0_OR_GREATER
#pragma warning disable CA1031 // General exceptions needed for handling errors
using System.Runtime.InteropServices;
namespace Xdg.Directories.FFI;
/// <summary>
/// Native library export wrappers
/// </summary>
internal static partial class Exports
{
[UnmanagedCallersOnly(EntryPoint = "xdg_data_home")]
public static IntPtr DataHome()
{
try
{
return StringToPtr(BaseDirectory.DataHome);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_config_home")]
public static IntPtr ConfigHome()
{
try
{
return StringToPtr(BaseDirectory.ConfigHome);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_state_home")]
public static IntPtr StateHome()
{
try
{
return StringToPtr(BaseDirectory.StateHome);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_bin_home")]
public static IntPtr BinHome()
{
try
{
return StringToPtr(BaseDirectory.BinHome);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_cache_home")]
public static IntPtr CacheHome()
{
try
{
return StringToPtr(BaseDirectory.CacheHome);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_runtime_dir")]
public static IntPtr RuntimeDir()
{
try
{
return StringToPtr(BaseDirectory.RuntimeDir);
}
catch
{
return IntPtr.Zero;
}
}
}
#endif

View File

@ -0,0 +1,23 @@
#if NET7_0_OR_GREATER
using System.Runtime.InteropServices;
namespace Xdg.Directories.FFI;
internal static partial class Exports
{
/// <summary>
/// Frees the specified pointer
/// </summary>
/// <remarks>
/// CALL THIS EVERY SINGLE TIME YOU USE SOMETHING FROM THIS LIBRARY!!!!!! <br />
/// You <em>will</em> leak memory otherwise.
/// </remarks>
/// <param name="p">The .NET Pointer to free</param>
[UnmanagedCallersOnly(EntryPoint = "xdg_free")]
public static void Free(IntPtr p)
=> Marshal.FreeCoTaskMem(p);
internal static IntPtr StringToPtr(string? str)
=> Marshal.StringToCoTaskMemUTF8(str);
}
#endif

View File

@ -0,0 +1,21 @@
#if NET7_0_OR_GREATER
#pragma warning disable CA1031 // General exceptions needed for handling errors
using System.Runtime.InteropServices;
namespace Xdg.Directories.FFI;
internal static partial class Exports
{
[UnmanagedCallersOnly(EntryPoint = "xdg_user_home")]
public static IntPtr UserHome()
{
try
{
return StringToPtr(Other.Home);
}
catch
{
return IntPtr.Zero;
}
}
}
#endif

View File

@ -0,0 +1,112 @@
#if NET7_0_OR_GREATER
#pragma warning disable CA1031 // General exceptions needed for handling errors
using System.Runtime.InteropServices;
namespace Xdg.Directories.FFI;
internal static partial class Exports
{
[UnmanagedCallersOnly(EntryPoint = "xdg_desktop_dir")]
public static IntPtr Desktop()
{
try
{
return StringToPtr(UserDirectory.DesktopDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_download_dir")]
public static IntPtr Download()
{
try
{
return StringToPtr(UserDirectory.DownloadDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_documents_dir")]
public static IntPtr Documents()
{
try
{
return StringToPtr(UserDirectory.DocumentsDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_music_dir")]
public static IntPtr Music()
{
try
{
return StringToPtr(UserDirectory.MusicDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_pictures_dir")]
public static IntPtr Pictures()
{
try
{
return StringToPtr(UserDirectory.PicturesDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_videos_dir")]
public static IntPtr Videos()
{
try
{
return StringToPtr(UserDirectory.VideosDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_templates_dir")]
public static IntPtr Templates()
{
try
{
return StringToPtr(UserDirectory.TemplatesDir);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "xdg_public_dir")]
public static IntPtr Public()
{
try
{
return StringToPtr(UserDirectory.PublicDir);
}
catch
{
return IntPtr.Zero;
}
}
}
#endif

View File

@ -0,0 +1,57 @@
#ifndef XDG_DOTNET_H
#define XDG_DOTNET_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
// XDG directory specifications API
//
// Wrapper for XDG directories
typedef uintptr_t xdg_directory;
// The current user's home directory
xdg_directory xdg_user_home(void);
// Base directories
xdg_directory xdg_data_home(void);
xdg_directory xdg_config_home(void);
xdg_directory xdg_state_home(void);
xdg_directory xdg_bin_home(void);
xdg_directory xdg_cache_home(void);
xdg_directory xdg_runtime_dir(void);
// User directories
xdg_directory xdg_desktop_dir(void);
xdg_directory xdg_download_dir(void);
xdg_directory xdg_documents_dir(void);
xdg_directory xdg_music_dir(void);
xdg_directory xdg_pictures_dir(void);
xdg_directory xdg_videos_dir(void);
xdg_directory xdg_templates_dir(void);
xdg_directory xdg_public_dir(void);
// Frees the directory object.
void xdg_free(xdg_directory);
#endif // !XDG_DOTNET_H
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,10 @@
prefix=/usr/local
exec_prefix=${prefix}
includedir=${prefix}/include
libdir=${exec_prefix}/lib
Name: xdg
Description: xdg directory library
Version: 1.0.0
Libs: -L${libdir} -lxdg
Cflags: -I${includedir}

View File

@ -0,0 +1,17 @@
PREFIX ?= /usr/local
LIB ?= lib64
BASE ?= bin/Release/$(NETVERSION)/linux-x64/publish
.PHONY: install
install:
sed -i 's|prefix=.*|prefix=$(PREFIX)|' $(BASE)/xdg.pc
install -Dm755 $(BASE)/libxdg.so $(PREFIX)/$(LIB)
install -Dm644 $(BASE)/xdg.pc $(PREFIX)/$(LIB)/pkgconfig
install -Dm644 $(BASE)/include/xdg.h $(PREFIX)/include
.PHONY: uninstall
uninstall:
rm $(PREFIX)/$(LIB)/libxdg.so
rm $(PREFIX)/$(LIB)/pkgconfig/xdg.pc
rm $(PREFIX)/include/xdg.h

View File

@ -0,0 +1,70 @@
using System.Runtime.InteropServices;
namespace Xdg.Directories;
static internal class Helpers
{
/// <summary>
/// Return a specified value depending on the running operating system
/// </summary>
/// <param name="Env">Environment variable to test initially</param>
/// <param name="Windows">Windows directory</param>
/// <param name="MacOS">macOS Directory</param>
/// <param name="Unix">Linux/BSD Directory</param>
/// <returns><c>Env</c> if set, otherwise variable depending on operating system</returns>
/// <exception cref="NotSupportedException">If running on another operating system</exception>
internal static string? OS(string Env, string? Windows, string? MacOS, string? Unix)
{
string? env = GetEnvironmentVariable(Env);
if (env is not null)
return env;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return Windows;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return MacOS;
#if NETSTANDARD
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
#elif NET
else if (OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD())
#endif
return Unix;
else
throw new NotSupportedException("Platforms not supported by .NET Standard are not supported.");
}
/// <summary>
/// Return a specified value depending on the running operating system
/// </summary>
/// <param name="Env">Environment variable to test initially</param>
/// <param name="Windows">Windows directories</param>
/// <param name="MacOS">macOS Directories</param>
/// <param name="Unix">Linux/BSD Directories</param>
/// <returns><c>Env</c> if set, otherwise variable depending on operating system</returns>
/// <exception cref="NotSupportedException">If running on another operating system</exception>
internal static IList<string>? OS(string Env, IList<string>? Windows, IList<string>? MacOS, IList<string>? Unix)
{
string? env = GetEnvironmentVariable(Env);
if (env is not null)
return env.Split(':')!;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return Windows;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return MacOS;
#if NETSTANDARD
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
#elif NET
else if (OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD())
#endif
return Unix;
else
throw new NotSupportedException("Platforms not supported by .NET Standard are not supported.");
}
/// <summary>
/// Returns B if and only if A is empty.
/// </summary>
/// <param name="A">Value to test</param>
/// <param name="B">Alternative if A is null or empty</param>
/// <returns>B if A is null or empty, A if not</returns>
internal static string AorB(string A, string B)
=> A is { Length: 0 } ? B : A;
}

View File

@ -0,0 +1,78 @@
namespace Xdg.Directories;
/// <include file='docs/Other.xml' path='docs/Other'/>
public static class Other
{
/// <include file='docs/Other.xml' path='docs/Home'/>
public static string Home
{
get
{
// Unix ?? Windows
string? home =
GetEnvironmentVariable("HOME")
?? GetEnvironmentVariable("USERPROFILE");
if (home is not null)
return home;
else
return GetFolderPath(SpecialFolder.UserProfile);
}
}
/// <include file='docs/Other.xml' path='docs/Applications'/>
public static IList<string> Applications
{
get =>
Helpers.OS(
"",
new string[]
{
GetFolderPath(SpecialFolder.Programs),
GetFolderPath(SpecialFolder.CommonPrograms)
},
new string[] { "/Applications" },
new string[]
{
$"{BaseDirectory.DataHome}/applications",
$"{Home}/.local/share/applications",
"/usr/local/share/applications",
"/usr/share/applications",
// TODO: Add $XDG_DATA_DIRS/applications
}
)!;
}
/// <include file='docs/Other.xml' path='docs/Fonts'/>
public static IList<string> Fonts
{
get =>
Helpers.OS(
"",
new string[]
{
GetEnvironmentVariable("SystemRoot") is not null
? $"{GetEnvironmentVariable("SystemRoot")}\\Fonts"
: GetFolderPath(SpecialFolder.Fonts),
GetEnvironmentVariable("LOCALAPPDATA") is not null
? $"{GetEnvironmentVariable("LOCALAPPDATA")}\\Microsoft\\Windows\\Fonts"
: $"{GetFolderPath(SpecialFolder.LocalApplicationData)}\\Microsoft\\Windows\\Fonts"
},
new string[]
{
$"{Home}/Library/Fonts",
"/Library/Fonts",
"/System/Library/Fonts",
"/Network/Library/Fonts"
},
new string[]
{
$"{BaseDirectory.DataHome}/fonts",
$"{Home}/.fonts",
$"{Home}/.local/share/fonts",
"/usr/local/share/fonts",
"/usr/share/fonts",
// TODO: Add $XDG_DATA_DIRS/fonts
}
)!;
}
}

View File

@ -0,0 +1,101 @@
namespace Xdg.Directories;
/// <include file='docs/UserDirectory.xml' path='docs/UserDirectory'/>
public static class UserDirectory
{
/// <include file='docs/UserDirectory.xml' path='docs/DesktopDir'/>
public static string DesktopDir
{
get =>
Helpers.OS(
"XDG_DESKTOP_DIR",
GetFolderPath(SpecialFolder.Desktop),
$"{Other.Home}/Desktop",
$"{Other.Home}/Desktop"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/DownloadDir'/>
public static string? DownloadDir
{
get =>
Helpers.OS(
"XDG_DOWNLOAD_DIR",
null, // TODO: Actually Implement?
$"{Other.Home}/Downloads",
$"{Other.Home}/Downloads"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/DocumentsDir'/>
public static string DocumentsDir
{
get =>
Helpers.OS(
"XDG_DOCUMENTS_DIR",
GetFolderPath(SpecialFolder.MyDocuments),
$"{Other.Home}/Documents",
$"{Other.Home}/Documents"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/MusicDir'/>
public static string MusicDir
{
get =>
Helpers.OS(
"XDG_MUSIC_DIR",
GetFolderPath(SpecialFolder.MyMusic),
$"{Other.Home}/Music",
$"{Other.Home}/Music"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/PicturesDir'/>
public static string PicturesDir
{
get =>
Helpers.OS(
"XDG_PICTURES_DIR",
GetFolderPath(SpecialFolder.MyPictures),
$"{Other.Home}/Pictures",
$"{Other.Home}/Pictures"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/VideosDir'/>
public static string VideosDir
{
get =>
Helpers.OS(
"XDG_VIDEOS_DIR",
GetFolderPath(SpecialFolder.MyVideos),
$"{Other.Home}/Movies",
$"{Other.Home}/Videos"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/TemplatesDir'/>
public static string TemplatesDir
{
get =>
Helpers.OS(
"XDG_TEMPLATES_DIR",
GetFolderPath(SpecialFolder.Templates),
$"{Other.Home}/Templates",
$"{Other.Home}/Templates"
)!;
}
/// <include file='docs/UserDirectory.xml' path='docs/PublicDir'/>
public static string PublicDir
{
get =>
Helpers.OS(
"XDG_PUBLICSHARE_DIR",
GetEnvironmentVariable("PUBLIC"),
$"{Other.Home}/Public",
$"{Other.Home}/Public"
)!;
}
}

View File

@ -0,0 +1 @@
global using static System.Environment;

View File

@ -0,0 +1,110 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup Condition="'$(CI)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
<PropertyGroup Label="SDK Stuff">
<TargetFrameworks>net7.0;netstandard2.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<IsPackable>true</IsPackable>
<IsTrimmable>true</IsTrimmable>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<EnableNETAnalyzers>True</EnableNETAnalyzers>
<AnalysisLevel>latest-all</AnalysisLevel>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<RestoreLockedMode Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</RestoreLockedMode>
</PropertyGroup>
<PropertyGroup Label="NuGet Packaging">
<Title>Xdg.Directories.Net</Title>
<Description>.NET implementation of the XDG Base Directory Specification and user
directories</Description>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageTags>xdg;base-directories;base-directory;xdg-base-directory;</PackageTags>
<RepositoryType>git</RepositoryType>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<MinVerDefaultPreReleaseIdentifiers>preview.0</MinVerDefaultPreReleaseIdentifiers>
</PropertyGroup>
<PropertyGroup Label="NativeAOT">
<PublishAot>True</PublishAot>
<StripSymbols>True</StripSymbols>
<TrimMode>Link</TrimMode>
<RootAllApplicationAssemblies>false</RootAllApplicationAssemblies>
<IlcGenerateStackTraceData>false</IlcGenerateStackTraceData>
<IlcDisableUnhandledExceptionExperience>true</IlcDisableUnhandledExceptionExperience>
<IlcGenerateCompleteTypeMetadata>false</IlcGenerateCompleteTypeMetadata>
<IlcTrimMetadata>true</IlcTrimMetadata>
<IlcFoldIdenticalMethodBodies>true</IlcFoldIdenticalMethodBodies>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<!-- The holy grail of size reduction - would cut the library's size in half, but doesn't
work -->
<!--<IlcDisableReflection>true</IlcDisableReflection>-->
</PropertyGroup>
<PropertyGroup
Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net7.0|AnyCPU'">
<WarningLevel>9999</WarningLevel>
</PropertyGroup>
<PropertyGroup
Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net7.0|AnyCPU'">
<WarningLevel>9999</WarningLevel>
</PropertyGroup>
<PropertyGroup
Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'">
<WarningLevel>9999</WarningLevel>
</PropertyGroup>
<PropertyGroup
Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|netstandard2.0|AnyCPU'">
<WarningLevel>9999</WarningLevel>
</PropertyGroup>
<ItemGroup Label="Extra files">
<None Include="..\..\LICENSE" Visible="false">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<!--FFI-->
<None Remove="FFI\include\xdg.h" />
<None Include="FFI\include\xdg.h">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Link>include\%(Filename)%(Extension)</Link>
</None>
<None Remove="FFI\xdg.pc" />
<None Include="FFI\xdg.pc">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Link>%(Filename)%(Extension)</Link>
</None>
</ItemGroup>
<ItemGroup Label="NuGet Packages">
<PackageReference Include="Microsoft.SourceLink.Gitea" Version="1.1.1" PrivateAssets="All" />
<SourceLinkGiteaHost Include="git.froth.zone" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="MinVer" Version="4.3.0">