Coder Social home page Coder Social logo

known-folders's Introduction

Zig Known Folders Project

Design Goals

  • Minimal API surface
  • Provide the user with an option to either obtain a directory handle or a path name
  • Keep to folders that are available on all operating systems

API

pub const KnownFolder = enum {
    home,
    documents,
    pictures,
    music,
    videos,
    desktop,
    downloads,
    public,
    fonts,
    app_menu,
    cache,
    roaming_configuration,
    local_configuration,
    global_configuration,
    data,
    runtime,
    executable_dir,
};

pub const Error = error{ ParseError, OutOfMemory };

pub const KnownFolderConfig = struct {
    xdg_force_default: bool = false,
    xdg_on_mac: bool = false,
};

/// Returns a directory handle, or, if the folder does not exist, `null`.
pub fn open(allocator: std.mem.Allocator, folder: KnownFolder, args: std.fs.Dir.OpenOptions) (std.fs.Dir.OpenError || Error)!?std.fs.Dir;

/// Returns the path to the folder or, if the folder does not exist, `null`.
pub fn getPath(allocator: std.mem.Allocator, folder: KnownFolder) Error!?[]const u8;

Installation

Initialize a zig build project if you haven't already.

zig init

Add the known-folders package to your build.zig.zon.

zig fetch --save git+https://github.com/ziglibs/known-folders.git

You can then import known-folders in your build.zig with:

const known_folders = b.dependency("known-folders", .{}).module("known-folders");
const exe = b.addExecutable(...);
// This adds the known-folders module to the executable which can then be imported with `@import("known-folders")`
exe.root_module.addImport("known-folders", known_folders);

Configuration

In your root file, add something like this to configure known-folders:

pub const known_folders_config = .{
    .xdg_on_mac = true,
}

known-folders's People

Contributors

antlilja avatar der-teufel-programming avatar flaminator avatar ikskuh avatar joachimschmidt557 avatar kcbanner avatar kristoff-it avatar leecannon avatar lordmzte avatar magejohn avatar mattnite avatar minebill avatar mochalins avatar nektro avatar nycex avatar superauguste avatar tau-dev avatar techatrix avatar thechampagne avatar vrischmann avatar weskoerber avatar xdbronch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

known-folders's Issues

Tag released versions

Please use upload git tags referring to milestones of this project. It makes it easier to package this project.
Also, I believe you should update the project version in the build.zig.zon file.

XDG_CONFIG_DIRS interpreted incorrectly

Most XDG base directory envvars just point to a single directory, but XDG_CONFIG_DIRS is a search path - currently it's expected to contain a single directory instead. The default value is also set to /etc/, while the XDG spec calls for /etc/xdg.

Given the name global_configuration I'd guess we should just use /etc here.

Build error on windows

When building ZLS on windows, the following error comes from known-folders:

C:\Users\Martin\Projects\zls>zig build -Drelease-safe
C:\Program Files\Zig\Current\lib\std\mem.zig:664:19: error: deprecated; use use std.mem.span() or std.mem.sliceTo()
pub const spanZ = @compileError("deprecated; use use std.mem.span() or std.mem.sliceTo()");
                  ^
.\src\known-folders\known-folders.zig:72:97: note: referenced here
                            const global_dir = std.unicode.utf16leToUtf8Alloc(allocator, std.mem.spanZ(dir_path_ptr)) catch |err| switch (err) {
                                                                                                ^
zls...The following command exited with error code 1:

Run Tests

Run test on the following machines:

  • Windows 7 (x86_64, German)
  • Windows 10 (x86_64, German)
  • Windows 10 (x86_64, US/English) (thanks @alexnask)
  • Ubuntu 20.04 LTS (x86_64, German)
  • Manjaro Latest (x86_64, US/English)
  • macOS Catalina (Version 10.15.5, Build 19F53f) (thanks @haze)

Implement Windows Support

 var dir_path_ptr: [*:0]u16 = undefined;
            switch (os.windows.shell32.SHGetKnownFolderPath(
                &os.windows.FOLDERID_LocalAppData,
                os.windows.KF_FLAG_CREATE,
                null,
                &dir_path_ptr,
            )) {
                os.windows.S_OK => {
                    defer os.windows.ole32.CoTaskMemFree(@ptrCast(*c_void, dir_path_ptr));
                    const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.spanZ(dir_path_ptr)) catch |err| switch (err) {
                        error.UnexpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,
                        error.ExpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,
                        error.DanglingSurrogateHalf => return error.AppDataDirUnavailable,
                        error.OutOfMemory => return error.OutOfMemory,
                    };
                    defer allocator.free(global_dir);
                    return fs.path.join(allocator, &[_][]const u8{ global_dir, appname });
                },
                os.windows.E_OUTOFMEMORY => return error.OutOfMemory,
                else => return error.AppDataDirUnavailable,
            }

