diff --git a/Makefile b/Makefile index ec5d1c3e..f4796dc4 100644 --- a/Makefile +++ b/Makefile @@ -183,6 +183,7 @@ crossbuild_targets = $(addprefix build/mgmt-,$(subst /,-,${GOOSARCHES})) crossbuild: ${crossbuild_targets} clean: ## clean things up + $(MAKE) --quiet -C test clean $(MAKE) --quiet -C bindata clean $(MAKE) --quiet -C lang/funcs clean $(MAKE) --quiet -C lang clean @@ -196,6 +197,8 @@ clean: ## clean things up rm -f build/mgmt-* test: build ## run tests + @# recursively run make in child dir named test + @$(MAKE) --quiet -C test ./test.sh # create all test targets for make tab completion (eg: make test-gofmt) diff --git a/docs/resource-guide.md b/docs/resource-guide.md index 6e3eb94a..ab6e6beb 100644 --- a/docs/resource-guide.md +++ b/docs/resource-guide.md @@ -642,8 +642,8 @@ The signature intentionally matches what is required to satisfy the `go-yaml` #### Example ```golang -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *FooRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes FooRes // indirection to avoid infinite recursion diff --git a/engine/autoedge.go b/engine/autoedge.go index ee6a44f7..e17120f0 100644 --- a/engine/autoedge.go +++ b/engine/autoedge.go @@ -68,7 +68,8 @@ type AutoEdge interface { Test([]bool) bool // call until false } -// ResUID is a unique identifier for a resource, namely it's name, and the kind ("type"). +// ResUID is a unique identifier for a resource, namely it's name, and the kind +// ("type"). type ResUID interface { fmt.Stringer // String() string @@ -104,9 +105,9 @@ func (obj *BaseUID) String() string { } // IFF looks at two UID's and if and only if they are equivalent, returns true. -// If they are not equivalent, it returns false. -// Most resources will want to override this method, since it does the important -// work of actually discerning if two resources are identical in function. +// If they are not equivalent, it returns false. Most resources will want to +// override this method, since it does the important work of actually discerning +// if two resources are identical in function. func (obj *BaseUID) IFF(uid ResUID) bool { res, ok := uid.(*BaseUID) if !ok { diff --git a/engine/graph/autogroup/autogroup_test.go b/engine/graph/autogroup/autogroup_test.go index 066d9fa0..55490864 100644 --- a/engine/graph/autogroup/autogroup_test.go +++ b/engine/graph/autogroup/autogroup_test.go @@ -595,10 +595,11 @@ func TestPgraphGrouping11(t *testing.T) { runGraphCmp(t, g1, g2) } -// simple merge 1 +/* simple merge 1 // a1 a2 a1,a2 // \ / >>> | (arrows point downwards) // b b +*/ func TestPgraphGrouping12(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -620,10 +621,11 @@ func TestPgraphGrouping12(t *testing.T) { runGraphCmp(t, g1, g2) } -// simple merge 2 +/* simple merge 2 // b b // / \ >>> | (arrows point downwards) // a1 a2 a1,a2 +*/ func TestPgraphGrouping13(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -645,10 +647,11 @@ func TestPgraphGrouping13(t *testing.T) { runGraphCmp(t, g1, g2) } -// triple merge +/* triple merge // a1 a2 a3 a1,a2,a3 // \ | / >>> | (arrows point downwards) // b b +*/ func TestPgraphGrouping14(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -673,12 +676,13 @@ func TestPgraphGrouping14(t *testing.T) { runGraphCmp(t, g1, g2) } -// chain merge +/* chain merge // a1 a1 // / \ | // b1 b2 >>> b1,b2 (arrows point downwards) // \ / | // c1 c1 +*/ func TestPgraphGrouping15(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -708,7 +712,7 @@ func TestPgraphGrouping15(t *testing.T) { runGraphCmp(t, g1, g2) } -// re-attach 1 (outer) +/* re-attach 1 (outer) // technically the second possibility is valid too, depending on which order we // merge edges in, and if we don't filter out any unnecessary edges afterwards! // a1 a2 a1,a2 a1,a2 @@ -716,6 +720,7 @@ func TestPgraphGrouping15(t *testing.T) { // b1 / >>> b1 OR b1 / (arrows point downwards) // | / | | / // c1 c1 c1 +*/ func TestPgraphGrouping16(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -743,12 +748,13 @@ func TestPgraphGrouping16(t *testing.T) { runGraphCmp(t, g1, g2) } -// re-attach 2 (inner) +/* re-attach 2 (inner) // a1 b2 a1 // | / | // b1 / >>> b1,b2 (arrows point downwards) // | / | // c1 c1 +*/ func TestPgraphGrouping17(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -776,13 +782,14 @@ func TestPgraphGrouping17(t *testing.T) { runGraphCmp(t, g1, g2) } -// re-attach 3 (double) +/* re-attach 3 (double) // similar to "re-attach 1", technically there is a second possibility for this // a2 a1 b2 a1,a2 // \ | / | // \ b1 / >>> b1,b2 (arrows point downwards) // \ | / | // c1 c1 +*/ func TestPgraphGrouping18(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -813,10 +820,11 @@ func TestPgraphGrouping18(t *testing.T) { runGraphCmp(t, g1, g2) } -// connected merge 0, (no change!) +/* connected merge 0, (no change!) // a1 a1 // \ >>> \ (arrows point downwards) // a2 a2 +*/ func TestPgraphGroupingConnected0(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { @@ -835,12 +843,13 @@ func TestPgraphGroupingConnected0(t *testing.T) { runGraphCmp(t, g1, g2) } -// connected merge 1, (no change!) +/* connected merge 1, (no change!) // a1 a1 // \ \ // b >>> b (arrows point downwards) // \ \ // a2 a2 +*/ func TestPgraphGroupingConnected1(t *testing.T) { g1, _ := pgraph.NewGraph("g1") // original graph { diff --git a/engine/graph/autogroup/util.go b/engine/graph/autogroup/util.go index b4dedf2c..57d9a54f 100644 --- a/engine/graph/autogroup/util.go +++ b/engine/graph/autogroup/util.go @@ -25,8 +25,8 @@ import ( "github.com/purpleidea/mgmt/util/errwrap" ) -// VertexMerge merges v2 into v1 by reattaching the edges where appropriate, -// and then by deleting v2 from the graph. Since more than one edge between two +// VertexMerge merges v2 into v1 by reattaching the edges where appropriate, and +// then by deleting v2 from the graph. Since more than one edge between two // vertices is not allowed, duplicate edges are merged as well. an edge merge // function can be provided if you'd like to control how you merge the edges! func VertexMerge(g *pgraph.Graph, v1, v2 pgraph.Vertex, vertexMergeFn func(pgraph.Vertex, pgraph.Vertex) (pgraph.Vertex, error), edgeMergeFn func(pgraph.Edge, pgraph.Edge) pgraph.Edge) error { diff --git a/engine/resources.go b/engine/resources.go index 3f99a68d..278a6398 100644 --- a/engine/resources.go +++ b/engine/resources.go @@ -30,8 +30,8 @@ import ( // TODO: should each resource be a sub-package? var registeredResources = map[string]func() Res{} -// RegisterResource registers a new resource by providing a constructor -// function that returns a resource object ready to be unmarshalled from YAML. +// RegisterResource registers a new resource by providing a constructor function +// that returns a resource object ready to be unmarshalled from YAML. func RegisterResource(kind string, fn func() Res) { f := fn() if kind == "" { @@ -242,8 +242,8 @@ func Validate(res Res) error { // the Interrupt method to shutdown the resource quickly. Running this method // may leave the resource in a partial state, however this may be desired if you // want a faster exit or if you'd prefer a partial state over letting the -// resource complete in a situation where you made an error and you wish to -// exit quickly to avoid data loss. It is usually triggered after multiple ^C +// resource complete in a situation where you made an error and you wish to exit +// quickly to avoid data loss. It is usually triggered after multiple ^C // signals. type InterruptableRes interface { Res diff --git a/engine/resources/augeas.go b/engine/resources/augeas.go index aa14b24a..1287f254 100644 --- a/engine/resources/augeas.go +++ b/engine/resources/augeas.go @@ -124,8 +124,8 @@ func (obj *AugeasRes) Close() error { return nil } -// Watch is the primary listener for this resource and it outputs events. -// Taken from the File resource. +// Watch is the primary listener for this resource and it outputs events. This +// was taken from the File resource. // FIXME: DRY - This is taken from the file resource func (obj *AugeasRes) Watch() error { var err error @@ -301,8 +301,8 @@ func (obj *AugeasRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *AugeasRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes AugeasRes // indirection to avoid infinite recursion diff --git a/engine/resources/aws_ec2.go b/engine/resources/aws_ec2.go index 3df9850b..0e08b721 100644 --- a/engine/resources/aws_ec2.go +++ b/engine/resources/aws_ec2.go @@ -121,8 +121,8 @@ const ( ) // AwsRegions is a list of all AWS regions generated using ec2.DescribeRegions. -// cn-north-1 and us-gov-west-1 are not returned, probably due to security. -// List available at http://docs.aws.amazon.com/general/latest/gr/rande.html +// cn-north-1 and us-gov-west-1 are not returned, probably due to security. List +// available at http://docs.aws.amazon.com/general/latest/gr/rande.html var AwsRegions = []string{ "ap-northeast-1", "ap-northeast-2", @@ -187,7 +187,8 @@ type AwsEc2Res struct { InstanceID string } -// chanStruct defines the type for a channel used to pass events and errors to watch. +// chanStruct defines the type for a channel used to pass events and errors to +// watch. type chanStruct struct { event awsEc2Event state string @@ -233,7 +234,8 @@ type ruleDetail struct { State []string `json:"state"` } -// postData is the format of the messages received and decoded by snsPostHandler(). +// postData is the format of the messages received and decoded by +// snsPostHandler(). type postData struct { Type string `json:"Type"` MessageID string `json:"MessageId"` @@ -247,7 +249,8 @@ type postData struct { SigningCertURL string `json:"SigningCertURL"` } -// postMsg is used to unmarshal the postData message if it's an event notification. +// postMsg is used to unmarshal the postData message if it's an event +// notification. type postMsg struct { InstanceID string `json:"instance-id"` State string `json:"state"` @@ -413,7 +416,8 @@ func (obj *AwsEc2Res) Watch() error { return obj.longpollWatch() } -// longpollWatch uses the ec2 api's built in methods to watch ec2 resource state. +// longpollWatch uses the ec2 api's built in methods to watch ec2 resource +// state. func (obj *AwsEc2Res) longpollWatch() error { send := false @@ -510,10 +514,10 @@ func (obj *AwsEc2Res) longpollWatch() error { } // snsWatch uses amazon's SNS and CloudWatchEvents APIs to get instance state- -// change notifications pushed to the http endpoint (snsServer) set up below. -// In Init() a CloudWatch rule is created along with a corresponding SNS topic -// that it can publish to. snsWatch creates an http server which listens for -// messages published to the topic and processes them accordingly. +// change notifications pushed to the http endpoint (snsServer) set up below. In +// Init() a CloudWatch rule is created along with a corresponding SNS topic that +// it can publish to. snsWatch creates an http server which listens for messages +// published to the topic and processes them accordingly. func (obj *AwsEc2Res) snsWatch() error { send := false defer obj.wg.Wait() @@ -795,8 +799,8 @@ type AwsEc2UID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *AwsEc2Res) UIDs() []engine.ResUID { x := &AwsEc2UID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -805,8 +809,8 @@ func (obj *AwsEc2Res) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *AwsEc2Res) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes AwsEc2Res // indirection to avoid infinite recursion @@ -942,8 +946,8 @@ func (obj *AwsEc2Res) snsVerifySignature(post postData) error { return nil } -// snsGetCert downloads and parses the signing certificate from the provided -// URL for message verification. +// snsGetCert downloads and parses the signing certificate from the provided URL +// for message verification. func (obj *AwsEc2Res) snsGetCert(url string) (*x509.Certificate, error) { // only download valid certificates from amazon matchURL, err := regexp.MatchString(SnsCertURLRegex, url) @@ -1035,8 +1039,8 @@ func (obj *AwsEc2Res) snsDeleteTopic(topicArn string) error { return nil } -// snsSubscribe subscribes the endpoint to the sns topic. -// Returning SubscriptionArn here is useless as it is still pending confirmation. +// snsSubscribe subscribes the endpoint to the sns topic. Returning +// SubscriptionArn here is useless as it is still pending confirmation. func (obj *AwsEc2Res) snsSubscribe(endpoint string, topicArn string) error { // subscribe to the topic subInput := &sns.SubscribeInput{ @@ -1052,8 +1056,8 @@ func (obj *AwsEc2Res) snsSubscribe(endpoint string, topicArn string) error { return nil } -// snsConfirmSubscription confirms the sns subscription. -// Returning SubscriptionArn here is useless as it is still pending confirmation. +// snsConfirmSubscription confirms the sns subscription. Returning +// SubscriptionArn here is useless as it is still pending confirmation. func (obj *AwsEc2Res) snsConfirmSubscription(topicArn string, token string) error { // confirm the subscription csInput := &sns.ConfirmSubscriptionInput{ @@ -1105,7 +1109,8 @@ func (obj *AwsEc2Res) snsProcessEvent(message, instanceName string) (awsEc2Event return awsEc2EventNone, nil } -// snsAuthorize adds the necessary permission for cloudwatch to publish to the SNS topic. +// snsAuthorize adds the necessary permission for cloudwatch to publish to the +// SNS topic. func (obj *AwsEc2Res) snsAuthorizeCloudWatch(topicArn string) error { // get the topic attributes, including the security policy gaInput := &sns.GetTopicAttributesInput{ diff --git a/engine/resources/config_etcd.go b/engine/resources/config_etcd.go index 9c7043a1..8e4e067a 100644 --- a/engine/resources/config_etcd.go +++ b/engine/resources/config_etcd.go @@ -229,8 +229,8 @@ func (obj *ConfigEtcdRes) Interrupt() error { return nil } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *ConfigEtcdRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes ConfigEtcdRes // indirection to avoid infinite recursion diff --git a/engine/resources/cron.go b/engine/resources/cron.go index 0991037f..0a0941fa 100644 --- a/engine/resources/cron.go +++ b/engine/resources/cron.go @@ -139,9 +139,9 @@ func (obj *CronRes) Default() engine.Res { } } -// makeComposite creates a pointer to a FileRes. The pointer is used to -// validate and initialize the nested file resource and to apply the file state -// in CheckApply. +// makeComposite creates a pointer to a FileRes. The pointer is used to validate +// and initialize the nested file resource and to apply the file state in +// CheckApply. func (obj *CronRes) makeComposite() (*FileRes, error) { p, err := obj.UnitFilePath() if err != nil { @@ -466,8 +466,8 @@ func (obj *CronRes) AutoEdges() (engine.AutoEdge, error) { return nil, nil } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one although some resources can return multiple. func (obj *CronRes) UIDs() []engine.ResUID { unit := fmt.Sprintf("%s.service", obj.Name()) if obj.Unit != "" { @@ -486,8 +486,8 @@ func (obj *CronRes) UIDs() []engine.ResUID { return uids } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *CronRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes CronRes // indirection to avoid infinite recursion diff --git a/engine/resources/docker_container.go b/engine/resources/docker_container.go index 54fca968..bdc31ecd 100644 --- a/engine/resources/docker_container.go +++ b/engine/resources/docker_container.go @@ -450,7 +450,8 @@ func (obj *DockerContainerResAutoEdges) Next() []engine.ResUID { return []engine.ResUID{value} } -// Test gets results of the earlier Next() call, & returns if we should continue. +// Test gets results of the earlier Next() call, & returns if we should +// continue. func (obj *DockerContainerResAutoEdges) Test(input []bool) bool { if len(obj.UIDs) <= obj.pointer { return false @@ -461,8 +462,8 @@ func (obj *DockerContainerResAutoEdges) Test(input []bool) bool { return true // keep going } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *DockerContainerRes) UIDs() []engine.ResUID { x := &DockerContainerUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -471,8 +472,8 @@ func (obj *DockerContainerRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *DockerContainerRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes DockerContainerRes // indirection to avoid infinite recursion diff --git a/engine/resources/docker_image.go b/engine/resources/docker_image.go index 05a23d09..62f0932c 100644 --- a/engine/resources/docker_image.go +++ b/engine/resources/docker_image.go @@ -241,8 +241,8 @@ type DockerImageUID struct { image string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *DockerImageRes) UIDs() []engine.ResUID { x := &DockerImageUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -265,8 +265,8 @@ func (obj *DockerImageUID) IFF(uid engine.ResUID) bool { return obj.image == res.image } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *DockerImageRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes DockerImageRes // indirection to avoid infinite recursion diff --git a/engine/resources/exec.go b/engine/resources/exec.go index c06e4429..88891ef5 100644 --- a/engine/resources/exec.go +++ b/engine/resources/exec.go @@ -553,7 +553,8 @@ func (obj *ExecResAutoEdges) Next() []engine.ResUID { return obj.edges } -// Test gets results of the earlier Next() call, & returns if we should continue! +// Test gets results of the earlier Next() call, & returns if we should +// continue! func (obj *ExecResAutoEdges) Test(input []bool) bool { return false // never keep going // TODO: we could return false if we find as many edges as the number of different path's in cmdFiles() @@ -578,8 +579,8 @@ func (obj *ExecRes) AutoEdges() (engine.AutoEdge, error) { }, nil } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *ExecRes) UIDs() []engine.ResUID { x := &ExecUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -609,8 +610,8 @@ func (obj *ExecRes) Sends() interface{} { } } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *ExecRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes ExecRes // indirection to avoid infinite recursion @@ -690,9 +691,9 @@ type cmdOutput struct { } // cmdOutputRunner wraps the Cmd in with a StdoutPipe scanner and reads for -// errors. It runs Start and Wait, and errors runtime things in the channel. -// If it can't start up the command, it will fail early. Once it's running, it -// will return the channel which can be used for the duration of the process. +// errors. It runs Start and Wait, and errors runtime things in the channel. If +// it can't start up the command, it will fail early. Once it's running, it will +// return the channel which can be used for the duration of the process. // Cancelling the context merely unblocks the sending on the output channel, it // does not Kill the cmd process. For that you must do it yourself elsewhere. func (obj *ExecRes) cmdOutputRunner(ctx context.Context, cmd *exec.Cmd) (chan *cmdOutput, error) { diff --git a/engine/resources/file.go b/engine/resources/file.go index cf27166a..79383e3d 100644 --- a/engine/resources/file.go +++ b/engine/resources/file.go @@ -62,8 +62,8 @@ const ( FileModeAllowAssign = false ) -// FileRes is a file and directory resource. Dirs are defined by names ending -// in a slash. +// FileRes is a file and directory resource. Dirs are defined by names ending in +// a slash. type FileRes struct { traits.Base // add the base methods without re-implementation traits.Edgeable @@ -324,11 +324,11 @@ func (obj *FileRes) Close() error { return nil } -// Watch is the primary listener for this resource and it outputs events. -// This one is a file watcher for files and directories. -// Modify with caution, it is probably important to write some test cases first! -// If the Watch returns an error, it means that something has gone wrong, and it -// must be restarted. On a clean exit it returns nil. +// Watch is the primary listener for this resource and it outputs events. This +// one is a file watcher for files and directories. Modify with caution, it is +// probably important to write some test cases first! If the Watch returns an +// error, it means that something has gone wrong, and it must be restarted. On a +// clean exit it returns nil. func (obj *FileRes) Watch() error { // TODO: chan *recwatch.Event instead? inputEvents := make(chan recwatch.Event) @@ -1322,7 +1322,8 @@ func (obj *FileResAutoEdges) Next() []engine.ResUID { return []engine.ResUID{value} // we return one, even though api supports N } -// Test gets results of the earlier Next() call, & returns if we should continue! +// Test gets results of the earlier Next() call, & returns if we should +// continue! func (obj *FileResAutoEdges) Test(input []bool) bool { // We do all of these first... if !obj.fdone && len(obj.frags) > 0 { @@ -1390,8 +1391,8 @@ func (obj *FileRes) AutoEdges() (engine.AutoEdge, error) { }, nil } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *FileRes) UIDs() []engine.ResUID { x := &FileUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -1417,8 +1418,8 @@ func (obj *FileRes) CollectPattern(pattern string) { obj.Dirname = pattern // XXX: simplistic for now } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *FileRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes FileRes // indirection to avoid infinite recursion diff --git a/engine/resources/group.go b/engine/resources/group.go index b8ee9e86..b6b78fa5 100644 --- a/engine/resources/group.go +++ b/engine/resources/group.go @@ -271,8 +271,8 @@ func (obj *GroupUID) IFF(uid engine.ResUID) bool { return true } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *GroupRes) UIDs() []engine.ResUID { x := &GroupUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -282,8 +282,8 @@ func (obj *GroupRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *GroupRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes GroupRes // indirection to avoid infinite recursion diff --git a/engine/resources/hostname.go b/engine/resources/hostname.go index 99b85994..3f23437f 100644 --- a/engine/resources/hostname.go +++ b/engine/resources/hostname.go @@ -46,12 +46,12 @@ var ErrResourceInsufficientParameters = errors.New("insufficient parameters for // HostnameRes is a resource that allows setting and watching the hostname. // -// StaticHostname is the one configured in /etc/hostname or a similar file. -// It is chosen by the local user. It is not always in sync with the current -// host name as returned by the gethostname() system call. +// StaticHostname is the one configured in /etc/hostname or a similar file. It +// is chosen by the local user. It is not always in sync with the current host +// name as returned by the gethostname() system call. // -// TransientHostname is the one configured via the kernel's sethostbyname(). -// It can be different from the static hostname in case DHCP or mDNS have been +// TransientHostname is the one configured via the kernel's sethostbyname(). It +// can be different from the static hostname in case DHCP or mDNS have been // configured to change the name based on network information. // // PrettyHostname is a free-form UTF8 host name for presentation to the user. @@ -248,8 +248,8 @@ type HostnameUID struct { transientHostname string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *HostnameRes) UIDs() []engine.ResUID { x := &HostnameUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -261,8 +261,8 @@ func (obj *HostnameRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *HostnameRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes HostnameRes // indirection to avoid infinite recursion diff --git a/engine/resources/kv.go b/engine/resources/kv.go index 58426131..d984d8b2 100644 --- a/engine/resources/kv.go +++ b/engine/resources/kv.go @@ -34,10 +34,12 @@ func init() { engine.RegisterResource("kv", func() engine.Res { return &KVRes{} }) } -// KVResSkipCmpStyle represents the different styles of comparison when using SkipLessThan. +// KVResSkipCmpStyle represents the different styles of comparison when using +// SkipLessThan. type KVResSkipCmpStyle int -// These are the different allowed comparison styles. Most folks will want SkipCmpStyleInt. +// These are the different allowed comparison styles. Most folks will want +// SkipCmpStyleInt. const ( SkipCmpStyleInt KVResSkipCmpStyle = iota SkipCmpStyleString @@ -308,8 +310,8 @@ type KVUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *KVRes) UIDs() []engine.ResUID { x := &KVUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -318,8 +320,8 @@ func (obj *KVRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *KVRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes KVRes // indirection to avoid infinite recursion diff --git a/engine/resources/mount.go b/engine/resources/mount.go index a86ebc27..7c098d8b 100644 --- a/engine/resources/mount.go +++ b/engine/resources/mount.go @@ -403,8 +403,8 @@ func (obj *MountUID) IFF(uid engine.ResUID) bool { return obj.name == res.name } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one although some resources can return multiple. func (obj *MountRes) UIDs() []engine.ResUID { x := &MountUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -413,8 +413,8 @@ func (obj *MountRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *MountRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes MountRes // indirection to avoid infinite recursion @@ -499,8 +499,8 @@ func (obj *MountRes) fstabEntryRemove(file string, mount *fstab.Mount) error { return obj.fstabWrite(file, mounts) } -// fstabWrite generates an fstab file with the given mounts, and writes them -// to the provided fstab file. +// fstabWrite generates an fstab file with the given mounts, and writes them to +// the provided fstab file. func (obj *MountRes) fstabWrite(file string, mounts fstab.Mounts) error { // build the file contents contents := fmt.Sprintf("# Generated by %s at %d", obj.init.Program, time.Now().UnixNano()) + "\n" @@ -541,9 +541,9 @@ func mountExists(file string, mount *fstab.Mount) (bool, error) { return false, nil } -// mountCompare compares two mounts. It is assumed that the first comes from -// a resource definition, and the second comes from /proc/mounts. It compares -// the two after resolving the loopback device's file path (if necessary,) and +// mountCompare compares two mounts. It is assumed that the first comes from a +// resource definition, and the second comes from /proc/mounts. It compares the +// two after resolving the loopback device's file path (if necessary,) and // ignores freq and passno, as they may differ between the definition and // /proc/mounts. func mountCompare(def, proc *fstab.Mount) (bool, error) { @@ -599,8 +599,8 @@ func mountReload() error { return nil } -// restartUnit restarts the given dbus unit and waits for it to finish -// starting up. If restartTimeout is exceeded, it will return an error. +// restartUnit restarts the given dbus unit and waits for it to finish starting +// up. If restartTimeout is exceeded, it will return an error. func restartUnit(conn *dbus.Conn, unit string) error { // timeout if we don't get the JobRemoved event ctx, cancel := context.WithTimeout(context.TODO(), dbusRestartCtxTimeout*time.Second) diff --git a/engine/resources/msg.go b/engine/resources/msg.go index b32ffdc8..6a41dc1d 100644 --- a/engine/resources/msg.go +++ b/engine/resources/msg.go @@ -231,8 +231,8 @@ type MsgUID struct { body string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *MsgRes) UIDs() []engine.ResUID { x := &MsgUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -241,8 +241,8 @@ func (obj *MsgRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *MsgRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes MsgRes // indirection to avoid infinite recursion diff --git a/engine/resources/net.go b/engine/resources/net.go index 87acd3e7..92a53020 100644 --- a/engine/resources/net.go +++ b/engine/resources/net.go @@ -81,9 +81,9 @@ const ( socketFile = "pipe.sock" // path in vardir to store our socket file ) -// NetRes is a network interface resource based on netlink. It manages the -// state of a network link. Configuration is also stored in a networkd -// configuration file, so the network is available upon reboot. +// NetRes is a network interface resource based on netlink. It manages the state +// of a network link. Configuration is also stored in a networkd configuration +// file, so the network is available upon reboot. type NetRes struct { traits.Base // add the base methods without re-implementation @@ -99,8 +99,8 @@ type NetRes struct { socketFile string // path for storing the pipe socket file } -// nlChanStruct defines the channel used to send netlink messages and errors -// to the event processing loop in Watch. +// nlChanStruct defines the channel used to send netlink messages and errors to +// the event processing loop in Watch. type nlChanStruct struct { msg []syscall.NetlinkMessage err error @@ -371,8 +371,8 @@ func (obj *NetRes) addrCheckApply(apply bool) (bool, error) { return false, nil } -// gatewayCheckApply checks if the interface has the correct default gateway -// and adds/deletes routes as necessary. +// gatewayCheckApply checks if the interface has the correct default gateway and +// adds/deletes routes as necessary. func (obj *NetRes) gatewayCheckApply(apply bool) (bool, error) { // get all routes from the interface routes, err := netlink.RouteList(obj.iface.link, netlink.FAMILY_V4) @@ -548,8 +548,8 @@ func (obj *NetUID) IFF(uid engine.ResUID) bool { return obj.name == res.name } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one although some resources can return multiple. func (obj *NetRes) UIDs() []engine.ResUID { x := &NetUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -558,8 +558,8 @@ func (obj *NetRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *NetRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes NetRes // indirection to avoid infinite recursion @@ -625,8 +625,8 @@ func (obj *iface) linkUpDown(state string) error { return netlink.LinkSetDown(obj.link) } -// getAddrs returns a list of strings containing all of the interface's -// IP addresses in CIDR format. +// getAddrs returns a list of strings containing all of the interface's IP +// addresses in CIDR format. func (obj *iface) getAddrs() ([]string, error) { var ifaceAddrs []string a, err := obj.iface.Addrs() @@ -694,8 +694,8 @@ func (obj *iface) kernelApply(addrs []string) error { return nil } -// addrApplyDelete, checks the interface's addresses and deletes any that are not -// in the list/definition. +// addrApplyDelete, checks the interface's addresses and deletes any that are +// not in the list/definition. func (obj *iface) addrApplyDelete(objAddrs []string) error { ifaceAddrs, err := obj.getAddrs() if err != nil { diff --git a/engine/resources/noop.go b/engine/resources/noop.go index 80853340..f0f2ecfb 100644 --- a/engine/resources/noop.go +++ b/engine/resources/noop.go @@ -103,8 +103,8 @@ type NoopUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *NoopRes) UIDs() []engine.ResUID { x := &NoopUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -126,8 +126,8 @@ func (obj *NoopRes) GroupCmp(r engine.GroupableRes) error { return nil // noop resources can always be grouped together! } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *NoopRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes NoopRes // indirection to avoid infinite recursion diff --git a/engine/resources/nspawn.go b/engine/resources/nspawn.go index f8045ecf..119c188b 100644 --- a/engine/resources/nspawn.go +++ b/engine/resources/nspawn.go @@ -73,8 +73,8 @@ func (obj *NspawnRes) Default() engine.Res { } } -// makeComposite creates a pointer to a SvcRes. The pointer is used to -// validate and initialize the nested svc. +// makeComposite creates a pointer to a SvcRes. The pointer is used to validate +// and initialize the nested svc. func (obj *NspawnRes) makeComposite() (*SvcRes, error) { res, err := engine.NewNamedResource("svc", fmt.Sprintf(nspawnServiceTmpl, obj.Name())) if err != nil { @@ -304,8 +304,8 @@ func (obj *NspawnUID) IFF(uid engine.ResUID) bool { return obj.name == res.name } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one although some resources can return multiple. func (obj *NspawnRes) UIDs() []engine.ResUID { x := &NspawnUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -314,8 +314,8 @@ func (obj *NspawnRes) UIDs() []engine.ResUID { return append([]engine.ResUID{x}, obj.svc.UIDs()...) } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *NspawnRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes NspawnRes // indirection to avoid infinite recursion diff --git a/engine/resources/packagekit/packagekit.go b/engine/resources/packagekit/packagekit.go index 6497240c..88ae481b 100644 --- a/engine/resources/packagekit/packagekit.go +++ b/engine/resources/packagekit/packagekit.go @@ -37,7 +37,8 @@ const ( Paranoid = false // enable if you see any ghosts ) -// constants which might need to be tweaked or which contain special dbus strings. +// constants which might need to be tweaked or which contain special dbus +// strings. const ( // FIXME: if PkBufferSize is too low, install seems to drop signals PkBufferSize = 1000 @@ -71,7 +72,7 @@ var ( } ) -//type enum_filter uint64 +// type enum_filter uint64 // https://github.com/hughsie/PackageKit/blob/master/lib/packagekit-glib2/pk-enum.c const ( //static const PkEnumMatch enum_filter[] PkFilterEnumUnknown uint64 = 1 << iota // "unknown" @@ -154,7 +155,8 @@ type Conn struct { Logf func(format string, v ...interface{}) } -// PkPackageIDActionData is a struct that is returned by PackagesToPackageIDs in the map values. +// PkPackageIDActionData is a struct that is returned by PackagesToPackageIDs in +// the map values. type PkPackageIDActionData struct { Found bool Installed bool @@ -185,7 +187,8 @@ func (obj *Conn) Close() error { return obj.conn.Close() } -// internal helper to add signal matches to the bus, should only be called once +// matchSignal is an internal helper to add signal matches to the bus. It should +// only be called once. func (obj *Conn) matchSignal(ch chan *dbus.Signal, path dbus.ObjectPath, iface string, signals []string) (func() error, error) { if obj.Debug { obj.Logf("matchSignal(%v, %v, %s, %v)", ch, path, iface, signals) @@ -565,7 +568,8 @@ loop: return nil } -// GetFilesByPackageID gets the list of files that are contained inside a list of packageIDs. +// GetFilesByPackageID gets the list of files that are contained inside a list +// of packageIDs. func (obj *Conn) GetFilesByPackageID(packageIDs []string) (files map[string][]string, err error) { // NOTE: the maximum number of files in an RPM is 52116 in Fedora 23 // https://gist.github.com/purpleidea/b98e60dcd449e1ac3b8a @@ -634,7 +638,8 @@ loop: return } -// GetUpdates gets a list of packages that are installed and which can be updated, mod filter. +// GetUpdates gets a list of packages that are installed and which can be +// updated, mod filter. func (obj *Conn) GetUpdates(filter uint64) ([]string, error) { if obj.Debug { obj.Logf("GetUpdates()") @@ -876,7 +881,8 @@ func (obj *Conn) PackagesToPackageIDs(packageMap map[string]string, filter uint6 return result, nil } -// FilterPackageIDs returns a list of packageIDs which match the set of package names in packages. +// FilterPackageIDs returns a list of packageIDs which match the set of package +// names in packages. func FilterPackageIDs(m map[string]*PkPackageIDActionData, packages []string) ([]string, error) { result := []string{} for _, k := range packages { @@ -890,7 +896,8 @@ func FilterPackageIDs(m map[string]*PkPackageIDActionData, packages []string) ([ return result, nil } -// FilterState returns a map of whether each package queried matches the particular state. +// FilterState returns a map of whether each package queried matches the +// particular state. func FilterState(m map[string]*PkPackageIDActionData, packages []string, state string) (result map[string]bool, err error) { result = make(map[string]bool) pkgs := []string{} // bad pkgs that don't have a bool state @@ -920,7 +927,8 @@ func FilterState(m map[string]*PkPackageIDActionData, packages []string, state s return result, err } -// FilterPackageState returns all packages that are in package and match the specific state. +// FilterPackageState returns all packages that are in package and match the +// specific state. func FilterPackageState(m map[string]*PkPackageIDActionData, packages []string, state string) (result []string, err error) { result = []string{} for _, k := range packages { @@ -946,7 +954,8 @@ func FilterPackageState(m map[string]*PkPackageIDActionData, packages []string, return result, err } -// FlagInData asks whether a flag exists inside the data portion of a packageID field? +// FlagInData asks whether a flag exists inside the data portion of a packageID +// field? func FlagInData(flag, data string) bool { flags := strings.Split(data, ":") for _, f := range flags { diff --git a/engine/resources/password.go b/engine/resources/password.go index f0ff4d11..cad1fcce 100644 --- a/engine/resources/password.go +++ b/engine/resources/password.go @@ -322,8 +322,8 @@ type PasswordUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *PasswordRes) UIDs() []engine.ResUID { x := &PasswordUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -347,8 +347,8 @@ func (obj *PasswordRes) Sends() interface{} { } } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *PasswordRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes PasswordRes // indirection to avoid infinite recursion diff --git a/engine/resources/pkg.go b/engine/resources/pkg.go index 643503ec..8e7ab83a 100644 --- a/engine/resources/pkg.go +++ b/engine/resources/pkg.go @@ -100,8 +100,8 @@ func (obj *PkgRes) Close() error { return nil } -// Watch is the primary listener for this resource and it outputs events. -// It uses the PackageKit UpdatesChanged signal to watch for changes. +// Watch is the primary listener for this resource and it outputs events. It +// uses the PackageKit UpdatesChanged signal to watch for changes. // TODO: https://github.com/hughsie/PackageKit/issues/109 // TODO: https://github.com/hughsie/PackageKit/issues/110 func (obj *PkgRes) Watch() error { @@ -504,7 +504,8 @@ func (obj *PkgResAutoEdges) Next() []engine.ResUID { return result } -// Test gets results of the earlier Next() call, & returns if we should continue! +// Test gets results of the earlier Next() call, & returns if we should +// continue! func (obj *PkgResAutoEdges) Test(input []bool) bool { if !obj.testIsNext { panic("expecting a call to Next()") @@ -591,8 +592,8 @@ func (obj *PkgRes) AutoEdges() (engine.AutoEdge, error) { }, nil } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *PkgRes) UIDs() []engine.ResUID { x := &PkgUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -611,9 +612,9 @@ func (obj *PkgRes) UIDs() []engine.ResUID { return result } -// GroupCmp returns whether two resources can be grouped together or not. -// Can these two resources be merged, aka, does this resource support doing so? -// Will resource allow itself to be grouped _into_ this obj? +// GroupCmp returns whether two resources can be grouped together or not. Can +// these two resources be merged, aka, does this resource support doing so? Will +// resource allow itself to be grouped _into_ this obj? func (obj *PkgRes) GroupCmp(r engine.GroupableRes) error { res, ok := r.(*PkgRes) if !ok { @@ -631,8 +632,8 @@ func (obj *PkgRes) GroupCmp(r engine.GroupableRes) error { return nil } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *PkgRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes PkgRes // indirection to avoid infinite recursion @@ -651,7 +652,8 @@ func (obj *PkgRes) UnmarshalYAML(unmarshal func(interface{}) error) error { return nil } -// ReturnSvcInFileList returns a list of svc names for matches like: `/usr/lib/systemd/system/*.service`. +// ReturnSvcInFileList returns a list of svc names for matches like: +// `/usr/lib/systemd/system/*.service`. func ReturnSvcInFileList(fileList []string) []string { result := []string{} for _, x := range fileList { diff --git a/engine/resources/print.go b/engine/resources/print.go index d54ff3e5..b70062cc 100644 --- a/engine/resources/print.go +++ b/engine/resources/print.go @@ -133,8 +133,8 @@ type PrintUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *PrintRes) UIDs() []engine.ResUID { x := &PrintUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -156,8 +156,8 @@ func (obj *PrintRes) GroupCmp(r engine.GroupableRes) error { return nil // grouped together if we were asked to } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *PrintRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes PrintRes // indirection to avoid infinite recursion diff --git a/engine/resources/resources_test.go b/engine/resources/resources_test.go index 5ac9b3ce..a03c2d42 100644 --- a/engine/resources/resources_test.go +++ b/engine/resources/resources_test.go @@ -118,7 +118,8 @@ func (obj *changedStep) Action() error { } func (obj *changedStep) Expect() error { return nil } -// NewChangedStep waits up to this many ms for a CheckApply action to occur. Watch function to startup. +// NewChangedStep waits up to this many ms for a CheckApply action to occur. +// Watch function to startup. func NewChangedStep(ms uint, expect bool) Step { return &changedStep{ ms: ms, diff --git a/engine/resources/svc.go b/engine/resources/svc.go index cf0f7efa..441f90a2 100644 --- a/engine/resources/svc.go +++ b/engine/resources/svc.go @@ -419,7 +419,8 @@ func (obj *SvcResAutoEdges) Next() []engine.ResUID { return []engine.ResUID{value} // we return one, even though api supports N } -// Test gets results of the earlier Next() call, & returns if we should continue! +// Test gets results of the earlier Next() call, & returns if we should +// continue! func (obj *SvcResAutoEdges) Test(input []bool) bool { // if there aren't any more remaining if len(obj.data) <= obj.pointer { @@ -513,8 +514,8 @@ func (obj *SvcRes) AutoEdges() (engine.AutoEdge, error) { return engineUtil.AutoEdgeCombiner(fileEdge, cronEdge) } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *SvcRes) UIDs() []engine.ResUID { x := &SvcUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -536,8 +537,8 @@ func (obj *SvcRes) UIDs() []engine.ResUID { // return fmt.Errorf("not possible at the moment") //} -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *SvcRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes SvcRes // indirection to avoid infinite recursion diff --git a/engine/resources/test.go b/engine/resources/test.go index e2bb39f4..30c4d5b4 100644 --- a/engine/resources/test.go +++ b/engine/resources/test.go @@ -367,8 +367,8 @@ type TestUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *TestRes) UIDs() []engine.ResUID { x := &TestUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -405,8 +405,8 @@ func (obj *TestRes) Sends() interface{} { } } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *TestRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes TestRes // indirection to avoid infinite recursion diff --git a/engine/resources/tftp.go b/engine/resources/tftp.go index 7e479a62..fc82a206 100644 --- a/engine/resources/tftp.go +++ b/engine/resources/tftp.go @@ -255,8 +255,8 @@ func (obj *TftpServerRes) Cmp(r engine.Res) error { // } //} -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *TftpServerRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes TftpServerRes // indirection to avoid infinite recursion @@ -275,9 +275,9 @@ func (obj *TftpServerRes) UnmarshalYAML(unmarshal func(interface{}) error) error return nil } -// GroupCmp returns whether two resources can be grouped together or not. -// Can these two resources be merged, aka, does this resource support doing so? -// Will resource allow itself to be grouped _into_ this obj? +// GroupCmp returns whether two resources can be grouped together or not. Can +// these two resources be merged, aka, does this resource support doing so? Will +// resource allow itself to be grouped _into_ this obj? func (obj *TftpServerRes) GroupCmp(r engine.GroupableRes) error { res, ok := r.(*TftpFileRes) // different from what we usually do! if !ok { @@ -582,8 +582,8 @@ func (obj *TftpFileRes) Cmp(r engine.Res) error { return nil } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *TftpFileRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes TftpFileRes // indirection to avoid infinite recursion diff --git a/engine/resources/timer.go b/engine/resources/timer.go index 17e7a234..906ef171 100644 --- a/engine/resources/timer.go +++ b/engine/resources/timer.go @@ -133,8 +133,8 @@ type TimerUID struct { name string } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *TimerRes) UIDs() []engine.ResUID { x := &TimerUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -143,8 +143,8 @@ func (obj *TimerRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *TimerRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes TimerRes // indirection to avoid infinite recursion diff --git a/engine/resources/user.go b/engine/resources/user.go index f0b07c3e..d33b2195 100644 --- a/engine/resources/user.go +++ b/engine/resources/user.go @@ -341,12 +341,12 @@ type UserResAutoEdges struct { pointer int } -// AutoEdges returns edges from the user resource to each group found in -// its definition. The groups can be in any of the three applicable fields -// (GID, Group and Groups.) If the user exists, reversed ensures the edge -// goes from group to user, and if the user is absent the edge goes from -// user to group. This ensures that we don't add users to groups that -// don't exist or delete groups before we delete their members. +// AutoEdges returns edges from the user resource to each group found in its +// definition. The groups can be in any of the three applicable fields (GID, +// Group and Groups.) If the user exists, reversed ensures the edge goes from +// group to user, and if the user is absent the edge goes from user to group. +// This ensures that we don't add users to groups that don't exist or delete +// groups before we delete their members. func (obj *UserRes) AutoEdges() (engine.AutoEdge, error) { var result []engine.ResUID var reversed bool @@ -393,7 +393,8 @@ func (obj *UserResAutoEdges) Next() []engine.ResUID { return []engine.ResUID{value} } -// Test gets results of the earlier Next() call, & returns if we should continue. +// Test gets results of the earlier Next() call, & returns if we should +// continue. func (obj *UserResAutoEdges) Test(input []bool) bool { if len(obj.UIDs) <= obj.pointer { return false @@ -404,8 +405,8 @@ func (obj *UserResAutoEdges) Test(input []bool) bool { return true // keep going } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *UserRes) UIDs() []engine.ResUID { x := &UserUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -414,8 +415,8 @@ func (obj *UserRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *UserRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes UserRes // indirection to avoid infinite recursion diff --git a/engine/resources/virt.go b/engine/resources/virt.go index 4bc272a5..897b551d 100644 --- a/engine/resources/virt.go +++ b/engine/resources/virt.go @@ -1262,8 +1262,8 @@ type VirtUID struct { engine.BaseUID } -// UIDs includes all params to make a unique identification of this object. -// Most resources only return one, although some resources can return multiple. +// UIDs includes all params to make a unique identification of this object. Most +// resources only return one, although some resources can return multiple. func (obj *VirtRes) UIDs() []engine.ResUID { x := &VirtUID{ BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()}, @@ -1272,8 +1272,8 @@ func (obj *VirtRes) UIDs() []engine.ResUID { return []engine.ResUID{x} } -// UnmarshalYAML is the custom unmarshal handler for this struct. -// It is primarily useful for setting the defaults. +// UnmarshalYAML is the custom unmarshal handler for this struct. It is +// primarily useful for setting the defaults. func (obj *VirtRes) UnmarshalYAML(unmarshal func(interface{}) error) error { type rawRes VirtRes // indirection to avoid infinite recursion diff --git a/engine/util/mode.go b/engine/util/mode.go index ffd072f0..025d559b 100644 --- a/engine/util/mode.go +++ b/engine/util/mode.go @@ -215,15 +215,15 @@ func modeValueFrom(who string, modeType uint32) os.FileMode { // ParseSymbolicModes parses a slice of symbolic mode strings. By default it // will only accept the assignment input (=), but if allowAssign is true, then -// all symbolic mode strings (=,+,-) can be used as well. +// all symbolic mode strings (=, +, -) can be used as well. // -// Symbolic mode is expected to be a string of who (user, group, other) then -// the operation (=, +, -) then the change (read, write, execute, setuid, -// setgid, sticky). +// Symbolic mode is expected to be a string of who (user, group, other) then the +// operation (=, +, -) then the change (read, write, execute, setuid, setgid, +// sticky). // // Eg: ug=rw // -// If you repeat yourself in the slice (ex. u=rw,u=w) ParseSymbolicModes will +// If you repeat yourself in the slice (eg. u=rw,u=w) ParseSymbolicModes will // fail with an error. func ParseSymbolicModes(modes []string, from os.FileMode, allowAssign bool) (os.FileMode, error) { symModes := make([]struct { diff --git a/engine/util/util.go b/engine/util/util.go index 208987d5..ce3a7ba6 100644 --- a/engine/util/util.go +++ b/engine/util/util.go @@ -91,7 +91,8 @@ func ResToB64(res engine.Res) (string, error) { return base64.StdEncoding.EncodeToString(b.Bytes()), nil } -// B64ToRes decodes a resource from a base64 encoded string (after deserialization). +// B64ToRes decodes a resource from a base64 encoded string (after +// deserialization). func B64ToRes(str string) (engine.Res, error) { var output interface{} bb, err := base64.StdEncoding.DecodeString(str) @@ -441,12 +442,11 @@ func (obj *autoEdgeCombiner) Test(input []bool) bool { return len(obj.ae) > obj.ptr // are there any auto edges left? } -// AutoEdgeCombiner takes any number of AutoEdge structs, and combines them -// into a single one, so that the logic from each one can be built separately, -// and then combined using this utility. This makes implementing different -// AutoEdge generators much easier. This respects the Next() and Test() API, -// and ratchets through each AutoEdge entry until they have all run their -// course. +// AutoEdgeCombiner takes any number of AutoEdge structs, and combines them into +// a single one, so that the logic from each one can be built separately, and +// then combined using this utility. This makes implementing different AutoEdge +// generators much easier. This respects the Next() and Test() API, and ratchets +// through each AutoEdge entry until they have all run their course. func AutoEdgeCombiner(ae ...engine.AutoEdge) (engine.AutoEdge, error) { return &autoEdgeCombiner{ ae: ae, diff --git a/engine/world.go b/engine/world.go index c9ddf68a..74d94375 100644 --- a/engine/world.go +++ b/engine/world.go @@ -23,9 +23,9 @@ import ( "github.com/purpleidea/mgmt/etcd/scheduler" ) -// World is an interface to the rest of the different graph state. It allows -// the GAPI to store state and exchange information throughout the cluster. It -// is the interface each machine uses to communicate with the rest of the world. +// World is an interface to the rest of the different graph state. It allows the +// GAPI to store state and exchange information throughout the cluster. It is +// the interface each machine uses to communicate with the rest of the world. type World interface { // TODO: is there a better name for this interface? ResWatch(context.Context) (chan error, error) ResExport(context.Context, []Res) error diff --git a/etcd/client/resources/resources.go b/etcd/client/resources/resources.go index cadc76da..53c6fb06 100644 --- a/etcd/client/resources/resources.go +++ b/etcd/client/resources/resources.go @@ -114,11 +114,11 @@ func SetResources(ctx context.Context, client interfaces.Client, hostname string return err } -// GetResources collects all of the resources which match a filter from etcd. -// If the kindfilter or hostnameFilter is empty, then it assumes no filtering... +// GetResources collects all of the resources which match a filter from etcd. If +// the kindfilter or hostnameFilter is empty, then it assumes no filtering... // TODO: Expand this with a more powerful filter based on what we eventually // support in our collect DSL. Ideally a server side filter like WithFilter() -// We could do this if the pattern was $NS/exported/$kind/$hostname/$uid = $data. +// could do this if the pattern was $NS/exported/$kind/$hostname/$uid = $data. func GetResources(ctx context.Context, client interfaces.Client, hostnameFilter, kindFilter []string) ([]engine.Res, error) { // key structure is $NS/exported/$hostname/resources/$uid = $data path := fmt.Sprintf("%s/exported/", ns) diff --git a/etcd/client/simple.go b/etcd/client/simple.go index d54948ef..975b1db0 100644 --- a/etcd/client/simple.go +++ b/etcd/client/simple.go @@ -372,10 +372,8 @@ func (obj *Simple) Watcher(ctx context.Context, path string, opts ...etcd.OpOpti // will return an error. Remember to add the WithPrefix() option if you want to // watch recursively. // TODO: do we need to support retry and changed client connections? -// XXX: do we need to track last successful revision and retry from there? -// XXX: if so, use: -// lastRev := response.Header.Revision // TODO: +1 ? -// etcd.WithRev(rev) +// XXX: do we need to track last successful revision and retry from there? If so +// use: lastRev := response.Header.Revision // TODO: +1 ? and: etcd.WithRev(rev) func (obj *Simple) ComplexWatcher(ctx context.Context, path string, opts ...etcd.OpOption) (*interfaces.WatcherInfo, error) { if obj.client == nil { // catch bugs, this often means programming error return nil, fmt.Errorf("client is nil") // extra safety! diff --git a/etcd/client/str/str.go b/etcd/client/str/str.go index 0095c2b2..ba6eaf70 100644 --- a/etcd/client/str/str.go +++ b/etcd/client/str/str.go @@ -37,8 +37,9 @@ const ( // something goes wrong. // XXX: since the caller of this (via the World API) has no way to tell it it's // done, does that mean we leak go-routines since it might still be running, but -// perhaps even blocked??? Could this cause a dead-lock? Should we instead return -// some sort of struct which has a close method with it to ask for a shutdown? +// perhaps even blocked??? Could this cause a dead-lock? Should we instead +// return some sort of struct which has a close method with it to ask for a +// shutdown? func WatchStr(ctx context.Context, client interfaces.Client, key string) (chan error, error) { // new key structure is $NS/strings/$key = $data path := fmt.Sprintf("%s/strings/%s", ns, key) @@ -70,8 +71,8 @@ func GetStr(ctx context.Context, client interfaces.Client, key string) (string, return val, nil } -// SetStr sets a key and hostname pair to a certain value. If the value is -// nil, then it deletes the key. Otherwise the value should point to a string. +// SetStr sets a key and hostname pair to a certain value. If the value is nil, +// then it deletes the key. Otherwise the value should point to a string. // TODO: TTL or delete disconnect? func SetStr(ctx context.Context, client interfaces.Client, key string, data *string) error { // key structure is $NS/strings/$key = $data diff --git a/etcd/deployer/deployer.go b/etcd/deployer/deployer.go index 56ffb1b0..156298fa 100644 --- a/etcd/deployer/deployer.go +++ b/etcd/deployer/deployer.go @@ -128,7 +128,8 @@ func calculateMax(deploys map[uint64]string) uint64 { // GetDeploy returns the deploy with the specified id if it exists. If you input // an id of 0, you'll get back an empty deploy without error. This is useful so // that you can pass through this function easily. -// FIXME: implement this more efficiently so that it doesn't have to download *all* the old deploys from etcd! +// FIXME: implement this more efficiently so that it doesn't have to download +// *all* the old deploys from etcd! func (obj *SimpleDeploy) GetDeploy(ctx context.Context, id uint64) (string, error) { result, err := obj.GetDeploys(ctx) if err != nil { diff --git a/etcd/fs/fs.go b/etcd/fs/fs.go index 0b2a8f4b..03645707 100644 --- a/etcd/fs/fs.go +++ b/etcd/fs/fs.go @@ -82,9 +82,9 @@ var ( // update the metadata pointer to point to the new blob. This might seem slow, // but it has the unique advantage of being relatively straight forward to // implement, and repeated uploads of the same file cost almost nothing. Since -// etcd isn't meant for large file systems, this fits the desired use case. -// This implementation is designed to have a single writer for each superblock, -// but as many readers as you like. +// etcd isn't meant for large file systems, this fits the desired use case. This +// implementation is designed to have a single writer for each superblock, but +// as many readers as you like. // FIXME: this is not currently thread-safe, nor is it clear if it needs to be. // XXX: we probably aren't updating the modification time everywhere we should! // XXX: because we never delete data blocks, we need to occasionally "vacuum". @@ -656,10 +656,10 @@ func (obj *Fs) RemoveAll(path string) error { } // Rename moves or renames a file or directory. -// TODO: seems it's okay to move files or directories, but you can't clobber dirs -// but you can clobber single files. a dir can't clobber a file and a file can't -// clobber a dir. but a file can clobber another file but a dir can't clobber -// another dir. you can also transplant dirs or files into other dirs. +// TODO: seems it's okay to move files or directories, but you can't clobber +// dirs but you can clobber single files. a dir can't clobber a file and a file +// can't clobber a dir. but a file can clobber another file but a dir can't +// clobber another dir. you can also transplant dirs or files into other dirs. func (obj *Fs) Rename(oldname, newname string) error { // XXX: do we need to check if dest path is inside src path? // XXX: if dirs/files are next to each other, do we mess up the .Children list of the common parent? diff --git a/etcd/fs/util.go b/etcd/fs/util.go index 2b2175f1..c8157f1e 100644 --- a/etcd/fs/util.go +++ b/etcd/fs/util.go @@ -24,56 +24,53 @@ import ( "github.com/spf13/afero" ) -// ReadAll reads from r until an error or EOF and returns the data it read. -// A successful call returns err == nil, not err == EOF. Because ReadAll is -// defined to read from src until EOF, it does not treat an EOF from Read -// as an error to be reported. +// ReadAll reads from r until an error or EOF and returns the data it read. A +// successful call returns err == nil, not err == EOF. Because ReadAll is +// defined to read from src until EOF, it does not treat an EOF from Read as an +// error to be reported. //func (obj *Fs) ReadAll(r io.Reader) ([]byte, error) { // // NOTE: doesn't need Fs, same as ioutil.ReadAll package // return afero.ReadAll(r) //} -// ReadDir reads the directory named by dirname and returns -// a list of sorted directory entries. +// ReadDir reads the directory named by dirname and returns a list of sorted +// directory entries. func (obj *Fs) ReadDir(dirname string) ([]os.FileInfo, error) { return afero.ReadDir(obj, dirname) } -// ReadFile reads the file named by filename and returns the contents. -// A successful call returns err == nil, not err == EOF. Because ReadFile -// reads the whole file, it does not treat an EOF from Read as an error -// to be reported. +// ReadFile reads the file named by filename and returns the contents. A +// successful call returns err == nil, not err == EOF. Because ReadFile reads +// the whole file, it does not treat an EOF from Read as an error to be +// reported. func (obj *Fs) ReadFile(filename string) ([]byte, error) { return afero.ReadFile(obj, filename) } -// TempDir creates a new temporary directory in the directory dir -// with a name beginning with prefix and returns the path of the -// new directory. If dir is the empty string, TempDir uses the -// default directory for temporary files (see os.TempDir). -// Multiple programs calling TempDir simultaneously -// will not choose the same directory. It is the caller's responsibility -// to remove the directory when no longer needed. +// TempDir creates a new temporary directory in the directory dir with a name +// beginning with prefix and returns the path of the new directory. If dir is +// the empty string, TempDir uses the default directory for temporary files (see +// os.TempDir). Multiple programs calling TempDir simultaneously will not choose +// the same directory. It is the caller's responsibility to remove the directory +// when no longer needed. func (obj *Fs) TempDir(dir, prefix string) (name string, err error) { return afero.TempDir(obj, dir, prefix) } -// TempFile creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility +// TempFile creates a new temporary file in the directory dir with a name +// beginning with prefix, opens the file for reading and writing, and returns +// the resulting *File. If dir is the empty string, TempFile uses the default +// directory for temporary files (see os.TempDir). Multiple programs calling +// TempFile simultaneously will not choose the same file. The caller can use +// f.Name() to find the pathname of the file. It is the caller's responsibility // to remove the file when no longer needed. func (obj *Fs) TempFile(dir, prefix string) (f afero.File, err error) { return afero.TempFile(obj, dir, prefix) } -// WriteFile writes data to a file named by filename. -// If the file does not exist, WriteFile creates it with permissions perm; -// otherwise WriteFile truncates it before writing. +// WriteFile writes data to a file named by filename. If the file does not +// exist, WriteFile creates it with permissions perm; otherwise WriteFile +// truncates it before writing. func (obj *Fs) WriteFile(filename string, data []byte, perm os.FileMode) error { return afero.WriteFile(obj, filename, data, perm) } @@ -81,9 +78,8 @@ func (obj *Fs) WriteFile(filename string, data []byte, perm os.FileMode) error { // Walk walks the file tree rooted at root, calling walkFn for each file or // directory in the tree, including root. All errors that arise visiting files // and directories are filtered by walkFn. The files are walked in lexical -// order, which makes the output deterministic but means that for very -// large directories Walk can be inefficient. -// Walk does not follow symbolic links. +// order, which makes the output deterministic but means that for very large +// directories Walk can be inefficient. Walk does not follow symbolic links. func (obj *Fs) Walk(root string, walkFn filepath.WalkFunc) error { return afero.Walk(obj, root, walkFn) } diff --git a/etcd/world.go b/etcd/world.go index 86177225..96fc0927 100644 --- a/etcd/world.go +++ b/etcd/world.go @@ -132,7 +132,8 @@ func (obj *World) StrDel(ctx context.Context, namespace string) error { return str.SetStr(ctx, obj.Client, namespace, nil) } -// StrMapWatch returns a channel which spits out events on possible string changes. +// StrMapWatch returns a channel which spits out events on possible string +// changes. func (obj *World) StrMapWatch(ctx context.Context, namespace string) (chan error, error) { return strmap.WatchStrMap(ctx, obj.Client, namespace) } diff --git a/examples/longpoll/redirect-server.go b/examples/longpoll/redirect-server.go index 20939f60..0b9d8112 100644 --- a/examples/longpoll/redirect-server.go +++ b/examples/longpoll/redirect-server.go @@ -13,8 +13,8 @@ import ( "time" ) -// you can use `wget http://127.0.0.1:12345/hello -O /dev/null` -// or `go run client.go` +// you can use `wget http://127.0.0.1:12345/hello -O /dev/null` or you can run +// `go run client.go` const ( addr = ":12345" ) diff --git a/lang/funcs/core/datetime/format_func.go b/lang/funcs/core/datetime/format_func.go index 4e4f48a2..eb25faf8 100644 --- a/lang/funcs/core/datetime/format_func.go +++ b/lang/funcs/core/datetime/format_func.go @@ -35,8 +35,7 @@ func init() { // Format returns returns a textual representation of the input time. The format // has to be defined like specified by the golang "time" package. The time is // the number of seconds since the epoch, and matches what comes from our Now -// function. -// Golang documentation: https://golang.org/pkg/time/#Time.Format +// function. Golang documentation: https://golang.org/pkg/time/#Time.Format func Format(input []types.Value) (types.Value, error) { epochDelta := input[0].Int() if epochDelta < 0 { diff --git a/lang/funcs/core/fmt/printf_func.go b/lang/funcs/core/fmt/printf_func.go index 327a6f80..3ddcc940 100644 --- a/lang/funcs/core/fmt/printf_func.go +++ b/lang/funcs/core/fmt/printf_func.go @@ -67,8 +67,8 @@ func (obj *PrintfFunc) ArgGen(index int) (string, error) { // Polymorphisms returns the possible type signature for this function. In this // case, since the number of arguments can be infinite, it returns the final // precise type if it can be gleamed from the format argument. If it cannot, it -// is because either the format argument was not known statically, or because -// it had an invalid format string. +// is because either the format argument was not known statically, or because it +// had an invalid format string. func (obj *PrintfFunc) Polymorphisms(partialType *types.Type, partialValues []types.Value) ([]*types.Type, error) { if partialType == nil || len(partialValues) < 1 { return nil, fmt.Errorf("first argument must be a static format string") diff --git a/lang/funcs/core/strings/split_func.go b/lang/funcs/core/strings/split_func.go index d3517489..1259bac5 100644 --- a/lang/funcs/core/strings/split_func.go +++ b/lang/funcs/core/strings/split_func.go @@ -31,8 +31,8 @@ func init() { }) } -// Split splits the input string using the separator and returns the -// segments as a list. +// Split splits the input string using the separator and returns the segments as +// a list. func Split(input []types.Value) (types.Value, error) { str, sep := input[0].Str(), input[1].Str() diff --git a/lang/funcs/core/sys/cpucount_fact.go b/lang/funcs/core/sys/cpucount_fact.go index fae01d0f..00bb2311 100644 --- a/lang/funcs/core/sys/cpucount_fact.go +++ b/lang/funcs/core/sys/cpucount_fact.go @@ -66,8 +66,8 @@ func (obj *CPUCountFact) Init(init *facts.Init) error { } // Stream returns the changing values that this fact has over time. It will -// first poll sysfs to get the initial cpu count, and then receives UEvents -// from the kernel as CPUs are added/removed. +// first poll sysfs to get the initial cpu count, and then receives UEvents from +// the kernel as CPUs are added/removed. func (obj CPUCountFact) Stream() error { defer close(obj.init.Output) // signal when we're done @@ -178,8 +178,8 @@ func getCPUCount() (int64, error) { return parseCPUList(string(dat)) } -// Parses a line of the form X,Y,Z,... where X,Y,Z can be either a single CPU or a -// contiguous range of CPUs. e.g. "2,4-31,32-63". If there is an error parsing +// Parses a line of the form X,Y,Z,... where X,Y,Z can be either a single CPU or +// a contiguous range of CPUs. e.g. "2,4-31,32-63". If there is an error parsing // the line the function will return 0. func parseCPUList(list string) (int64, error) { var count int64 diff --git a/lang/funcs/core/sys/env_func.go b/lang/funcs/core/sys/env_func.go index fb4d3531..97796416 100644 --- a/lang/funcs/core/sys/env_func.go +++ b/lang/funcs/core/sys/env_func.go @@ -44,14 +44,16 @@ func init() { }) } -// GetEnv gets environment variable by name or returns empty string if non existing. +// GetEnv gets environment variable by name or returns empty string if non +// existing. func GetEnv(input []types.Value) (types.Value, error) { return &types.StrValue{ V: os.Getenv(input[0].Str()), }, nil } -// DefaultEnv gets environment variable by name or returns default if non existing. +// DefaultEnv gets environment variable by name or returns default if non +// existing. func DefaultEnv(input []types.Value) (types.Value, error) { value, exists := os.LookupEnv(input[0].Str()) if !exists { diff --git a/lang/funcs/core/template_func.go b/lang/funcs/core/template_func.go index eb0e935c..da7a16e1 100644 --- a/lang/funcs/core/template_func.go +++ b/lang/funcs/core/template_func.go @@ -86,9 +86,9 @@ func (obj *TemplateFunc) ArgGen(index int) (string, error) { // case, since the second argument can be an infinite number of values, it // instead returns either the final precise type (if it can be gleamed from the // input partials) or if it cannot, it returns a single entry with the complete -// type but with the variable second argument specified as a `variant` type. -// If it encounters any partial type specifications which are not possible, then -// it errors out. This could happen if you specified a non string template arg. +// type but with the variable second argument specified as a `variant` type. If +// it encounters any partial type specifications which are not possible, then it +// errors out. This could happen if you specified a non string template arg. // XXX: is there a better API than returning a buried `variant` type? func (obj *TemplateFunc) Polymorphisms(partialType *types.Type, partialValues []types.Value) ([]*types.Type, error) { // TODO: return `variant` as second arg for now -- maybe there's a better way? diff --git a/lang/funcs/engine.go b/lang/funcs/engine.go index 0568d42d..16534ab6 100644 --- a/lang/funcs/engine.go +++ b/lang/funcs/engine.go @@ -131,7 +131,8 @@ type Engine struct { // Init initializes the struct. This is the first call you must make. Do not // proceed with calls to other methods unless this succeeds first. This also // loads all the functions by calling Init on each one in the graph. -// TODO: should Init take the graph as an input arg to keep it as a private field? +// TODO: should Init take the graph as an input arg to keep it as a private +// field? func (obj *Engine) Init() error { obj.ag = make(chan error) obj.agLock = &sync.Mutex{} diff --git a/lang/funcs/facts/facts.go b/lang/funcs/facts/facts.go index 39be987b..6034b94f 100644 --- a/lang/funcs/facts/facts.go +++ b/lang/funcs/facts/facts.go @@ -61,8 +61,8 @@ type Info struct { Err error // did this fact validate? } -// Init is the structure of values and references which is passed into all -// facts on initialization. +// Init is the structure of values and references which is passed into all facts +// on initialization. type Init struct { Hostname string // uuid for the host //Noop bool diff --git a/lang/funcs/funcgen/func.go b/lang/funcs/funcgen/func.go index f805709a..f44f7b67 100644 --- a/lang/funcs/funcgen/func.go +++ b/lang/funcs/funcgen/func.go @@ -149,7 +149,8 @@ func (obj *function) MakeGoReturn() (string, error) { return obj.Return[0].ToGolang() } -// ConvertStart returns the start of a casting function required to convert from mcl to golang. +// ConvertStart returns the start of a casting function required to convert from +// mcl to golang. func (obj *function) ConvertStart() string { t := obj.Return[0].Type switch t { @@ -162,7 +163,8 @@ func (obj *function) ConvertStart() string { } } -// ConvertStop returns the end of the conversion function required to convert from mcl to golang. +// ConvertStop returns the end of the conversion function required to convert +// from mcl to golang. func (obj *function) ConvertStop() string { t := obj.Return[0].Type switch t { diff --git a/lang/interfaces/metadata.go b/lang/interfaces/metadata.go index 434b8a72..0659d24a 100644 --- a/lang/interfaces/metadata.go +++ b/lang/interfaces/metadata.go @@ -225,9 +225,9 @@ func ParseMetadata(reader io.Reader) (*Metadata, error) { return metadata, nil } -// FindModulesPath returns an absolute path to the Path dir where modules can -// be found. This can vary, because the current metadata file might not specify -// a Path value, meaning we'd have to return the global modules path. +// FindModulesPath returns an absolute path to the Path dir where modules can be +// found. This can vary, because the current metadata file might not specify a +// Path value, meaning we'd have to return the global modules path. // Additionally, we can search upwards for a path if our metadata file allows // this. It searches with respect to the calling base directory, and uses the // ParentPathBlock field to determine if we're allowed to search upwards. It diff --git a/lang/interfaces/unification.go b/lang/interfaces/unification.go index a03bfc20..116d0f23 100644 --- a/lang/interfaces/unification.go +++ b/lang/interfaces/unification.go @@ -24,8 +24,8 @@ import ( ) // Invariant represents a constraint that is described by the Expr's and Stmt's, -// and which is passed into the unification solver to describe what is known -// by the AST. +// and which is passed into the unification solver to describe what is known by +// the AST. type Invariant interface { // TODO: should we add any other methods to this type? fmt.Stringer diff --git a/lang/structs.go b/lang/structs.go index 5c4812d8..ebab9e14 100644 --- a/lang/structs.go +++ b/lang/structs.go @@ -4459,8 +4459,8 @@ func (obj *StmtInclude) Graph() (*pgraph.Graph, error) { return graph, nil } -// Output returns the output that this include produces. This output is what -// is used to build the output graph. This only exists for statements. The +// Output returns the output that this include produces. This output is what is +// used to build the output graph. This only exists for statements. The // analogous function for expressions is Value. Those Value functions might get // called by this Output function if they are needed to produce the output. The // ultimate source of this output comes from the previously defined StmtClass @@ -4550,8 +4550,8 @@ func (obj *StmtImport) Graph() (*pgraph.Graph, error) { return graph, errwrap.Wrapf(err, "could not create graph") } -// Output returns the output that this include produces. This output is what -// is used to build the output graph. This only exists for statements. The +// Output returns the output that this include produces. This output is what is +// used to build the output graph. This only exists for statements. The // analogous function for expressions is Value. Those Value functions might get // called by this Output function if they are needed to produce the output. This // import statement itself produces no output, as it is only used to populate @@ -4827,10 +4827,12 @@ func (obj *ExprBool) SetScope(scope *interfaces.Scope) error { } // SetType will make no changes if called here. It will error if anything other -// than a Bool is passed in, and doesn't need to be called for this expr to work. +// than a Bool is passed in, and doesn't need to be called for this expr to +// work. func (obj *ExprBool) SetType(typ *types.Type) error { return types.TypeBool.Cmp(typ) } -// Type returns the type of this expression. This method always returns Bool here. +// Type returns the type of this expression. This method always returns Bool +// here. func (obj *ExprBool) Type() (*types.Type, error) { return types.TypeBool, nil } // Unify returns the list of invariants that this node produces. It recursively @@ -4919,9 +4921,8 @@ func (obj *ExprStr) Init(data *interfaces.Data) error { // generally increases the size of the AST when it is used. It calls Interpolate // on any child elements and builds the new node with those new node contents. // Here it attempts to expand the string if there are any internal variables -// which need interpolation. If any are found, it returns a larger AST which -// has a function which returns a string as its root. Otherwise it returns -// itself. +// which need interpolation. If any are found, it returns a larger AST which has +// a function which returns a string as its root. Otherwise it returns itself. func (obj *ExprStr) Interpolate() (interfaces.Expr, error) { pos := &Pos{ // column/line number, starting at 1 @@ -4997,10 +4998,12 @@ func (obj *ExprStr) SetScope(scope *interfaces.Scope) error { } // SetType will make no changes if called here. It will error if anything other -// than an Str is passed in, and doesn't need to be called for this expr to work. +// than an Str is passed in, and doesn't need to be called for this expr to +// work. func (obj *ExprStr) SetType(typ *types.Type) error { return types.TypeStr.Cmp(typ) } -// Type returns the type of this expression. This method always returns Str here. +// Type returns the type of this expression. This method always returns Str +// here. func (obj *ExprStr) Type() (*types.Type, error) { return types.TypeStr, nil } // Unify returns the list of invariants that this node produces. It recursively @@ -5121,10 +5124,12 @@ func (obj *ExprInt) SetScope(scope *interfaces.Scope) error { } // SetType will make no changes if called here. It will error if anything other -// than an Int is passed in, and doesn't need to be called for this expr to work. +// than an Int is passed in, and doesn't need to be called for this expr to +// work. func (obj *ExprInt) SetType(typ *types.Type) error { return types.TypeInt.Cmp(typ) } -// Type returns the type of this expression. This method always returns Int here. +// Type returns the type of this expression. This method always returns Int +// here. func (obj *ExprInt) Type() (*types.Type, error) { return types.TypeInt, nil } // Unify returns the list of invariants that this node produces. It recursively @@ -5247,10 +5252,12 @@ func (obj *ExprFloat) SetScope(scope *interfaces.Scope) error { } // SetType will make no changes if called here. It will error if anything other -// than a Float is passed in, and doesn't need to be called for this expr to work. +// than a Float is passed in, and doesn't need to be called for this expr to +// work. func (obj *ExprFloat) SetType(typ *types.Type) error { return types.TypeFloat.Cmp(typ) } -// Type returns the type of this expression. This method always returns Float here. +// Type returns the type of this expression. This method always returns Float +// here. func (obj *ExprFloat) Type() (*types.Type, error) { return types.TypeFloat, nil } // Unify returns the list of invariants that this node produces. It recursively @@ -9052,7 +9059,6 @@ func (obj *ExprIf) Value() (types.Value, error) { // getScope pulls the local stored scope out of an Expr, without needing to add // a similarly named method to the Expr interface. This is private and not part // of the interface, because it is only used internally. -// is only used // TODO: we could extend this to include Stmt's if it was ever useful func getScope(node interfaces.Expr) (*interfaces.Scope, error) { //if _, ok := node.(interfaces.Expr); !ok { diff --git a/lang/types/type.go b/lang/types/type.go index 076304eb..e51bafb7 100644 --- a/lang/types/type.go +++ b/lang/types/type.go @@ -72,8 +72,8 @@ type Type struct { // cannot represent the type in our type system. Common examples of things it // cannot express include reflect.Invalid, reflect.Interface, Reflect.Complex128 // and more. It is not reversible because some information may be either added -// or lost. For example, reflect.Array and reflect.Slice are both converted to -// a Type of KindList, and KindFunc names the arguments of a func sequentially. +// or lost. For example, reflect.Array and reflect.Slice are both converted to a +// Type of KindList, and KindFunc names the arguments of a func sequentially. // The lossy inverse of this is Reflect. func TypeOf(t reflect.Type) (*Type, error) { typ := t diff --git a/lang/unification/unification.go b/lang/unification/unification.go index 9ad25e9c..97c0d064 100644 --- a/lang/unification/unification.go +++ b/lang/unification/unification.go @@ -906,8 +906,8 @@ func (obj *ExclusiveInvariant) simplify(partials []interfaces.Invariant) ([]inte } // exclusivesProduct returns a list of different products produced from the -// combinatorial product of the list of exclusives. Each ExclusiveInvariant -// must contain between one and more Invariants. This takes every combination of +// combinatorial product of the list of exclusives. Each ExclusiveInvariant must +// contain between one and more Invariants. This takes every combination of // Invariants (choosing one from each ExclusiveInvariant) and returns that list. // In other words, if you have three exclusives, with invariants named (A1, B1), // (A2), and (A3, B3, C3) you'll get: (A1, A2, A3), (A1, A2, B3), (A1, A2, C3), diff --git a/langpuppet/gapi.go b/langpuppet/gapi.go index 24eabeef..5084f972 100644 --- a/langpuppet/gapi.go +++ b/langpuppet/gapi.go @@ -43,11 +43,10 @@ func init() { gapi.Register(Name, func() gapi.GAPI { return &GAPI{} }) // register } -// GAPI implements the main langpuppet GAPI interface. -// It wraps the Puppet and Lang GAPIs and receives graphs from both. -// It then runs a merging algorithm that mainly just makes a union -// of both the sets of vertices and edges. Some vertices are merged -// using a naming convention. Details can be found in the +// GAPI implements the main langpuppet GAPI interface. It wraps the Puppet and +// Lang GAPIs and receives graphs from both. It then runs a merging algorithm +// that mainly just makes a union of both the sets of vertices and edges. Some +// vertices are merged using a naming convention. Details can be found in the // langpuppet.mergeGraphs function. type GAPI struct { langGAPI gapi.GAPI // the wrapped lang entrypoint @@ -66,9 +65,9 @@ type GAPI struct { wg sync.WaitGroup // sync group for tunnel go routines } -// CliFlags returns a list of flags used by this deploy subcommand. -// It consists of all flags accepted by lang and puppet mode, -// with a respective "lp-" prefix. +// CliFlags returns a list of flags used by this deploy subcommand. It consists +// of all flags accepted by lang and puppet mode, with a respective "lp-" +// prefix. func (obj *GAPI) CliFlags(command string) []cli.Flag { langFlags := (&lang.GAPI{}).CliFlags(command) puppetFlags := (&puppet.GAPI{}).CliFlags(command) diff --git a/langpuppet/merge.go b/langpuppet/merge.go index 2466d5a8..6ccdce34 100644 --- a/langpuppet/merge.go +++ b/langpuppet/merge.go @@ -33,17 +33,15 @@ const ( MergePrefixPuppet = "mgmt_" ) -// mergeGraph returns the merged graph containing all vertices -// and edges found in the graphs produced by the lang and Puppet GAPIs -// associated with the wrapping GAPI. -// Vertices are merged if they adhere to the following rules (for any -// given value of POSTFIX): -// 1. The graph from lang contains a noop vertex named puppet_POSTFIX -// 2. The graph from Puppet contains an empty class mgmt_POSTFIX -// 3. The resulting graph will contain one noop vertex named POSTFIX -// that replaces all nodes mentioned in (1) and (2) -// All edges connecting to any of the vertices merged this way -// will be present in the merged graph. +// mergeGraph returns the merged graph containing all vertices and edges found +// in the graphs produced by the lang and Puppet GAPIs associated with the +// wrapping GAPI. Vertices are merged if they adhere to the following rules (for +// any given value of POSTFIX): (1) The graph from lang contains a noop vertex +// named puppet_POSTFIX. (2) The graph from Puppet contains an empty class +// mgmt_POSTFIX. (3) The resulting graph will contain one noop vertex named +// POSTFIX that replaces all nodes mentioned in (1) and (2). All edges +// connecting to any of the vertices merged this way will be present in the +// merged graph. func mergeGraphs(graphFromLang, graphFromPuppet *pgraph.Graph) (*pgraph.Graph, error) { if graphFromLang == nil || graphFromPuppet == nil { return nil, fmt.Errorf("cannot merge graphs until both child graphs are loaded") diff --git a/pgp/pgp.go b/pgp/pgp.go index afb7ae30..46df0d88 100644 --- a/pgp/pgp.go +++ b/pgp/pgp.go @@ -71,7 +71,8 @@ func Import(privKeyPath string) (*PGP, error) { return obj, nil } -// Generate creates new key pair. This key pair must be saved or it will be lost. +// Generate creates new key pair. This key pair must be saved or it will be +// lost. func Generate(name, comment, email string, hash *crypto.Hash) (*PGP, error) { if hash != nil { CONFIG.DefaultHash = *hash diff --git a/pgraph/graphsync.go b/pgraph/graphsync.go index 676dc354..f9d3d164 100644 --- a/pgraph/graphsync.go +++ b/pgraph/graphsync.go @@ -38,10 +38,10 @@ func strEdgeCmpFn(e1, e2 Edge) (bool, error) { } // GraphSync updates the Graph so that it matches the newGraph. It leaves -// identical elements alone so that they don't need to be refreshed. -// It tries to mutate existing elements into new ones, if they support this. -// This updates the Graph on success only. If it fails, then the graph won't -// have been modified. +// identical elements alone so that they don't need to be refreshed. It tries to +// mutate existing elements into new ones, if they support this. This updates +// the Graph on success only. If it fails, then the graph won't have been +// modified. // FIXME: should we do this with copies of the vertex resources? func (obj *Graph) GraphSync(newGraph *Graph, vertexCmpFn func(Vertex, Vertex) (bool, error), vertexAddFn func(Vertex) error, vertexRemoveFn func(Vertex) error, edgeCmpFn func(Edge, Edge) (bool, error)) error { oldGraph := obj.Copy() // work on a copy of the old graph diff --git a/pgraph/pgraph.go b/pgraph/pgraph.go index 5510e1b0..48038841 100644 --- a/pgraph/pgraph.go +++ b/pgraph/pgraph.go @@ -26,8 +26,8 @@ import ( "github.com/purpleidea/mgmt/util/errwrap" ) -// Graph is the graph structure in this library. -// The graph abstract data type (ADT) is defined as follows: +// Graph is the graph structure in this library. The graph abstract data type +// (ADT) is defined as follows: // * the directed graph arrows point from left to right ( -> ) // * the arrows point away from their dependencies (eg: arrows mean "before") // * IOW, you might see package -> file -> service (where package runs first) @@ -197,8 +197,8 @@ func (g *Graph) FindEdge(v1, v2 Vertex) Edge { return edge } -// Vertices returns a randomly sorted slice of all vertices in the graph. -// The order is random, because the map implementation is intentionally so! +// Vertices returns a randomly sorted slice of all vertices in the graph. The +// order is random, because the map implementation is intentionally so! func (g *Graph) Vertices() []Vertex { var vertices []Vertex for k := range g.adjacency { @@ -207,8 +207,8 @@ func (g *Graph) Vertices() []Vertex { return vertices } -// Edges returns a randomly sorted slice of all edges in the graph. -// The order is random, because the map implementation is intentionally so! +// Edges returns a randomly sorted slice of all edges in the graph. The order is +// random, because the map implementation is intentionally so! func (g *Graph) Edges() []Edge { var edges []Edge for vertex := range g.adjacency { @@ -246,8 +246,8 @@ func (vs VertexSlice) Less(i, j int) bool { return vs[i].String() < vs[j].String // Sort is a convenience method. func (vs VertexSlice) Sort() { sort.Sort(vs) } -// VerticesSorted returns a sorted slice of all vertices in the graph. -// The order is sorted by String() to avoid the non-determinism in the map type. +// VerticesSorted returns a sorted slice of all vertices in the graph. The order +// is sorted by String() to avoid the non-determinism in the map type. func (g *Graph) VerticesSorted() []Vertex { var vertices []Vertex for k := range g.adjacency { @@ -321,8 +321,8 @@ func (g *Graph) OutgoingGraphVertices(v Vertex) []Vertex { return s } -// GraphVertices returns an array (slice) of all vertices that connect to vertex v. -// This is the union of IncomingGraphVertices and OutgoingGraphVertices. +// GraphVertices returns an array (slice) of all vertices that connect to vertex +// v. This is the union of IncomingGraphVertices and OutgoingGraphVertices. func (g *Graph) GraphVertices(v Vertex) []Vertex { var s []Vertex s = append(s, g.IncomingGraphVertices(v)...) @@ -330,7 +330,8 @@ func (g *Graph) GraphVertices(v Vertex) []Vertex { return s } -// IncomingGraphEdges returns all of the edges that point to vertex v (??? -> v). +// IncomingGraphEdges returns all of the edges that point to vertex v. +// Eg: (??? -> v). func (g *Graph) IncomingGraphEdges(v Vertex) []Edge { var edges []Edge for v1 := range g.adjacency { // reverse paths @@ -343,7 +344,8 @@ func (g *Graph) IncomingGraphEdges(v Vertex) []Edge { return edges } -// OutgoingGraphEdges returns all of the edges that point from vertex v (v -> ???). +// OutgoingGraphEdges returns all of the edges that point from vertex v. +// Eg: (v -> ???). func (g *Graph) OutgoingGraphEdges(v Vertex) []Edge { var edges []Edge for _, e := range g.adjacency[v] { // forward paths @@ -435,7 +437,8 @@ func (g *Graph) DisconnectedGraphs() ([]*Graph, error) { return graphs, nil } -// InDegree returns the count of vertices that point to me in one big lookup map. +// InDegree returns the count of vertices that point to me in one big lookup +// map. func (g *Graph) InDegree() map[Vertex]int { result := make(map[Vertex]int) if g == nil || g.adjacency == nil { @@ -453,7 +456,8 @@ func (g *Graph) InDegree() map[Vertex]int { return result } -// OutDegree returns the count of vertices that point away in one big lookup map. +// OutDegree returns the count of vertices that point away in one big lookup +// map. func (g *Graph) OutDegree() map[Vertex]int { result := make(map[Vertex]int) if g == nil || g.adjacency == nil { @@ -468,8 +472,8 @@ func (g *Graph) OutDegree() map[Vertex]int { return result } -// TopologicalSort returns the sort of graph vertices in that order. -// It is based on descriptions and code from wikipedia and rosetta code. +// TopologicalSort returns the sort of graph vertices in that order. It is based +// on descriptions and code from wikipedia and rosetta code. // TODO: add memoization, and cache invalidation to speed this up :) func (g *Graph) TopologicalSort() ([]Vertex, error) { // kahn's algorithm var L []Vertex // empty list that will contain the sorted elements @@ -523,6 +527,7 @@ func (g *Graph) TopologicalSort() ([]Vertex, error) { // kahn's algorithm // Since there could be more than one possible result for this operation, we // arbitrarily choose one of the shortest possible. As a result, this should // actually return a tree if we cared about correctness. +// // This operates by a recursive algorithm; a more efficient version is likely. // If you don't give this function a DAG, you might cause infinite recursion! func (g *Graph) Reachability(a, b Vertex) ([]Vertex, error) { @@ -667,7 +672,8 @@ Loop: return nil // success! } -// VertexContains is an "in array" function to test for a vertex in a slice of vertices. +// VertexContains is an "in array" function to test for a vertex in a slice of +// vertices. func VertexContains(needle Vertex, haystack []Vertex) bool { for _, v := range haystack { if needle == v { @@ -677,7 +683,8 @@ func VertexContains(needle Vertex, haystack []Vertex) bool { return false } -// EdgeContains is an "in array" function to test for an edge in a slice of edges. +// EdgeContains is an "in array" function to test for an edge in a slice of +// edges. func EdgeContains(needle Edge, haystack []Edge) bool { for _, v := range haystack { if needle == v { diff --git a/pgraph/subgraph.go b/pgraph/subgraph.go index 7a876fac..5c2699bf 100644 --- a/pgraph/subgraph.go +++ b/pgraph/subgraph.go @@ -22,36 +22,36 @@ func (g *Graph) AddGraph(graph *Graph) { g.addEdgeVertexGraphHelper(nil, graph, nil, false, false) } -// AddEdgeVertexGraph adds a directed edge to the graph from a vertex. -// This is useful for flattening the relationship between a subgraph and an -// existing graph, without having to run the subgraph recursively. It adds the -// maximum number of edges, creating a relationship to every vertex. +// AddEdgeVertexGraph adds a directed edge to the graph from a vertex. This is +// useful for flattening the relationship between a subgraph and an existing +// graph, without having to run the subgraph recursively. It adds the maximum +// number of edges, creating a relationship to every vertex. func (g *Graph) AddEdgeVertexGraph(vertex Vertex, graph *Graph, edgeGenFn func(v1, v2 Vertex) Edge) { g.addEdgeVertexGraphHelper(vertex, graph, edgeGenFn, false, false) } -// AddEdgeVertexGraphLight adds a directed edge to the graph from a vertex. -// This is useful for flattening the relationship between a subgraph and an -// existing graph, without having to run the subgraph recursively. It adds the -// minimum number of edges, creating a relationship to the vertices with -// indegree equal to zero. +// AddEdgeVertexGraphLight adds a directed edge to the graph from a vertex. This +// is useful for flattening the relationship between a subgraph and an existing +// graph, without having to run the subgraph recursively. It adds the minimum +// number of edges, creating a relationship to the vertices with indegree equal +// to zero. func (g *Graph) AddEdgeVertexGraphLight(vertex Vertex, graph *Graph, edgeGenFn func(v1, v2 Vertex) Edge) { g.addEdgeVertexGraphHelper(vertex, graph, edgeGenFn, false, true) } -// AddEdgeGraphVertex adds a directed edge to the vertex from a graph. -// This is useful for flattening the relationship between a subgraph and an -// existing graph, without having to run the subgraph recursively. It adds the -// maximum number of edges, creating a relationship from every vertex. +// AddEdgeGraphVertex adds a directed edge to the vertex from a graph. This is +// useful for flattening the relationship between a subgraph and an existing +// graph, without having to run the subgraph recursively. It adds the maximum +// number of edges, creating a relationship from every vertex. func (g *Graph) AddEdgeGraphVertex(graph *Graph, vertex Vertex, edgeGenFn func(v1, v2 Vertex) Edge) { g.addEdgeVertexGraphHelper(vertex, graph, edgeGenFn, true, false) } -// AddEdgeGraphVertexLight adds a directed edge to the vertex from a graph. -// This is useful for flattening the relationship between a subgraph and an -// existing graph, without having to run the subgraph recursively. It adds the -// minimum number of edges, creating a relationship from the vertices with -// outdegree equal to zero. +// AddEdgeGraphVertexLight adds a directed edge to the vertex from a graph. This +// is useful for flattening the relationship between a subgraph and an existing +// graph, without having to run the subgraph recursively. It adds the minimum +// number of edges, creating a relationship from the vertices with outdegree +// equal to zero. func (g *Graph) AddEdgeGraphVertexLight(graph *Graph, vertex Vertex, edgeGenFn func(v1, v2 Vertex) Edge) { g.addEdgeVertexGraphHelper(vertex, graph, edgeGenFn, true, true) } diff --git a/prometheus/prometheus.go b/prometheus/prometheus.go index 4968ea77..8227d216 100644 --- a/prometheus/prometheus.go +++ b/prometheus/prometheus.go @@ -46,8 +46,8 @@ const ( ResStateHardFail ) -// Prometheus is the struct that contains information about the -// prometheus instance. Run Init() on it. +// Prometheus is the struct that contains information about the prometheus +// instance. Run Init() on it. type Prometheus struct { Listen string // the listen specification for the net/http server @@ -133,8 +133,8 @@ func (obj *Prometheus) Init() error { return nil } -// Start runs a http server in a go routine, that responds to /metrics -// as prometheus would expect. +// Start runs a http server in a go routine, that responds to /metrics as +// prometheus would expect. func (obj *Prometheus) Start() error { http.Handle("/metrics", promhttp.Handler()) go http.ListenAndServe(obj.Listen, nil) @@ -148,8 +148,8 @@ func (obj *Prometheus) Stop() error { return nil } -// InitKindMetrics initialized prometheus counters. For each kind of -// resource checkApply counters are initialized with all the possible value. +// InitKindMetrics initialized prometheus counters. For each kind of resource, +// checkApply counters are initialized with all the possible value. func (obj *Prometheus) InitKindMetrics(kinds []string) error { if obj == nil { return nil // happens when mgmt is launched without --prometheus @@ -194,8 +194,8 @@ func (obj *Prometheus) UpdateCheckApplyTotal(kind string, apply, eventful, error return nil } -// UpdatePgraphStartTime updates the mgmt_graph_start_time_seconds metric -// to the current timestamp. +// UpdatePgraphStartTime updates the mgmt_graph_start_time_seconds metric to the +// current timestamp. func (obj *Prometheus) UpdatePgraphStartTime() error { if obj == nil { return nil // happens when mgmt is launched without --prometheus @@ -204,7 +204,8 @@ func (obj *Prometheus) UpdatePgraphStartTime() error { return nil } -// AddManagedResource increments the Managed Resource counter and updates the resource status. +// AddManagedResource increments the Managed Resource counter and updates the +// resource status. func (obj *Prometheus) AddManagedResource(resUUID string, rtype string) error { if obj == nil { return nil // happens when mgmt is launched without --prometheus @@ -216,7 +217,8 @@ func (obj *Prometheus) AddManagedResource(resUUID string, rtype string) error { return nil } -// RemoveManagedResource decrements the Managed Resource counter and updates the resource status. +// RemoveManagedResource decrements the Managed Resource counter and updates the +// resource status. func (obj *Prometheus) RemoveManagedResource(resUUID string, rtype string) error { if obj == nil { return nil // happens when mgmt is launched without --prometheus @@ -228,7 +230,8 @@ func (obj *Prometheus) RemoveManagedResource(resUUID string, rtype string) error return nil } -// deleteState removes the resources for the state map and re-populates the failing gauge. +// deleteState removes the resources for the state map and re-populates the +// failing gauge. func (obj *Prometheus) deleteState(resUUID string) error { if obj == nil { return nil // happens when mgmt is launched without --prometheus @@ -242,8 +245,8 @@ func (obj *Prometheus) deleteState(resUUID string) error { return nil } -// UpdateState updates the state of the resources in our internal state map -// then triggers a refresh of the failing gauge. +// UpdateState updates the state of the resources in our internal state map then +// triggers a refresh of the failing gauge. func (obj *Prometheus) UpdateState(resUUID string, rtype string, newState ResState) error { defer obj.updateFailingGauge() if obj == nil { @@ -266,8 +269,8 @@ func (obj *Prometheus) UpdateState(resUUID string, rtype string, newState ResSta return nil } -// updateFailingGauge refreshes the failing gauge by parsking the internal -// state map. +// updateFailingGauge refreshes the failing gauge by parsking the internal state +// map. func (obj *Prometheus) updateFailingGauge() error { if obj == nil { return nil // happens when mgmt is launched without --prometheus diff --git a/prometheus/prometheus_test.go b/prometheus/prometheus_test.go index 19a64e51..004c84e2 100644 --- a/prometheus/prometheus_test.go +++ b/prometheus/prometheus_test.go @@ -25,8 +25,8 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -// TestInitKindMetrics tests that we are initializing the Prometheus -// metrics correctly for all kind of resources. +// TestInitKindMetrics tests that we are initializing the Prometheus metrics +// correctly for all kinds of resources. func TestInitKindMetrics(t *testing.T) { var prom Prometheus prom.Init() diff --git a/puppet/puppet.go b/puppet/puppet.go index f1aa5aa7..a4f9b455 100644 --- a/puppet/puppet.go +++ b/puppet/puppet.go @@ -117,7 +117,8 @@ func (obj *GAPI) ParseConfigFromPuppet() (*yamlgraph.GraphConfig, error) { return &config, nil } -// RefreshInterval returns the graph refresh interval from the puppet configuration. +// RefreshInterval returns the graph refresh interval from the puppet +// configuration. func (obj *GAPI) refreshInterval() int { if obj.data.Debug { obj.data.Logf("determining graph refresh interval") diff --git a/test/.gitignore b/test/.gitignore new file mode 100644 index 00000000..c993889f --- /dev/null +++ b/test/.gitignore @@ -0,0 +1 @@ +comment_parser diff --git a/test/Makefile b/test/Makefile new file mode 100644 index 00000000..433ba329 --- /dev/null +++ b/test/Makefile @@ -0,0 +1,30 @@ +# Mgmt +# Copyright (C) 2013-2020+ James Shubin and the project contributors +# Written by James Shubin and the project contributors +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +SHELL = /usr/bin/env bash +.PHONY: all build clean + +all: build + +build: comment_parser + +clean: + @rm -f comment_parser || true + +comment_parser: comment_parser.go + @echo "Generating: comment_parser..." + go build comment_parser.go diff --git a/test/comment_parser.go b/test/comment_parser.go new file mode 100644 index 00000000..f834d5bc --- /dev/null +++ b/test/comment_parser.go @@ -0,0 +1,262 @@ +// Mgmt +// Copyright (C) 2013-2020+ James Shubin and the project contributors +// Written by James Shubin and the project contributors +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +package main + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "log" + "os" + "strings" + "unicode" +) + +const ( + // Debug specifies if we want to be more verbose. + Debug = false + + // CommentPrefix is the prefix we look for at the beginning of comments. + CommentPrefix = "// " + + // CommentMultilinePrefix is what a multiline comment starts with. + CommentMultilinePrefix = "/*" + + // StandardWidth is 80 chars. If something sneaks past, this is okay, + // but there is no excuse if docstrings don't wrap and reflow to this. + StandardWidth = 80 + + // maxLength is the effective maximum length of each comment line. + maxLength = StandardWidth - len(CommentPrefix) +) + +var ( + // commentPrefixTrimmed is a trimmed copy of the CommentPrefix constant. + commentPrefixTrimmed = strings.TrimRightFunc(CommentPrefix, unicode.IsSpace) +) + +func main() { + if len(os.Args) != 2 { + fmt.Fprintf(os.Stderr, "usage: ./%s \n", os.Args[0]) + os.Exit(2) + return + } + + filename := os.Args[1] + if filename == "" { + fmt.Fprintf(os.Stderr, "filename is empty\n") + os.Exit(2) + return + } + + if err := Check(filename); err != nil { + fmt.Fprintf(os.Stderr, "failed with: %+v\n", err) + os.Exit(1) + return + } +} + +// Check returns the comment checker on an individual filename. +func Check(filename string) error { + if Debug { + log.Printf("filename: %s", filename) + } + + fset := token.NewFileSet() + + // f is a: https://golang.org/pkg/go/ast/#File + f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) + if err != nil { + return err + } + + // XXX: f.Doc // CommentGroup + // XXX: f.Comments []*CommentGroup // list of all comments in the source file + // XXX: f.Decls []Decl // top-level declarations; or nil + + for _, node := range f.Decls { + var doc *ast.CommentGroup + + // TODO: move to type switch ? + if x, ok := node.(*ast.FuncDecl); ok { + doc = x.Doc + } else if x, ok := node.(*ast.GenDecl); ok { + switch x.Tok { + case token.IMPORT: // i don't think this is needed, aiui + case token.VAR: + // TODO: recurse into https://golang.org/pkg/go/ast/#ValueSpec + doc = x.Doc + case token.CONST: + // TODO: recurse into https://golang.org/pkg/go/ast/#ValueSpec + doc = x.Doc + case token.TYPE: // struct, usually + // TODO: recurse into x.Tok (eg: TypeSpec.Doc and so on) + doc = x.Doc + default: + } + } + + if doc == nil { // we got nothing + continue + } + + pos := doc.Pos() + ff := fset.File(pos) + items := strings.Split(ff.Name(), "/") + if len(items) == 0 { + return fmt.Errorf("file name is empty") + } + name := items[len(items)-1] + ident := fmt.Sprintf("%s:%d", name, ff.Line(pos)) + + block := []string{} + for _, comment := range doc.List { + if comment == nil { + continue + } + s := comment.Text + + // TODO: how do we deal with multiline comments? + if strings.HasPrefix(s, CommentMultilinePrefix) { + break // skip + } + + if s != commentPrefixTrimmed && !strings.HasPrefix(s, CommentPrefix) { + return fmt.Errorf("location (%s) missing comment prefix", ident) + } + if s == commentPrefixTrimmed { // blank lines + s = "" + } + + s = strings.TrimPrefix(s, CommentPrefix) + + block = append(block, s) + } + + if err := IsWrappedProperly(block, maxLength); err != nil { + m := strings.Join(block, "\n") + msg := filename + " " + strings.Repeat(".", maxLength-len(filename+" "+"V")) + fmt.Sprintf("V\n%+v\n", m) + fmt.Fprintf(os.Stderr, msg) + return fmt.Errorf("block (%s) failed: %+v", ident, err) // TODO: errwrap ? + } + } + + return nil +} + +// IsWrappedProperly returns whether a block of lines are correctly wrapped. +// This also checks for a few related formatting situations. The list of lines +// should not have trailing newline characters present. While you most surely +// will want to ensure a maximum length of 80 characters, you'll want to +// subtract the comment prefix length from this value so that the final result +// is correctly wrapped. +func IsWrappedProperly(lines []string, length int) error { + blank := false + previous := length // default to full + for i, line := range lines { + lineno := i + 1 // human indexing + + // Allow a maximum of one blank line in a row. + if line == "" { + if blank { + return fmt.Errorf("line %d was a sequential blank line", lineno) + } + blank = true + previous = length // reset + continue + } + blank = false + + if line != strings.TrimSpace(line) { + return fmt.Errorf("line %d wasn't trimmed properly", lineno) + } + + if strings.Contains(line, " ") { // double spaces + return fmt.Errorf("line %d contained multiple spaces", lineno) + } + + if len(line) > length && !IsSpecialLine(line) { + return fmt.Errorf("line %d is too long", lineno) + } + + fields := strings.Fields(line) + if len(fields) == 0 { + //continue // should not happen with above check + return fmt.Errorf("line %d had an unexpected empty list of fields", lineno) + } + + // If we have a new start word, then we don't need to reflow it + // back to the previous line, and if not, then we check the fit. + if !IsNewStart(fields[0]) && previous+len(" ")+len(fields[0]) <= length { + return fmt.Errorf("line %d is not reflowed properly", lineno) + } + + previous = len(line) // prepare for next iteration + } + + return nil +} + +// IsNewStart returns true if the input word is one which is a valid start to a +// new line. This means that it doesn't need to get reflowed into the previous +// line. You should pass in the word without any surrounding whitespace. +func IsNewStart(word string) bool { + if word == "TODO:" { + return true + } + if word == "FIXME:" { + return true + } + if word == "XXX:" { + return true + } + + if word == "NOTE:" { + return true + } + if word == "Eg:" || word == "Example:" { // might as well + return true + } + + if word == "https://" || word == "http://" { // for the occasional docs + return true + } + + if word == "*" { // bullets + return true + } + + return false +} + +// IsSpecialLine allows lines that contain an entire special sentence to be +// allowed without breaking the reflow rules. +func IsSpecialLine(line string) bool { + fields := strings.Fields(line) + + // If it's a URL and it doesn't contain any words after the end of it... + if strings.HasPrefix(line, "https://") && len(fields) == 1 { + return true + } + if strings.HasPrefix(line, "http://") && len(fields) == 1 { + return true + } + + return false +} diff --git a/test/test-govet.sh b/test/test-govet.sh index ea4dc58e..901648f6 100755 --- a/test/test-govet.sh +++ b/test/test-govet.sh @@ -8,6 +8,8 @@ ROOT=$(dirname "${BASH_SOURCE}")/.. cd "${ROOT}" . test/util.sh +make --quiet -C test # run make in test directory to prepare any needed tools + failures='' function run-test() { @@ -98,6 +100,22 @@ function consistent-imports() { fi } +function reflowed-comments() { + if [[ $1 == *"/bindata.go" ]]; then # ends with bindata.go ? + return 0 # skip those generated files + fi + + if [ "$1" = './lang/funcs/core/generated_funcs.go' ]; then + return 0 + fi + + if [ "$1" = './lang/lexer.nn.go' ]; then + return 0 + fi + + ./test/comment_parser "$1" +} + # run go vet on a per-package basis base=$(go list .) for pkg in `go list -e ./... | grep -v "^${base}/vendor/" | grep -v "^${base}/examples/" | grep -v "^${base}/test/" | grep -v "^${base}/old" | grep -v "^${base}/old/" | grep -v "^${base}/tmp" | grep -v "^${base}/tmp/"`; do @@ -119,6 +137,7 @@ for file in `find . -maxdepth 9 -type f -name '*.go' -not -path './old/*' -not - run-test naked-error "$file" run-test lowercase-errors "$file" run-test consistent-imports "$file" + run-test reflowed-comments "$file" done if [[ -n "$failures" ]]; then diff --git a/util/socketset/socketset.go b/util/socketset/socketset.go index acaab445..1c4ce807 100644 --- a/util/socketset/socketset.go +++ b/util/socketset/socketset.go @@ -35,8 +35,8 @@ import ( ) // SocketSet is used to receive events from a socket and shut it down cleanly -// when asked. It contains a socket for events and a pipe socket to unblock receive -// on shutdown. +// when asked. It contains a socket for events and a pipe socket to unblock +// receive on shutdown. type SocketSet struct { fdEvents int fdPipe int @@ -80,8 +80,8 @@ func NewSocketSet(groups uint32, name string, proto int) (*SocketSet, error) { } // ReceiveBytes waits for bytes from fdEvents and return a byte array truncated -// to the message length. It will block until an event is produced, or shutdown is -// called. +// to the message length. It will block until an event is produced, or shutdown +// is called. func (obj *SocketSet) ReceiveBytes() ([]byte, error) { // Select will return when any fd in fdSet (fdEvents and fdPipe) is ready // to read. diff --git a/util/util.go b/util/util.go index c40963eb..95c90fd8 100644 --- a/util/util.go +++ b/util/util.go @@ -70,8 +70,8 @@ func Uint64KeyFromStrInMap(needle string, haystack map[uint64]string) (uint64, b return 0, false } -// StrRemoveDuplicatesInList removes any duplicate values in the list. -// This implementation is possibly sub-optimal (O(n^2)?) but preserves ordering. +// StrRemoveDuplicatesInList removes any duplicate values in the list. This +// implementation is possibly sub-optimal (O(n^2)?) but preserves ordering. func StrRemoveDuplicatesInList(list []string) []string { unique := []string{} for _, x := range list { @@ -561,8 +561,8 @@ func SessionBusPrivateUsable() (conn *dbus.Conn, err error) { } // PriorityStrSliceSort filters any elements matching fn to the end of the list. -// You can reverse the match result with a not to filter to the front instead! -// A copy of the list is returned, the original is not modified. +// You can reverse the match result with a not to filter to the front instead! A +// copy of the list is returned, the original is not modified. func PriorityStrSliceSort(input []string, fn func(string) bool) []string { output := []string{} found := []string{} @@ -605,9 +605,9 @@ func SortedStrSliceCompare(a, b []string) error { } // PathSlice is a type used to implement sort.Interface on a slice of strings, -// where each string is a path. This allows you to call sort.Sort() on a list -// of paths, after casting the []string{} to this type. Paths will be sorted -// by depth in alphabetical order. +// where each string is a path. This allows you to call sort.Sort() on a list of +// paths, after casting the []string{} to this type. Paths will be sorted by +// depth in alphabetical order. type PathSlice []string // Len returns the length of obj. It is required to satisfy sort.Interface.