about summary refs log tree commit diff stats
path: root/pkgs/by-name/ts/tskm/src/task/mod.rs
blob: 03a12faa228e04bc5f629b6e12e8edd88e113927 (plain) (blame)
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
use std::{
    fmt::Display,
    fs::{self, read_to_string, File},
    path::PathBuf,
    process::Command,
    str::FromStr,
    sync::OnceLock,
};

use anyhow::{bail, Context, Result};
use log::{debug, info, trace};
use taskchampion::Tag;

use crate::{interface::project::ProjectName, state::State};

/// The `taskwarrior` id of a task.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
pub struct Task {
    uuid: taskchampion::Uuid,
}

impl From<&taskchampion::Task> for Task {
    fn from(value: &taskchampion::Task) -> Self {
        Self {
            uuid: value.get_uuid(),
        }
    }
}
impl From<&taskchampion::TaskData> for Task {
    fn from(value: &taskchampion::TaskData) -> Self {
        Self {
            uuid: value.get_uuid(),
        }
    }
}

impl Task {
    pub fn from_working_set(id: usize, state: &mut State) -> Result<Option<Self>> {
        Ok(state
            .replica()
            .working_set()?
            .by_index(id)
            .map(|uuid| Self { uuid }))
    }

    pub fn get_current(state: &mut State) -> Result<Option<Self>> {
        let tasks = state
            .replica()
            .pending_tasks()?
            .into_iter()
            .filter(taskchampion::Task::is_active)
            .collect::<Vec<_>>();

        assert!(
            tasks.len() <= 1,
            "We have ensured that only one task may be active, via a hook"
        );
        if let Some(active) = tasks.first() {
            Ok(Some(Self::from(active)))
        } else {
            Ok(None)
        }
    }

    #[must_use]
    pub fn uuid(&self) -> &taskchampion::Uuid {
        &self.uuid
    }

    fn as_task(&self, state: &mut State) -> Result<taskchampion::Task> {
        Ok(state
            .replica()
            .get_task(self.uuid)?
            .expect("We have the task from this replica, it should still be in it"))
    }

    /// Adds a tag to the task, to show the user that it has additional neorg data.
    pub fn mark_neorg_data(&self, state: &mut State) -> Result<()> {
        let mut ops = vec![];
        self.as_task(state)?
            .add_tag(&Tag::from_str("neorg_data").expect("Is valid"), &mut ops)?;
        state.replica().commit_operations(ops)?;
        Ok(())
    }

    /// Try to start this task.
    /// It will stop previously active tasks.
    pub fn start(&self, state: &mut State) -> Result<()> {
        info!("Activating {self}");

        if let Some(active) = Self::get_current(state)? {
            active.stop(state)?;
        }

        let mut ops = vec![];
        self.as_task(state)?.start(&mut ops)?;
        state.replica().commit_operations(ops)?;
        Ok(())
    }

    /// Stops this task.
    pub fn stop(&self, state: &mut State) -> Result<()> {
        info!("Stopping {self}");

        let mut ops = vec![];
        self.as_task(state)?.stop(&mut ops)?;
        state.replica().commit_operations(ops)?;
        Ok(())
    }

    pub fn description(&self, state: &mut State) -> Result<String> {
        Ok(self.as_task(state)?.get_description().to_owned())
    }

    pub fn project(&self, state: &mut State) -> Result<Project> {
        let output = {
            let task = self.as_task(state)?;
            let task_data = task.into_task_data();
            task_data
                .get("project")
                .expect("Every task should have a project")
                .to_owned()
        };
        let project = Project::from_project_string(output.as_str())
            .expect("This comes from tw, it should be valid");
        Ok(project)
    }
}

impl Display for Task {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.uuid.fmt(f)
    }
}

impl FromStr for Task {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let uuid = taskchampion::Uuid::from_str(s)?;
        Ok(Self { uuid })
    }
}

/// A registered task Project
#[derive(Debug, Clone, PartialEq)]
pub struct Project {
    /// The project name.
    /// For example:
    /// ```no_run
    /// &["trinitrix", "testing", "infra"]
    /// ```
    name: Vec<String>,
}

static ALL_CACHE: OnceLock<Vec<Project>> = OnceLock::new();
impl Project {
    #[must_use]
    pub fn to_project_display(&self) -> String {
        self.name.join(".")
    }
    #[must_use]
    pub fn to_context_display(&self) -> String {
        self.name.join("_")
    }

    /// # Errors
    /// - When the string does not encode a previously registered project.
    /// - When the string does not adhere to the project syntax.
    pub fn from_project_string(s: &str) -> Result<Self> {
        Self::from_input(s, ProjectName::from_project)
    }

    /// # Errors
    /// - When the string does not encode a previously registered project.
    /// - When the string does not adhere to the context syntax.
    pub fn from_context_string(s: &str) -> Result<Self> {
        Self::from_input(s, ProjectName::from_context)
    }

