Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Daiki48 committed Aug 26, 2022
0 parents commit d6874a6
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
/target
39 changes: 39 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions Cargo.toml
@@ -0,0 +1,9 @@
[package]
name = "todoapp_cli"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde_json = "1.0.60"
19 changes: 19 additions & 0 deletions README.md
@@ -0,0 +1,19 @@
# This is Todo App with Rust lang.

CLI's Todo App.

## Usage

### For Example

Input command

```
$ cargo run -- add "todo test1"
```

confirmation

```
$ cat ./data/db.json
```
5 changes: 5 additions & 0 deletions data/db.json
@@ -0,0 +1,5 @@
{
"second test": true,
"code test": true,
"first test": false
}
71 changes: 71 additions & 0 deletions src/main.rs
@@ -0,0 +1,71 @@
use std::collections::HashMap;

struct Todo {
map: HashMap<String, bool>,
}

impl Todo {
fn insert(&mut self, key: String) {
// insert a new item into our map.
// we pass true as value
self.map.insert(key, true);
}

fn save(self) -> Result<(), Box<dyn std::error::Error>> {
let content = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("./data/db.json")?;
serde_json::to_writer_pretty(content, &self.map)?;
Ok(())
}

fn new() -> Result<Todo, std::io::Error> {
let list = std::fs::OpenOptions::new()
.write(true)
.create(true)
.read(true)
.open("./data/db.json")?;

match serde_json::from_reader(list) {
Ok(map) => Ok(Todo {map}),
Err(e) if e.is_eof() => Ok(Todo {
map: HashMap::new(),
}),
Err(e) => panic!("An error occurred: {}", e),
}
}

fn complete(&mut self, key: &String) -> Option<()> {
match self.map.get_mut(key) {
Some(v) => Some(*v = false),
None => None,
}
}


}

fn main() {
let action = std::env::args().nth(1).expect("Please specify an action");
let item = std::env::args().nth(2).expect("Please specify an item");

let mut todo = Todo::new().expect("Initialisation of db failed");

if action == "add" {
todo.insert(item);
match todo.save() {
Ok(_) => println!("todo saved"),
Err(why) => println!("An error occurred: {}", why),
}
} else if action == "complete" {
match todo.complete(&item) {
None => println!("'{}' is not present in the list", item),
Some(_) => match todo.save() {
Ok(_) => println!("todo saved"),
Err(why) => println!("An error occurred: {}", why),
},
}
}
}

0 comments on commit d6874a6

Please sign in to comment.