@@ -2,6 +2,10 @@ use home::home_dir;
22use serde:: { Deserialize , Serialize } ;
33use std:: fmt;
44use std:: fs;
5+ use substring:: Substring ;
6+ use chrono:: prelude:: Local ;
7+
8+ use super :: parser:: { is_url, get_domain_name} ;
59
610#[ derive( Serialize , Deserialize , Debug ) ]
711pub struct Bookmark {
@@ -12,6 +16,37 @@ pub struct Bookmark {
1216 pub id : u32 ,
1317}
1418
19+ impl Bookmark {
20+ /// Generate a suitable name for Bookmark
21+ /// If name is empty or not provided, link is parsed to get the domain name.
22+ /// If name contains spaces, it is converted to underscores
23+ pub fn generate_name ( link : & String , name : Option < String > ) -> String {
24+ let mut name = name. unwrap_or ( "" . to_owned ( ) ) ;
25+
26+ // If name is not provided, use the domain name
27+ // If provided, replace ' ' with '_'
28+ if name == "" {
29+ let m = get_domain_name ( & link) ;
30+ name = link. substring ( m. start ( ) , m. end ( ) ) . to_owned ( ) ;
31+ } else {
32+ name = name. replace ( ' ' , "_" ) ;
33+ }
34+
35+ return name;
36+ }
37+
38+ /// Return bookmark with values
39+ pub fn generate_bookmark ( id : u32 , link : String , name : String ) -> Bookmark {
40+ Bookmark {
41+ is_file : !is_url ( & link) ,
42+ link : link,
43+ name : name,
44+ date : Local :: now ( ) . to_string ( ) ,
45+ id : id,
46+ }
47+ }
48+ }
49+
1550impl fmt:: Display for Bookmark {
1651 fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
1752 write ! ( f, "{} {} {}" , self . id, self . name, self . link)
@@ -24,6 +59,19 @@ pub struct Data {
2459 pub last_id : u32 ,
2560}
2661
62+ impl Data {
63+ /// Prettify the json and write to file
64+ pub fn write_to_file ( & self ) {
65+ fs:: write (
66+ get_data_file_path ( ) ,
67+ serde_json:: to_string_pretty ( & self ) . unwrap ( ) ,
68+ )
69+ . unwrap ( ) ;
70+ }
71+ }
72+
73+ /// Create data directory and data file.data
74+ /// Write a barebones JSON to the data file
2775pub fn create_data_file ( ) {
2876 let data_dir = home_dir ( ) . unwrap ( ) . join ( ".local/share/rbmenu/" ) ;
2977 let data_file = data_dir. join ( "bookmark.json" ) ;
@@ -36,11 +84,15 @@ pub fn create_data_file() {
3684 fs:: File :: create ( & data_file) . unwrap ( ) ;
3785 }
3886
39- let data = Data { bookmarks : vec ! [ ] , last_id : 0 } ;
87+ let data = Data {
88+ bookmarks : vec ! [ ] ,
89+ last_id : 0 ,
90+ } ;
4091
4192 fs:: write ( data_file, serde_json:: to_string_pretty ( & data) . unwrap ( ) ) . unwrap ( ) ;
4293}
4394
95+ /// Read and parse data file into Data struct
4496pub fn read_data_file ( ) -> Data {
4597 let data_file = get_data_file_path ( ) ;
4698
@@ -52,6 +104,7 @@ pub fn read_data_file() -> Data {
52104 serde_json:: from_str ( & content) . unwrap ( )
53105}
54106
107+ /// Return data file path
55108pub fn get_data_file_path ( ) -> std:: path:: PathBuf {
56109 home_dir ( )
57110 . unwrap ( )
0 commit comments