File modifications
- Dominant language
- Go
- Stars
- 48
- Forks
- 4
- PR merge metrics
- No merged PRs in 30d
Description
An array of directive objects called `modifications`, which can be variants/components-overriden.
Available "directives":
- **in** _(path, mandatory)_ which file to modify. Modifications are run on files that _have been copied_
- **after** _(regex | string)_ run the modification only on the part of the file after the specified line
- **before** _(regex | string)_ run the modification only on the part of the file before the specified line
- **append** _(string)_ append content to the file.
- if _before_ is specified, put the line just above the one matched by _before_
- if _after_ is specified, put the line just below the one matched by _after_
- else, put the line at the end of the file
- **prepend** _(string)_ like append, but the roles of _before_/_after_ are reversed.
- **replace** _(string | regex)_ search a string to be replaced with something
- **with** _(string, mandatory if **replace** used)_ Replace content matched by _replace_ with this. If _replace_ is a regex, `$n` will refer to the `n`-th capture group
Specifying a regex instead of a string is done via the custom YAML tag `!regex`.
This requires switching to gopkg.in/yaml.v3 ~~and use a special struct:~~
```go
type stringOrRegexp struct {
yaml.Node
}
func (sor stringOrRegexp) isRegexp() bool {
return sor.Tag == "!regex"
}
func (sor stringOrRegexp) isString() bool {
return sor.Tag == "!!str"
}
func (sor stringOrRegexp) regexp() (*regexp.Regexp, error) {
return regexp.Compile(sor.Value)
}
func (sor stringOrRegexp) string() string {
return fmt.Sprint(sor.Value)
}
```
**tested in Go playground, yaml won't unmarshal to stringOrRegexp even if it embeds yaml.Node, instead:**
```go
type stringOrRegexp = yaml.Node
func isRegexp(sor stringOrRegexp) bool {
return sor.Tag == "!regex"
}
func isString(sor stringOrRegexp) bool {
return sor.Tag == "!!str"
}
```
And in the manifest:
```go
type Modification struct {
In string
Before stringOrRegexp
After stringOrRegexp
Replace stringOrRegexp
With string
Append string
Preprend string
}
type Manifest struct {
...
Modifications []Modification
...
}
func (m Modification) searchAndReplace() {
var searchPattern *regexp.Regexp
if isRegexp(m.Replace) {
searchPattern, err := regexp.Compile(m.Replace.Value)
} else if isString(m.Replace) {
searchPattern, err := regexp.Compile(regexp.Escape(m.Replace.Value)) # ^1
} else {
return // no replacement to do, `replace` field not mentionned
}
if err != nil {
...
}
...
}
```
[^1]: Apparently regexp has no "escape" function, i found [a website that explains how to escape regexps](https://riptutorial.com/regex/example/15848/what-characters-need-to-be-escaped), I might have to implement it myself.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.