Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow changing values without deleting comment #134

Open
ufechner7 opened this issue Aug 7, 2023 · 1 comment
Open

Allow changing values without deleting comment #134

ufechner7 opened this issue Aug 7, 2023 · 1 comment

Comments

@ufechner7
Copy link

I use yaml files to store my simulation parameters and I am commenting every line. Sometimes I need to change values from a software and not manually. Then the comments would get lost. To avoid this I wrote some helper functions which are not very generic:

# modify a variable in a yaml file

# read as text
function readfile(filename)
    open(filename) do file
        readlines(file)
    end
end

function writefile(lines, filename)
    open(filename, "w") do file
        for line in lines
            write(file, line, '\n')
        end
    end
end

function change_value(lines, varname, value::Union{Integer, Float64})
    change_value(lines, varname, repr(value))
end

function change_value(lines, varname, value::String)
    res = String[]
    for line in lines
        if startswith(lstrip(line), varname)
            start = (findfirst(varname, line)).stop+1
            stop  = findfirst('#', line)-1
            new_line = ""
            leading = true
            j = 1
            for (i, chr) in pairs(line)
                if i < start || i > stop
                    new_line *= chr
                elseif line[i] == ' ' && leading
                    new_line *= ' '
                elseif j <= length(value)
                    new_line *= value[j]
                    j += 1
                    leading = false
                elseif i <= stop
                    new_line *= ' '
                end
            end
            push!(res, new_line)
        else
            push!(res, line)
        end
    end
    res
end

Would it make sense to add something like this to this package or to the documentation?

@kescobo
Copy link
Collaborator

kescobo commented Aug 7, 2023

I would 100% accept a PR to add this as an example in the docs.

Being able to round-trip with comments would certainly be nice, but I don't know how complicated it would be to do so in a robust way. Happy to accept proposals though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants