gopath

package module
v0.0.0-...-83d01dc Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2016 License: MIT Imports: 5 Imported by: 4

README

gopath

A Go library for nicer ways to cope with errors while working on the filesystem.

Do the work first -- check for errors later.

This library realizes the recommondations from the blog.golang.org article Errors are values. For even more information, also have a look at Error handling and Go.

Build Status GoDoc

Usage

Instead of doing a lot of error handling between each step ...

var err error
var p = "/my/path/to/somewhere"

if p, err = filepath.Abs(p); err != nil {
  // handle error
}
if p, err = filepath.EvalSymlinks(p); err != nil {
  // handle error
}
if p, err = filepath.Rel(p, "/other/path"); err != nil {
  // handle error
}

// go on

...GoPath allows you to write the operations first, and do the error checking later.

var p = gopath.FromPath("/my/path/to/somewhere").Abs().EvalSymlinks().Rel(otherPath)

if p.HasErr() {
  // handle error
}

// go on

The idea: the GoPath object encapsulates a path and an error object. Now, as soon as an error occured, each operation turns to a no-op. That's why it suffices to check for errors in the end.

So, just import gopath and go ahead:

import "github.com/fxnn/gopath"

We don't pull thirdparty libs into your project.

Extensibility

GoPath has an extension mechanism that allows you to chain function calls with your own code. The first step is to define your own transformation function:

func normalizePath(p gopath.GoPath) gopath.GoPath {
	return p.Abs().Clean()
}

Now, you are able to use GoPath's Do method:

var p = gopath.FromPath("/some/path").Do(normalizePath)

Development

While this project embeds functions from the os, path and filepath packages, it is far from being complete. Pull requests are welcome!

Please note, that I split the functionality into several files. I hope you find their names to be quite self-explanatory. We have

  • gopath.go: typedef, constructor and elementary functions
  • err.go: functionality around error handling
  • transform.go: transformations from GoPath to GoPath objects
  • terminal.go: transformations from GoPath to other values
  • predicate.go: functions on GoPaths with boolean results
  • assert.go: assertions just return an error object if they fail

The GitHub project go-on/queue also provides a way for elegant error handling in Go, but is not restricted to path operations. It rather allows you to execute any sequence of functions with separated error handling. However, that approach needs some amount of extra code and may reduce code readability, while this GoPath aims to support a readable notation of path operations.

License (MIT)

Licensed under the MIT License, see LICENSE file for more information.

Documentation

Overview

Package gopath implements an alternative API to Go's path processing libraries. It implements the recommondations from the article https://blog.golang.org/errors-are-values. For even more information, also have a look at the article http://blog.golang.org/error-handling-and-go.

Idea

What's special to gopath is its ability to write code that processes paths in a fluent way, while doing the error handling later. This is possible by using the immutable object gopath.GoPath, which either represents a path, or an error.

var p1 = gopath.FromPath("/existing/file").Stat()
assert.Nil(p1.Err())

var p2 = gopath.FromPath("/doesnt/exist").Stat()
assert.NotNil(p2.Err())

All operations on an errorneous GoPath are no-ops, therefore the first error ever occured in a chain of operations will remain visible. This way, you can work with GoPaths like you would with any other object.

var p = gopath.FromPath("/my/path/to/somewhere").Abs().EvalSymlinks().Rel(otherPath)

if p.HasErr() {
	// handle error
}

// go on

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GoPath

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

GoPath is an immutable object, representing a computational stage in path processing. It might either represent a path after zero or more successfully executed operations, or it might represent an errorneous state after an operation that returned an error.

func Empty

func Empty() GoPath

Empty returns the empty GoPath.

func FromErr

func FromErr(err error) GoPath

FromErr constructs an errorneous GoPath instance.

func FromPath

func FromPath(p string) GoPath

FromPath constructs a GoPath instance with the given path.

func (GoPath) Abs

func (g GoPath) Abs() GoPath

Abs calls filepath.Abs() on the path.

If the path is already absolute, it returns the path itself. Otherwise, it returns an absolute representation of the path using the current working directory.

If an error occurs, it returns an errorneous GoPath.

func (GoPath) Append

func (g GoPath) Append(s string) GoPath

Append appends the given string to this GoPath. It doesn't use any separator, especially no slash.

If this GoPath is errorneous, it returns simply this GoPath.

func (GoPath) AssertExists

func (g GoPath) AssertExists() GoPath

AssertExists returns an errorneous path, iff a Stat() call fails, and sets the error value. Otherwise, it returns the GoPath itself.

Note that it seems wrong to only return an errorneous path when Stat() fails with an error that yields os.IsNotExist(err) == true, because a different error does not necessarily mean that the file does exist.

func (GoPath) Base

func (g GoPath) Base() string

func (GoPath) Clean

func (g GoPath) Clean() GoPath

Clean calls filepath.Clean(). It returns the shortest path equivalent to the given path. It might not return an errorneous GoPath, unless the given GoPath is already errorneous.

func (GoPath) ClearErr

func (g GoPath) ClearErr() GoPath

ClearErr returns a GoPath instance with the same fields as this instance, except for the err field being nil.

func (GoPath) Components

func (g GoPath) Components() []string

Components returns all path components in this gopath. That is, the path is split at each os.PathSeparator.

If this gopath is errorneous, it returns the empty array.

func (GoPath) Dir

func (g GoPath) Dir() GoPath

Dir calls path.Dir() and returns all but the last element of this GoPath, typically the directory containing the file or directory this path points to.

If this GoPath is errorneous, it returns simply this GoPath.

func (GoPath) Do

func (g GoPath) Do(transformer Transformer) GoPath