    fn from_input<F>(s: &str, f: F) -> Result<Self>
    where
        F: Fn(&str) -> ProjectName,
    {
        if s.is_empty() {
            bail!("Your project is empty")
        }

        let all = Self::all()?;
        let me = Self::from_project_name_unchecked(&f(s));
        if all.contains(&me) {
            Ok(me)
        } else {
            bail!(
                "Your project '{}' is not registered!",
                me.to_project_display()
            );
        }
    }
    fn from_project_name_unchecked(pn: &ProjectName) -> Self {
        Self {
            name: pn.segments().to_owned(),
        }
    }

    /// Return all known valid projects.
    ///
    /// # Errors
    /// When file operations fail.
    ///
    /// # Panics
    /// Only when internal assertions fail.
    pub fn all<'a>() -> Result<&'a [Project]> {
        // Inlined from `OnceLock::get_or_try_init`
        {
            let this = &ALL_CACHE;
            let f = || {
                let file = dirs::config_local_dir()
                    .expect("Should be some")
                    .join("tskm/projects.list");
                let contents = read_to_string(&file)
                    .with_context(|| format!("Failed to read file: '{}'", file.display()))?;

                Ok::<_, anyhow::Error>(
                    contents
                        .lines()
                        .map(|s| Self::from_project_name_unchecked(&ProjectName::from_project(s)))
                        .collect::<Vec<_>>(),
                )
            };

            // Fast path check
            // NOTE: We need to perform an acquire on the state in this method
            // in order to correctly synchronize `LazyLock::force`. This is
            // currently done by calling `self.get()`, which in turn calls
            // `self.is_initialized()`, which in turn performs the acquire.
            if let Some(value) = this.get() {
                return Ok(value);
            }

            this.set(f()?).expect(
                "This should always be able to take our value, as we initialize only once.",
            );

            Ok(this.get().expect("This was initialized"))
        }
    }

    fn touch_dir(&self) -> PathBuf {
        let lock_dir = dirs::data_dir()
            .expect("Should be found")
            .join("tskm/review");
        lock_dir.join(format!("{}.opened", self.to_project_display()))
    }

    /// Mark this project as having been interacted with.
    ///
    /// # Errors
    /// When IO operations fail.
    pub fn touch(&self) -> Result<()> {
        let lock_file = self.touch_dir();

        File::create(&lock_file)
            .with_context(|| format!("Failed to create lock_file at: {}", lock_file.display()))?;

        Ok(())
    }
    /// Returns [`true`] if it was previously [`Self::touch`]ed.
    #[must_use]
    pub fn is_touched(&self) -> bool {
        let lock_file = self.touch_dir();
        lock_file.exists()
    }
    /// Mark this project as having not been interacted with.
    ///
    /// # Errors
    /// When IO operations fail.
    pub fn untouch(&self) -> Result<()> {
        let lock_file = self.touch_dir();

        fs::remove_file(&lock_file)
            .with_context(|| format!("Failed to create lock_file at: {}", lock_file.display()))?;

        Ok(())
    }

    /// # Errors
    /// When `task` execution fails.
    pub fn get_tasks(&self, state: &mut State) -> Result<Vec<Task>> {
        Ok(state
            .replica()
            .pending_task_data()?
            .into_iter()
            .filter(|t| t.get("project").expect("Is set") == self.to_project_display())
            .map(|t| Task::from(&t))
            .collect())
    }

    /// # Errors
    /// When `task` execution fails.
    pub fn activate(&self) -> Result<()> {
        debug!("Setting project {}", self.to_context_display());

        run_task(&["context", self.to_context_display().as_str()]).map(|_| ())
    }
    /// # Errors
    /// When `task` execution fails.
    pub fn clear() -> Result<()> {
        debug!("Clearing active project");

        run_task(&["context", "none"]).map(|_| ())
    }

    /// # Errors
    /// When `task` execution fails.
    pub fn get_current() -> Result<Option<Self>> {
        let self_str = run_task(&["_get", "rc.context"])?;

        if self_str.is_empty() {
            Ok(None)
        } else {
            Self::from_context_string(&self_str).map(Some)
        }
    }
}

pub(crate) fn run_task(args: &[&str]) -> Result<String> {
    debug!("Running task command: `task {}`", args.join(" "));

    let output = Command::new("task")
        .args(args)
        .output()
        .with_context(|| format!("Failed to run `task {}`", args.join(" ")))?;

    let stdout = String::from_utf8(output.stdout).context("Failed to read task output as utf8")?;
    let stderr = String::from_utf8(output.stderr).context("Failed to read task output as utf8")?;

    trace!("Output (stdout): '{}'", stdout.trim());
    trace!("Output (stderr): '{}'", stderr.trim());

    Ok(stdout.trim().to_owned())
}