workspace

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2022 License: MIT Imports: 7 Imported by: 0

README

go-workspace

Simplify the platform-aware access to the Cache, Config, Home, Workspace, and Temp folders for a Go application

Go Reference Go Module

AboutBuilt WithPrerequisitesInstallationUsageContributingDonateLicense

About

go-workspace is a Go package to simplify the access to the Cache, Config, Home, Workspace, and Temp folders for an application. It uses common settings for Unix, macOS, Plan 9, and Windows. In addition, it supports the substitution of configurable keywords, such as $CACHE, $HOME, $workspaceRoot, and $TEMP. Finally, go-workspace sets the workspace folder to the correct path when ran from source.

Built With

The project uses the following core software components:

  • Testify - Go unit-testing toolkit with common assertions and mocks.

Prerequisites

go-workspace requires Go version 1.16 or later to be installed on your system.

Installation

go get -u go.markdumay.org/workspace

Usage

Import go-workspace into your application to start using the package. The following code snippet illustrates the basic usage of go-workspace. Please refer to the package documentation for more details.

	const appName = "my_app"

	// initialize the application directories
	dirs, e := NewAppDirs(appName)
	if e != nil {
		fmt.Println("ERROR: cannot initialize application directories")
		os.Exit(1)
	}

	// show the cache directory for 'user', expected output (macOS):
	// /Users/user/Library/Caches/my_app
	fmt.Println(dirs.Cache())

	// show the absolute path of 'test' relative to the home directory, expected output (macOS):
	// /Users/user/test
	fmt.Println(dirs.MakeAbsolute(dirs.Workspace(), "$HOME/test"))

	// show the path of a custom keyword, expected output (macOS):
	// $MYDIR
	w, e := NewDir(Workspace, appName, WithPath("/mydir"), WithAliases([]string{"$MYDIR"}))
	if e != nil {
		fmt.Println("ERROR: cannot initialize workspace directory")
		os.Exit(1)
	}
	dirs.Assign(*w)
	fmt.Println(dirs.Parameterize(dirs.Workspace(), "/mydir"))
Supported Folders

go-workspace supports the following five types of folders.

Type Description
Cache User-specific cache directory
Config Current directory (when running from console) or project root (when running from source)
Home User home directory
Workspace Current directory (when running from console) or project root (when running from source)
Temp Temp directory

Unfold one of the below operating systems to see the mapping of the folders to their physical location. The locations are prioritized from left to right in case multiple locations are specified.

Unix
Type Default location
Cache $XDG_CACHE_HOME/$APP_NAME or $HOME/.cache/$APP_NAME
Config $PWD
Home $HOME/.$APP_NAME
Workspace $PWD
Temp $TMPDIR or /tmp
macOS
Type Default location
Cache $HOME/Library/Caches/$APP_NAME
Config $PWD
Home $HOME/.$APP_NAME
Workspace $PWD
Temp $TMPDIR or /tmp
Plan 9
Type Default location
Cache $home/lib/cache/$APP_NAME
Config $pwd
Home $home/.$APP_NAME
Workspace $pwd
Temp /tmp
Windows
Type Default location
Cache %LocalAppData%\$APP_NAME
Config %cd%
Home %HOME%\$APP_NAME, %HOMEDRIVE%\$APP_NAME, %HOMEPATH%\$APP_NAME, or %USERPROFILE%\$APP_NAME
Workspace %cd%
Temp %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory

Contributing

go-workspace welcomes contributions of any kind. It is recommended to create an issue to discuss your intended contribution before submitting a larger pull request though. Please consider the following guidelines when contributing:

  • Address all linting recommendations from golangci-lint run (using .golangci.yml from the repository).
  • Ensure the code is covered by one or more unit tests (using Testify when applicable).
  • Follow the recommendations from Effective Go and the Uber Go Style Guide.

The following steps decribe how to submit a Pull Request:

  1. Clone the repository and create a new branch
    $ git checkout https://github.com/markdumay/go-workspace.git -b name_for_new_branch
    
  2. Make and test the changes
  3. Submit a Pull Request with a comprehensive description of the changes

Donate

