blob: 889704428e2d9f09406aaad722301b445ae91897 [file] [log] [blame]
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package codifier
import "log"
// Signature for functions passed into DoFn. The function will be given a
// Proc's replacement string and should return a new replacement string
// and error.
type fnForDoFn func(string) (string, error)
// Signature for functions passed into DoFnWith. The function will be given the
// value stored under the given key and the current replacement string. It
// should return the updated replacement string, a slice containing any files it
// changed, a map of any new values to be added to the store, and an error.
type fnForDoFnWith func(string, string) (string, []string, map[string]interface{}, error)
// DoFn applies the given function to the replacement string, allowing
// developers to write their own modification functions. For example, if the
// function were:
// f := func(i string) (string, error) { return i + "bar", nil }
// Then p.DoFn(f) would append "bar" to the existing p.replacement.
func (p *Proc) DoFn(fn fnForDoFn) *Proc {
if p == nil {
log.Println(" DoFn() error: nil receiver")
return nil
}
if fn == nil {
log.Println(" DoFn() error: nil function argument")
return nil
}
replacement, err := fn(p.replacement)
if err != nil {
log.Printf(" DoFn() error: %v", err)
return nil
}
p.replacement = replacement
return p
}
// DoFnWith applies the given function to the replacement string, allowing
// developers to write their own modification functions. In this case, the
// function is not applied to the existing replacement string, as in DoFn, but
// instead is applied to the value stored under the given key. The function will
// return a new replacement string, any changedFiles, any new key/values for the
// store, and an error.
func (p *Proc) DoFnWith(key string, fn fnForDoFnWith) *Proc {
if p == nil {
log.Println(" DoFnWith() error: nil receiver")
return nil
}
if fn == nil {
log.Println(" DoFnWith() error: nil function argument")
return nil
}
val, ok := p.Store[key].(string)
if !ok {
log.Printf(" DoFnWith(): key %q not present in store", key)
return nil
}
replacement, changedFiles, additions, err := fn(val, p.replacement)
if err != nil {
log.Printf(" DoFnWith() error: %v", err)
return nil
}
for k, v := range additions {
p = p.StoreKeyValue(k, v.(string))
if p == nil {
return nil
}
}
if p.replacement != replacement {
p.replacement = replacement
p.changedFiles.Add(changedFiles...)
// No need to include p.filename in p.changedFiles, even though it just
// changed. It will be added when the file is actually changed in
// WriteFile().
} else {
log.Printf("[DoFnWith() no changes]")
}
return p
}