gooseberry 0.10.1

A command line utility to generate a knowledge base from Hypothesis annotations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
use std::collections::{HashMap, HashSet};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::{env, fmt, fs, io};

use chrono::Utc;
use color_eyre::Help;
use dialoguer::{theme, Confirm, Input, MultiSelect, Select};
use directories_next::{ProjectDirs, UserDirs};
use eyre::eyre;
use hypothesis::annotations::{Annotation, Document, Permissions, Selector, Target, UserInfo};
use hypothesis::{Hypothesis, UserAccountID};
use serde::{Deserialize, Serialize};

use crate::errors::Apologize;
use crate::gooseberry::knowledge_base::{
    get_handlebars, AnnotationTemplate, LinkTemplate, PageTemplate, Templates,
};
use crate::{utils, NAME};

pub static DEFAULT_NESTED_TAG: &str = "/";
pub static DEFAULT_ANNOTATION_TEMPLATE: &str = r#"

### {{id}}
Group: {{group}} ({{group_name}})
Created: {{date_format "%c" created}}
Tags: {{#each tags}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}

{{#each highlight}}> {{this}}{{/each}}

{{text}}

[See in context]({{incontext}}) at [{{title}}]({{uri}})

"#;
pub static DEFAULT_PAGE_TEMPLATE: &str = r#"
# {{name}}
{{#each annotations}}{{this}}{{/each}}

"#;
pub static DEFAULT_INDEX_LINK_TEMPLATE: &str = r#"
- [{{name}}]({{relative_path}})"#;
pub static DEFAULT_INDEX_FILENAME: &str = "SUMMARY";
pub static DEFAULT_FILE_EXTENSION: &str = "md";

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum OrderBy {
    Tag,
    URI,
    BaseURI,
    Title,
    ID,
    Empty,
    Created,
    Updated,
    Group,
    GroupName,
}

impl fmt::Display for OrderBy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrderBy::Tag => write!(f, "tag"),
            OrderBy::URI => write!(f, "uri"),
            OrderBy::BaseURI => write!(f, "base_uri"),
            OrderBy::Title => write!(f, "title"),
            OrderBy::ID => write!(f, "id"),
            OrderBy::Empty => write!(f, "empty"),
            OrderBy::Created => write!(f, "created"),
            OrderBy::Updated => write!(f, "updated"),
            OrderBy::Group => write!(f, "group"),
            OrderBy::GroupName => write!(f, "group_name"),
        }
    }
}

/// Configuration struct, asks for user input to fill in the optional values the first time gooseberry is run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GooseberryConfig {
    /// Hypothesis username
    pub(crate) hypothesis_username: Option<String>,
    /// Hypothesis personal API key
    pub(crate) hypothesis_key: Option<String>,
    /// Hypothesis group with knowledge base annotations
    pub(crate) hypothesis_group: Option<String>,
    /// Related to tagging and editing
    /// Directory to store `sled` database files
    pub(crate) db_dir: PathBuf,

    /// Relating to the generated markdown knowledge base:
    /// Directory to write out knowledge base markdown files
    pub(crate) kb_dir: Option<PathBuf>,
    /// Handlebars annotation template
    pub(crate) annotation_template: Option<String>,
    /// Handlebars index link template
    pub(crate) index_link_template: Option<String>,
    /// Handlebars page template
    pub(crate) page_template: Option<String>,
    /// Handlebars index file name
    pub(crate) index_name: Option<String>,
    /// Wiki file extension
    pub(crate) file_extension: Option<String>,
    /// Define the hierarchy of folders
    pub(crate) hierarchy: Option<Vec<OrderBy>>,
    /// Define how annotations on a page are sorted
    pub(crate) sort: Option<Vec<OrderBy>>,
    /// Define tags to ignore
    pub(crate) ignore_tags: Option<Vec<String>>,
    /// Define nested tag pattern
    pub(crate) nested_tag: Option<String>,
    /// Hypothesis groups with knowledge base annotations
    #[serde(default)]
    pub(crate) hypothesis_groups: HashMap<String, String>,
}

/// Main project directory, cross-platform
pub fn get_project_dir() -> color_eyre::Result<ProjectDirs> {
    Ok(ProjectDirs::from("rs", "", NAME).ok_or(Apologize::Homeless)?)
}

impl Default for GooseberryConfig {
    fn default() -> Self {
        let config = Self {
            hypothesis_username: None,
            hypothesis_key: None,
            hypothesis_group: None,
            hypothesis_groups: HashMap::new(),
            db_dir: get_project_dir()
                .map(|dir| dir.data_dir().join("gooseberry_db"))
                .expect("Couldn't make database directory"),
            kb_dir: None,
            annotation_template: None,
            page_template: None,
            index_link_template: None,
            index_name: None,
            file_extension: None,
            hierarchy: None,
            sort: None,
            ignore_tags: None,
            nested_tag: None,
        };
        config.make_dirs().expect("Couldn't make directories");
        config
    }
}

impl GooseberryConfig {
    pub fn default_config(file: Option<&Path>) -> color_eyre::Result<()> {
        let writer: Box<dyn io::Write> = match file {
            Some(file) => Box::new(fs::File::create(file)?),
            None => Box::new(io::stdout()),
        };
        let mut buffered = io::BufWriter::new(writer);
        let contents = format!(
            r#"
hypothesis_username = '<Hypothesis username>'
hypothesis_key = '<Hypothesis personal API key>'
db_dir = '<full path to database folder>'
kb_dir = '<knowledge-base folder>'
hierarchy = ['Tag']
sort = ['Created']
ignore_tags = []
nested_tag = {}
annotation_template = '''{}'''
page_template = '''{}'''
index_link_template = '''{}'''
index_name = '{}'
file_extension = '{}'
"#,
            DEFAULT_NESTED_TAG,
            DEFAULT_ANNOTATION_TEMPLATE,
            DEFAULT_PAGE_TEMPLATE,
            DEFAULT_INDEX_LINK_TEMPLATE,
            DEFAULT_INDEX_FILENAME,
            DEFAULT_FILE_EXTENSION
        );
        write!(&mut buffered, "{}", contents)?;
        Ok(())
    }

    /// Print location of config.toml file
    pub fn print_location(config_file: Option<&Path>) -> color_eyre::Result<()> {
        println!("{}", Self::location(config_file)?.to_string_lossy());
        Ok(())
    }

    /// Make db and kb directories
    pub fn make_dirs(&self) -> color_eyre::Result<()> {
        if !self.db_dir.exists() {
            fs::create_dir_all(&self.db_dir).map_err(|e: io::Error| Apologize::ConfigError {
                message: format!(
                    "Couldn't create database directory {:?}, {}",
                    self.db_dir, e
                ),
            })?;
        }
        if let Some(kb_dir) = &self.kb_dir {
            if !kb_dir.exists() {
                fs::create_dir_all(kb_dir).map_err(|e: io::Error| Apologize::ConfigError {
                    message: format!(
                        "Couldn't create knowledge base directory {:?}, {}",
                        kb_dir, e
                    ),
                })?;
            }
        }
        Ok(())
    }

    /// Get a template for making a custom config file
    /// If you leave kb_dir and hypothesis details empty, Gooseberry asks you for them the first time
    fn get_default_config_file() -> color_eyre::Result<PathBuf> {
        let dir = get_project_dir()?;
        let config_dir = dir.config_dir();
        Ok(config_dir.join(format!("{}.toml", NAME)))
    }

    /// Gets the current config file location
    pub fn location(config_file: Option<&Path>) -> color_eyre::Result<PathBuf> {
        match config_file {
            Some(path) => {
                if path.exists() {
                    Ok(PathBuf::from(path))
                } else {
                    let error: color_eyre::Result<PathBuf> = Err(Apologize::ConfigError {
                        message: format!("No such file {:?}", path),
                    }
                    .into());
                    error.suggestion(format!(
                        "Use `gooseberry config default {:?}` to write out the default configuration and modify the generated file",
                        path
                    ))
                }
            }
            None => Self::get_default_config_file(),
        }
    }

    /// Get current configuration
    /// Hides the developer key (except last three digits)
    pub fn get(config_file: Option<&Path>) -> color_eyre::Result<String> {
        let mut file = fs::File::open(Self::location(config_file)?)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        Ok(contents
            .split('\n')
            .map(|k| {
                let parts = k.split(" = ").collect::<Vec<_>>();
                if parts[0] == "hypothesis_key" {
                    format!(
                        "{} = '{}{}'\n",
                        parts[0],
                        (0..(parts[1].len() - 2 - 3))
                            .map(|_| '*')
                            .collect::<String>(),
                        &parts[1][parts[1].len() - 5..parts[1].len() - 2]
                    )
                } else {
                    format!("{}\n", parts.join(" = "))
                }
            })
            .collect::<String>())
    }

    /// Read config from default location
    pub async fn load(config_file: Option<&Path>) -> color_eyre::Result<Self> {
        // Reads the GOOSEBERRY_CONFIG environment variable to get config file location
        let mut config = match config_file {
            Some(path) => {
                if path.exists() {
                    let config: Self = confy::load_path(path)?;
                    config.make_dirs()?;
                    Ok(config)
                } else {
                    let error: color_eyre::Result<Self> = Err(Apologize::ConfigError {
                        message: format!("No such file {:?}", path),
                    }
                        .into());
                    error.suggestion(format!(
                        "Use `gooseberry config default {:?}` to write out the default configuration and modify the generated file",
                        path
                    ))
                }
            }
            None => {
                Ok(confy::load(NAME).suggestion(Apologize::ConfigError {
                    message: "Couldn't load from the default config location, maybe you don't have access? \
                    Try running `gooseberry config default config_file.toml`, modify the generated file, \
                then `export GOOSEBERRY_CONFIG=<full/path/to/config_file.toml>`".into()
                })?)
            },
        }?;

        if config.hypothesis_username.is_none()
            || config.hypothesis_key.is_none()
            || !Self::authorize(
                config
                    .hypothesis_username
                    .as_deref()
                    .ok_or_else(|| eyre!("No hypothesis username"))?,
                config
                    .hypothesis_key
                    .as_deref()
                    .ok_or_else(|| eyre!("No hypothesis key"))?,
            )
            .await?
        {
            config.set_credentials().await?;
        }
        if config.hypothesis_groups.is_empty() {
            let mut group_ids = Vec::new();
            if let Some(ref group_id) = config.hypothesis_group {
                group_ids.push(group_id.to_owned());
            }
            config.set_groups(group_ids).await?;
        }
        Ok(config)
    }

    /// Queries and sets all knowledge base related configuration options
    pub fn set_kb_all(&mut self) -> color_eyre::Result<()> {
        self.set_kb_dir(None)?;
        self.set_annotation_template()?;
        self.set_page_template()?;
        self.set_index_link_template()?;
        self.set_index_name()?;
        self.set_nested_tag()?;
        self.set_file_extension()?;
        self.set_hierarchy()?;
        self.set_sort()?;
        Ok(())
    }

    /// Sets the knowledge base directory
    pub fn set_kb_dir(&mut self, directory: Option<&Path>) -> color_eyre::Result<()> {
        if let Some(path) = directory {
            if path.exists() || fs::create_dir(path).is_ok() {
                self.kb_dir = Some(path.to_owned());
                self.store()?;
                return Ok(());
            } else {
                println!(
                    "\nDirectory could not be created, make sure all parent folders exist and you have the right permissions.\n"
                )
            }
        }
        let default = UserDirs::new()
            .ok_or(Apologize::Homeless)?
            .home_dir()
            .join(NAME);
        self.kb_dir = loop {
            println!("NOTE: the directory will be deleted and regenerated on each make!");
            let input = utils::user_input(
                "Directory to build knowledge base",
                Some(
                    default
                        .to_str()
                        .ok_or_else(|| eyre!("Couldn't convert directory to string"))?,
                ),
                true,
                false,
            )?;
            let path = Path::new(&input);
            if path.exists() || fs::create_dir(path).is_ok() {
                break Some(path.to_owned());
            } else {
                println!(
                    "\nDirectory could not be created, make sure all parent folders exist and you have the right permissions.\n"
                )
            }
        };
        self.store()?;
        Ok(())
    }

    fn get_order_bys(selections: Vec<OrderBy>) -> color_eyre::Result<Vec<OrderBy>> {
        let mut selections = selections;
        let selection = Select::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("Field 1")
            .items(&selections[..])
            .interact()?;
        let mut order = Vec::new();
        if selections[selection] != OrderBy::Empty {
            order.push(selections[selection]);
            selections.remove(selection);
            selections.retain(|&x| x != OrderBy::Empty);
            let mut number = 2;
            loop {
                if selections.is_empty() {
                    break;
                }
                if Confirm::with_theme(&theme::ColorfulTheme::default())
                    .with_prompt("Add more fields?")
                    .interact()?
                {
                    let selection = Select::with_theme(&theme::ColorfulTheme::default())
                        .with_prompt(&format!("Field {}", number))
                        .items(&selections[..])
                        .interact()?;
                    order.push(selections[selection]);
                    selections.remove(selection);
                    number += 1
                } else {
                    break;
                }
            }
        }
        Ok(order)
    }

    /// Sets the hierarchy fields which determines the folder hierarchy
    pub fn set_hierarchy(&mut self) -> color_eyre::Result<()> {
        println!("Set folder hierarchy order");
        let selections = vec![
            OrderBy::Empty,
            OrderBy::Tag,
            OrderBy::URI,
            OrderBy::BaseURI,
            OrderBy::Title,
            OrderBy::ID,
            OrderBy::Group,
            OrderBy::GroupName,
        ];
        let order = Self::get_order_bys(selections)?;
        if order.is_empty() {
            println!(
                "Single file: {}.{}",
                self.index_name
                    .as_ref()
                    .ok_or_else(|| eyre!("No index name"))?,
                self.file_extension
                    .as_ref()
                    .ok_or_else(|| eyre!("No file extension"))?
            );
        } else {
            println!(
                "Folder structure: {}.{}",
                order
                    .iter()
                    .map(|o| o.to_string())
                    .collect::<Vec<_>>()
                    .join("/"),
                self.file_extension
                    .as_ref()
                    .ok_or_else(|| eyre!("No file extension"))?
            );
        }
        self.hierarchy = Some(order);
        self.store()?;
        Ok(())
    }

    /// Sets the sort order for annotations within a page
    pub fn set_sort(&mut self) -> color_eyre::Result<()> {
        println!("Set sort order for annotations within a page");
        let selections = vec![
            OrderBy::Tag,
            OrderBy::URI,
            OrderBy::BaseURI,
            OrderBy::ID,
            OrderBy::Title,
            OrderBy::Created,
            OrderBy::Updated,
            OrderBy::Group,
            OrderBy::GroupName,
        ];
        let order = Self::get_order_bys(selections)?;

        println!(
            "Sort order: {}",
            order
                .iter()
                .map(|o| o.to_string())
                .collect::<Vec<_>>()
                .join(", "),
        );

        self.sort = Some(order);
        self.store()?;
        Ok(())
    }

    pub fn set_ignore_tags(&mut self) -> color_eyre::Result<()> {
        println!("Set tags to ignore during knowledge base generation");
        let ignore_tags: String = Input::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("Enter comma-separated tags")
            .with_initial_text(
                self.ignore_tags
                    .as_ref()
                    .map(|tags| tags.join(", "))
                    .unwrap_or_default(),
            )
            .allow_empty(true)
            .interact_text()?;
        if ignore_tags.is_empty() {
            self.ignore_tags = None
        } else {
            self.ignore_tags = Some(
                ignore_tags
                    .split(',')
                    .map(|t| t.trim().to_owned())
                    .collect(),
            )
        }
        self.store()?;
        Ok(())
    }

    pub(crate) fn get_templates(&self) -> Templates {
        Templates {
            annotation_template: self
                .annotation_template
                .as_deref()
                .unwrap_or(DEFAULT_ANNOTATION_TEMPLATE),
            page_template: self
                .page_template
                .as_deref()
                .unwrap_or(DEFAULT_PAGE_TEMPLATE),
            index_link_template: self
                .index_link_template
                .as_deref()
                .unwrap_or(DEFAULT_INDEX_LINK_TEMPLATE),
        }
    }
    /// Sets the annotation template in Handlebars format.
    pub fn set_annotation_template(&mut self) -> color_eyre::Result<()> {
        let selections = &[
            "Use default annotation template",
            "Edit annotation template",
        ];

        let selection = Select::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("How should gooseberry format annotations?")
            .items(&selections[..])
            .interact()?;
        if selection == 0 {
            self.annotation_template = Some(DEFAULT_ANNOTATION_TEMPLATE.to_string());
        } else {
            let test_annotation = Annotation {
                id: "test".to_string(),
                created: Utc::now(),
                updated: Utc::now(),
                user: Default::default(),
                uri: "https://github.com/out-of-cheese-error/gooseberry".to_string(),
                text: "testing annotation".to_string(),
                tags: vec!["tag1".to_string(), "tag2".to_string()],
                group: "group_id".to_string(),
                permissions: Permissions {
                    read: vec![],
                    delete: vec![],
                    admin: vec![],
                    update: vec![],
                },
                target: vec![Target::builder()
                    .source("https://www.example.com")
                    .selector(vec![Selector::new_quote(
                        "exact text in website to highlight",
                        "prefix of text",
                        "suffix of text",
                    )])
                    .build()?],
                links: vec![(
                    "incontext".to_string(),
                    "https://incontext_link.com".to_string(),
                )]
                .into_iter()
                .collect(),
                hidden: false,
                flagged: false,
                document: Some(Document {
                    title: vec!["Web page title".into()],
                    dc: None,
                    highwire: None,
                    link: vec![],
                }),
                references: vec![],
                user_info: Some(UserInfo {
                    display_name: Some("test_display_name".to_string()),
                }),
            };
            let mut group_name_mapping = HashMap::new();
            group_name_mapping.insert("group_id".to_owned(), "group_name".to_owned());
            let test_markdown_annotation =
                AnnotationTemplate::from_annotation(test_annotation, &group_name_mapping);
            self.annotation_template = loop {
                let template = utils::external_editor_input(
                    Some(
                        self.annotation_template
                            .as_deref()
                            .unwrap_or(DEFAULT_ANNOTATION_TEMPLATE),
                    ),
                    ".hbs",
                )?;
                let templates = Templates {
                    annotation_template: &template,
                    ..Default::default()
                };
                match get_handlebars(templates)
                    .map(|hbs| hbs.render("annotation", &test_markdown_annotation))
                {
                    Err(e) => {
                        eprintln!("TemplateRenderError: {}\n Try again.", e);
                        continue;
                    }
                    Ok(Err(e)) => {
                        eprintln!("TemplateRenderError: {}\n Try again.", e);
                        continue;
                    }
                    Ok(Ok(md)) => {
                        println!("Template looks like this:");
                        println!();
                        println!("{}", md)
                    }
                }
                break Some(template);
            };
        }
        self.store()?;
        Ok(())
    }

    /// Sets the annotation template in Handlebars format.
    pub fn set_page_template(&mut self) -> color_eyre::Result<()> {
        let selections = &["Use default page template", "Edit page template"];

        let selection = Select::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("How should gooseberry format pages?")
            .items(&selections[..])
            .interact()?;
        if selection == 0 {
            self.page_template = Some(DEFAULT_PAGE_TEMPLATE.to_string());
        } else {
            let test_annotation_1 = Annotation {
                id: "test".to_string(),
                created: Utc::now(),
                updated: Utc::now(),
                user: Default::default(),
                uri: "https://github.com/out-of-cheese-error/gooseberry".to_string(),
                text: "testing annotation".to_string(),
                tags: vec!["tag1".to_string(), "tag2".to_string()],
                group: "group_id".to_string(),
                permissions: Permissions {
                    read: vec![],
                    delete: vec![],
                    admin: vec![],
                    update: vec![],
                },
                target: vec![Target::builder()
                    .source("https://www.example.com")
                    .selector(vec![Selector::new_quote(
                        "exact text in website to highlight\nmore text",
                        "prefix of text",
                        "suffix of text",
                    )])
                    .build()?],
                links: vec![(
                    "incontext".to_string(),
                    "https://incontext_link.com".to_string(),
                )]
                .into_iter()
                .collect(),
                hidden: false,
                flagged: false,
                document: Some(Document {
                    title: vec!["Web page title".into()],
                    dc: None,
                    highwire: None,
                    link: vec![],
                }),
                references: vec![],
                user_info: Some(UserInfo {
                    display_name: Some("test_display_name".to_string()),
                }),
            };
            let mut test_annotation_2 = test_annotation_1.clone();
            test_annotation_2.text = "Another annotation".to_string();
            test_annotation_2.group = "group_id_2".to_string();

            let mut group_name_mapping = HashMap::new();
            group_name_mapping.insert("group_id".to_owned(), "group_name".to_owned());
            group_name_mapping.insert("group_id_2".to_owned(), "group_name_2".to_owned());
            let templates = Templates {
                annotation_template: self
                    .annotation_template
                    .as_ref()
                    .ok_or_else(|| eyre!("No annotation template"))?,
                ..Default::default()
            };
            let hbs = get_handlebars(templates)?;

            let page_data = PageTemplate {
                link_data: LinkTemplate {
                    name: "page_name".to_string(),
                    relative_path: "relative/path/to/page.md".to_string(),
                    absolute_path: "absolute/path/to/page.md".to_string(),
                },
                annotations: vec![test_annotation_1.clone(), test_annotation_2.clone()]
                    .into_iter()
                    .map(|a| {
                        hbs.render(
                            "annotation",
                            &AnnotationTemplate::from_annotation(a, &group_name_mapping),
                        )
                    })
                    .collect::<Result<Vec<String>, _>>()?,
                raw_annotations: vec![
                    AnnotationTemplate::from_annotation(test_annotation_1, &group_name_mapping),
                    AnnotationTemplate::from_annotation(test_annotation_2, &group_name_mapping),
                ],
            };

            self.page_template = loop {
                let template = utils::external_editor_input(
                    Some(
                        self.page_template
                            .as_deref()
                            .unwrap_or(DEFAULT_PAGE_TEMPLATE),
                    ),
                    ".hbs",
                )?;
                let templates = Templates {
                    page_template: &template,
                    ..Default::default()
                };
                match get_handlebars(templates).map(|hbs| hbs.render("page", &page_data)) {
                    Err(e) => {
                        eprintln!("TemplateRenderError: {}\n Try again.", e);
                        continue;
                    }
                    Ok(Err(e)) => {
                        eprintln!("TemplateRenderError: {}\n Try again.", e);
                        continue;
                    }
                    Ok(Ok(md)) => {
                        println!("Template looks like this:");
                        println!();
                        println!("{}", md)
                    }
                }
                break Some(template);
            };
        }
        self.store()?;
        Ok(())
    }

    /// Sets the annotation template in Handlebars format.
    pub fn set_index_link_template(&mut self) -> color_eyre::Result<()> {
        let selections = &[
            "Use default index link template",
            "Edit index link template",
        ];

        let selection = Select::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("How should gooseberry format the link in the Index file?")
            .items(&selections[..])
            .interact()?;
        if selection == 0 {
            self.index_link_template = Some(DEFAULT_INDEX_LINK_TEMPLATE.to_string());
        } else {
            self.index_link_template = loop {
                let template = utils::external_editor_input(
                    Some(
                        self.index_link_template
                            .as_deref()
                            .unwrap_or(DEFAULT_INDEX_LINK_TEMPLATE),
                    ),
                    ".hbs",
                )?;
                let templates = Templates {
                    index_link_template: &template,
                    ..Default::default()
                };
                if let Err(e) = get_handlebars(templates) {
                    eprintln!("TemplateRenderError: {}\n Try again.", e);
                    continue;
                }
                break Some(template);
            };
        }
        self.store()?;
        Ok(())
    }

    pub fn set_index_name(&mut self) -> color_eyre::Result<()> {
        self.index_name = Some(utils::user_input(
            "What name should gooseberry use for the index file",
            Some(self.index_name.as_deref().unwrap_or(DEFAULT_INDEX_FILENAME)),
            true,
            false,
        )?);
        self.store()?;
        Ok(())
    }

    pub fn set_nested_tag(&mut self) -> color_eyre::Result<()> {
        self.nested_tag = Some(utils::user_input(
            "What pattern should gooseberry use to define nested tags",
            Some(self.nested_tag.as_deref().unwrap_or(DEFAULT_NESTED_TAG)),
            true,
            false,
        )?);
        self.store()?;
        Ok(())
    }

    pub fn set_file_extension(&mut self) -> color_eyre::Result<()> {
        self.file_extension = Some(utils::user_input(
            "What extension should gooseberry use for wiki files",
            Some(
                self.file_extension
                    .as_deref()
                    .unwrap_or(DEFAULT_FILE_EXTENSION),
            ),
            true,
            false,
        )?);
        self.store()?;
        Ok(())
    }

    /// This opens a command-line prompt where the user can select from either creating a new group or
    /// using an existing group by ID, with the option of selecting multiple groups
    pub async fn get_groups(&self, api: Hypothesis) -> color_eyre::Result<HashMap<String, String>> {
        let selections = &[
            "Create a new Hypothesis group",
            "Use existing Hypothesis groups",
        ];
        let selection = Select::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("Where should gooseberry take annotations from?")
            .items(&selections[..])
            .interact()?;
        let mut selected = HashSet::new();
        if selection == 0 {
            loop {
                let group_name = utils::user_input("Enter a group name", Some(NAME), true, false)?;
                let group_description = utils::user_input(
                    "Enter a group description",
                    Some("Gooseberry knowledge base annotations"),
                    true,
                    true,
                )?;

                let group_id = api
                    .create_group(&group_name, Some(&group_description))
                    .await?
                    .id;

                selected.insert(group_id.clone());
                if Confirm::with_theme(&theme::ColorfulTheme::default())
                    .with_prompt("Add more groups?")
                    .interact()?
                {
                    continue;
                } else {
                    break;
                }
            }
        }
        let groups = api
            .get_groups(&hypothesis::groups::GroupFilters::default())
            .await?;
        let group_selection: Vec<_> = groups
            .iter()
            .map(|g| format!("{}: {}", g.id, g.name))
            .collect();
        let defaults: Vec<_> = groups.iter().map(|g| selected.contains(&g.id)).collect();
        let mut group_name_mapping = HashMap::new();
        for group_index in MultiSelect::with_theme(&theme::ColorfulTheme::default())
            .with_prompt("Which groups should gooseberry use?")
            .items(&group_selection[..])
            .defaults(&defaults[..])
            .interact()?
        {
            api.fetch_group(&groups[group_index].id, Vec::new())
                .await
                .map_err(|error| Apologize::GroupNotFound {
                    id: groups[group_index].id.clone(),
                    error,
                })?;
            group_name_mapping.insert(
                groups[group_index].id.to_owned(),
                groups[group_index].name.to_owned(),
            );
        }
        Ok(group_name_mapping)
    }

    /// Sets the Hypothesis groups used for Gooseberry annotations
    /// This opens a command-line prompt where the user can select from either creating a new group or
    /// using an existing group by ID, with the option of selecting multiple groups
    pub async fn set_groups(&mut self, group_ids: Vec<String>) -> color_eyre::Result<()> {
        let (username, key) = (
            self.hypothesis_username
                .as_deref()
                .ok_or_else(|| eyre!("No Hypothesis username"))?,
            self.hypothesis_key
                .as_deref()
                .ok_or_else(|| eyre!("No Hypothesis key"))?,
        );
        let api = Hypothesis::new(username, key)?;
        if group_ids.is_empty() {
            self.hypothesis_groups = self.get_groups(api).await?;
        } else {
            for group_id in group_ids {
                let group = api
                    .fetch_group(&group_id, Vec::new())
                    .await
                    .map_err(|error| Apologize::GroupNotFound {
                        id: group_id.clone(),
                        error,
                    })?;
                self.hypothesis_groups
                    .insert(group.id.to_owned(), group.name.to_owned());
            }
        }
        self.hypothesis_group = None;
        self.store()?;
        Ok(())
    }

    /// Check if user can be authorized
    pub async fn authorize(name: &str, key: &str) -> color_eyre::Result<bool> {
        Ok(Hypothesis::new(name, key)?
            .fetch_user_profile()
            .await?
            .userid
            == Some(UserAccountID(format!("acct:{}@hypothes.is", name))))
    }

    /// Asks user for Hypothesis credentials and sets them in the config
    pub async fn request_credentials(&mut self) -> color_eyre::Result<()> {
        let mut name = String::new();
        let mut key;
        loop {
            name = utils::user_input(
                "Hypothesis username",
                if name.is_empty() { None } else { Some(&name) },
                true,
                false,
            )?;
            key = dialoguer::Password::with_theme(&dialoguer::theme::ColorfulTheme::default())
                .with_prompt("Hypothesis developer API key")
                .interact()?;
            if Self::authorize(&name, &key).await? {
                self.hypothesis_username = Some(name);
                self.hypothesis_key = Some(key);
                self.store()?;
                return Ok(());
            } else {
                println!("Could not authorize your Hypothesis credentials, please try again.");
            }
        }
    }
    /// Reads the `HYPOTHESIS_NAME` and `HYPOTHESIS_KEY` environment variables to get Hypothesis credentials.
    /// If not present or invalid, requests credentials from user.
    pub async fn set_credentials(&mut self) -> color_eyre::Result<()> {
        let (name, key) = (
            env::var("HYPOTHESIS_NAME").ok(),
            env::var("HYPOTHESIS_KEY").ok(),
        );
        if let (Some(n), Some(k)) = (&name, &key) {
            if Self::authorize(n, k).await? {
                self.hypothesis_username = Some(n.to_owned());
                self.hypothesis_key = Some(k.to_owned());
                self.store()?;
            } else {
                println!(
                    "Authorization with environment variables did not work. Enter details below"
                );
                self.request_credentials().await?;
            }
        } else {
            self.request_credentials().await?;
        }
        Ok(())
    }

    /// Write possibly modified config
    pub fn store(&self) -> color_eyre::Result<()> {
        // Reads the GOOSEBERRY_CONFIG environment variable to get config file location
        let config_file = env::var("GOOSEBERRY_CONFIG").ok();
        match config_file {
            Some(file) => confy::store_path(Path::new(&file), (*self).clone()).suggestion(Apologize::ConfigError {
                message: "The current config_file location does not seem to have write access. \
                   Use `export GOOSEBERRY_CONFIG=<full/path/to/config_file.toml>` to set a new location".into()
            })?,
            None => confy::store(NAME, (*self).clone()).suggestion(Apologize::ConfigError {
                message: "The current config_file location does not seem to have write access. \
                    Use `export GOOSEBERRY_CONFIG=<full/path/to/config_file.toml>` to set a new location".into()
            })?,
        };
        Ok(())
    }
}