Do executes the transformer on this GoPath. It therefore is an extension point. For example, you could define a transformer like the following:

func normalizePath(p gopath.GoPath) gopath.GoPath {
    return p.Abs().Clean()
}

Now, you can invoke it using Do:

var p = gopath.FromPath("some/path").Do(normalizePath)

func (GoPath) Err

func (g GoPath) Err() error

Err returns the error represented by the GoPath. When the GoPath is not errorneous, it returns nil.

func (g GoPath) EvalSymlinks() GoPath

EvalSymlinks calls filepath.EvalSymlinks(). It evaluates any symlinks in the path.

If the path is relative, the result might be relative, too. If an error occurs, it returns an errorneous GoPath.

func (GoPath) Ext

func (g GoPath) Ext() string

func (GoPath) FileInfo

func (g GoPath) FileInfo() os.FileInfo

FileInfo calls Stat() on GoPath and returns the resulting FileInfo. When Stat() results in an error, or GoPath is already errorneous, the result is a zero interface. When the Stat() result is already cached inside the GoPath, Stat() is not called again.

func (GoPath) FileMode

func (g GoPath) FileMode() os.FileMode

FileMode returns g.FileInfo().Mode(), or 0, when FileInfo() fails.

func (GoPath) Glob

func (g GoPath) Glob() (matches []string, err error)

Glob calls filepath.Glob(string) and returns the matches and any possible error.

See also GlobAny(), if you just want one GoPath value. Especially it returns g.Err(), if this GoPath is errorneous.

func (GoPath) GlobAny

func (g GoPath) GlobAny() GoPath

GlobAny runs Glob() and selects the first match.

If any error occurs, it returns an errorneous GoPath. Note, that -- according to https://godoc.org/path/filepath#Glob -- this may only occur when the glob expression is not formatted correctly.

If there is no match, an empty GoPath is returned.

func (GoPath) HasErr

func (g GoPath) HasErr() bool

HasErr returns true iff the GoPath is errorneous. It returns false otherwise, including the empty GoPath.

func (GoPath) HasFileMode

func (g GoPath) HasFileMode(mode os.FileMode) bool

func (GoPath) IsDirectory

func (g GoPath) IsDirectory() bool

IsDirectory returns true iff we have no error and the path points to a directory.

func (GoPath) IsEmpty

func (g GoPath) IsEmpty() bool

IsEmpty returns true exactly iff this GoPath contains the empty path:

assert.True(gopath.FromPath("").IsEmpty())
assert.False(gopath.FromPath("/some/empty/file").IsEmpty())

Note, that this does not check the file size, contents or anything like this.

func (GoPath) IsExists

func (g GoPath) IsExists() bool

IsExists returns true iff we have no error and Stat() succeeds.

func (GoPath) IsRegular

func (g GoPath) IsRegular() bool
func (g GoPath) IsSymlink() bool

func (GoPath) IsTemporary

func (g GoPath) IsTemporary() bool

func (GoPath) Join

func (g GoPath) Join(other GoPath) GoPath

Join appends the other GoPath to this GoPath, separated by the operating systems path separator.

If this GoPath is errorneous, it returns simply this GoPath.

func (GoPath) JoinPath

func (g GoPath) JoinPath(p string) GoPath

Join appends the given path to this GoPath, separated by the operating systmes path separator.

If this GoPath is errorneous, it returns simply this GoPath.

func (GoPath) Path

func (g GoPath) Path() string

Path returns the path represented by the given GoPath object. If that GoPath is errorneous, a zero value is returned.

func (GoPath) PrependErr

func (g GoPath) PrependErr(prefix string) GoPath

PrependErr modifies this GoPath by prefixing its error text with the given string, followed by a colon and a space. When this GoPath doesn't have an err set, it is returned unchanged.

func (GoPath) Rel

func (g GoPath) Rel(targpath GoPath) GoPath

Rel returns the other (targpath) GoPath, expressed as path relative to this GoPath.

var base = gopath.FromPath("/a")
var target = gopath.FromPath("/b/c")
var rel = base.Rel(target)

assert.Equal(rel.Path(), "../b/c")

Note that this func follows the argument order of the filepath.Rel func, while the RelTo() func implements the reverse argument order.

func (GoPath) RelTo

func (g GoPath) RelTo(base GoPath) GoPath

RelTo returns this GoPath, expressed as path relative to the other (base) GoPath.

var base = gopath.FromPath("/a")
var target = gopath.FromPath("/b/c")
var rel = target.RelTo(base)

assert.Equal(rel.Path(), "../b/c")

Note that this func uses the inverse argument order of the filepath.Rel func, while the Rel() func implements the exact argument order.

func (GoPath) Stat

func (g GoPath) Stat() GoPath

Stat calls os.Stat and caches the FileInfo result inside the returned GoPath. When the Stat call fails, an errorneous GoPath is returned. Stat always calls os.Stat, even if the GoPath already contains a FileInfo.

Be warned: Stat() might cause an errorneous path to be returned, even in normal operation (e.g. file does not exist). An errorneous GoPath will have all operations being no-ops, so take care when using this function.

Note, that Stat() is only useful for caching purposes. FileInfo() delivers the Stat() results even if Stat() was not called explicitly.

func (GoPath) String

func (g GoPath) String() string

func (GoPath) ToSlash

func (g GoPath) ToSlash() GoPath

ToSlash returns the result of replacing each separator character in this GoPath's path with a slash ('/') character. This is done simply by invoking filepath's ToSlash(string) func.

type Transformer

type Transformer func(GoPath) GoPath

Transformer is a func that transforms one GoPath instance into another.

Jump to

Keyboard shortcuts

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