Buy Me A Coffee

License

The go-workspace codebase is released under the MIT license. The documentation (including the "README") is licensed under the Creative Commons (CC BY-NC 4.0) license.

Documentation

Overview

Package workspace is a Go package to simplify the access to the Cache, Config, Home, Workspace, and Temp folders for an application. It uses common settings for Unix, macOS, Plan 9, and Windows. In addition, it supports the substitution of configurable keywords, such as $CACHE, $HOME, $workspaceRoot, and $TEMP. Finally, go-workspace sets the workspace folder to the correct path when ran from source.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbsPath

func AbsPath(base string, path string) string

AbsPath returns the absolute path for a given base path and path. If path is relative it is joined with the base path, otherwise the path itself is returned. AbsPath calls filepath.Clean on the result. The special character "~" is expanded to the user's home directory (if set as prefix).

func Root

func Root(appName string) (path string, err error)

Root returns the working directory of the repository or the running command. In debugging mode, the current working directory may actually be a sub directory, such as 'src' or 'cmd'. In these cases, the workspace root is set to the nearest parent directory containing a ".git" repository. When running a compiled binary, the function returns the current working directory.

Types

type AppDirs

type AppDirs struct {
	// contains filtered or unexported fields
}

AppDirs holds a reference to the initialized directories for the application cache, configuration directory, home directory, workspace directory, and the application's temp directory.

func NewAppDirs

func NewAppDirs(appName string) (dirs *AppDirs, err error)

NewAppDirs initializes a AppDirs type with default values for the application-specific cache, config, home, temp, and workspace directories. Default aliases are added to enable keyword expansion. The keywords follow POSIX string expansion rules, using "$" as sigil and optional braces. The following keywords are supported: $HOME, $CACHE, $PWD, $TEMP, $TMP, $TMPDIR, $TEMPDIR, and $workspaceRoot. The special character '~' is expanded to the home directory (unless the OS is Windows).

func (*AppDirs) Assign

func (a *AppDirs) Assign(d Dir)

Assign initializes a new application-specific directory and updates the internal keyword map to enable parameterization of paths. Default aliases are added when no aliases are provided. The full keyword map is updated when an existing entry is updated, otherwise the new keywords are appended. Assign does not check for potential duplicate keywords.

func (*AppDirs) Cache

func (a *AppDirs) Cache() string

Cache retrieves the current cache directory. It returns an empty string if the directory is not set. Use Assign() to initialize a new Cache directory.

func (*AppDirs) Config

func (a *AppDirs) Config() string

Config retrieves the current config directory. It returns an empty string if the directory is not set. Use Assign() to initialize a new Config directory.

func (*AppDirs) CreateTemp

func (a *AppDirs) CreateTemp() (err error)

CreateTemp creates the application's temp directory, with mode set to 0755. Nothing happens if the directory already exists.

func (*AppDirs) Home

func (a *AppDirs) Home() string

Home retrieves the current home directory. It returns an empty string if the directory is not set. Use Assign() to initialize a new Home directory.

func (*AppDirs) MakeAbsolute

func (a *AppDirs) MakeAbsolute(basePath string, input string) (path string)

MakeAbsolute returns the absolute path for a given input. It replaces supported keywords with their replacement values and converts a relative path to an absolute path. MakeAbsolute calls filepath.Clean on the result.

func (*AppDirs) MakeRelative

func (a *AppDirs) MakeRelative(basePath string, input string) (path string)

MakeRelative returns the path for a given input relative to a base path. It replaces supported keywords with their replacement values. If input cannot be made relative to the base path, the input itself is returned as result. MakeRelative calls filepath.Clean on the result.

func (*AppDirs) Parameterize

func (a *AppDirs) Parameterize(basePath string, input string) (path string)

Parameterize returns the path for a given input relative to the provided base directory, if applicable. Matched path segments are replaced with their parameter alias. A non-deterministic match is returned in case of duplicate keywords. The first alias is returned when multiple aliases are defined for a directory. Parameterize calls filepath.Clean on the result.

func (*AppDirs) RecreateTemp

func (a *AppDirs) RecreateTemp(subdir string) (err error)

