pyinfra icon indicating copy to clipboard operation
pyinfra copied to clipboard

operation for managing an annotated section inside a file

Open khimaros opened this issue 2 years ago • 2 comments

Is your feature request related to a problem? Please describe

there are cases where a user needs to control most of the contents of a file outside of pyinfra, but still have pyinfra manage a particular block in the file, for example:

<some content maintained by the user or other tool>

### BEGIN CONTROL BLOCK ###

<data from pyinfra goes here>
<should support multiple lines>

### END CONTROL BLOCK ###

<other content maintained by user or other tool>

everything between the ### control blocks should be replaced.

Describe the solution you'd like

a new operation, perhaps called file.insert, which could be invoked as follows:

file.insert(
    path="/path/to/file",
    match_begin="### BEGIN CONTROL BLOCK ###",
    match_end = "### END CONTROL BLOCK ###",
    content = "something interesting\nand something else",
)

Future Scope

something to consider is inlined cases, where the block start and block end do not have newlines surrounding them. maybe that should be handled by a separate operation?

for example:

my_variable = "<content>"
file.insert(
    path="/path/to/file",
    match_begin="my_variable = \"",
    match_end="\"",
    content="some value",
    inline=True,
)

other potential parameters for this operation:

  • match_greedy to match until the last instance of match_end
  • match_index to match blocks other than the first one
  • match_all to match all blocks instead of just the first

khimaros avatar May 26 '23 18:05 khimaros

actually, it looks like this is present in git but not released (or not in documentation) yet:

https://github.com/Fizzadar/pyinfra/blob/2.x/pyinfra/facts/files.py#L359 https://github.com/Fizzadar/pyinfra/blob/2.x/pyinfra/operations/files.py#L1607

khimaros avatar May 26 '23 20:05 khimaros

however, the documentation for files.block is written as files.marked_block, which should be fixed.

khimaros avatar May 27 '23 19:05 khimaros