Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25c20aaeb2 | ||
|
|
4c665ec69c | ||
|
|
75ed779b17 | ||
|
|
6c360ffc5c | ||
|
|
f40731d3b4 | ||
|
|
afb10cc02c | ||
|
|
5d2e8864e5 | ||
|
|
d82f198b48 | ||
|
|
bbbf2bac51 | ||
|
|
d87a8ee5ed | ||
|
|
a81cc1e4ca | ||
|
|
6c5111fd6e | ||
|
|
e846c16336 | ||
|
|
dde01c6931 | ||
|
|
8b40dc9d19 | ||
|
|
63fb4c0c52 | ||
|
|
76047f4146 | ||
|
|
fc4c6ec246 | ||
|
|
f5e93825d8 | ||
|
|
73d74394c8 | ||
|
|
3469d8c6e8 | ||
|
|
be082c1075 | ||
|
|
f271b18d97 | ||
|
|
a728d0352e | ||
|
|
2096d7d048 |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
assets/
|
||||
testdata/
|
||||
caddy/
|
||||
.github/
|
||||
+2
-3
@@ -9,7 +9,6 @@ env:
|
||||
install:
|
||||
- go get ./...
|
||||
- go get github.com/mitchellh/gox
|
||||
- go get github.com/tcnksm/ghr
|
||||
# Install gometalinter and certain linters
|
||||
- go get github.com/alecthomas/gometalinter
|
||||
- go get github.com/client9/misspell/cmd/misspell
|
||||
@@ -20,11 +19,11 @@ install:
|
||||
script:
|
||||
- gometalinter --disable-all -E vet -E gofmt -E misspell -E ineffassign -E goimports -E deadcode --exclude="rice-box.go" --tests ./...
|
||||
- go test ./... -timeout 30s
|
||||
|
||||
before_deploy:
|
||||
- cd cmd/filemanager
|
||||
- mkdir dist
|
||||
- gox -output "dist/{{.OS}}-{{.Arch}}-{{.Dir}}"
|
||||
- ls dist/
|
||||
- ghr --username hacdias --token $GITHUB_TOKEN --replace --prerelease --debug latest dist/
|
||||
|
||||
deploy:
|
||||
provider: releases
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"port": 80,
|
||||
"address": "",
|
||||
"database": "/etc/database.db",
|
||||
"scope": "/srv",
|
||||
"allowCommands": true,
|
||||
"allowEdit": true,
|
||||
"allowNew": true,
|
||||
"commands": []
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
FROM golang:alpine
|
||||
|
||||
COPY . /go/src/github.com/hacdias/filemanager
|
||||
|
||||
WORKDIR /go/src/github.com/hacdias/filemanager
|
||||
RUN apk add --no-cache git
|
||||
RUN go get ./...
|
||||
|
||||
WORKDIR /go/src/github.com/hacdias/filemanager/cmd/filemanager
|
||||
RUN go install
|
||||
|
||||
FROM alpine:latest
|
||||
COPY --from=0 /go/bin/filemanager /usr/local/bin/filemanager
|
||||
|
||||
VOLUME /srv
|
||||
EXPOSE 80
|
||||
|
||||
COPY Docker.json /etc/config.json
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/filemanager"]
|
||||
CMD ["--config", "/etc/config.json"]
|
||||
@@ -34,7 +34,7 @@ The easiest way to get started is using this with Caddy web server. You just nee
|
||||
|
||||
## Standalone
|
||||
|
||||
You can use filemanager as a standalone executable. You just need to download it from the [releases page](https://github.com/hacdias/filemanager/releases), where you can find multiple releases. The 'latest' always corresponds to the latest commit made to the master branch so it might not be stable.
|
||||
You can use filemanager as a standalone executable. You just need to download it from the [releases page](https://github.com/hacdias/filemanager/releases), where you can find multiple releases.
|
||||
|
||||
You can either use flags or a JSON configuration file, which should have the following appearance:
|
||||
|
||||
@@ -77,6 +77,10 @@ Otherwise, you may not want to use a configuration file, which can be done using
|
||||
Default scope for new users (default ".")
|
||||
```
|
||||
|
||||
## Docker
|
||||
|
||||
(TODO)
|
||||
|
||||
# Features
|
||||
|
||||
Easy login system.
|
||||
@@ -127,18 +131,19 @@ this are keywords case:insensitive
|
||||
|
||||
# Contributing
|
||||
|
||||
If you want to contribute or want to build the code from source, you will need to have NodeJS and Go installed on your computer. You should start by doing the following:
|
||||
If you want to contribute or want to build the code from source, you will need to have the most recent version of Go and, if you want to change the static assets (JS, CSS, ...), Node.js installed on your computer. To start developing, you just need to do the following:
|
||||
|
||||
```
|
||||
go get github.com/hacdias/filemanager
|
||||
```
|
||||
1. `go get github.com/hacdias/filemanager`
|
||||
2. `cd $GOPATH/src/github.com/hacdias/filemanager`
|
||||
3. `npm install`
|
||||
4. `npm start dev` - regenerates the static assets automatically
|
||||
5. `go install gihthub.com/hacdias/filemanager/cmd/filemanager`
|
||||
6. Execute `$GOPATH/bin/filemanager`
|
||||
|
||||
Then, you should navigate to `$GOPATH/src/github.com/hacdias/filemanager` and execute `npm install`. You can start the live build of static assets with the command `npm start dev`.
|
||||
The steps 3 and 4 are only required **if you want to develop the front-end**. Otherwise, you can ignore them. Before pulling, if you made any change on assets folder, you must run the `build.sh` script on the root of this repository.
|
||||
|
||||
If you are using this as a Caddy plugin, you should use its [official instructions for plugins](https://github.com/mholt/caddy/wiki/Extending-Caddy#2-plug-in-your-plugin) and import `github.com/hacdias/filemanager/caddy/filemanager`.
|
||||
|
||||
Before pulling, and if you made any change on assets folder, you must run the `build.sh` script on the root of this repository.
|
||||
|
||||
# Donate
|
||||
|
||||
Enjoying this project? You can [donate to its creator](https://henriquedias.com/donate/). He will appreciate.
|
||||
@@ -47,7 +47,8 @@ export default {
|
||||
ongoing: false,
|
||||
scrollable: null,
|
||||
search: [],
|
||||
commands: []
|
||||
commands: [],
|
||||
reload: false
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
@@ -57,12 +58,17 @@ export default {
|
||||
// If the hover was search and now it's something else
|
||||
// we should blur the input.
|
||||
if (old === 'search' && val !== 'search') {
|
||||
if (this.reload) {
|
||||
this.$store.commit('setReload', true)
|
||||
}
|
||||
|
||||
this.$refs.input.blur()
|
||||
}
|
||||
|
||||
// If we are starting to show the search box, we should
|
||||
// focus the input.
|
||||
if (val === 'search') {
|
||||
this.reload = false
|
||||
this.$refs.input.focus()
|
||||
}
|
||||
}
|
||||
@@ -129,7 +135,7 @@ export default {
|
||||
let pieces = this.value.split(' ')
|
||||
|
||||
for (let i = 0; i < this.user.commands.length; i++) {
|
||||
if (pieces[0] === this.user.commands[0]) {
|
||||
if (pieces[0] === this.user.commands[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -166,9 +172,9 @@ export default {
|
||||
this.scrollable.scrollTop = this.scrollable.scrollHeight
|
||||
},
|
||||
(event) => {
|
||||
this.reload = true
|
||||
this.ongoing = false
|
||||
this.scrollable.scrollTop = this.scrollable.scrollHeight
|
||||
this.$store.commit('setReload', true)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
</div>
|
||||
|
||||
<p class="credits">
|
||||
<span>Served with <a rel="noopener noreferrer" href="https://github.com/hacdias/caddy-filemanager">File Manager</a>.</span>
|
||||
<span>Served with <a rel="noopener noreferrer" href="https://github.com/hacdias/filemanager">File Manager</a>.</span>
|
||||
<span v-for="plugin in plugins" :key="plugin.name" v-html="plugin.credits"><br></span>
|
||||
<span><a @click="help">Help</a></span>
|
||||
</p>
|
||||
|
||||
@@ -163,7 +163,7 @@ function checksum (url, algo) {
|
||||
function command (url, command, onmessage, onclose) {
|
||||
let protocol = (ssl ? 'wss:' : 'ws:')
|
||||
url = removePrefix(url)
|
||||
url = `${protocol}//${window.location.hostname}${store.state.baseURL}/api/command${url}`
|
||||
url = `${protocol}//${window.location.host}${store.state.baseURL}/api/command${url}`
|
||||
|
||||
let conn = new window.WebSocket(url)
|
||||
conn.onopen = () => conn.send(command)
|
||||
@@ -174,7 +174,7 @@ function command (url, command, onmessage, onclose) {
|
||||
function search (url, search, onmessage, onclose) {
|
||||
let protocol = (ssl ? 'wss:' : 'ws:')
|
||||
url = removePrefix(url)
|
||||
url = `${protocol}//${window.location.hostname}${store.state.baseURL}/api/search${url}`
|
||||
url = `${protocol}//${window.location.host}${store.state.baseURL}/api/search${url}`
|
||||
|
||||
let conn = new window.WebSocket(url)
|
||||
conn.onopen = () => conn.send(search)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"strings"
|
||||
|
||||
. "github.com/hacdias/filemanager"
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
@@ -136,7 +136,7 @@ func parse(c *caddy.Controller) ([]*config, error) {
|
||||
Regexp: &Regexp{Raw: "\\/\\..+"},
|
||||
}},
|
||||
CSS: "",
|
||||
FileSystem: dir.Dir(baseScope),
|
||||
FileSystem: fileutils.Dir(baseScope),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
File renamed without changes.
+4
-6
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
rice "github.com/GeertJohan/go.rice"
|
||||
"github.com/hacdias/filemanager"
|
||||
"github.com/hacdias/filemanager/variables"
|
||||
"github.com/hacdias/varutils"
|
||||
"github.com/robfig/cron"
|
||||
)
|
||||
|
||||
@@ -71,7 +71,6 @@ func (h hugo) BeforeAPI(c *filemanager.RequestContext, w http.ResponseWriter, r
|
||||
}
|
||||
|
||||
filename := filepath.Join(string(c.User.FileSystem), r.URL.Path)
|
||||
filename = strings.TrimPrefix(filename, "/")
|
||||
archetype := r.Header.Get("archetype")
|
||||
|
||||
ext := filepath.Ext(filename)
|
||||
@@ -100,7 +99,6 @@ func (h hugo) BeforeAPI(c *filemanager.RequestContext, w http.ResponseWriter, r
|
||||
}
|
||||
|
||||
filename := filepath.Join(string(c.User.FileSystem), r.URL.Path)
|
||||
filename = strings.TrimPrefix(filename, "/")
|
||||
|
||||
// Before save command handler.
|
||||
if err := c.FM.Runner("before_publish", filename); err != nil {
|
||||
@@ -110,7 +108,7 @@ func (h hugo) BeforeAPI(c *filemanager.RequestContext, w http.ResponseWriter, r
|
||||
// We only run undraft command if it is a file.
|
||||
if !strings.HasSuffix(filename, "/") {
|
||||
args := []string{"undraft", filename}
|
||||
if err := Run(h.Exe, args, h.Root); err != nil {
|
||||
if err := Run(h.Exe, args, h.Root); err != nil && !strings.Contains(err.Error(), "not a Draft") {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
@@ -142,7 +140,7 @@ func (h hugo) AfterAPI(c *filemanager.RequestContext, w http.ResponseWriter, r *
|
||||
}
|
||||
|
||||
func (h hugo) JavaScript() string {
|
||||
return rice.MustFindBox("./").MustString("hugo.js")
|
||||
return rice.MustFindBox("./assets/").MustString("hugo.js")
|
||||
}
|
||||
|
||||
// run runs Hugo with the define arguments.
|
||||
@@ -153,7 +151,7 @@ func (h hugo) run(force bool) {
|
||||
}
|
||||
|
||||
// Prevent running if watching is enabled
|
||||
if b, pos := variables.StringInSlice("--watch", h.Args); b && !force {
|
||||
if b, pos := varutils.StringInSlice("--watch", h.Args); b && !force {
|
||||
if len(h.Args) > pos && h.Args[pos+1] != "false" {
|
||||
return
|
||||
}
|
||||
|
||||
+7
-42
@@ -9,47 +9,17 @@ func init() {
|
||||
|
||||
// define files
|
||||
file2 := &embedded.EmbeddedFile{
|
||||
Filename: `README.md`,
|
||||
FileModTime: time.Unix(1500389874, 0),
|
||||
Content: string("# hugo - a caddy plugin\n\n[](https://caddy.community)\n\nhugo fills the gap between Hugo and the browser. [Hugo][6] is an easy and fast static website generator. This plugin fills the gap between Hugo and the end-user, providing you a web interface to manage the whole website.\n\nUsing this plugin, you won't need to have your own computer to edit posts, neither regenerate your static website, because you can do all of that just through your browser. It is an implementation of [hacdias/filemanager][1] library.\n\n**Requirements:** you need to have the hugo executable in your PATH. You can download it from its [official page][6].\n\n## Get Started\n\nTo start using this plugin you just need to go to the [download Caddy page][3] and choose `http.hugo` in the directives section. For further information on how Caddy works refer to [its documentation][4].\n\nThe default credentials are `admin` for both the user and the password. It is highy recommended to change them after logging in for the first time and to use HTTPS. You can create more users and define their own permissions using the web interface.\n\n## Syntax\n\n```\nhugo [directory] [admin] {\n database path\n}\n```\n\n+ `directory` is the path, relative or absolute to the directory of your Hugo files. Defaults to `./`.\n+ `admin` is the URL path where you will access the admin interface. Defaults to `/admin`.\n+ `path` is the database path where the settings will be stored. By default, the settings will be stored on [`.caddy`][5] folder.\n\n## Database\n\nBy default the database will be stored on [`.caddy`][5] directory, in a sub-directory called `hugo`. Each file name is an hash of the combination of the host and the base URL.\n\nIf you don't set a database path, you will receive a warning like this:\n\n> [WARNING] A database is going to be created for your File Manager instace at ~/.caddy/hugo/xxx.db. It is highly recommended that you set the 'database' option to 'xxx.db'\n\nWhy? If you don't set a database path and you change the host or the base URL, your settings will be reseted. So it is *highly* recommended to set this option.\n\nWhen you set a relative path, such as `xxxxxxxxxx.db`, it will always be relative to `.caddy/hugo` directory. Although, you may also use an absolute path if you wish to store the database in other place.\n\n## Examples\n\nManage the current working directory's Hugo website at `/admin` and display the ```public``` folder to the user.\n\n```\nroot public\nhugo {\n database myinstance.db\n}\n```\n\nManage the Hugo website located at `/var/www/mysite` at `/admin` and display the ```public``` folder to the user.\n\n```\nroot /var/www/mysite/public\nhugo /var/www/mysite {\n database myinstance.db\n}\n```\n\nManage the Hugo website located at `/var/www/mysite` at `/private` and display the ```public``` folder to the user.\n\n```\nroot /var/www/mysite/public\nhugo /var/www/mysite /private {\n database myinstance.db\n}\n```\n\n## Known Issues\n\nIf you are having troubles **handling large files** you might need to check out the [`timeouts`][2] plugin, which can be used to change the default HTTP Timeouts.\n\n[1]:https://github.com/hacdias/filemanager\n[2]:https://caddyserver.com/docs/timeouts\n[3]:https://caddyserver.com/download\n[4]:https://caddyserver.com/docs\n[5]:https://caddyserver.com/docs/automatic-https#dot-caddy\n[6]:http://gohugo.io\n"),
|
||||
}
|
||||
file3 := &embedded.EmbeddedFile{
|
||||
Filename: `hugo.go`,
|
||||
FileModTime: time.Unix(1501060368, 0),
|
||||
Content: string("package hugo\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\trice \"github.com/GeertJohan/go.rice\"\n\t\"github.com/hacdias/filemanager\"\n\t\"github.com/hacdias/filemanager/variables\"\n\t\"github.com/robfig/cron\"\n)\n\ntype hugo struct {\n\t// Website root\n\tRoot string `description:\"The relative or absolute path to the place where your website is located.\"`\n\t// Public folder\n\tPublic string `description:\"The relative or absolute path to the public folder.\"`\n\t// Hugo executable path\n\tExe string `description:\"The absolute path to the Hugo executable or the command to execute.\"`\n\t// Hugo arguments\n\tArgs []string `description:\"The arguments to run when running Hugo\"`\n\t// Indicates if we should clean public before a new publish.\n\tCleanPublic bool `description:\"Indicates if the public folder should be cleaned before publishing the website.\"`\n\n\t// TODO: admin interface to cgange options\n}\n\nfunc (h hugo) BeforeAPI(c *filemanager.RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {\n\t// If we are using the 'magic url' for the settings, we should redirect the\n\t// request for the acutual path.\n\tif r.URL.Path == \"/settings/\" || r.URL.Path == \"/settings\" {\n\t\tvar frontmatter string\n\t\tvar err error\n\n\t\tif _, err = os.Stat(filepath.Join(h.Root, \"config.yaml\")); err == nil {\n\t\t\tfrontmatter = \"yaml\"\n\t\t}\n\n\t\tif _, err = os.Stat(filepath.Join(h.Root, \"config.json\")); err == nil {\n\t\t\tfrontmatter = \"json\"\n\t\t}\n\n\t\tif _, err = os.Stat(filepath.Join(h.Root, \"config.toml\")); err == nil {\n\t\t\tfrontmatter = \"toml\"\n\t\t}\n\n\t\tr.URL.Path = \"/config.\" + frontmatter\n\t\treturn 0, nil\n\t}\n\n\t// From here on, we only care about 'hugo' router so we can bypass\n\t// the others.\n\tif c.Router != \"hugo\" {\n\t\treturn 0, nil\n\t}\n\n\t// If we are not using HTTP Post, we shall return Method Not Allowed\n\t// since we are only working with this method.\n\tif r.Method != http.MethodPost {\n\t\treturn http.StatusMethodNotAllowed, nil\n\t}\n\n\t// If we are creating a file built from an archetype.\n\tif r.Header.Get(\"Archetype\") != \"\" {\n\t\tif !c.User.AllowNew {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tfilename := filepath.Join(string(c.User.FileSystem), r.URL.Path)\n\t\tfilename = strings.TrimPrefix(filename, \"/\")\n\t\tarchetype := r.Header.Get(\"archetype\")\n\n\t\text := filepath.Ext(filename)\n\n\t\t// If the request isn't for a markdown file, we can't\n\t\t// handle it.\n\t\tif ext != \".markdown\" && ext != \".md\" {\n\t\t\treturn http.StatusBadRequest, errUnsupportedFileType\n\t\t}\n\n\t\t// Tries to create a new file based on this archetype.\n\t\targs := []string{\"new\", filename, \"--kind\", archetype}\n\t\tif err := Run(h.Exe, args, h.Root); err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\t// Writes the location of the new file to the Header.\n\t\tw.Header().Set(\"Location\", \"/files/content/\"+filename)\n\t\treturn http.StatusCreated, nil\n\t}\n\n\t// If we are trying to regenerate the website.\n\tif r.Header.Get(\"Regenerate\") == \"true\" {\n\t\tif !c.User.Permissions[\"allowPublish\"] {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tfilename := filepath.Join(string(c.User.FileSystem), r.URL.Path)\n\t\tfilename = strings.TrimPrefix(filename, \"/\")\n\n\t\t// Before save command handler.\n\t\tif err := c.FM.Runner(\"before_publish\", filename); err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\t// We only run undraft command if it is a file.\n\t\tif !strings.HasSuffix(filename, \"/\") {\n\t\t\targs := []string{\"undraft\", filename}\n\t\t\tif err := Run(h.Exe, args, h.Root); err != nil {\n\t\t\t\treturn http.StatusInternalServerError, err\n\t\t\t}\n\t\t}\n\n\t\t// Regenerates the file\n\t\th.run(false)\n\n\t\t// Executed the before publish command.\n\t\tif err := c.FM.Runner(\"before_publish\", filename); err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\treturn http.StatusOK, nil\n\t}\n\n\tif r.Header.Get(\"Schedule\") != \"\" {\n\t\tif !c.User.Permissions[\"allowPublish\"] {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\treturn h.schedule(c, w, r)\n\t}\n\n\treturn http.StatusNotFound, nil\n}\n\nfunc (h hugo) AfterAPI(c *filemanager.RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {\n\treturn 0, nil\n}\n\nfunc (h hugo) JavaScript() string {\n\treturn rice.MustFindBox(\"./\").MustString(\"hugo.js\")\n}\n\n// run runs Hugo with the define arguments.\nfunc (h hugo) run(force bool) {\n\t// If the CleanPublic option is enabled, clean it.\n\tif h.CleanPublic {\n\t\tos.RemoveAll(h.Public)\n\t}\n\n\t// Prevent running if watching is enabled\n\tif b, pos := variables.StringInSlice(\"--watch\", h.Args); b && !force {\n\t\tif len(h.Args) > pos && h.Args[pos+1] != \"false\" {\n\t\t\treturn\n\t\t}\n\n\t\tif len(h.Args) == Line truncated
|
||||
}
|
||||
file4 := &embedded.EmbeddedFile{
|
||||
Filename: `hugo.js`,
|
||||
FileModTime: time.Unix(1500387945, 0),
|
||||
FileModTime: time.Unix(1501232329, 0),
|
||||
Content: string("'use strict';\r\n\r\n(function () {\r\n if (window.plugins === undefined || window.plugins === null) {\r\n window.plugins = []\r\n }\r\n\r\n let regenerate = function (data, url) {\r\n url = data.api.removePrefix(url)\r\n\r\n return new Promise((resolve, reject) => {\r\n let request = new window.XMLHttpRequest()\r\n request.open('POST', `${data.store.state.baseURL}/api/hugo${url}`, true)\r\n request.setRequestHeader('Authorization', `Bearer ${data.store.state.jwt}`)\r\n request.setRequestHeader('Regenerate', 'true')\r\n\r\n request.onload = () => {\r\n if (request.status === 200) {\r\n resolve()\r\n } else {\r\n reject(request.responseText)\r\n }\r\n }\r\n\r\n request.onerror = (error) => reject(error)\r\n request.send()\r\n })\r\n }\r\n\r\n let newArchetype = function (data, url, type) {\r\n url = data.api.removePrefix(url)\r\n\r\n return new Promise((resolve, reject) => {\r\n let request = new window.XMLHttpRequest()\r\n request.open('POST', `${data.store.state.baseURL}/api/hugo${url}`, true)\r\n request.setRequestHeader('Authorization', `Bearer ${data.store.state.jwt}`)\r\n request.setRequestHeader('Archetype', encodeURIComponent(type))\r\n\r\n request.onload = () => {\r\n if (request.status === 200) {\r\n resolve(request.getResponseHeader('Location'))\r\n } else {\r\n reject(request.responseText)\r\n }\r\n }\r\n\r\n request.onerror = (error) => reject(error)\r\n request.send()\r\n })\r\n }\r\n\r\n let schedule = function (data, file, date) {\r\n file = data.api.removePrefix(file)\r\n\r\n return new Promise((resolve, reject) => {\r\n let request = new window.XMLHttpRequest()\r\n request.open('POST', `${data.store.state.baseURL}/api/hugo${file}`, true)\r\n request.setRequestHeader('Authorization', `Bearer ${data.store.state.jwt}`)\r\n request.setRequestHeader('Schedule', date)\r\n\r\n request.onload = () => {\r\n if (request.status === 200) {\r\n resolve(request.getResponseHeader('Location'))\r\n } else {\r\n reject(request.responseText)\r\n }\r\n }\r\n\r\n request.onerror = (error) => reject(error)\r\n request.send()\r\n })\r\n }\r\n\r\n window.plugins.push({\r\n name: 'hugo',\r\n credits: 'With a flavour of <a rel=\"noopener noreferrer\" href=\"https://github.com/hacdias/caddy-hugo\">Hugo</a>.',\r\n header: {\r\n visible: [\r\n {\r\n if: function (data, route) {\r\n return (data.store.state.req.kind === 'editor' &&\r\n !data.store.state.loading &&\r\n data.store.state.req.metadata !== undefined &&\r\n data.store.state.req.metadata !== null &&\r\n data.store.state.user.allowEdit &\r\n data.store.state.user.permissions.allowPublish)\r\n },\r\n click: function (event, data, route) {\r\n event.preventDefault()\r\n document.getElementById('save-button').click()\r\n // TODO: wait for save to finish?\r\n data.buttons.loading('publish')\r\n\r\n regenerate(data, route.path)\r\n .then(() => {\r\n data.buttons.done('publish')\r\n data.store.commit('showSuccess', 'Post published!')\r\n data.store.commit('setReload', true)\r\n })\r\n .catch((error) => {\r\n data.buttons.done('publish')\r\n data.store.commit('showError', error)\r\n })\r\n },\r\n id: 'publish-button',\r\n icon: 'send',\r\n name: 'Publish'\r\n }\r\n ],\r\n hidden: [\r\n {\r\n if: function (data, route) {\r\n return (data.store.state.req.kind === 'editor' &&\r\n !data.store.state.loading &&\r\n data.store.state.req.metadata !== undefined &&\r\n data.store.state.req.metadata !== null &&\r\n data.store.state.user.permissions.allowPublish)\r\n },\r\n click: function (event, data, route) {\r\n document.getElementById('save-button').click()\r\n data.store.commit('showHover', 'schedule')\r\n },\r\n id: 'schedule-button',\r\n icon: 'alarm',\r\n name: 'Schedule'\r\n }\r\n ]\r\n },\r\n sidebar: [\r\n {\r\n click: function (event, data, route) {\r\n data.router.push({ path: '/files/settings' })\r\n },\r\n icon: 'settings',\r\n name: 'Hugo Settings'\r\n },\r\n {\r\n click: function (event, data, route) {\r\n data.store.commit('showHover', 'new-archetype')\r\n },\r\n if: function (data, route) {\r\n return data.store.state.user.allowNew\r\n },\r\n Line truncated
|
||||
}
|
||||
file5 := &embedded.EmbeddedFile{
|
||||
Filename: `rice-box.go`,
|
||||
FileModTime: time.Unix(1501088534, 0),
|
||||
Content: string("package hugo\n\nimport (\n\t\"github.com/GeertJohan/go.rice/embedded\"\n\t\"time\"\n)\n\nfunc init() {\n\n\t// define files\n\tfile2 := &embedded.EmbeddedFile{\n\t\tFilename: `README.md`,\n\t\tFileModTime: time.Unix(1500389874, 0),\n\t\tContent: string(\"# hugo - a caddy plugin\\n\\n[](https://caddy.community)\\n\\nhugo fills the gap between Hugo and the browser. [Hugo][6] is an easy and fast static website generator. This plugin fills the gap between Hugo and the end-user, providing you a web interface to manage the whole website.\\n\\nUsing this plugin, you won't need to have your own computer to edit posts, neither regenerate your static website, because you can do all of that just through your browser. It is an implementation of [hacdias/filemanager][1] library.\\n\\n**Requirements:** you need to have the hugo executable in your PATH. You can download it from its [official page][6].\\n\\n## Get Started\\n\\nTo start using this plugin you just need to go to the [download Caddy page][3] and choose `http.hugo` in the directives section. For further information on how Caddy works refer to [its documentation][4].\\n\\nThe default credentials are `admin` for both the user and the password. It is highy recommended to change them after logging in for the first time and to use HTTPS. You can create more users and define their own permissions using the web interface.\\n\\n## Syntax\\n\\n```\\nhugo [directory] [admin] {\\n database path\\n}\\n```\\n\\n+ `directory` is the path, relative or absolute to the directory of your Hugo files. Defaults to `./`.\\n+ `admin` is the URL path where you will access the admin interface. Defaults to `/admin`.\\n+ `path` is the database path where the settings will be stored. By default, the settings will be stored on [`.caddy`][5] folder.\\n\\n## Database\\n\\nBy default the database will be stored on [`.caddy`][5] directory, in a sub-directory called `hugo`. Each file name is an hash of the combination of the host and the base URL.\\n\\nIf you don't set a database path, you will receive a warning like this:\\n\\n> [WARNING] A database is going to be created for your File Manager instace at ~/.caddy/hugo/xxx.db. It is highly recommended that you set the 'database' option to 'xxx.db'\\n\\nWhy? If you don't set a database path and you change the host or the base URL, your settings will be reseted. So it is *highly* recommended to set this option.\\n\\nWhen you set a relative path, such as `xxxxxxxxxx.db`, it will always be relative to `.caddy/hugo` directory. Although, you may also use an absolute path if you wish to store the database in other place.\\n\\n## Examples\\n\\nManage the current working directory's Hugo website at `/admin` and display the ```public``` folder to the user.\\n\\n```\\nroot public\\nhugo {\\n database myinstance.db\\n}\\n```\\n\\nManage the Hugo website located at `/var/www/mysite` at `/admin` and display the ```public``` folder to the user.\\n\\n```\\nroot /var/www/mysite/public\\nhugo /var/www/mysite {\\n database myinstance.db\\n}\\n```\\n\\nManage the Hugo website located at `/var/www/mysite` at `/private` and display the ```public``` folder to the user.\\n\\n```\\nroot /var/www/mysite/public\\nhugo /var/www/mysite /private {\\n database myinstance.db\\n}\\n```\\n\\n## Known Issues\\n\\nIf you are having troubles **handling large files** you might need to check out the [`timeouts`][2] plugin, which can be used to change the default HTTP Timeouts.\\n\\n[1]:https://github.com/hacdias/filemanager\\n[2]:https://caddyserver.com/docs/timeouts\\n[3]:https://caddyserver.com/download\\n[4]:https://caddyserver.com/docs\\n[5]:https://caddyserver.com/docs/automatic-https#dot-caddy\\n[6]:http://gohugo.io\\n\"),\n\t}\n\tfile3 := &embedded.EmbeddedFile{\n\t\tFilename: `hugo.go`,\n\t\tFileModTime: time.Unix(1501060368, 0),\n\t\tContent: string(\"package hugo\\n\\nimport (\\n\\t\\\"log\\\"\\n\\t\\\"net/http\\\"\\n\\t\\\"os\\\"\\n\\t\\\"path/filepath\\\"\\n\\t\\\"strings\\\"\\n\\t\\\"time\\\"\\n\\n\\trice \\\"github.com/GeertJohan/go.rice\\\"\\n\\t\\\"github.com/hacdias/filemanager\\\"\\n\\t\\\"github.com/hacdias/filemanager/variables\\\"\\n\\t\\\"github.com/robfig/cron\\\"\\n)\\n\\ntype hugo struct {\\n\\t// Website root\\n\\tRoot string `description:\\\"The relative or absolute path to the place where your website is located.\\\"`\\n\\t// Public folder\\n\\tPublic string `description:\\\"The relative or absolute path to the public folder.\\\"`\\n\\t// Hugo executable path\\n\\tExe string `description:\\\"The absolute path to the Hugo executable or the command to execute.\\\"`\\n\\t// Hugo arguments\\n\\tArgs []string `description:\\\"The arguments to run when running Hugo\\\"`\\n\\t// Indicates if we should clean public before a new publish.\\n\\tCleanPublic bool `description:\\\"Indicates if the public folder should be cleaned before publLine truncated
|
||||
}
|
||||
file6 := &embedded.EmbeddedFile{
|
||||
Filename: `setup.go`,
|
||||
FileModTime: time.Unix(1501060372, 0),
|
||||
Content: string("package hugo\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/hacdias/filemanager\"\n\t\"github.com/hacdias/filemanager/dir\"\n\t\"github.com/mholt/caddy\"\n\t\"github.com/mholt/caddy/caddyhttp/httpserver\"\n)\n\nvar (\n\terrHugoNotFound = errors.New(\"It seems that tou don't have 'hugo' on your PATH\")\n\terrUnsupportedFileType = errors.New(\"The type of the provided file isn't supported for this action\")\n)\n\n// setup configures a new FileManager middleware instance.\nfunc setup(c *caddy.Controller) error {\n\tconfigs, err := parse(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\treturn plugin{Configs: configs, Next: next}\n\t})\n\n\treturn nil\n}\n\nfunc parse(c *caddy.Controller) ([]*filemanager.FileManager, error) {\n\tvar (\n\t\tconfigs []*filemanager.FileManager\n\t)\n\n\tfor c.Next() {\n\t\t// hugo [directory] [admin] {\n\t\t// \t\tdatabase path\n\t\t// }\n\t\tdirectory := \".\"\n\t\tadmin := \"/admin\"\n\t\tdatabase := \"\"\n\n\t\t// Get the baseURL and baseScope\n\t\targs := c.RemainingArgs()\n\n\t\tif len(args) == 1 {\n\t\t\tdirectory = args[0]\n\t\t}\n\n\t\tif len(args) > 1 {\n\t\t\tadmin = args[1]\n\t\t}\n\n\t\tfor c.NextBlock() {\n\t\t\tswitch c.Val() {\n\t\t\tcase \"database\":\n\t\t\t\tif !c.NextArg() {\n\t\t\t\t\treturn nil, c.ArgErr()\n\t\t\t\t}\n\n\t\t\t\tdatabase = c.Val()\n\t\t\t}\n\t\t}\n\n\t\tcaddyConf := httpserver.GetConfig(c)\n\n\t\tpath := filepath.Join(caddy.AssetsPath(), \"hugo\")\n\t\terr := os.MkdirAll(path, 0700)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// if there is a database path and it is not absolute,\n\t\t// it will be relative to \".caddy\" folder.\n\t\tif !filepath.IsAbs(database) && database != \"\" {\n\t\t\tdatabase = filepath.Join(path, database)\n\t\t}\n\n\t\t// If there is no database path on the settings,\n\t\t// store one in .caddy/hugo/{name}.db.\n\t\tif database == \"\" {\n\t\t\t// The name of the database is the hashed value of a string composed\n\t\t\t// by the host, address path and the baseurl of this File Manager\n\t\t\t// instance.\n\t\t\thasher := md5.New()\n\t\t\thasher.Write([]byte(caddyConf.Addr.Host + caddyConf.Addr.Path + admin))\n\t\t\tsha := hex.EncodeToString(hasher.Sum(nil))\n\t\t\tdatabase = filepath.Join(path, sha+\".db\")\n\n\t\t\tfmt.Println(\"[WARNING] A database is going to be created for your Hugo instace at \" + database +\n\t\t\t\t\". It is highly recommended that you set the 'database' option to '\" + sha + \".db'\\n\")\n\t\t}\n\n\t\tm, err := filemanager.New(database, filemanager.User{\n\t\t\tAllowCommands: true,\n\t\t\tAllowEdit: true,\n\t\t\tAllowNew: true,\n\t\t\tPermissions: map[string]bool{},\n\t\t\tCommands: []string{\"git\", \"svn\", \"hg\"},\n\t\t\tRules: []*filemanager.Rule{{\n\t\t\t\tRegex: true,\n\t\t\t\tAllow: false,\n\t\t\t\tRegexp: &filemanager.Regexp{Raw: \"\\\\/\\\\..+\"},\n\t\t\t}},\n\t\t\tCSS: \"\",\n\t\t\tFileSystem: dir.Dir(directory),\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Initialize the default settings for Hugo.\n\t\thugo := &hugo{\n\t\t\tRoot: directory,\n\t\t\tPublic: filepath.Join(directory, \"public\"),\n\t\t\tArgs: []string{},\n\t\t\tCleanPublic: true,\n\t\t}\n\n\t\t// Try to find the Hugo executable path.\n\t\tif hugo.Exe, err = exec.LookPath(\"hugo\"); err != nil {\n\t\t\treturn nil, errHugoNotFound\n\t\t}\n\n\t\terr = m.RegisterPlugin(\"hugo\", hugo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = m.RegisterEventType(\"before_publish\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = m.RegisterEventType(\"after_publish\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = m.RegisterPermission(\"allowPublish\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm.SetBaseURL(admin)\n\t\tm.SetPrefixURL(strings.TrimSuffix(caddyConf.Addr.Path, \"/\"))\n\t\tconfigs = append(configs, m)\n\t}\n\n\treturn configs, nil\n}\n\n// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.\nfunc (p plugin) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {\n\tfor i := range p.Configs {\n\t\t// Checks if this Path should be handled by File Manager.\n\t\tif !httpserver.Path(r.URL.Path).Matches(p.Configs[i].BaseURL) {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.Configs[i].ServeHTTP(w, r)\n\t\treturn 0, nil\n\t}\n\n\treturn p.Next.ServeHTTP(w, r)\n}\n\nfunc init() {\n\tcaddy.RegisterPlugin(\"hugo\", caddy.Plugin{\n\t\tServerType: \"http\",\n\t\tAction: setup,\n\t})\n}\n\ntype plugin struct {\n\tNext httpserver.Handler\n\tConfigs []*filemanager.FileManager\n}\n"),
|
||||
}
|
||||
file7 := &embedded.EmbeddedFile{
|
||||
Filename: `utils.go`,
|
||||
FileModTime: time.Unix(1500981861, 0),
|
||||
Content: string("package hugo\n\nimport (\n\t\"errors\"\n\t\"os/exec\"\n)\n\n// Run executes an external command\nfunc Run(command string, args []string, path string) error {\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = path\n\tout, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\treturn errors.New(string(out))\n\t}\n\n\treturn nil\n}\n"),
|
||||
}
|
||||
|
||||
// define dirs
|
||||
dir1 := &embedded.EmbeddedDir{
|
||||
Filename: ``,
|
||||
DirModTime: time.Unix(1501081088, 0),
|
||||
DirModTime: time.Unix(1501232329, 0),
|
||||
ChildFiles: []*embedded.EmbeddedFile{
|
||||
file2, // README.md
|
||||
file3, // hugo.go
|
||||
file4, // hugo.js
|
||||
file5, // rice-box.go
|
||||
file6, // setup.go
|
||||
file7, // utils.go
|
||||
file2, // hugo.js
|
||||
|
||||
},
|
||||
}
|
||||
@@ -58,19 +28,14 @@ func init() {
|
||||
dir1.ChildDirs = []*embedded.EmbeddedDir{}
|
||||
|
||||
// register embeddedBox
|
||||
embedded.RegisterEmbeddedBox(`./`, &embedded.EmbeddedBox{
|
||||
Name: `./`,
|
||||
Time: time.Unix(1501081088, 0),
|
||||
embedded.RegisterEmbeddedBox(`./assets/`, &embedded.EmbeddedBox{
|
||||
Name: `./assets/`,
|
||||
Time: time.Unix(1501232329, 0),
|
||||
Dirs: map[string]*embedded.EmbeddedDir{
|
||||
"": dir1,
|
||||
},
|
||||
Files: map[string]*embedded.EmbeddedFile{
|
||||
"README.md": file2,
|
||||
"hugo.go": file3,
|
||||
"hugo.js": file4,
|
||||
"rice-box.go": file5,
|
||||
"setup.go": file6,
|
||||
"utils.go": file7,
|
||||
"hugo.js": file2,
|
||||
},
|
||||
})
|
||||
}
|
||||
+3
-3
@@ -12,7 +12,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/hacdias/filemanager"
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
@@ -52,7 +52,7 @@ func parse(c *caddy.Controller) ([]*filemanager.FileManager, error) {
|
||||
// Get the baseURL and baseScope
|
||||
args := c.RemainingArgs()
|
||||
|
||||
if len(args) == 1 {
|
||||
if len(args) >= 1 {
|
||||
directory = args[0]
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ func parse(c *caddy.Controller) ([]*filemanager.FileManager, error) {
|
||||
Regexp: &filemanager.Regexp{Raw: "\\/\\..+"},
|
||||
}},
|
||||
CSS: "",
|
||||
FileSystem: dir.Dir(directory),
|
||||
FileSystem: fileutils.Dir(directory),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/hacdias/filemanager"
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
)
|
||||
|
||||
// confFile contains the configuration file for this File Manager instance.
|
||||
@@ -65,7 +65,7 @@ func main() {
|
||||
Commands: strings.Split(strings.TrimSpace(commands), " "),
|
||||
Rules: []*filemanager.Rule{},
|
||||
CSS: "",
|
||||
FileSystem: dir.Dir(scope),
|
||||
FileSystem: fileutils.Dir(scope),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
-230
@@ -1,230 +0,0 @@
|
||||
// Package dir implements a FileSystem interface using the native
|
||||
// file system restricted to a specific directory tree. Originally from
|
||||
// https://github.com/golang/net/blob/master/webdav/file.go#L68
|
||||
package dir
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A Dir uses the native file system restricted to a specific directory tree.
|
||||
//
|
||||
// While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's
|
||||
// string value is a filename on the native file system, not a URL, so it is
|
||||
// separated by filepath.Separator, which isn't necessarily '/'.
|
||||
//
|
||||
// An empty Dir is treated as ".".
|
||||
type Dir string
|
||||
|
||||
func (d Dir) resolve(name string) string {
|
||||
// This implementation is based on Dir.Open's code in the standard net/http package.
|
||||
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
|
||||
strings.Contains(name, "\x00") {
|
||||
return ""
|
||||
}
|
||||
|
||||
dir := string(d)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
|
||||
return filepath.Join(dir, filepath.FromSlash(SlashClean(name)))
|
||||
}
|
||||
|
||||
// Mkdir implements os.Mkdir in this directory context.
|
||||
func (d Dir) Mkdir(name string, perm os.FileMode) error {
|
||||
if name = d.resolve(name); name == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
return os.Mkdir(name, perm)
|
||||
}
|
||||
|
||||
// OpenFile implements os.OpenFile in this directory context.
|
||||
func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
|
||||
if name = d.resolve(name); name == "" {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
f, err := os.OpenFile(name, flag, perm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// RemoveAll implements os.RemoveAll in this directory context.
|
||||
func (d Dir) RemoveAll(name string) error {
|
||||
if name = d.resolve(name); name == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
if name == filepath.Clean(string(d)) {
|
||||
// Prohibit removing the virtual root directory.
|
||||
return os.ErrInvalid
|
||||
}
|
||||
return os.RemoveAll(name)
|
||||
}
|
||||
|
||||
// Rename implements os.Rename in this directory context.
|
||||
func (d Dir) Rename(oldName, newName string) error {
|
||||
if oldName = d.resolve(oldName); oldName == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
if newName = d.resolve(newName); newName == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
if root := filepath.Clean(string(d)); root == oldName || root == newName {
|
||||
// Prohibit renaming from or to the virtual root directory.
|
||||
return os.ErrInvalid
|
||||
}
|
||||
return os.Rename(oldName, newName)
|
||||
}
|
||||
|
||||
// Stat implements os.Stat in this directory context.
|
||||
func (d Dir) Stat(name string) (os.FileInfo, error) {
|
||||
if name = d.resolve(name); name == "" {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
return os.Stat(name)
|
||||
}
|
||||
|
||||
// Copy copies a file or directory from src to dst. If it is
|
||||
// a directory, all of the files and sub-directories will be copied.
|
||||
func (d Dir) Copy(src, dst string) error {
|
||||
if src = d.resolve(src); src == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
if dst = d.resolve(dst); dst == "" {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
if root := filepath.Clean(string(d)); root == src || root == dst {
|
||||
// Prohibit copying from or to the virtual root directory.
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
if dst == src {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
info, err := os.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return CopyDir(src, dst)
|
||||
}
|
||||
|
||||
return CopyFile(src, dst)
|
||||
}
|
||||
|
||||
// SlashClean is equivalent to but slightly more efficient than
|
||||
// path.Clean("/" + name).
|
||||
func SlashClean(name string) string {
|
||||
if name == "" || name[0] != '/' {
|
||||
name = "/" + name
|
||||
}
|
||||
return path.Clean(name)
|
||||
}
|
||||
|
||||
// CopyFile copies a file from source to dest and returns
|
||||
// an error if any.
|
||||
func CopyFile(source string, dest string) error {
|
||||
// Open the source file.
|
||||
src, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// Makes the directory needed to create the dst
|
||||
// file.
|
||||
err = os.MkdirAll(filepath.Dir(dest), 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create the destination file.
|
||||
dst, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
// Copy the contents of the file.
|
||||
_, err = io.Copy(dst, src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Copy the mode if the user can't
|
||||
// open the file.
|
||||
info, err := os.Stat(source)
|
||||
if err != nil {
|
||||
err = os.Chmod(dest, info.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyDir copies a directory from source to dest and all
|
||||
// of its sub-directories. It doesn't stop if it finds an error
|
||||
// during the copy. Returns an error if any.
|
||||
func CopyDir(source string, dest string) error {
|
||||
// Get properties of source.
|
||||
srcinfo, err := os.Stat(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create the destination directory.
|
||||
err = os.MkdirAll(dest, srcinfo.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dir, _ := os.Open(source)
|
||||
obs, err := dir.Readdir(-1)
|
||||
|
||||
var errs []error
|
||||
|
||||
for _, obj := range obs {
|
||||
fsource := source + "/" + obj.Name()
|
||||
fdest := dest + "/" + obj.Name()
|
||||
|
||||
if obj.IsDir() {
|
||||
// Create sub-directories, recursively.
|
||||
err = CopyDir(fsource, fdest)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
} else {
|
||||
// Perform the file copy.
|
||||
err = CopyFile(fsource, fdest)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errString string
|
||||
for _, err := range errs {
|
||||
errString += err.Error() + "\n"
|
||||
}
|
||||
|
||||
if errString != "" {
|
||||
return errors.New(errString)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+2
-2
@@ -9,7 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/archiver"
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ func downloadHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
// Clean the slashes.
|
||||
name = dir.SlashClean(name)
|
||||
name = fileutils.SlashClean(name)
|
||||
files = append(files, filepath.Join(c.FI.Path, name))
|
||||
}
|
||||
} else {
|
||||
|
||||
+3
-3
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
rice "github.com/GeertJohan/go.rice"
|
||||
"github.com/asdine/storm"
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
"github.com/mholt/caddy"
|
||||
)
|
||||
|
||||
@@ -76,7 +76,7 @@ type User struct {
|
||||
Admin bool `json:"admin"`
|
||||
|
||||
// FileSystem is the virtual file system the user has access.
|
||||
FileSystem dir.Dir `json:"filesystem"`
|
||||
FileSystem fileutils.Dir `json:"filesystem"`
|
||||
|
||||
// Rules is an array of access and deny rules.
|
||||
Rules []*Rule `json:"rules"`
|
||||
@@ -136,7 +136,7 @@ var DefaultUser = User{
|
||||
Rules: []*Rule{},
|
||||
CSS: "",
|
||||
Admin: true,
|
||||
FileSystem: dir.Dir("."),
|
||||
FileSystem: fileutils.Dir("."),
|
||||
}
|
||||
|
||||
// New creates a new File Manager instance. If 'database' file already
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
)
|
||||
|
||||
type test struct {
|
||||
@@ -28,13 +28,13 @@ func newTest(t *testing.T) *test {
|
||||
scope := filepath.Join(temp, "scope")
|
||||
database := filepath.Join(temp, "database.db")
|
||||
|
||||
err = dir.CopyDir("./testdata", scope)
|
||||
err = fileutils.CopyDir("./testdata", scope)
|
||||
if err != nil {
|
||||
t.Fatalf("Error copying the test data: %v", err)
|
||||
}
|
||||
|
||||
user := DefaultUser
|
||||
user.FileSystem = dir.Dir(scope)
|
||||
user.FileSystem = fileutils.Dir(scope)
|
||||
|
||||
fm, err := New(database, user)
|
||||
|
||||
|
||||
+3
-3
@@ -10,13 +10,13 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/hacdias/filemanager/dir"
|
||||
"github.com/hacdias/fileutils"
|
||||
)
|
||||
|
||||
// sanitizeURL sanitizes the URL to prevent path transversal
|
||||
// using dir.SlashClean and adds the trailing slash bar.
|
||||
// using fileutils.SlashClean and adds the trailing slash bar.
|
||||
func sanitizeURL(url string) string {
|
||||
path := dir.SlashClean(url)
|
||||
path := fileutils.SlashClean(url)
|
||||
if strings.HasSuffix(url, "/") && path != "/" {
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
be97c942365e7a765698a8c0175b4eec18cb4899
|
||||
8868d0da70d74a9255e7fd2617e88a63ba160479
|
||||
@@ -1,13 +0,0 @@
|
||||
package variables
|
||||
|
||||
import "reflect"
|
||||
|
||||
// IsMap checks if some variable is a map
|
||||
func IsMap(sth interface{}) bool {
|
||||
return reflect.ValueOf(sth).Kind() == reflect.Map
|
||||
}
|
||||
|
||||
// IsSlice checks if some variable is a slice
|
||||
func IsSlice(sth interface{}) bool {
|
||||
return reflect.ValueOf(sth).Kind() == reflect.Slice
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package variables
|
||||
|
||||
import "testing"
|
||||
|
||||
type interfaceToBool struct {
|
||||
Value interface{}
|
||||
Result bool
|
||||
}
|
||||
|
||||
var testIsMap = []*interfaceToBool{
|
||||
{"teste", false},
|
||||
{453478, false},
|
||||
{-984512, false},
|
||||
{true, false},
|
||||
{map[string]bool{}, true},
|
||||
{map[int]bool{}, true},
|
||||
{map[interface{}]bool{}, true},
|
||||
{[]string{}, false},
|
||||
}
|
||||
|
||||
func TestIsMap(t *testing.T) {
|
||||
for _, test := range testIsMap {
|
||||
if IsMap(test.Value) != test.Result {
|
||||
t.Errorf("Incorrect value on IsMap for %v; want: %v; got: %v", test.Value, test.Result, !test.Result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var testIsSlice = []*interfaceToBool{
|
||||
{"teste", false},
|
||||
{453478, false},
|
||||
{-984512, false},
|
||||
{true, false},
|
||||
{map[string]bool{}, false},
|
||||
{map[int]bool{}, false},
|
||||
{map[interface{}]bool{}, false},
|
||||
{[]string{}, true},
|
||||
{[]int{}, true},
|
||||
{[]bool{}, true},
|
||||
{[]interface{}{}, true},
|
||||
}
|
||||
|
||||
func TestIsSlice(t *testing.T) {
|
||||
for _, test := range testIsSlice {
|
||||
if IsSlice(test.Value) != test.Result {
|
||||
t.Errorf("Incorrect value on IsSlice for %v; want: %v; got: %v", test.Value, test.Result, !test.Result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package variables
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// Dict allows to send more than one variable into a template.
|
||||
func Dict(values ...interface{}) (map[string]interface{}, error) {
|
||||
if len(values)%2 != 0 {
|
||||
return nil, errors.New("invalid dict call")
|
||||
}
|
||||
dict := make(map[string]interface{}, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("dict keys must be strings")
|
||||
}
|
||||
dict[key] = values[i+1]
|
||||
}
|
||||
|
||||
return dict, nil
|
||||
}
|
||||
|
||||
// FieldInStruct checks if variable is defined in a struct.
|
||||
func FieldInStruct(data interface{}, field string) bool {
|
||||
t := reflect.Indirect(reflect.ValueOf(data)).Type()
|
||||
|
||||
if t.Kind() != reflect.Struct {
|
||||
log.Print("Non-struct type not allowed.")
|
||||
return false
|
||||
}
|
||||
|
||||
_, b := t.FieldByName(field)
|
||||
return b
|
||||
}
|
||||
|
||||
// StringInSlice checks if a slice contains a string.
|
||||
func StringInSlice(a string, list []string) (bool, int) {
|
||||
for i, b := range list {
|
||||
if b == a {
|
||||
return true, i
|
||||
}
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package variables
|
||||
|
||||
import "testing"
|
||||
|
||||
type testFieldInStructData struct {
|
||||
f1 string
|
||||
f2 bool
|
||||
f3 int
|
||||
f4 func()
|
||||
}
|
||||
|
||||
type testFieldInStruct struct {
|
||||
data interface{}
|
||||
field string
|
||||
result bool
|
||||
}
|
||||
|
||||
var testFieldInStructCases = []testFieldInStruct{
|
||||
{testFieldInStructData{}, "f1", true},
|
||||
{testFieldInStructData{}, "f2", true},
|
||||
{testFieldInStructData{}, "f3", true},
|
||||
{testFieldInStructData{}, "f4", true},
|
||||
{testFieldInStructData{}, "f5", false},
|
||||
{[]string{}, "", false},
|
||||
{map[string]int{"oi": 4}, "", false},
|
||||
{"asa", "", false},
|
||||
{"int", "", false},
|
||||
}
|
||||
|
||||
func TestFieldInStruct(t *testing.T) {
|
||||
for _, pair := range testFieldInStructCases {
|
||||
v := FieldInStruct(pair.data, pair.field)
|
||||
if v != pair.result {
|
||||
t.Error(
|
||||
"For", pair.data,
|
||||
"expected", pair.result,
|
||||
"got", v,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user