commands: Make the --poll flag a duration
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Mon, 5 Jul 2021 08:13:41 +0000 (10:13 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Mon, 5 Jul 2021 08:23:29 +0000 (10:23 +0200)
So you can do:

```
hugo server --poll 700ms
```

See #8720

commands/commands.go
commands/hugo.go
common/types/convert.go
common/types/convert_test.go
docs/content/en/commands/hugo.md
docs/content/en/commands/hugo_mod.md
docs/content/en/commands/hugo_new.md
docs/content/en/commands/hugo_server.md
hugolib/site.go

index 6aacc8e0bded32ddf0e7967a40899b729f710f8c..235f3591768cfb6dc56811dd1bfccc695206bc6c 100644 (file)
@@ -204,7 +204,7 @@ type hugoBuilderCommon struct {
        environment string
 
        buildWatch bool
-       poll       bool
+       poll       string
 
        gc bool
 
@@ -292,7 +292,7 @@ func (cc *hugoBuilderCommon) handleFlags(cmd *cobra.Command) {
        cmd.Flags().StringVarP(&cc.baseURL, "baseURL", "b", "", "hostname (and path) to the root, e.g. http://spf13.com/")
        cmd.Flags().Bool("enableGitInfo", false, "add Git revision, date and author info to the pages")
        cmd.Flags().BoolVar(&cc.gc, "gc", false, "enable to run some cleanup tasks (remove unused cache files) after the build")
-       cmd.Flags().BoolVar(&cc.poll, "poll", false, "use a poll based approach to watch for file system changes")
+       cmd.Flags().StringVar(&cc.poll, "poll", "", "set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes")
 
        cmd.Flags().Bool("templateMetrics", false, "display metrics about template executions")
        cmd.Flags().Bool("templateMetricsHints", false, "calculate some improvement hints when combined with --templateMetrics")
index 7f3b41048a1de30b3ce2edddb006441191bee072..86aa8d5733e0f6395a77c55b7dd75dbc43aac083 100644 (file)
@@ -30,6 +30,8 @@ import (
        "syscall"
        "time"
 
+       "github.com/gohugoio/hugo/common/types"
+
        "github.com/gohugoio/hugo/hugofs"
 
        "github.com/gohugoio/hugo/resources/page"
@@ -820,7 +822,7 @@ func (c *commandeer) fullRebuild(changeType string) {
 }
 
 // newWatcher creates a new watcher to watch filesystem events.
-func (c *commandeer) newWatcher(poll bool, dirList ...string) (*watcher.Batcher, error) {
+func (c *commandeer) newWatcher(pollIntervalStr string, dirList ...string) (*watcher.Batcher, error) {
        if runtime.GOOS == "darwin" {
                tweakLimit()
        }
@@ -830,10 +832,17 @@ func (c *commandeer) newWatcher(poll bool, dirList ...string) (*watcher.Batcher,
                return nil, err
        }
 
-       // The second interval is used by the poll based watcher.
-       // Setting a shorter interval would make it snappier,
-       // but it would consume more CPU.
-       watcher, err := watcher.New(500*time.Millisecond, 700*time.Millisecond, poll)
+       var pollInterval time.Duration
+       poll := pollIntervalStr != ""
+       if poll {
+               pollInterval, err = types.ToDurationE(pollIntervalStr)
+               if err != nil {
+                       return nil, fmt.Errorf("invalid value for flag poll: %s", err)
+               }
+               c.logger.Printf("Use watcher with poll interval %v", pollInterval)
+       }
+
+       watcher, err := watcher.New(500*time.Millisecond, pollInterval, poll)
        if err != nil {
                return nil, err
        }
index 7beb3404e36813a926d1a9180fb2dc381b14c088..0560eda0de09708701f7ca35344734c6e8b92cd8 100644 (file)
@@ -18,10 +18,30 @@ import (
        "fmt"
        "html/template"
        "reflect"
+       "time"
 
        "github.com/spf13/cast"
 )
 
+// ToDuration converts v to time.Duration.
+// See ToDurationE if you need to handle errors.
+func ToDuration(v interface{}) time.Duration {
+       d, _ := ToDurationE(v)
+       return d
+}
+
+// ToDurationE converts v to time.Duration.
+func ToDurationE(v interface{}) (time.Duration, error) {
+       if n := cast.ToInt(v); n > 0 {
+               return time.Duration(n) * time.Millisecond, nil
+       }
+       d, err := time.ParseDuration(cast.ToString(v))
+       if err != nil {
+               return 0, fmt.Errorf("cannot convert %v to time.Duration", v)
+       }
+       return d, nil
+}
+
 // ToStringSlicePreserveString is the same as ToStringSlicePreserveStringE,
 // but it never fails.
 func ToStringSlicePreserveString(v interface{}) []string {
index 364228f4116d8875ab6bfe4cd45276132026111d..88b3036046365af1f590d7aacde076bced54c697 100644 (file)
@@ -16,6 +16,7 @@ package types
 import (
        "encoding/json"
        "testing"
+       "time"
 
        qt "github.com/frankban/quicktest"
 )
@@ -36,3 +37,13 @@ func TestToString(t *testing.T) {
        c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo")
        c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo")
 }
+
+func TestToDuration(t *testing.T) {
+       c := qt.New(t)
+
+       c.Assert(ToDuration("200ms"), qt.Equals, 200*time.Millisecond)
+       c.Assert(ToDuration("200"), qt.Equals, 200*time.Millisecond)
+       c.Assert(ToDuration("4m"), qt.Equals, 4*time.Minute)
+       c.Assert(ToDuration("asdfadf"), qt.Equals, time.Duration(0))
+
+}
index f1e9c95cb83cf255373f2d343c6302ddb2d40fe8..43d9e77b7e1c837e244889e569b2a2458c98cf3e 100644 (file)
@@ -51,7 +51,7 @@ hugo [flags]
       --noChmod                    don't sync permission mode of files
       --noTimes                    don't sync modification time of files
       --path-warnings              print warnings on duplicate target paths etc.
-      --poll                       use a poll based approach to watch for file system changes
+      --poll string                set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes
       --print-mem                  print memory usage to screen at intervals
       --quiet                      build in quiet mode
       --renderToMemory             render to memory (only useful for benchmark testing)
index 70c765e91def7e8c9d2fd56ae57aaeb44d1427ee..044cff1a2700e9c705cb5c706804c3d4c673ec86 100644 (file)
@@ -46,7 +46,7 @@ See https://gohugo.io/hugo-modules/ for more information.
       --noChmod                don't sync permission mode of files
       --noTimes                don't sync modification time of files
       --path-warnings          print warnings on duplicate target paths etc.
-      --poll                   use a poll based approach to watch for file system changes
+      --poll string            set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes
       --print-mem              print memory usage to screen at intervals
       --templateMetrics        display metrics about template executions
       --templateMetricsHints   calculate some improvement hints when combined with --templateMetrics
index d6afe7ed2bf2e75e12e89c3e72ed16866d0fc9f7..4c49d11c7c1a367c467b31c3064911339f47d0af 100644 (file)
@@ -47,7 +47,7 @@ hugo new [path] [flags]
       --noChmod                don't sync permission mode of files
       --noTimes                don't sync modification time of files
       --path-warnings          print warnings on duplicate target paths etc.
-      --poll                   use a poll based approach to watch for file system changes
+      --poll string            set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes
       --print-mem              print memory usage to screen at intervals
       --templateMetrics        display metrics about template executions
       --templateMetricsHints   calculate some improvement hints when combined with --templateMetrics
index 3c9675824aea997e8e4d2733fe8f18a0ad308922..d801054dc5101737156eb5a68c6f9f603660b343 100644 (file)
@@ -59,7 +59,7 @@ hugo server [flags]
       --noHTTPCache            prevent HTTP caching
       --noTimes                don't sync modification time of files
       --path-warnings          print warnings on duplicate target paths etc.
-      --poll                   use a poll based approach to watch for file system changes
+      --poll string            set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes
   -p, --port int               port on which the server will listen (default 1313)
       --print-mem              print memory usage to screen at intervals
       --renderToDisk           render to Destination path (default is render to memory & serve from there)
index 2e23368d723830968cf3548bc34d30f19d7bc108..2e7e1d7f9b01f71902a3703dacff0d7df4779ff8 100644 (file)
@@ -29,6 +29,8 @@ import (
        "strings"
        "time"
 
+       "github.com/gohugoio/hugo/common/types"
+
        "github.com/gohugoio/hugo/common/paths"
 
        "github.com/gohugoio/hugo/common/constants"
@@ -523,13 +525,9 @@ But this also means that your site configuration may not do what you expect. If
        timeout := 30 * time.Second
        if cfg.Language.IsSet("timeout") {
                v := cfg.Language.Get("timeout")
-               if n := cast.ToInt(v); n > 0 {
-                       timeout = time.Duration(n) * time.Millisecond
-               } else {
-                       d, err := time.ParseDuration(cast.ToString(v))
-                       if err == nil {
-                               timeout = d
-                       }
+               d, err := types.ToDurationE(v)
+               if err == nil {
+                       timeout = d
                }
        }