Breaking change with InvalidUtf8 as zig introduces Wtf8

Running into this issue on Windows building ZLS nightly (as uses the latest known-folders.zig), on zig nightly (as of 6c2eb0f131588be111652a755a4492ff72d16440 but built with 0.12.0-dev.3008+b2374c4d7).

Since zig upstream has adopted Wtf8 for better Windows support, it's breaking some error handling downstream, and InvalidUtf8 is no longer used on Windows (i.e. with InvalidWtf8 it's become a WASI only error for now) which hasn't been properly documented with a release (yet, but the merge ziglang/zig#19005 has the summary of changes).

This isn't critical yet, as ZLS naturally also needs time to update, plus it's only been two days, but best to have an issue that people can at least see is there before figuring out support for 0.12. Similar to ZLS figuring out their backwards compatibility (zigtools/zls#1020) I suspect known-folders will have to make some considerations here as well, especially with breaking changes like this, though this isn't an issue for that discussion.

> zig build
install
└─ install zls
   └─ zig build-exe zls Debug native 1 errors
C:\Users\alexb\AppData\Local\zig\p\12209925016f4b5486a713828ead3bcc900fa4f039c93de1894aa7d5253f7633b92c\known-folders.zig:100:29: error: expected type 'error{OutOfMemory,InvalidWtf8,EnvironmentVariableNotFound}', found 'error{InvalidUtf8}'
                            error.InvalidUtf8 => return null,
                            ^~~~~~~~~~~~~~~~~
C:\Users\alexb\AppData\Local\zig\p\12209925016f4b5486a713828ead3bcc900fa4f039c93de1894aa7d5253f7633b92c\known-folders.zig:100:29: note: 'error.InvalidUtf8' not a member of destination error set
referenced by:
    comptime_0: C:\Users\alexb\AppData\Local\zig\p\12209925016f4b5486a713828ead3bcc900fa4f039c93de1894aa7d5253f7633b92c\known-folders.zig:339:9
    remaining reference traces hidden; use '-freference-trace' to see all reference traces
error: the following command failed with 1 compilation errors:
C:\bin\zig\zig.exe build-exe -ODebug --dep exe_options --dep tracy --dep known-folders --dep zls -Mroot=C:\code\zig\zls\src\main.zig -Mexe_options=C:\code\zig\zls\zig-cache\c\0b9c30ddea2c61b29aa9971e1deb8de5\options.zig -ODebug --dep options -Mtracy=C:\code\zig\zls\src\tracy.zig -Mknown-folders=C:\Users\alexb\AppData\Local\zig\p\12209925016f4b5486a713828ead3bcc900fa4f039c93de1894aa7d5253f7633b92c\known-folders.zig --dep known-folders --dep diffz --dep tracy --dep build_options --dep version_data -Mzls=C:\code\zig\zls\src\zls.zig -Moptions=C:\code\zig\zls\zig-cache\c\85d0d8879cce6839a2a4dcf23c53e5d5\options.zig -Mdiffz=C:\Users\alexb\AppData\Local\zig\p\12200d71e4b7029ea56a429e24260c6c0e85a3069b0d4ba85eace21a0fd75910aa64\DiffMatchPatch.zig -Mbuild_options=C:\code\zig\zls\zig-cache\c\7e53829d1ea0122006493119e8b9b4f7\options.zig -Mversion_data=C:\code\zig\zls\zig-cache\o\328408cdc1d92dec548fab4d92e87b51\version_data_master_19780.zig --cache-dir C:\code\zig\zls\zig-cache --global-cache-dir C:\Users\alexb\AppData\Local\zig --name zls --listen=-
Build Summary: 5/8 steps succeeded; 1 failed (disable with --summary none)
install transitive failure
└─ install zls transitive failure
   └─ zig build-exe zls Debug native 1 errors
error: the following build command failed with exit code 1:
C:\code\zig\zls\zig-cache\o\9f088f9bb5978bbefa45ac1174cba596\build.exe C:\bin\zig\zig.exe C:\code\zig\zls C:\code\zig\zls\zig-cache C:\Users\alexb\AppData\Local\zig --seed 0xadf294b1 -Z1c6b4bd0bfd2d3ca

Use build.zig.zon file

Zig now requires all packages to use the build.zig.zon file. Not having this makes this project unusable with with newer projects.

xdg dirs on mac

Some command line applications use the XDG Base Directory Specification also on mac.
Do we want to support this use case?

Detect the XDG runtime setting in env instead of configuration (on macOS)

For some compatibility reasons, I set my own XDG Base Directories. Not equal to default macOS folder suggestions.
I know there is a configuration to open XDG support on Mac, but some zig tools (such as zls ) don't provide a method to change it. If known-folders can read env and follow the XDG settings, will resolve this problem.

error: enum 'std.target.Tag' has no field named 'macosx'

On Zig 0.6.0+3ab4d112e on macOS, the zls build for zigtools/zls@e8c2035 breaks with the following error:

./src/known-folders/known-folders.zig:95:9: error: enum 'std.target.Tag' has no field named 'macosx'
        .macosx => {
        ^
/Users/jsolom206/meta/build/zig/build/lib/zig/std/target.zig:23:25: note: 'std.target.Tag' declared here
        pub const Tag = enum {
                        ^
./src/known-folders/known-folders.zig:50:5: note: referenced here
    switch (std.builtin.os.tag) {

This is easily resolved by correcting the enum value to macos:

https://github.com/ziglang/zig/blob/e02655798fbd97a069ee8be38a6eceac18335a4d/lib/std/target.zig#L34

This change was introduced in Zig by the following commit:

ziglang/zig@2ab0c73

`std.os.getenv` no longer usable on wasi

When targeting wasm32-wasi the below error is shown, this is due to ziglang/zig#17140.

The easy fix is to replace every usage of std.os.getenv in getPathXdg with std.process.getEnvVarOwned, but that would pessimize non-wasi.

$ zig test known-folders.zig -target wasm32-wasi -freference-trace
/home/lee/zig/0.12.0-dev.378+4f952c7e0/files/lib/std/os.zig:1912:9: error: std.os.getenv is unavailable for WASI. See std.process.getEnvMap or std.process.getEnvVarOwned for a cross-platform API.
        @compileError("std.os.getenv is unavailable for WASI. See std.process.getEnvMap or std.process.getEnvVarOwned for a cross-platform API.");
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
    getPathXdg: known-folders.zig:202:32

Fails on 0.9.1

Tried with Zig 0.9.1 on Windows 11 and got some deprecation compile errors.

/home/mark/zig-linux-x86_64-0.9.1/lib/std/builtin.zig:13:16: error: get this from @import("builtin") instead of std.builtin
pub const os = @compileError("get this from @import(\"builtin\") instead of std.builtin");

I went and find-replaced this, and ended up with some other errors like

/home/mark/zig-linux-x86_64-0.9.1/lib/std/target.zig:1322:25: error: instead of std.Target.current, use @import("builtin").target
    pub const current = @compileError("instead of std.Target.current, use @import(\"builtin\").target");
                        ^
/home/mark/zig-upaya/src/deps/sokol/build.zig:35:39: error: container 'std.zig.system' has no member called 'getSDKPath'
    const sdk_dir = try std.zig.system.getSDKPath(b.allocator);

Could not open /etc/xdg/xdg-pop:/etc/xdg: error.FileNotFound.

While running zls config it showed this error:

/zig-out/bin/zls config
Welcome to the ZLS configuration wizard!
      *
       |\
      /* \
      |  *\
    _/_*___|_    x
      | @ @     /
     @     \   /
      \__-/   /

? Should this configuration be system-wide? (y/n) > y
Could not open /etc/xdg/xdg-pop:/etc/xdg: error.FileNotFound.

Maybe this is the variable that is being used:

echo $XDG_CONFIG_DIRS 
/etc/xdg/xdg-pop:/etc/xdg

Implement Unix Support

basic structure:

        else => std.process.getEnvVarOwned(&path_arena.allocator, "XDG_CONFIG_HOME") catch |err| switch (err) {
            error.EnvironmentVariableNotFound => blk: {
                const home_dir = std.process.getEnvVarOwned(&path_arena.allocator, "HOME") catch {
                    try stderr.writeAll("Failed to get $HOME variable!\n");
                    return 1;
                };

                break :blk try std.fs.path.join(&path_arena.allocator, &[_][]const u8{ home_dir, ".config" });
            },
            else => return err,
        },

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.