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
use crate::errors::*;
use crate::args::{Args, Publish, Install, Search};
use crate::api::Client;
use crate::auth;
use crate::config::Config;
use crate::engine::{Engine, Module};
use colored::Colorize;
use separator::Separatable;
use sn0int_common::ModuleID;
use sn0int_common::api::ModuleInfoResponse;
use sn0int_common::metadata::Metadata;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::paths;
use crate::term;
use crate::worker::{self, Task, EventSender, LogEvent};


pub struct Updater {
    client: Client,
}

impl Updater {
    pub fn new(config: &Config) -> Result<Updater> {
        let client = Client::new(&config)?;
        Ok(Updater {
            client,
        })
    }

    #[inline]
    pub fn query_module(&self, module: &ModuleID) -> Result<ModuleInfoResponse> {
        self.client.query_module(module)
    }

    fn path(&self, module: &ModuleID) -> Result<PathBuf> {
        let path = paths::module_dir()?
            .join(format!("{}/{}.lua", module.author,
                                       module.name));
        Ok(path)
    }

    pub fn install(&self, install: Install) -> Result<String> {
        if let Some(version) = install.version {
            let module = self.client.download_module(&install.module, &version)
                .context("Failed to download module")?;

            let path = self.path(&install.module)?;

            fs::create_dir_all(path.parent().unwrap())
                .context("Failed to create folder")?;

            fs::write(&path, module.code)
                .context(format_err!("Failed to write to {:?}", path))?;

            Ok(version.to_string())
        } else {
            let infos = self.query_module(&install.module)
                        .context("Failed to query module infos")?;

            if !install.force {
                if let Some(redirect) = infos.redirect {
                    return self.install(Install {
                        module: redirect,
                        version: None,
                        force: install.force,
                    });
                }
            }

            let latest = infos
                        .latest
                        .ok_or_else(|| format_err!("Module doesn't have a latest version"))?;
            self.install(Install {
                module: install.module,
                version: Some(latest),
                force: install.force,
            })
        }
    }

    pub fn uninstall(&self, module: &ModuleID) -> Result<()> {
        let path = self.path(module)?;
        fs::remove_file(&path)?;

        // try to delete parent folder if empty
        if let Some(parent) = path.parent() {
            fs::remove_dir(parent).ok();
        }

        Ok(())
    }
}

pub fn run_publish(_args: &Args, publish: &Publish, config: &Config) -> Result<()> {
    let session = auth::load_token()
        .context("Failed to load auth token, login first")?;

    let mut client = Client::new(&config)?;
    client.authenticate(session);

    for path in &publish.paths {
        let path = Path::new(path);
        let name = path.file_stem().ok_or_else(|| format_err!("Couldn't get file name"))?;
        let ext = path.extension().ok_or_else(|| format_err!("Couldn't get file extension"))?;

        if ext != "lua" {
            bail!("File extension has to be .lua");
        }

        let name = name.to_os_string().into_string()
            .map_err(|_| format_err!("Failed to decode file name"))?;

        let code = fs::read_to_string(path)
            .context("Failed to read module")?;
        let metadata = code.parse::<Metadata>()?;

        let label = format!("Uploading {} {} ({:?})", name, metadata.version, path);
        match worker::spawn_fn(&label, || {
            client.publish_module(&name, code.to_string())
        }, true) {
            Ok(result) => term::info(&format!("Published {}/{} {} ({:?})",
                                              result.author,
                                              result.name,
                                              result.version,
                                              path)),
            Err(err) => term::error(&format!("Failed to publish {} {} ({:?}): {}",
                                             name,
                                             metadata.version,
                                             path,
                                             err)),
        }
    }

    Ok(())
}

pub struct InstallTask {
    install: Install,
    client: Arc<Updater>,
}

impl InstallTask {
    pub fn new(install: Install, client: Arc<Updater>) -> InstallTask {
        InstallTask {
            install,
            client,
        }
    }
}

impl Task for InstallTask {
    #[inline]
    fn initial_label(name: &str) -> String {
        format!("Installing {}", name)
    }

    #[inline]
    fn name(&self) -> String {
        self.install.module.to_string()
    }

    fn run(self, tx: &EventSender) -> Result<()> {
        let version = self.client.install(self.install)?;
        let label = format!("installed v{}", version);
        tx.log(LogEvent::Success(label));
        Ok(())
    }
}


pub fn run_install(arg: Install, config: &Config) -> Result<()> {
    let label = format!("Installing {}", arg.module);
    worker::spawn_fn(&label, || {
        let client = Updater::new(config)?;
        client.install(arg)?;
        Ok(())
    }, false)
}

pub struct UpdateTask {
    module: Module,
    client: Arc<Updater>,
}

impl UpdateTask {
    pub fn new(module: Module, client: Arc<Updater>) -> UpdateTask {
        UpdateTask {
            module,
            client,
        }
    }
}

impl Task for UpdateTask {
    #[inline]
    fn initial_label(name: &str) -> String {
        format!("Searching for updates: {}", name)
    }

    #[inline]
    fn name(&self) -> String {
        self.module.canonical()
    }

    fn run(self, tx: &EventSender) -> Result<()> {
        let installed = self.module.version();

        let infos = self.client.query_module(&self.module.id())?;
        debug!("Latest version: {:?}", infos);
        let latest = infos.latest.ok_or_else(|| format_err!("Module doesn't have any released versions"))?;

        if let Some(redirect) = infos.redirect {
            let label = format!("Replacing {}: {}", self.name(), redirect);
            tx.log(LogEvent::Status(label));

            self.client.install(Install {
                module: self.module.id(),
                version: None,
                force: false,
            })?;
            self.client.uninstall(&self.module.id())?;

            let label = format!("replaced with {}", redirect);
            tx.log(LogEvent::Success(label));
        } else if installed != latest {
            let label = format!("Updating {}: v{} -> v{}", self.name(), installed, latest);
            tx.log(LogEvent::Status(label));

            self.client.install(Install {
                module: self.module.id(),
                version: Some(latest.clone()),
                force: false,
            })?;

            let label = format!("updated v{} -> v{}", installed, latest);
            tx.log(LogEvent::Success(label));
        }

        Ok(())
    }
}

pub fn run_search(engine: &Engine, search: &Search, config: &Config) -> Result<()> {
    let client = Client::new(&config)?;

    let label = format!("Searching {:?}", search.query);
    let modules = worker::spawn_fn(&label, || {
        client.search(&search.query)
    }, true)?;

    for module in &modules {
        let canonical = module.canonical();
        let installed = engine.get_opt(&canonical)?;

        if search.new && installed.is_some() {
            continue;
        }

        println!("{} ({}) - {} downloads{}{}", canonical.green(),
                            module.latest.yellow(),
                            module.downloads.separated_string(),
                            (if module.featured { " [featured]" } else { "" }).cyan(),
                            (if installed.is_some() { " [installed]" } else { "" }).green());
        println!("\t{}", module.description);
    }

    Ok(())
}