RecreateTemp recreates a subdirectory of the application's temp directory, deleting all existing files. Leave subdir empty to recreate the entire application's temp directory. It uses RemoveTempDir to safely remove the directory. The mode is set to 0755.

func (*AppDirs) RemoveTemp

func (a *AppDirs) RemoveTemp(subdir string) (err error)

RemoveTemp removes the configured temp dir, deleting all existing files. It uses a failsafe to ensure the configured temp dir is valid and within the scope of the system's default temp directory. The expected base paths are '$TMPDIR' (on Unix or macOS) or '/tmp' (on Unix, macOS or Plan 9). On Windows, the directories can be either '%TMP%' or '%TEMP%'.

func (*AppDirs) Temp

func (a *AppDirs) Temp() string

Temp retrieves the current temp directory. It returns an empty string if the directory is not set. Use Assign() to initialize a new Temp directory.

func (*AppDirs) Workspace

func (a *AppDirs) Workspace() string

Workspace retrieves the current workspace directory. It returns an empty string if the directory is not set. Use Assign() to initialize a new Workspace directory.

type Dir

type Dir struct {
	// contains filtered or unexported fields
}

Dir holds a reference to a specific application directory and it's aliases (keywords).

func NewDir

func NewDir(dirType DirType, appName string, opts ...Option) (dir *Dir, err error)

NewDir creates a new Dir instance for the provided arguments. NewDir supports two optional parameters, set by WithAliases and WithPath respectively. WithAliases associates specific aliases with the application directory. WithPath initializes the application directory for a specific path. If omitted, both parameters revert to a default value pending the dir type.

func (*Dir) Aliases

func (d *Dir) Aliases() (a []string)

Aliases retrieves a collection of the aliases (keywords) associated with a directory.

func (*Dir) AppendAliases

func (d *Dir) AppendAliases(aliases ...string)

AppendAliases appends one or more aliases to the collection of aliases (keywords) associated with a directory.

func (*Dir) DirType

func (d *Dir) DirType() DirType

DirType retrieves the type of configured directory, either Cache, Config, Home, Workspace, or Temp.

func (*Dir) Path

func (d *Dir) Path() string

Path retrieves the absolute path associated with the directory.

func (*Dir) RemoveAliases

func (d *Dir) RemoveAliases(aliases ...string)

RemoveAliases removes one or more aliases from the collection of aliases. Unrecognized aliases are ignored.

type DirType

type DirType int

DirType defines the type of directory to be configured.

const (
	// Cache is the OS's user-specific cache directory. On Unix, this is either '$XDG_CACHE_HOME' or '$HOME/.cache'. On
	// macOS, this is '$HOME/Library/Caches'. On Plan 9, the cache directory is '$home/lib/cache'. And lastly, on
	// Windows the cache directory is derived from '%LocalAppData%'.
	Cache DirType = iota + 1

	// Config is the directory containing the main application configuration file, if any. It is derived from
	// viper.ConfigFileUsed().
	Config

	// Home is the default, fully expanded user home directory.
	Home

	// Workspace is working directory of the repository or the running command. It is typically initialized by
	// WorkspaceRoot().
	Workspace

	// Temp is the OS-specific temp directory used by ShellDoc. The path is set to either '$TMPDIR' (on Unix or macOS)
	// or '/tmp' (on Unix, macOS or Plan 9). On Windows, the directory can be either '%TMP%', '%TEMP%',
	// '%USERPROFILE%', or the Windows directory.
	//
	// The path is not guaranteed to exist. Use RecreateTempDir() to recreate the directory prior to accessing it, and
	// use RemoveTempDir() once done.
	Temp
)

Defines a pseudo enumeration of possible application directories.

func (DirType) String

func (d DirType) String() string

String converts a directory type to it's string representation.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option defines an optional argument for creating new application directory.

func WithAliases

func WithAliases(aliases []string) Option

WithAliases associates optional aliases to be used by the application directory. A default value is used if omitted.

func WithPath

func WithPath(path string) Option

WithPath associates an optional path to be used by the application directory. A default value is used if omitted.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL