reactivate before save and after save commands

pull/144/head
Henrique Dias 2017-06-25 20:58:08 +01:00
parent 9f1003ee8d
commit 9f51b1fcb4
No known key found for this signature in database
GPG Key ID: 936F5EB68D786730
3 changed files with 227 additions and 281 deletions

View File

@ -1,46 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hacdias@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@ -4,12 +4,29 @@
package filemanager
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/hacdias/filemanager"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("filemanager", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
// FileManager is an http.Handler that can show a file listing when
// directories in the given paths are specified.
type FileManager struct {
@ -30,3 +47,213 @@ func (f FileManager) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, err
return f.Next.ServeHTTP(w, r)
}
// setup configures a new FileManager middleware instance.
func setup(c *caddy.Controller) error {
configs, err := parse(c)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
return FileManager{Configs: configs, Next: next}
})
return nil
}
func parse(c *caddy.Controller) ([]*filemanager.FileManager, error) {
var (
configs []*filemanager.FileManager
err error
)
for c.Next() {
var (
m = filemanager.New(".")
u = m.User
name = ""
)
// Get the baseURL
args := c.RemainingArgs()
if len(args) > 0 {
m.SetBaseURL(args[0])
m.SetWebDavURL("/webdav")
}
for c.NextBlock() {
switch c.Val() {
case "before_save":
if m.BeforeSave, err = CommandRunner(c); err != nil {
return configs, err
}
case "after_save":
if m.AfterSave, err = CommandRunner(c); err != nil {
return configs, err
}
case "webdav":
if !c.NextArg() {
return configs, c.ArgErr()
}
m.SetWebDavURL(c.Val())
case "show":
if !c.NextArg() {
return configs, c.ArgErr()
}
m.SetScope(c.Val(), name)
case "styles":
if !c.NextArg() {
return configs, c.ArgErr()
}
var tplBytes []byte
tplBytes, err = ioutil.ReadFile(c.Val())
if err != nil {
return configs, err
}
u.StyleSheet = string(tplBytes)
case "allow_new":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowNew, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_edit":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowEdit, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_commands":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowCommands, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_command":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.Commands = append(u.Commands, c.Val())
case "block_command":
if !c.NextArg() {
return configs, c.ArgErr()
}
index := 0
for i, val := range u.Commands {
if val == c.Val() {
index = i
}
}
u.Commands = append(u.Commands[:index], u.Commands[index+1:]...)
case "allow", "allow_r", "block", "block_r":
ruleType := c.Val()
if !c.NextArg() {
return configs, c.ArgErr()
}
if c.Val() == "dotfiles" && !strings.HasSuffix(ruleType, "_r") {
ruleType += "_r"
}
rule := &filemanager.Rule{
Allow: ruleType == "allow" || ruleType == "allow_r",
Regex: ruleType == "allow_r" || ruleType == "block_r",
}
if rule.Regex && c.Val() == "dotfiles" {
rule.Regexp = regexp.MustCompile("\\/\\..+")
} else if rule.Regex {
rule.Regexp = regexp.MustCompile(c.Val())
} else {
rule.Path = c.Val()
}
u.Rules = append(u.Rules, rule)
default:
// Is it a new user? Is it?
val := c.Val()
// Checks if it's a new user!
if !strings.HasSuffix(val, ":") {
fmt.Println("Unknown option " + val)
}
// Get the username, sets the current user, and initializes it
val = strings.TrimSuffix(val, ":")
m.NewUser(val)
name = val
}
}
configs = append(configs, m)
}
return configs, nil
}
// CommandRunner ...
func CommandRunner(c *caddy.Controller) (filemanager.Command, error) {
fn := func(r *http.Request, c *filemanager.FileManager, u *filemanager.User) error { return nil }
args := c.RemainingArgs()
if len(args) == 0 {
return fn, c.ArgErr()
}
nonblock := false
if len(args) > 1 && args[len(args)-1] == "&" {
// Run command in background; non-blocking
nonblock = true
args = args[:len(args)-1]
}
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
if err != nil {
return fn, c.Err(err.Error())
}
fn = func(r *http.Request, c *filemanager.FileManager, u *filemanager.User) error {
path := strings.Replace(r.URL.Path, c.WebDavURL, "", 1)
path = u.Scope() + "/" + path
path = filepath.Clean(path)
for i := range args {
args[i] = strings.Replace(args[i], "{path}", path, -1)
}
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if nonblock {
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Run()
}
return fn, nil
}

235
setup.go
View File

@ -1,235 +0,0 @@
package filemanager
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/hacdias/filemanager"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("filemanager", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
// setup configures a new FileManager middleware instance.
func setup(c *caddy.Controller) error {
configs, err := parse(c)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
return FileManager{Configs: configs, Next: next}
})
return nil
}
func parse(c *caddy.Controller) ([]*filemanager.FileManager, error) {
var (
configs []*filemanager.FileManager
err error
)
for c.Next() {
var (
m = filemanager.New(".")
u = m.User
name = ""
)
// Get the baseURL
args := c.RemainingArgs()
if len(args) > 0 {
m.SetBaseURL(args[0])
m.SetWebDavURL("/webdav")
}
for c.NextBlock() {
switch c.Val() {
case "before_save":
/* if cfg.BeforeSave, err = CommandRunner(c); err != nil {
return configs, err
} */
case "after_save":
/* if cfg.AfterSave, err = CommandRunner(c); err != nil {
return configs, err
} */
case "webdav":
if !c.NextArg() {
return configs, c.ArgErr()
}
m.SetWebDavURL(c.Val())
case "show":
if !c.NextArg() {
return configs, c.ArgErr()
}
m.SetScope(c.Val(), name)
case "styles":
if !c.NextArg() {
return configs, c.ArgErr()
}
var tplBytes []byte
tplBytes, err = ioutil.ReadFile(c.Val())
if err != nil {
return configs, err
}
u.StyleSheet = string(tplBytes)
case "allow_new":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowNew, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_edit":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowEdit, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_commands":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.AllowCommands, err = strconv.ParseBool(c.Val())
if err != nil {
return configs, err
}
case "allow_command":
if !c.NextArg() {
return configs, c.ArgErr()
}
u.Commands = append(u.Commands, c.Val())
case "block_command":
if !c.NextArg() {
return configs, c.ArgErr()
}
index := 0
for i, val := range u.Commands {
if val == c.Val() {
index = i
}
}
u.Commands = append(u.Commands[:index], u.Commands[index+1:]...)
case "allow", "allow_r", "block", "block_r":
ruleType := c.Val()
if !c.NextArg() {
return configs, c.ArgErr()
}
if c.Val() == "dotfiles" && !strings.HasSuffix(ruleType, "_r") {
ruleType += "_r"
}
rule := &filemanager.Rule{
Allow: ruleType == "allow" || ruleType == "allow_r",
Regex: ruleType == "allow_r" || ruleType == "block_r",
}
if rule.Regex && c.Val() == "dotfiles" {
rule.Regexp = regexp.MustCompile("\\/\\..+")
} else if rule.Regex {
rule.Regexp = regexp.MustCompile(c.Val())
} else {
rule.Path = c.Val()
}
u.Rules = append(u.Rules, rule)
default:
// Is it a new user? Is it?
val := c.Val()
// Checks if it's a new user!
if !strings.HasSuffix(val, ":") {
fmt.Println("Unknown option " + val)
}
// Get the username, sets the current user, and initializes it
val = strings.TrimSuffix(val, ":")
m.NewUser(val)
name = val
}
}
configs = append(configs, m)
}
return configs, nil
}
// CommandRunner ...
func CommandRunner(c *caddy.Controller) (filemanager.Command, error) {
fn := func(r *http.Request, c *filemanager.FileManager, u *filemanager.User) error { return nil }
args := c.RemainingArgs()
if len(args) == 0 {
return fn, c.ArgErr()
}
nonblock := false
if len(args) > 1 && args[len(args)-1] == "&" {
// Run command in background; non-blocking
nonblock = true
args = args[:len(args)-1]
}
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
if err != nil {
return fn, c.Err(err.Error())
}
fn = func(r *http.Request, c *filemanager.FileManager, u *filemanager.User) error {
path := strings.Replace(r.URL.Path, c.WebDavURL, "", 1)
path = u.Scope() + "/" + path
path = filepath.Clean(path)
for i := range args {
args[i] = strings.Replace(args[i], "{path}", path, -1)
}
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if nonblock {
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Run()
}
return fn, nil
}