chandrayaan1
chandrayaan1

Reputation: 735

Edit local yaml file in rust

I'm trying to edit yaml file using serde_yaml but using this i'm only able to edit in stdout but cannot write back to local file(/home/home/.kube/config)

    let kubeconfig = "/home/home/.kube/config"
    let contents = fs::read_to_string(kubeconfig)
    .expect("Something went wrong reading the file");

    let mut value: serde_yaml::Value = serde_yaml::from_str(&contents).unwrap();
    *value.get_mut("current-context").unwrap() = "new_user".into();
    // Below lines shows the edited file in stdout
    serde_yaml::to_writer(std::io::stdout(), &value).unwrap();

I did tired as below an other method but had no luck.

    let writer = serde_yaml::to_writer(std::io::stdout(), &value).unwrap();
    println!("{:?}",writer); // shows ()
    serde_yaml::to_writer(writer);

How do i write this edit back to /home/home/.kube/config ?

Upvotes: 0

Views: 171

Answers (1)

jthulhu
jthulhu

Reputation: 8678

It seems that you are trying to use to_writer as to_string:

let writer = serde_yaml::to_string(&value).unwrap();
println!("{:?}", writer);

Then you can save the string how you usually would.


Or, alternatively, you could write directly to a file:

let mut file = File::create("/home/home/.kube/config").unwrap();
serde_yaml.to_writer(&mut file, &value);

Upvotes: 3

Related Questions