<commit_before>use state::State;
use types::*;
use lua::Lua;

/**
 *  A generic trait for converting a Lua value to a Rust value.
 *
 *  Return None when the types didn't corresponds.
 */
pub trait FromLua
{
    fn from_lua(state: &State, idx: int) -> Option<Self>;
}

/// A generic trait for converting a Rust value to a Lua value.
pub trait ToLua
{
    fn to_lua(self, state: &State);
}

// float
impl FromLua for f64
{
    fn from_lua(state: &State, idx: int) -> Option<f64>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_float(idx)),
            _ => None,
        }
    }
}

impl ToLua for f64
{
    fn to_lua(self, state: &State)
    {
        state.push_float(self);
    }
}

// int
impl FromLua for int
{
    fn from_lua(state: &State, idx: int) -> Option<int>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_int(idx)),
            _ => None,
        }
    }
}

impl ToLua for int
{
    fn to_lua(self, state: &State)
    {
        state.push_int(self);
    }
}

// uint
impl FromLua for uint
{
    fn from_lua(state: &State, idx: int) -> Option<uint>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_uint(idx)),
            _ => None,
        }
    }
}

impl ToLua for uint
{
    fn to_lua(self, state: &State)
    {
        state.push_uint(self);
    }
}

// &str
impl<'a> ToLua for &'a str
{
    fn to_lua(self, state: &State)
    {
        state.push_str(self);
    }
}

// ~str
impl FromLua for ~str
{
    fn from_lua(state: &State, idx: int) -> Option<~str>
    {
        match state.get_type(idx)
        {
            LuaString => Some(state.get_str(idx)),
            _ => None,
        }
    }
}

impl ToLua for ~str
{
    fn to_lua(self, state: &State)
    {
        state.push_str(self);
    }
}

// bool
impl FromLua for bool
{
    fn from_lua(state: &State, idx: int) -> Option<bool>
    {
        match state.get_type(idx)
        {
            LuaBoolean => Some(state.get_bool(idx)),
            _ => None,
        }
    }
}

impl ToLua for bool
{
    fn to_lua(self, state: &State)
    {
        state.push_bool(self);
    }
}

// Pointer
impl<T> FromLua for *T
{
    fn from_lua(state: &State, idx: int) -> Option<*T>
    {
        match state.get_type(idx)
        {
            LuaUserData | LuaLightUserData => Some(state.get_userdata(idx)),
            _ => None,
        }
    }
}

impl<T> ToLua for *T
{
    fn to_lua(self, state: &State)
    {
        state.push_userdata(self);
    }
}

// Function
impl FromLua for fn(l: &Lua) -> int
{
    fn from_lua(state: &State, idx: int) -> Option<fn(l: &Lua) -> int>
    {
        match state.get_type(idx)
        {
            LuaUserData | LuaLightUserData => Some(state.get_userdata::<*()>(idx) as fn(l: &Lua) -> int),
            _ => None,
        }
    }
}

impl ToLua for fn(l: &Lua) -> int
{
    fn to_lua(self, state: &State)
    {
        state.push_function(self);
    }
}
<commit_msg>- Finally, can't cast arbitrary pointer to function!<commit_after>use std::libc::*;
use std::cast::transmute;

use state::State;
use types::*;
use lua::Lua;

/**
 *  A generic trait for converting a Lua value to a Rust value.
 *
 *  Return None when the types didn't corresponds.
 */
pub trait FromLua
{
    fn from_lua(state: &State, idx: int) -> Option<Self>;
}

/// A generic trait for converting a Rust value to a Lua value.
pub trait ToLua
{
    fn to_lua(self, state: &State);
}

// float
impl FromLua for f64
{
    fn from_lua(state: &State, idx: int) -> Option<f64>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_float(idx)),
            _ => None,
        }
    }
}

impl ToLua for f64
{
    fn to_lua(self, state: &State)
    {
        state.push_float(self);
    }
}

// int
impl FromLua for int
{
    fn from_lua(state: &State, idx: int) -> Option<int>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_int(idx)),
            _ => None,
        }
    }
}

impl ToLua for int
{
    fn to_lua(self, state: &State)
    {
        state.push_int(self);
    }
}

// uint
impl FromLua for uint
{
    fn from_lua(state: &State, idx: int) -> Option<uint>
    {
        match state.get_type(idx)
        {
            LuaNumber => Some(state.get_uint(idx)),
            _ => None,
        }
    }
}

impl ToLua for uint
{
    fn to_lua(self, state: &State)
    {
        state.push_uint(self);
    }
}

// &str
impl<'a> ToLua for &'a str
{
    fn to_lua(self, state: &State)
    {
        state.push_str(self);
    }
}

// ~str
impl FromLua for ~str
{
    fn from_lua(state: &State, idx: int) -> Option<~str>
    {
        match state.get_type(idx)
        {
            LuaString => Some(state.get_str(idx)),
            _ => None,
        }
    }
}

impl ToLua for ~str
{
    fn to_lua(self, state: &State)
    {
        state.push_str(self);
    }
}

// bool
impl FromLua for bool
{
    fn from_lua(state: &State, idx: int) -> Option<bool>
    {
        match state.get_type(idx)
        {
            LuaBoolean => Some(state.get_bool(idx)),
            _ => None,
        }
    }
}

impl ToLua for bool
{
    fn to_lua(self, state: &State)
    {
        state.push_bool(self);
    }
}

// Pointer
impl<T> FromLua for *T
{
    fn from_lua(state: &State, idx: int) -> Option<*T>
    {
        match state.get_type(idx)
        {
            LuaUserData | LuaLightUserData => Some(state.get_userdata(idx)),
            _ => None,
        }
    }
}

impl<T> ToLua for *T
{
    fn to_lua(self, state: &State)
    {
        state.push_userdata(self);
    }
}

// Function
impl FromLua for fn(l: &Lua) -> int
{
    fn from_lua(state: &State, idx: int) -> Option<fn(l: &Lua) -> int>
    {
        match state.get_type(idx)
        {
            LuaUserData | LuaLightUserData => {
                let ptr: fn(&Lua) -> int = unsafe {
                    transmute(state.get_userdata::<*c_void>(idx))
                };

                Some(ptr)
            }
            _ => None,
        }
    }
}

impl ToLua for fn(l: &Lua) -> int
{
    fn to_lua(self, state: &State)
    {
        state.push_function(self);
    }
}
<|endoftext|>


<commit_before>pub mod bldr;
pub mod cli;
pub mod config;
pub mod file;
pub mod license;
pub mod origin;
pub mod pkg;
pub mod plan;
pub mod ring;
pub mod studio;
pub mod sup;
pub mod svc;
#[cfg(test)]
mod tests;
pub mod user;
pub mod util;

use self::{bldr::{ConfigOptChannelCreate,
                  ConfigOptChannelDemote,
                  ConfigOptChannelDestroy,
                  ConfigOptChannelList,
                  ConfigOptChannelPromote,
                  ConfigOptJobCancel,
                  ConfigOptJobDemote,
                  ConfigOptJobPromote,
                  ConfigOptJobStart,
                  ConfigOptJobStatus,
                  ChannelCreate,
                  ChannelDemote,
                  ChannelDestroy,
                  ChannelList,
                  ChannelPromote,
                  JobCancel,
                  JobDemote,
                  JobPromote,
                  JobStart,
                  JobStatus},
           cli::{CliCompleters,
                 ConfigOptCliCompleters,
                 CliSetup,
                 ConfigOptCliSetup},
           config::{ConfigOptServiceConfigApply,
                    ConfigOptServiceConfigShow,
                    ServiceConfigApply,
                    ServiceConfigShow},
           file::{ConfigOptFile,
                  File},
           license::{ConfigOptLicense,
                     License},
           origin::{ConfigOptOrigin,
                    Origin},
           pkg::{ConfigOptPkg,
                 ConfigOptPkgInstall,
                 Pkg,
                 PkgInstall},
           plan::{ConfigOptPlan,
                  Plan},
           ring::{ConfigOptRing,
                  Ring},
           studio::{ConfigOptStudio,
                    Studio},
           sup::{ConfigOptHabSup,
                 ConfigOptSupRun,
                 HabSup,
                 SupRun},
           svc::{ConfigOptSvc,
                 ConfigOptSvcStart,
                 ConfigOptSvcStop,
                 Svc,
                 SvcStart,
                 SvcStop},
           user::{ConfigOptUserKeyGenerate,
                  UserKeyGenerate},
           util::{CacheKeyPath,
                  ConfigOptCacheKeyPath}};
use crate::{cli::AFTER_HELP,
            VERSION};
use configopt::ConfigOpt;
use structopt::{clap::AppSettings,
                StructOpt};

#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "hab",
            version = VERSION,
            about = "Patents: https://chef.io/patents\n\"A Habitat is the natural environment for your services\" - Alan Turing",
            author = "\nThe Habitat Maintainers <humans@habitat.sh>\n",
            settings = &[AppSettings::GlobalVersion],
            after_help = AFTER_HELP
        )]
#[allow(clippy::large_enum_variant)]
pub enum Hab {
    #[structopt(no_version)]
    Bldr(Bldr),
    #[structopt(no_version)]
    Cli(Cli),
    #[structopt(no_version)]
    Config(ServiceConfig),
    #[structopt(no_version)]
    File(File),
    #[structopt(no_version, settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
    License(License),
    #[structopt(no_version)]
    Origin(Origin),
    #[structopt(no_version)]
    Pkg(Pkg),
    #[structopt(no_version)]
    Plan(Plan),
    #[structopt(no_version)]
    Ring(Ring),
    #[structopt(no_version, aliases = &["stu", "stud", "studi"])]
    Studio(Studio),
    #[structopt(no_version)]
    Sup(HabSup),
    /// Create a tarball of Habitat Supervisor data to send to support
    #[structopt(no_version)]
    Supportbundle,
    #[structopt(no_version)]
    Svc(Svc),
    #[structopt(no_version)]
    User(User),

    /// Alias for 'config apply'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Apply(ServiceConfigApply),
    /// Alias for 'pkg install'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["i", "in", "ins", "inst", "insta", "instal"])]
    Install(PkgInstall),
    #[cfg(not(target_os = "macos"))]
    /// Alias for 'sup run'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Run(SupRun),
    /// Alias for 'cli setup'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["set", "setu"])]
    Setup(CacheKeyPath),
    /// Alias for 'svc start'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["sta", "star"])]
    Start(SvcStart),
    /// Alias for 'svc stop'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["sto"])]
    Stop(SvcStop),
    #[cfg(not(target_os = "macos"))]
    /// Alias for 'sup term'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Term,
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["b", "bl", "bld"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder
pub enum Bldr {
    #[structopt(no_version)]
    Channel(Channel),
    #[structopt(no_version)]
    Job(Job),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["c", "ch", "cha", "chan", "chann", "channe"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder channels
pub enum Channel {
    #[structopt(no_version, aliases = &["c", "cr", "cre", "crea", "creat"])]
    Create(ChannelCreate),
    Demote(ChannelDemote),
    #[structopt(no_version, aliases = &["d", "de", "des", "dest", "destr", "destro"])]
    Destroy(ChannelDestroy),
    #[structopt(no_version, aliases = &["l", "li", "lis"])]
    List(ChannelList),
    Promote(ChannelPromote),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["j", "jo"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder jobs
pub enum Job {
    #[structopt(no_version, aliases = &["c", "ca", "can", "cance", "cancel"])]
    Cancel(JobCancel),
    #[structopt(no_version, aliases = &["d", "de", "dem", "demo", "demot"])]
    Demote(JobDemote),
    #[structopt(no_version, aliases = &["p", "pr", "pro", "prom", "promo", "promot"])]
    Promote(JobPromote),
    #[structopt(no_version, aliases = &["s", "st", "sta", "star"])]
    Start(JobStart),
    #[structopt(no_version, aliases = &["stat", "statu"])]
    Status(JobStatus),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["cl"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat runtime config
pub enum Cli {
    #[structopt(no_version, aliases = &["s", "se", "set", "setu"])]
    /// Sets up the CLI with reasonable defaults
    Setup(CliSetup),
    #[structopt(no_version, aliases = &["c", "co", "com", "comp"])]
    /// Creates command-line completers for your shell
    Completers(CliCompleters),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["co", "con", "conf", "confi"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to a Service's runtime config
pub enum ServiceConfig {
    #[structopt(no_version, aliases = &["ap", "app", "appl"])]
    Apply(ServiceConfigApply),
    #[structopt(no_version, aliases = &["sh", "sho"])]
    Show(ServiceConfigShow),
}

/// Commands relating to Habitat users
#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "user", no_version, aliases = &["u", "us", "use"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
pub enum User {
    Key(UserKey),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "key", no_version, aliases = &["k", "ke"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat user keys
pub enum UserKey {
    #[structopt(no_version, aliases = &["g", "ge", "gen", "gene", "gener", "genera", "generat"])]
    Generate(UserKeyGenerate),
}<commit_msg>[Refactor] added file wrapper to hab<commit_after>pub mod bldr;
pub mod cli;
pub mod config;
pub mod file;
pub mod license;
pub mod origin;
pub mod pkg;
pub mod plan;
pub mod ring;
pub mod studio;
pub mod sup;
pub mod svc;
#[cfg(test)]
mod tests;
pub mod user;
pub mod util;

use self::{bldr::{ConfigOptChannelCreate,
                  ConfigOptChannelDemote,
                  ConfigOptChannelDestroy,
                  ConfigOptChannelList,
                  ConfigOptChannelPromote,
                  ConfigOptJobCancel,
                  ConfigOptJobDemote,
                  ConfigOptJobPromote,
                  ConfigOptJobStart,
                  ConfigOptJobStatus,
                  ChannelCreate,
                  ChannelDemote,
                  ChannelDestroy,
                  ChannelList,
                  ChannelPromote,
                  JobCancel,
                  JobDemote,
                  JobPromote,
                  JobStart,
                  JobStatus},
           cli::{CliCompleters,
                 ConfigOptCliCompleters,
                 CliSetup,
                 ConfigOptCliSetup},
           config::{ConfigOptServiceConfigApply,
                    ConfigOptServiceConfigShow,
                    ServiceConfigApply,
                    ServiceConfigShow},
           file::{ConfigOptFileUpload,
                  FileUpload},
           license::{ConfigOptLicense,
                     License},
           origin::{ConfigOptOrigin,
                    Origin},
           pkg::{ConfigOptPkg,
                 ConfigOptPkgInstall,
                 Pkg,
                 PkgInstall},
           plan::{ConfigOptPlan,
                  Plan},
           ring::{ConfigOptRing,
                  Ring},
           studio::{ConfigOptStudio,
                    Studio},
           sup::{ConfigOptHabSup,
                 ConfigOptSupRun,
                 HabSup,
                 SupRun},
           svc::{ConfigOptSvc,
                 ConfigOptSvcStart,
                 ConfigOptSvcStop,
                 Svc,
                 SvcStart,
                 SvcStop},
           user::{ConfigOptUserKeyGenerate,
                  UserKeyGenerate},
           util::{CacheKeyPath,
                  ConfigOptCacheKeyPath}};
use crate::{cli::AFTER_HELP,
            VERSION};
use configopt::ConfigOpt;
use structopt::{clap::AppSettings,
                StructOpt};

#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "hab",
            version = VERSION,
            about = "Patents: https://chef.io/patents\n\"A Habitat is the natural environment for your services\" - Alan Turing",
            author = "\nThe Habitat Maintainers <humans@habitat.sh>\n",
            settings = &[AppSettings::GlobalVersion],
            after_help = AFTER_HELP
        )]
#[allow(clippy::large_enum_variant)]
pub enum Hab {
    #[structopt(no_version)]
    Bldr(Bldr),
    #[structopt(no_version)]
    Cli(Cli),
    #[structopt(no_version)]
    Config(ServiceConfig),
    #[structopt(no_version)]
    File(File),
    #[structopt(no_version, settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
    License(License),
    #[structopt(no_version)]
    Origin(Origin),
    #[structopt(no_version)]
    Pkg(Pkg),
    #[structopt(no_version)]
    Plan(Plan),
    #[structopt(no_version)]
    Ring(Ring),
    #[structopt(no_version, aliases = &["stu", "stud", "studi"])]
    Studio(Studio),
    #[structopt(no_version)]
    Sup(HabSup),
    /// Create a tarball of Habitat Supervisor data to send to support
    #[structopt(no_version)]
    Supportbundle,
    #[structopt(no_version)]
    Svc(Svc),
    #[structopt(no_version)]
    User(User),

    /// Alias for 'config apply'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Apply(ServiceConfigApply),
    /// Alias for 'pkg install'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["i", "in", "ins", "inst", "insta", "instal"])]
    Install(PkgInstall),
    #[cfg(not(target_os = "macos"))]
    /// Alias for 'sup run'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Run(SupRun),
    /// Alias for 'cli setup'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["set", "setu"])]
    Setup(CacheKeyPath),
    /// Alias for 'svc start'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["sta", "star"])]
    Start(SvcStart),
    /// Alias for 'svc stop'
    #[structopt(no_version, settings = &[AppSettings::Hidden], aliases = &["sto"])]
    Stop(SvcStop),
    #[cfg(not(target_os = "macos"))]
    /// Alias for 'sup term'
    #[structopt(no_version, settings = &[AppSettings::Hidden])]
    Term,
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["b", "bl", "bld"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder
pub enum Bldr {
    #[structopt(no_version)]
    Channel(Channel),
    #[structopt(no_version)]
    Job(Job),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["c", "ch", "cha", "chan", "chann", "channe"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder channels
pub enum Channel {
    #[structopt(no_version, aliases = &["c", "cr", "cre", "crea", "creat"])]
    Create(ChannelCreate),
    Demote(ChannelDemote),
    #[structopt(no_version, aliases = &["d", "de", "des", "dest", "destr", "destro"])]
    Destroy(ChannelDestroy),
    #[structopt(no_version, aliases = &["l", "li", "lis"])]
    List(ChannelList),
    Promote(ChannelPromote),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["j", "jo"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat Builder jobs
pub enum Job {
    #[structopt(no_version, aliases = &["c", "ca", "can", "cance", "cancel"])]
    Cancel(JobCancel),
    #[structopt(no_version, aliases = &["d", "de", "dem", "demo", "demot"])]
    Demote(JobDemote),
    #[structopt(no_version, aliases = &["p", "pr", "pro", "prom", "promo", "promot"])]
    Promote(JobPromote),
    #[structopt(no_version, aliases = &["s", "st", "sta", "star"])]
    Start(JobStart),
    #[structopt(no_version, aliases = &["stat", "statu"])]
    Status(JobStatus),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["cl"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat runtime config
pub enum Cli {
    #[structopt(no_version, aliases = &["s", "se", "set", "setu"])]
    /// Sets up the CLI with reasonable defaults
    Setup(CliSetup),
    #[structopt(no_version, aliases = &["c", "co", "com", "comp"])]
    /// Creates command-line completers for your shell
    Completers(CliCompleters),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["co", "con", "conf", "confi"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to a Service's runtime config
pub enum ServiceConfig {
    #[structopt(no_version, aliases = &["ap", "app", "appl"])]
    Apply(ServiceConfigApply),
    #[structopt(no_version, aliases = &["sh", "sho"])]
    Show(ServiceConfigShow),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(no_version, aliases = &["f", "fi", "fil"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat files
pub enum File {
    #[structopt(no_version, aliases = &["u", "up", "upl", "uplo", "uploa"])]
    /// Uploads a file to be shared between members of a Service Group
    Upload(FileUpload),
}

/// Commands relating to Habitat users
#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "user", no_version, aliases = &["u", "us", "use"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
pub enum User {
    Key(UserKey),
}

#[derive(ConfigOpt, StructOpt)]
#[structopt(name = "key", no_version, aliases = &["k", "ke"], settings = &[AppSettings::ArgRequiredElseHelp, AppSettings::SubcommandRequiredElseHelp])]
/// Commands relating to Habitat user keys
pub enum UserKey {
    #[structopt(no_version, aliases = &["g", "ge", "gen", "gene", "gener", "genera", "generat"])]
    Generate(UserKeyGenerate),
}<|endoftext|>


<commit_before>//! This module provides the logic necessary to implement a license prompt into
//! the hab CLI. When a user runs hab for the first time, they will be prompted
//! to accept the Chef license agreement. If they choose not to, then hab will
//! exit and they will be unable to use the tool.
//!
//! Choosing to accept the license will write a file to either
//! /hab/accepted-licenses/habitat (if run as root) or
//! ~/.hab/accepted-licenses/habitat. The presence of this file will
//! prevent further license prompts. The file itself contains various metadata
//! that we collect, but it's important to note that the contents of this file
//! are not strictly important. The important thing is the presence of the file.
//!
//! If a user was to read our code and pre-emptively create one of the above
//! files and leave its contents completely empty, that is sufficient for the
//! acceptance of the license. We will not overwrite their empty file, nor
//! will we care that it is empty.
//!
//! Because of this, the metadata that we store is not strictly necessary and
//! is more of a best effort scenario. If we can't collect all of it for
//! whatever reason, it's fine.
//!
//! Additionally, there are 2 environment variables that are supported to
//! constitute license acceptance. Setting HAB_LICENSE to "accept" will
//! accept the license and persist the file and setting HAB_LICENSE to
//! "accept-no-persist" will accept the license but not persist the
//! acceptance.
//!
//! More detailed information on the license spec is available at
//! https://github.com/chef/license-acceptance

use crate::{common::ui::{self,
                         UIReader,
                         UIWriter,
                         UI},
            error::{Error,
                    Result},
            hcore::{fs::{am_i_root,
                         FS_ROOT_PATH},
                    users::get_current_username}};
use chrono::{DateTime,
             Utc};
use std::{env,
          fs::{self,
               File},
          io::Write,
          path::PathBuf};

const LICENSE_FILE_FORMAT_VERSION: &str = "1.0";
const LICENSE_ACCEPT_ENVVAR: &str = "HAB_LICENSE";

#[derive(Debug, Serialize, Deserialize)]
pub struct LicenseData {
    pub date_accepted: DateTime<Utc>,
    pub accepting_product: String,
    pub accepting_product_version: String,
    pub user: Option<String>,
    pub file_format: String,
}

impl LicenseData {
    pub fn new() -> Self {
        LicenseData { date_accepted: Utc::now(),
                      accepting_product: String::from("hab"),
                      accepting_product_version: super::VERSION.to_string(),
                      user: get_current_username(),
                      file_format: String::from(LICENSE_FILE_FORMAT_VERSION), }
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum LicenseAcceptance {
    Accepted,
    /// Explicitly deny the license and do not prompt for license acceptance. This is useful for
    /// testing.
    Denied,
    NotYetAccepted,
}

impl LicenseAcceptance {
    pub fn accepted(self) -> bool { self == Self::Accepted }
}

impl Default for LicenseAcceptance {
    fn default() -> Self { Self::NotYetAccepted }
}

pub fn check_for_license_acceptance() -> Result<LicenseAcceptance> {
    match (env_var_present()?, license_exists()) {
        // The environment variable takes precedence regardless of the existence of the license
        // file
        (l @ LicenseAcceptance::Accepted, _) | (l @ LicenseAcceptance::Denied, _) => Ok(l),
        (_, true) => Ok(LicenseAcceptance::Accepted),
        (..) => Ok(LicenseAcceptance::NotYetAccepted),
    }
}

pub fn check_for_license_acceptance_and_prompt(ui: &mut UI) -> Result<()> {
    match check_for_license_acceptance()? {
        LicenseAcceptance::Accepted => Ok(()),
        LicenseAcceptance::Denied => Err(Error::LicenseNotAccepted),
        LicenseAcceptance::NotYetAccepted => {
            ui.heading("+---------------------------------------------+")?;
            ui.heading("            Chef License Acceptance")?;
            ui.br()?;
            ui.info("Before you can continue, 1 product license must be accepted.")?;
            ui.info("View the license at https://www.chef.io/end-user-license-agreement")?;
            ui.br()?;
            ui.info("License that needs accepting:")?;
            ui.br()?;
            ui.info("  * Habitat")?;
            ui.br()?;

            if ui.prompt_yes_no("Do you accept the 1 product license?", Some(false))? {
                accept_license(ui)
            } else {
                ui.br()?;
                ui.info("If you do not accept this license you will not be able to use Chef \
                         products.")?;
                ui.br()?;

                if ui.prompt_yes_no("Do you accept the 1 product license?", Some(false))? {
                    accept_license(ui)
                } else {
                    ui.br()?;
                    ui.heading("+---------------------------------------------+")?;
                    Err(Error::LicenseNotAccepted)
                }
            }
        }
    }
}

pub fn accept_license(ui: &mut UI) -> Result<()> {
    if license_exists() {
        ui.info("You have already accepted the license.")?;
        return Ok(());
    }

    ui.br()?;
    ui.info("Accepting 1 product license...")?;

    write_license_file()?;

    ui.status(ui::Status::Custom(ui::Glyph::CheckMark, String::from("")),
              "1 product license accepted.")?;
    ui.br()?;
    ui.heading("+---------------------------------------------+")?;

    Ok(())
}

fn superuser_license_root() -> PathBuf { PathBuf::from(&*FS_ROOT_PATH).join("hab") }

fn user_license_root() -> PathBuf {
    if let Some(home) = dirs::home_dir() {
        home.join(".hab")
    } else {
        panic!("No home directory available. Unable to find a suitable place to write a license \
                file.");
    }
}

fn license_path(root_path: &PathBuf) -> PathBuf { root_path.join("accepted-licenses") }

fn license_file(license_path: &PathBuf) -> PathBuf { license_path.join("habitat") }

fn writeable_license_path() -> PathBuf {
    let root_dir = if am_i_root() {
        superuser_license_root()
    } else {
        user_license_root()
    };

    license_path(&root_dir)
}

fn env_var_present() -> Result<LicenseAcceptance> {
    match env::var(LICENSE_ACCEPT_ENVVAR) {
        Ok(val) => {
            if &val == "accept" {
                write_license_file()?;
                Ok(LicenseAcceptance::Accepted)
            } else if &val == "accept-no-persist" {
                Ok(LicenseAcceptance::Accepted)
            } else if &val == "deny" {
                Ok(LicenseAcceptance::Denied)
            } else {
                Ok(LicenseAcceptance::NotYetAccepted)
            }
        }
        Err(_) => Ok(LicenseAcceptance::NotYetAccepted),
    }
}

fn write_license_file() -> Result<()> {
    let license = LicenseData::new();
    let content = serde_yaml::to_string(&license)?;
    fs::create_dir_all(writeable_license_path())?;
    let mut file = File::create(license_file(&writeable_license_path()))?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

pub fn license_exists() -> bool {
    license_file(&license_path(&user_license_root())).is_file()
    || license_file(&license_path(&superuser_license_root())).is_file()
}
<commit_msg>Rename env_var_present to acceptance_from_env_var<commit_after>//! This module provides the logic necessary to implement a license prompt into
//! the hab CLI. When a user runs hab for the first time, they will be prompted
//! to accept the Chef license agreement. If they choose not to, then hab will
//! exit and they will be unable to use the tool.
//!
//! Choosing to accept the license will write a file to either
//! /hab/accepted-licenses/habitat (if run as root) or
//! ~/.hab/accepted-licenses/habitat. The presence of this file will
//! prevent further license prompts. The file itself contains various metadata
//! that we collect, but it's important to note that the contents of this file
//! are not strictly important. The important thing is the presence of the file.
//!
//! If a user was to read our code and pre-emptively create one of the above
//! files and leave its contents completely empty, that is sufficient for the
//! acceptance of the license. We will not overwrite their empty file, nor
//! will we care that it is empty.
//!
//! Because of this, the metadata that we store is not strictly necessary and
//! is more of a best effort scenario. If we can't collect all of it for
//! whatever reason, it's fine.
//!
//! Additionally, there are 2 environment variables that are supported to
//! constitute license acceptance. Setting HAB_LICENSE to "accept" will
//! accept the license and persist the file and setting HAB_LICENSE to
//! "accept-no-persist" will accept the license but not persist the
//! acceptance.
//!
//! More detailed information on the license spec is available at
//! https://github.com/chef/license-acceptance

use crate::{common::ui::{self,
                         UIReader,
                         UIWriter,
                         UI},
            error::{Error,
                    Result},
            hcore::{fs::{am_i_root,
                         FS_ROOT_PATH},
                    users::get_current_username}};
use chrono::{DateTime,
             Utc};
use std::{env,
          fs::{self,
               File},
          io::Write,
          path::PathBuf};

const LICENSE_FILE_FORMAT_VERSION: &str = "1.0";
const LICENSE_ACCEPT_ENVVAR: &str = "HAB_LICENSE";

#[derive(Debug, Serialize, Deserialize)]
pub struct LicenseData {
    pub date_accepted: DateTime<Utc>,
    pub accepting_product: String,
    pub accepting_product_version: String,
    pub user: Option<String>,
    pub file_format: String,
}

impl LicenseData {
    pub fn new() -> Self {
        LicenseData { date_accepted: Utc::now(),
                      accepting_product: String::from("hab"),
                      accepting_product_version: super::VERSION.to_string(),
                      user: get_current_username(),
                      file_format: String::from(LICENSE_FILE_FORMAT_VERSION), }
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum LicenseAcceptance {
    Accepted,
    /// Explicitly deny the license and do not prompt for license acceptance. This is useful for
    /// testing.
    Denied,
    NotYetAccepted,
}

impl LicenseAcceptance {
    pub fn accepted(self) -> bool { self == Self::Accepted }
}

impl Default for LicenseAcceptance {
    fn default() -> Self { Self::NotYetAccepted }
}

pub fn check_for_license_acceptance() -> Result<LicenseAcceptance> {
    match (acceptance_from_env_var()?, license_exists()) {
        // The environment variable takes precedence regardless of the existence of the license
        // file
        (l @ LicenseAcceptance::Accepted, _) | (l @ LicenseAcceptance::Denied, _) => Ok(l),
        (_, true) => Ok(LicenseAcceptance::Accepted),
        (..) => Ok(LicenseAcceptance::NotYetAccepted),
    }
}

pub fn check_for_license_acceptance_and_prompt(ui: &mut UI) -> Result<()> {
    match check_for_license_acceptance()? {
        LicenseAcceptance::Accepted => Ok(()),
        LicenseAcceptance::Denied => Err(Error::LicenseNotAccepted),
        LicenseAcceptance::NotYetAccepted => {
            ui.heading("+---------------------------------------------+")?;
            ui.heading("            Chef License Acceptance")?;
            ui.br()?;
            ui.info("Before you can continue, 1 product license must be accepted.")?;
            ui.info("View the license at https://www.chef.io/end-user-license-agreement")?;
            ui.br()?;
            ui.info("License that needs accepting:")?;
            ui.br()?;
            ui.info("  * Habitat")?;
            ui.br()?;

            if ui.prompt_yes_no("Do you accept the 1 product license?", Some(false))? {
                accept_license(ui)
            } else {
                ui.br()?;
                ui.info("If you do not accept this license you will not be able to use Chef \
                         products.")?;
                ui.br()?;

                if ui.prompt_yes_no("Do you accept the 1 product license?", Some(false))? {
                    accept_license(ui)
                } else {
                    ui.br()?;
                    ui.heading("+---------------------------------------------+")?;
                    Err(Error::LicenseNotAccepted)
                }
            }
        }
    }
}

pub fn accept_license(ui: &mut UI) -> Result<()> {
    if license_exists() {
        ui.info("You have already accepted the license.")?;
        return Ok(());
    }

    ui.br()?;
    ui.info("Accepting 1 product license...")?;

    write_license_file()?;

    ui.status(ui::Status::Custom(ui::Glyph::CheckMark, String::from("")),
              "1 product license accepted.")?;
    ui.br()?;
    ui.heading("+---------------------------------------------+")?;

    Ok(())
}

fn superuser_license_root() -> PathBuf { PathBuf::from(&*FS_ROOT_PATH).join("hab") }

fn user_license_root() -> PathBuf {
    if let Some(home) = dirs::home_dir() {
        home.join(".hab")
    } else {
        panic!("No home directory available. Unable to find a suitable place to write a license \
                file.");
    }
}

fn license_path(root_path: &PathBuf) -> PathBuf { root_path.join("accepted-licenses") }

fn license_file(license_path: &PathBuf) -> PathBuf { license_path.join("habitat") }

fn writeable_license_path() -> PathBuf {
    let root_dir = if am_i_root() {
        superuser_license_root()
    } else {
        user_license_root()
    };

    license_path(&root_dir)
}

fn acceptance_from_env_var() -> Result<LicenseAcceptance> {
    match env::var(LICENSE_ACCEPT_ENVVAR) {
        Ok(val) => {
            if &val == "accept" {
                write_license_file()?;
                Ok(LicenseAcceptance::Accepted)
            } else if &val == "accept-no-persist" {
                Ok(LicenseAcceptance::Accepted)
            } else if &val == "deny" {
                Ok(LicenseAcceptance::Denied)
            } else {
                Ok(LicenseAcceptance::NotYetAccepted)
            }
        }
        Err(_) => Ok(LicenseAcceptance::NotYetAccepted),
    }
}

fn write_license_file() -> Result<()> {
    let license = LicenseData::new();
    let content = serde_yaml::to_string(&license)?;
    fs::create_dir_all(writeable_license_path())?;
    let mut file = File::create(license_file(&writeable_license_path()))?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

pub fn license_exists() -> bool {
    license_file(&license_path(&user_license_root())).is_file()
    || license_file(&license_path(&superuser_license_root())).is_file()
}
<|endoftext|>


<commit_before>//! [PUT /_matrix/app/v1/transactions/{txnId}](https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid)

use ruma_api::ruma_api;
use ruma_events::AnyRoomEvent;
use ruma_identifiers::TransactionId;
use ruma_serde::Raw;

ruma_api! {
    metadata: {
        description: "This API is called by the homeserver when it wants to push an event (or batch of events) to the application service.",
        method: PUT,
        name: "push_events",
        path: "/_matrix/app/v1/transactions/:txn_id",
        rate_limited: false,
        authentication: QueryOnlyAccessToken,
    }

    request: {
        /// The transaction ID for this set of events.
        ///
        /// Homeservers generate these IDs and they are used to ensure idempotency of results.
        #[ruma_api(path)]
        pub txn_id: &'a TransactionId,

        /// A list of events.
        pub events: &'a [Raw<AnyRoomEvent>],
    }

    #[derive(Default)]
    response: {}
}

impl<'a> Request<'a> {
    /// Creates a new `Request` with the given transaction ID and list of events.
    pub fn new(txn_id: &'a TransactionId, events: &'a [Raw<AnyRoomEvent>]) -> Self {
        Self { txn_id, events }
    }
}

impl IncomingRequest {
    /// Creates an `IncomingRequest` with the given transaction ID and list of events.
    pub fn new(txn_id: Box<TransactionId>, events: Vec<Raw<AnyRoomEvent>>) -> IncomingRequest {
        IncomingRequest { txn_id, events }
    }

    /// Consumes the `IncomingRequest` and tries to convert it to a `sync_events::Response`
    ///
    /// This is a helper conversion in cases where it's easier to work with `sync_events::Response`
    /// instead of the original `push_events::IncomingRequest`. It puts all events with a `room_id`
    /// into the `JoinedRoom`'s `timeline`. The rationale behind that is that incoming Appservice
    /// transactions from the homeserver are not necessarily bound to a specific user but can cover
    /// a multitude of namespaces, and as such the Appservice basically only "observes joined
    /// rooms".
    ///
    /// Note: Currently homeservers only push PDUs to appservices, no EDUs. There's the open
    /// [MSC2409] regarding supporting EDUs in the future, though it seems to be planned to put
    /// EDUs into a different JSON key than `events` to stay backwards compatible.
    ///
    /// [MSC2409]: https://github.com/matrix-org/matrix-doc/pull/2409
    #[cfg(feature = "helper")]
    pub fn try_into_sync_response(
        self,
        next_batch: impl Into<String>,
    ) -> serde_json::Result<ruma_client_api::r0::sync::sync_events::Response> {
        use ruma_client_api::r0::sync::sync_events;
        use ruma_identifiers::RoomId;
        use serde::Deserialize;
        use tracing::warn;

        #[derive(Debug, Deserialize)]
        struct EventDeHelper {
            room_id: Option<Box<RoomId>>,
        }

        let mut response = sync_events::Response::new(next_batch.into());

        for raw_event in self.events {
            let helper = raw_event.deserialize_as::<EventDeHelper>()?;
            let event_json = Raw::into_json(raw_event);

            if let Some(room_id) = helper.room_id {
                let join = response.rooms.join.entry(room_id).or_default();
                join.timeline.events.push(Raw::from_json(event_json));
            } else {
                warn!("Event without room_id: {}", event_json);
            }
        }

        Ok(response)
    }
}

impl Response {
    /// Creates an empty `Response`.
    pub fn new() -> Self {
        Self {}
    }
}

#[cfg(feature = "helper")]
#[cfg(test)]
mod helper_tests {
    use super::{AnyRoomEvent, IncomingRequest, Raw};
    use ruma_client_api::r0::sync::sync_events;
    use ruma_identifiers::room_id;
    use serde_json::json;

    #[test]
    fn convert_incoming_request_to_sync_response() {
        let txn_id = "any_txn_id".to_owned();
        let state_event: AnyRoomEvent = serde_json::from_value(json!({
            "content": {},
            "event_id": "$h29iv0s8:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@carl:example.com",
            "state_key": "",
            "type": "m.room.name"
        }))
        .unwrap();
        let message_event: AnyRoomEvent = serde_json::from_value(json!({
            "type": "m.room.message",
            "event_id": "$143273582443PhrSn:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@user:example.com",
            "content": {
                "body": "test",
                "msgtype": "m.audio",
                "url": "mxc://example.com/AuDi0",
            }
        }))
        .unwrap();

        let events = vec![Raw::new(&state_event).unwrap(), Raw::new(&message_event).unwrap()];
        let incoming_request = IncomingRequest { txn_id: txn_id.clone(), events };

        let response: sync_events::Response =
            incoming_request.try_into_sync_response(txn_id).unwrap();

        let response_rooms_join =
            response.rooms.join.get(room_id!("!roomid:room.com")).expect("joined room response");

        assert_eq!(response_rooms_join.timeline.events.len(), 2);
    }
}

#[cfg(feature = "server")]
#[cfg(test)]
mod tests {
    use ruma_api::{OutgoingRequest, SendAccessToken};
    use ruma_events::AnyRoomEvent;
    use ruma_serde::Raw;
    use serde_json::json;

    use super::Request;

    #[test]
    fn decode_request_contains_events_field() {
        let dummy_event: AnyRoomEvent = serde_json::from_value(json!({
            "type": "m.room.message",
            "event_id": "$143273582443PhrSn:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@user:example.com",
            "content": {
                "body": "test",
                "msgtype": "m.text",
            },
        }))
        .unwrap();
        let dummy_event = Raw::new(&dummy_event).unwrap();
        let events = vec![dummy_event];

        let req = Request { events: &events, txn_id: "any_txn_id".into() }
            .try_into_http_request::<Vec<u8>>(
                "https://homeserver.tld",
                SendAccessToken::IfRequired("auth_tok"),
            )
            .unwrap();
        let json_body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();

        assert_eq!(
            1,
            json_body.as_object().unwrap().get("events").unwrap().as_array().unwrap().len()
        );
    }
}
<commit_msg>appservice-api: Simplify a test<commit_after>//! [PUT /_matrix/app/v1/transactions/{txnId}](https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid)

use ruma_api::ruma_api;
use ruma_events::AnyRoomEvent;
use ruma_identifiers::TransactionId;
use ruma_serde::Raw;

ruma_api! {
    metadata: {
        description: "This API is called by the homeserver when it wants to push an event (or batch of events) to the application service.",
        method: PUT,
        name: "push_events",
        path: "/_matrix/app/v1/transactions/:txn_id",
        rate_limited: false,
        authentication: QueryOnlyAccessToken,
    }

    request: {
        /// The transaction ID for this set of events.
        ///
        /// Homeservers generate these IDs and they are used to ensure idempotency of results.
        #[ruma_api(path)]
        pub txn_id: &'a TransactionId,

        /// A list of events.
        pub events: &'a [Raw<AnyRoomEvent>],
    }

    #[derive(Default)]
    response: {}
}

impl<'a> Request<'a> {
    /// Creates a new `Request` with the given transaction ID and list of events.
    pub fn new(txn_id: &'a TransactionId, events: &'a [Raw<AnyRoomEvent>]) -> Self {
        Self { txn_id, events }
    }
}

impl IncomingRequest {
    /// Creates an `IncomingRequest` with the given transaction ID and list of events.
    pub fn new(txn_id: Box<TransactionId>, events: Vec<Raw<AnyRoomEvent>>) -> IncomingRequest {
        IncomingRequest { txn_id, events }
    }

    /// Consumes the `IncomingRequest` and tries to convert it to a `sync_events::Response`
    ///
    /// This is a helper conversion in cases where it's easier to work with `sync_events::Response`
    /// instead of the original `push_events::IncomingRequest`. It puts all events with a `room_id`
    /// into the `JoinedRoom`'s `timeline`. The rationale behind that is that incoming Appservice
    /// transactions from the homeserver are not necessarily bound to a specific user but can cover
    /// a multitude of namespaces, and as such the Appservice basically only "observes joined
    /// rooms".
    ///
    /// Note: Currently homeservers only push PDUs to appservices, no EDUs. There's the open
    /// [MSC2409] regarding supporting EDUs in the future, though it seems to be planned to put
    /// EDUs into a different JSON key than `events` to stay backwards compatible.
    ///
    /// [MSC2409]: https://github.com/matrix-org/matrix-doc/pull/2409
    #[cfg(feature = "helper")]
    pub fn try_into_sync_response(
        self,
        next_batch: impl Into<String>,
    ) -> serde_json::Result<ruma_client_api::r0::sync::sync_events::Response> {
        use ruma_client_api::r0::sync::sync_events;
        use ruma_identifiers::RoomId;
        use serde::Deserialize;
        use tracing::warn;

        #[derive(Debug, Deserialize)]
        struct EventDeHelper {
            room_id: Option<Box<RoomId>>,
        }

        let mut response = sync_events::Response::new(next_batch.into());

        for raw_event in self.events {
            let helper = raw_event.deserialize_as::<EventDeHelper>()?;
            let event_json = Raw::into_json(raw_event);

            if let Some(room_id) = helper.room_id {
                let join = response.rooms.join.entry(room_id).or_default();
                join.timeline.events.push(Raw::from_json(event_json));
            } else {
                warn!("Event without room_id: {}", event_json);
            }
        }

        Ok(response)
    }
}

impl Response {
    /// Creates an empty `Response`.
    pub fn new() -> Self {
        Self {}
    }
}

#[cfg(feature = "helper")]
#[cfg(test)]
mod helper_tests {
    use super::{AnyRoomEvent, IncomingRequest, Raw};
    use ruma_client_api::r0::sync::sync_events;
    use ruma_identifiers::room_id;
    use serde_json::json;

    #[test]
    fn convert_incoming_request_to_sync_response() {
        let txn_id = "any_txn_id".to_owned();
        let state_event: AnyRoomEvent = serde_json::from_value(json!({
            "content": {},
            "event_id": "$h29iv0s8:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@carl:example.com",
            "state_key": "",
            "type": "m.room.name"
        }))
        .unwrap();
        let message_event: AnyRoomEvent = serde_json::from_value(json!({
            "type": "m.room.message",
            "event_id": "$143273582443PhrSn:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@user:example.com",
            "content": {
                "body": "test",
                "msgtype": "m.audio",
                "url": "mxc://example.com/AuDi0",
            }
        }))
        .unwrap();

        let events = vec![Raw::new(&state_event).unwrap(), Raw::new(&message_event).unwrap()];
        let incoming_request = IncomingRequest { txn_id: txn_id.clone(), events };

        let response: sync_events::Response =
            incoming_request.try_into_sync_response(txn_id).unwrap();

        let response_rooms_join =
            response.rooms.join.get(room_id!("!roomid:room.com")).expect("joined room response");

        assert_eq!(response_rooms_join.timeline.events.len(), 2);
    }
}

#[cfg(feature = "server")]
#[cfg(test)]
mod tests {
    use ruma_api::{OutgoingRequest, SendAccessToken};
    use serde_json::json;

    use super::Request;

    #[test]
    fn decode_request_contains_events_field() {
        let dummy_event = serde_json::from_value(json!({
            "type": "m.room.message",
            "event_id": "$143273582443PhrSn:example.com",
            "origin_server_ts": 1,
            "room_id": "!roomid:room.com",
            "sender": "@user:example.com",
            "content": {
                "body": "test",
                "msgtype": "m.text",
            },
        }))
        .unwrap();
        let events = vec![dummy_event];

        let req = Request { events: &events, txn_id: "any_txn_id".into() }
            .try_into_http_request::<Vec<u8>>(
                "https://homeserver.tld",
                SendAccessToken::IfRequired("auth_tok"),
            )
            .unwrap();
        let json_body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();

        assert_eq!(
            1,
            json_body.as_object().unwrap().get("events").unwrap().as_array().unwrap().len()
        );
    }
}
<|endoftext|>


<commit_before>use homectl_types::{
    device::{
        Device, DeviceId, DeviceSceneState, DeviceState, DeviceStateKey, DevicesState, Light,
    },
    group::GroupDeviceLink,
    scene::{
        color_config_as_device_color, FlattenedSceneConfig, FlattenedScenesConfig, SceneConfig,
        SceneDeviceConfig, SceneDeviceStates, SceneDevicesConfig, SceneId, ScenesConfig,
    },
};

use crate::db::actions::db_get_scenes;

use super::{devices::find_device, groups::Groups};
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};

#[derive(Clone)]
pub struct Scenes {
    config: ScenesConfig,
    groups: Groups,
    db_scenes: Arc<RwLock<ScenesConfig>>,
}

impl Scenes {
    pub fn new(config: ScenesConfig, groups: Groups) -> Self {
        Scenes {
            config,
            groups,
            db_scenes: Default::default(),
        }
    }

    pub async fn refresh_db_scenes(&self) {
        let db_scenes = db_get_scenes().await.unwrap_or_default();
        let mut rw_lock = self.db_scenes.write().unwrap();
        *rw_lock = db_scenes;
    }

    pub fn get_scenes(&self) -> ScenesConfig {
        let mut db_scenes = self.db_scenes.read().unwrap().clone();
        db_scenes.extend(self.config.clone().into_iter());
        db_scenes
    }

    pub fn find_scene(&self, scene_id: &SceneId) -> Option<SceneConfig> {
        Some(self.get_scenes().get(scene_id)?.clone())
    }

    pub fn find_scene_devices_config(
        &self,
        devices: &DevicesState,
        scene_id: &SceneId,
    ) -> Option<SceneDevicesConfig> {
        let scene = self.find_scene(scene_id)?;

        let scene_devices_search_config = scene.devices.clone().unwrap_or_default();

        // replace device names by device_ids in device_configs
        let mut scene_devices_config: SceneDevicesConfig = scene_devices_search_config
            .iter()
            .map(|(integration_id, device_configs)| {
                (
                    integration_id.clone(),
                    device_configs
                        .iter()
                        .map(|(device_name, device_config)| {
                            let device =
                                find_device(devices, integration_id, None, Some(device_name));

                            let device_id = device.map(|d| d.id).unwrap_or_else(|| {
                                println!(
                                    "Could not find device_id for {} device with name {}",
                                    integration_id, device_name
                                );
                                DeviceId::new("N/A")
                            });
                            (device_id, device_config.clone())
                        })
                        .collect(),
                )
            })
            .collect();

        let scene_groups = scene.groups.unwrap_or_default();

        // merges in devices from scene_groups
        for (group_id, scene_device_config) in scene_groups {
            let group_devices = { self.groups.find_group_device_links(&group_id) };

            for GroupDeviceLink {
                integration_id,
                device_id,
                name,
            } in group_devices
            {
                let device =
                    find_device(devices, &integration_id, device_id.as_ref(), name.as_ref());

                if let Some(device) = device {
                    let empty_devices_integrations = HashMap::new();
                    let mut scene_devices_integrations = scene_devices_config
                        .get(&integration_id)
                        .unwrap_or(&empty_devices_integrations)
                        .to_owned();

                    // only insert device config if it did not exist yet
                    scene_devices_integrations
                        .entry(device.id)
                        .or_insert_with(|| scene_device_config.clone());
                    scene_devices_config.insert(integration_id, scene_devices_integrations.clone());
                }
            }
        }

        Some(scene_devices_config)
    }

    /// Finds current state of given device in its current scene
    pub fn find_scene_device_state(
        &self,
        device: &Device,
        devices: &DevicesState,
        ignore_transition: bool,
    ) -> Option<DeviceState> {
        let scene_id = &device.scene.as_ref()?.scene_id;

        let scene_devices = self.find_scene_devices_config(devices, scene_id)?;
        let integration_devices = scene_devices.get(&device.integration_id)?;
        let scene_device = integration_devices.get(&device.id)?;

        match scene_device {
            SceneDeviceConfig::SceneDeviceLink(link) => {
                // Use state from another device

                // Try finding device by integration_id, device_id, name
                let device = find_device(
                    devices,
                    &link.integration_id,
                    link.device_id.as_ref(),
                    link.name.as_ref(),
                )?;

                let state = device.state;

                // Brightness override
                let state = match state {
                    DeviceState::Light(mut state) => {
                        state.brightness = link.brightness.or(state.brightness);
                        DeviceState::Light(state)
                    }
                    DeviceState::MultiSourceLight(mut state) => {
                        state.brightness = link.brightness.or(state.brightness);
                        DeviceState::MultiSourceLight(state)
                    }
                    DeviceState::OnOffDevice(state) => DeviceState::OnOffDevice(state),
                    DeviceState::Sensor(state) => DeviceState::Sensor(state),
                };

                // Ignore device's transition_ms value
                let state = match (ignore_transition, state.clone()) {
                    (true, DeviceState::Light(mut state)) => {
                        state.transition_ms = None;
                        DeviceState::Light(state)
                    }
                    _ => state,
                };

                Some(state)
            }

            SceneDeviceConfig::SceneLink(link) => {
                // Use state from another scene
                let device = Device {
                    scene: Some(DeviceSceneState {
                        scene_id: link.scene_id.clone(),
                        ..device.scene.clone()?
                    }),
                    ..device.clone()
                };

                self.find_scene_device_state(&device, devices, ignore_transition)
            }

            SceneDeviceConfig::SceneDeviceState(scene_device) => Some(DeviceState::Light(Light {
                // Use state from scene_device
                brightness: scene_device.brightness,
                color: scene_device.color.clone().map(color_config_as_device_color),
                power: scene_device.power,
                transition_ms: scene_device.transition_ms,
                cct: scene_device.cct.clone(),
            })),
        }
    }

    pub fn get_flattened_scenes(&self, devices: &DevicesState) -> FlattenedScenesConfig {
        let scenes = self.get_scenes();

        scenes
            .into_iter()
            .filter_map(|(scene_id, config)| {
                let devices_config = self.find_scene_devices_config(devices, &scene_id)?;

                let devices: SceneDeviceStates = devices_config
                    .iter()
                    .map({
                        let scene_id = scene_id.clone();

                        move |(integration_id, device_configs)| {
                            device_configs.iter().filter_map({
                                let scene_id = scene_id.clone();

                                move |(device_id, _)| {
                                    let state_key = DeviceStateKey::new(
                                        integration_id.clone(),
                                        device_id.clone(),
                                    );

                                    let device = devices.0.get(&state_key)?;
                                    let device = Device {
                                        scene: Some(DeviceSceneState {
                                            scene_id: scene_id.clone(),
                                            ..device.scene.clone()?
                                        }),
                                        ..device.clone()
                                    };

                                    let device_state = self.find_scene_device_state(
                                        &device,
                                        devices,
                                        false,
                                    )?;

                                    Some((state_key, device_state))
                                }
                            })
                        }
                    })
                    .flatten()
                    .collect();

                Some((
                    scene_id,
                    FlattenedSceneConfig {
                        name: config.name,
                        devices,
                    },
                ))
            })
            .collect()
    }
}
<commit_msg>Fix bug causing scenes containing dummy devices not to display correctly<commit_after>use chrono::Utc;
use homectl_types::{
    device::{
        Device, DeviceId, DeviceSceneState, DeviceState, DeviceStateKey, DevicesState, Light,
    },
    group::GroupDeviceLink,
    scene::{
        color_config_as_device_color, FlattenedSceneConfig, FlattenedScenesConfig, SceneConfig,
        SceneDeviceConfig, SceneDeviceStates, SceneDevicesConfig, SceneId, ScenesConfig,
    },
};

use crate::db::actions::db_get_scenes;

use super::{devices::find_device, groups::Groups};
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};

#[derive(Clone)]
pub struct Scenes {
    config: ScenesConfig,
    groups: Groups,
    db_scenes: Arc<RwLock<ScenesConfig>>,
}

impl Scenes {
    pub fn new(config: ScenesConfig, groups: Groups) -> Self {
        Scenes {
            config,
            groups,
            db_scenes: Default::default(),
        }
    }

    pub async fn refresh_db_scenes(&self) {
        let db_scenes = db_get_scenes().await.unwrap_or_default();
        let mut rw_lock = self.db_scenes.write().unwrap();
        *rw_lock = db_scenes;
    }

    pub fn get_scenes(&self) -> ScenesConfig {
        let mut db_scenes = self.db_scenes.read().unwrap().clone();
        db_scenes.extend(self.config.clone().into_iter());
        db_scenes
    }

    pub fn find_scene(&self, scene_id: &SceneId) -> Option<SceneConfig> {
        Some(self.get_scenes().get(scene_id)?.clone())
    }

    pub fn find_scene_devices_config(
        &self,
        devices: &DevicesState,
        scene_id: &SceneId,
    ) -> Option<SceneDevicesConfig> {
        let scene = self.find_scene(scene_id)?;

        let scene_devices_search_config = scene.devices.clone().unwrap_or_default();

        // replace device names by device_ids in device_configs
        let mut scene_devices_config: SceneDevicesConfig = scene_devices_search_config
            .iter()
            .map(|(integration_id, device_configs)| {
                (
                    integration_id.clone(),
                    device_configs
                        .iter()
                        .map(|(device_name, device_config)| {
                            let device =
                                find_device(devices, integration_id, None, Some(device_name));

                            let device_id = device.map(|d| d.id).unwrap_or_else(|| {
                                println!(
                                    "Could not find device_id for {} device with name {}",
                                    integration_id, device_name
                                );
                                DeviceId::new("N/A")
                            });
                            (device_id, device_config.clone())
                        })
                        .collect(),
                )
            })
            .collect();

        let scene_groups = scene.groups.unwrap_or_default();

        // merges in devices from scene_groups
        for (group_id, scene_device_config) in scene_groups {
            let group_devices = { self.groups.find_group_device_links(&group_id) };

            for GroupDeviceLink {
                integration_id,
                device_id,
                name,
            } in group_devices
            {
                let device =
                    find_device(devices, &integration_id, device_id.as_ref(), name.as_ref());

                if let Some(device) = device {
                    let empty_devices_integrations = HashMap::new();
                    let mut scene_devices_integrations = scene_devices_config
                        .get(&integration_id)
                        .unwrap_or(&empty_devices_integrations)
                        .to_owned();

                    // only insert device config if it did not exist yet
                    scene_devices_integrations
                        .entry(device.id)
                        .or_insert_with(|| scene_device_config.clone());
                    scene_devices_config.insert(integration_id, scene_devices_integrations.clone());
                }
            }
        }

        Some(scene_devices_config)
    }

    /// Finds current state of given device in its current scene
    pub fn find_scene_device_state(
        &self,
        device: &Device,
        devices: &DevicesState,
        ignore_transition: bool,
    ) -> Option<DeviceState> {
        let scene_id = &device.scene.as_ref()?.scene_id;

        let scene_devices = self.find_scene_devices_config(devices, scene_id)?;
        let integration_devices = scene_devices.get(&device.integration_id)?;
        let scene_device = integration_devices.get(&device.id)?;

        match scene_device {
            SceneDeviceConfig::SceneDeviceLink(link) => {
                // Use state from another device

                // Try finding device by integration_id, device_id, name
                let device = find_device(
                    devices,
                    &link.integration_id,
                    link.device_id.as_ref(),
                    link.name.as_ref(),
                )?;

                let state = device.state;

                // Brightness override
                let state = match state {
                    DeviceState::Light(mut state) => {
                        state.brightness = link.brightness.or(state.brightness);
                        DeviceState::Light(state)
                    }
                    DeviceState::MultiSourceLight(mut state) => {
                        state.brightness = link.brightness.or(state.brightness);
                        DeviceState::MultiSourceLight(state)
                    }
                    DeviceState::OnOffDevice(state) => DeviceState::OnOffDevice(state),
                    DeviceState::Sensor(state) => DeviceState::Sensor(state),
                };

                // Ignore device's transition_ms value
                let state = match (ignore_transition, state.clone()) {
                    (true, DeviceState::Light(mut state)) => {
                        state.transition_ms = None;
                        DeviceState::Light(state)
                    }
                    _ => state,
                };

                Some(state)
            }

            SceneDeviceConfig::SceneLink(link) => {
                // Use state from another scene
                let device = Device {
                    scene: Some(DeviceSceneState {
                        scene_id: link.scene_id.clone(),
                        ..device.scene.clone()?
                    }),
                    ..device.clone()
                };

                self.find_scene_device_state(&device, devices, ignore_transition)
            }

            SceneDeviceConfig::SceneDeviceState(scene_device) => Some(DeviceState::Light(Light {
                // Use state from scene_device
                brightness: scene_device.brightness,
                color: scene_device.color.clone().map(color_config_as_device_color),
                power: scene_device.power,
                transition_ms: scene_device.transition_ms,
                cct: scene_device.cct.clone(),
            })),
        }
    }

    pub fn get_flattened_scenes(&self, devices: &DevicesState) -> FlattenedScenesConfig {
        let scenes = self.get_scenes();

        scenes
            .into_iter()
            .filter_map(|(scene_id, config)| {
                let devices_config = self.find_scene_devices_config(devices, &scene_id)?;

                let devices: SceneDeviceStates = devices_config
                    .iter()
                    .map({
                        let scene_id = scene_id.clone();

                        move |(integration_id, device_configs)| {
                            device_configs.iter().filter_map({
                                let scene_id = scene_id.clone();

                                move |(device_id, _)| {
                                    let state_key = DeviceStateKey::new(
                                        integration_id.clone(),
                                        device_id.clone(),
                                    );

                                    let device = devices.0.get(&state_key)?;
                                    let device = Device {
                                        scene: Some(DeviceSceneState {
                                            scene_id: scene_id.clone(),
                                            activation_time: device
                                                .scene
                                                .clone()
                                                .map(|s| s.activation_time)
                                                .unwrap_or_else(Utc::now),
                                        }),
                                        ..device.clone()
                                    };

                                    let device_state =
                                        self.find_scene_device_state(&device, devices, false)?;

                                    Some((state_key, device_state))
                                }
                            })
                        }
                    })
                    .flatten()
                    .collect();

                Some((
                    scene_id,
                    FlattenedSceneConfig {
                        name: config.name,
                        devices,
                    },
                ))
            })
            .collect()
    }
}
<|endoftext|>


<commit_before>use nom::{self, IResult};
use std::str;

#[derive(Debug)]
pub enum Expr<'a> {
    NumLit(&'a str),
    StrLit(&'a str),
    Var(&'a str),
    Attr(Box<Expr<'a>>, &'a str),
    Filter(&'a str, Vec<Expr<'a>>),
    BinOp(&'a str, Box<Expr<'a>>, Box<Expr<'a>>),
    Group(Box<Expr<'a>>),
    Call(Box<Expr<'a>>, &'a str, Vec<Expr<'a>>),
}

#[derive(Debug)]
pub enum Target<'a> {
    Name(&'a str),
}

#[derive(Clone, Copy, Debug)]
pub struct WS(pub bool, pub bool);

#[derive(Debug)]
pub enum Node<'a> {
    Lit(&'a str, &'a str, &'a str),
    Comment(),
    Expr(WS, Expr<'a>),
    Cond(Vec<(WS, Option<Expr<'a>>, Vec<Node<'a>>)>, WS),
    Loop(WS, Target<'a>, Expr<'a>, Vec<Node<'a>>, WS),
    Extends(Expr<'a>),
    BlockDef(WS, &'a str, Vec<Node<'a>>, WS),
    Block(WS, &'a str, WS),
}

pub type Cond<'a> = (WS, Option<Expr<'a>>, Vec<Node<'a>>);

fn split_ws_parts(s: &[u8]) -> Node {
    if s.is_empty() {
        let rs = str::from_utf8(s).unwrap();
        return Node::Lit(rs, rs, rs);
    }
    let is_ws = |c: &u8| {
        *c != b' ' && *c != b'\t' && *c != b'\r' && *c != b'\n'
    };
    let start = s.iter().position(&is_ws);
    let res = if start.is_none() {
            (s, &s[0..0], &s[0..0])
        } else {
            let start = start.unwrap();
            let end = s.iter().rposition(&is_ws);
            if end.is_none() {
                (&s[..start], &s[start..], &s[0..0])
            } else {
                let end = end.unwrap();
                (&s[..start], &s[start..end + 1], &s[end + 1..])
            }
        };
    Node::Lit(str::from_utf8(res.0).unwrap(),
              str::from_utf8(res.1).unwrap(),
              str::from_utf8(res.2).unwrap())
}

fn take_content(i: &[u8]) -> IResult<&[u8], Node> {
    if i.len() < 1 || i[0] == b'{' {
        return IResult::Error(error_position!(nom::ErrorKind::TakeUntil, i));
    }
    for (j, c) in i.iter().enumerate() {
        if *c == b'{' {
            if i.len() < j + 2 {
                return IResult::Done(&i[..0], split_ws_parts(&i[..]));
            } else if i[j + 1] == b'{' || i[j + 1] == b'%' || i[j + 1] == b'#' {
                return IResult::Done(&i[j..], split_ws_parts(&i[..j]));
            }
        }
    }
    IResult::Done(&i[..0], split_ws_parts(&i[..]))
}

fn identifier(input: &[u8]) -> IResult<&[u8], &str> {
    if !nom::is_alphabetic(input[0]) && input[0] != b'_' {
        return IResult::Error(nom::ErrorKind::Custom(0));
    }
    for (i, ch) in input.iter().enumerate() {
        if i == 0 || nom::is_alphanumeric(*ch) || *ch == b'_' {
            continue;
        }
        return IResult::Done(&input[i..],
                             str::from_utf8(&input[..i]).unwrap());
    }
    IResult::Done(&input[1..], str::from_utf8(&input[..1]).unwrap())
}

named!(expr_num_lit<Expr>, map!(nom::digit,
    |s| Expr::NumLit(str::from_utf8(s).unwrap())
));

named!(expr_str_lit<Expr>, map!(
    delimited!(char!('"'), is_not!("\""), char!('"')),
    |s| Expr::StrLit(str::from_utf8(s).unwrap())
));

named!(expr_var<Expr>, map!(identifier,
    |s| Expr::Var(s))
);

named!(target_single<Target>, map!(identifier,
    |s| Target::Name(s)
));

named!(arguments<Option<Vec<Expr>>>, opt!(
    do_parse!(
        tag_s!("(") >>
        arg0: ws!(opt!(expr_any)) >>
        args: many0!(do_parse!(
            tag_s!(",") >>
            argn: ws!(expr_any) >>
            (argn)
        )) >>
        tag_s!(")") >>
        ({
            let mut res = Vec::new();
            if arg0.is_some() {
                res.push(arg0.unwrap());
            }
            res.extend(args);
            res
        })
    )
));

named!(expr_group<Expr>, map!(
    delimited!(char!('('), expr_any, char!(')')),
    |s| Expr::Group(Box::new(s))
));

named!(expr_single<Expr>, alt!(
    expr_num_lit |
    expr_str_lit |
    expr_var |
    expr_group
));

named!(expr_attr<Expr>, alt!(
    do_parse!(
        obj: expr_single >>
        tag_s!(".") >>
        attr: identifier >>
        args: arguments >>
        (if args.is_some() {
            Expr::Call(Box::new(obj), attr, args.unwrap())
        } else {
            Expr::Attr(Box::new(obj), attr)
        })
    ) | expr_single
));

named!(filter<(&str, Option<Vec<Expr>>)>, do_parse!(
    tag_s!("|") >>
    fname: identifier >>
    args: arguments >>
    (fname, args)
));

named!(expr_filtered<Expr>, do_parse!(
    obj: expr_attr >>
    filters: many0!(filter) >>
    ({
       let mut res = obj;
       for (fname, args) in filters {
           res = Expr::Filter(fname, {
               let mut args = match args {
                   Some(inner) => inner,
                   None => Vec::new(),
               };
               args.insert(0, res);
               args
           });
       }
       res
    })
));

macro_rules! expr_prec_layer {
    ( $name:ident, $inner:ident, $( $op:expr ),* ) => {
        named!($name<Expr>, alt!(
            do_parse!(
                left: $inner >>
                op: ws!(alt!($( tag_s!($op) )|*)) >>
                right: $inner >>
                (Expr::BinOp(str::from_utf8(op).unwrap(),
                             Box::new(left), Box::new(right)))
            ) | $inner
        ));
    }
}

expr_prec_layer!(expr_muldivmod, expr_filtered, "*", "/", "%");
expr_prec_layer!(expr_addsub, expr_muldivmod, "+", "-");
expr_prec_layer!(expr_shifts, expr_addsub, ">>", "<<");
expr_prec_layer!(expr_band, expr_shifts, "&");
expr_prec_layer!(expr_bxor, expr_band, "^");
expr_prec_layer!(expr_bor, expr_bxor, "|");
expr_prec_layer!(expr_compare, expr_bor,
    "==", "!=", ">=", ">", "<=", "<"
);
expr_prec_layer!(expr_and, expr_compare, "&&");
expr_prec_layer!(expr_any, expr_and, "||");

named!(expr_node<Node>, do_parse!(
    tag_s!("{{") >>
    pws: opt!(tag_s!("-")) >>
    expr: ws!(expr_any) >>
    nws: opt!(tag_s!("-")) >>
    tag_s!("}}") >>
    (Node::Expr(WS(pws.is_some(), nws.is_some()), expr))
));

named!(cond_if<Expr>, do_parse!(
    ws!(tag_s!("if")) >>
    cond: ws!(expr_any) >>
    (cond)
));

named!(cond_block<Cond>, do_parse!(
    tag_s!("{%") >>
    pws: opt!(tag_s!("-")) >>
    ws!(tag_s!("else")) >>
    cond: opt!(cond_if) >>
    nws: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    (WS(pws.is_some(), nws.is_some()), cond, block)
));

named!(block_if<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    cond: ws!(cond_if) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    elifs: many0!(cond_block) >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endif")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    ({
       let mut res = Vec::new();
       res.push((WS(pws1.is_some(), nws1.is_some()), Some(cond), block));
       res.extend(elifs);
       Node::Cond(res, WS(pws2.is_some(), nws2.is_some()))
    })
));

named!(block_for<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    ws!(tag_s!("for")) >>
    var: ws!(target_single) >>
    ws!(tag_s!("in")) >>
    iter: ws!(expr_any) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endfor")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    (Node::Loop(WS(pws1.is_some(), nws1.is_some()),
                var, iter, block,
                WS(pws2.is_some(), pws2.is_some())))
));

named!(block_extends<Node>, do_parse!(
    tag_s!("{%") >>
    ws!(tag_s!("extends")) >>
    name: ws!(expr_str_lit) >>
    tag_s!("%}") >>
    (Node::Extends(name))
));

named!(block_block<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    ws!(tag_s!("block")) >>
    name: ws!(identifier) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    contents: parse_template >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endblock")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    (Node::BlockDef(WS(pws1.is_some(), nws1.is_some()),
                    name, contents,
                    WS(pws2.is_some(), pws2.is_some())))
));

named!(block_comment<Node>, do_parse!(
    tag_s!("{#") >>
    take_until_s!("#}") >>
    tag_s!("#}") >>
    (Node::Comment())
));

named!(parse_template<Vec<Node<'a>>>, many0!(alt!(
    take_content |
    block_comment |
    expr_node |
    block_if |
    block_for |
    block_extends |
    block_block
)));

pub fn parse(src: &str) -> Vec<Node> {
    match parse_template(src.as_bytes()) {
        IResult::Done(_, res) => res,
        IResult::Error(err) => panic!("problems parsing template source: {}", err),
        IResult::Incomplete(_) => panic!("parsing incomplete"),
    }
}

#[cfg(test)]
mod tests {
    fn check_ws_split(s: &str, res: &(&str, &str, &str)) {
        let node = super::split_ws_parts(s.as_bytes());
        match node {
            super::Node::Lit(lws, s, rws) => {
                assert_eq!(lws, res.0);
                assert_eq!(s, res.1);
                assert_eq!(rws, res.2);
            },
            _ => { panic!("fail"); },
        }
    }
    #[test]
    fn test_ws_splitter() {
        check_ws_split("", &("", "", ""));
        check_ws_split("a", &("", "a", ""));
        check_ws_split("\ta", &("\t", "a", ""));
        check_ws_split("b\n", &("", "b", "\n"));
        check_ws_split(" \t\r\n", &(" \t\r\n", "", ""));
    }
}
<commit_msg>Fix edge cases in content literal parser (fixes #24)<commit_after>use nom::{self, IResult};
use std::str;

#[derive(Debug)]
pub enum Expr<'a> {
    NumLit(&'a str),
    StrLit(&'a str),
    Var(&'a str),
    Attr(Box<Expr<'a>>, &'a str),
    Filter(&'a str, Vec<Expr<'a>>),
    BinOp(&'a str, Box<Expr<'a>>, Box<Expr<'a>>),
    Group(Box<Expr<'a>>),
    Call(Box<Expr<'a>>, &'a str, Vec<Expr<'a>>),
}

#[derive(Debug)]
pub enum Target<'a> {
    Name(&'a str),
}

#[derive(Clone, Copy, Debug)]
pub struct WS(pub bool, pub bool);

#[derive(Debug)]
pub enum Node<'a> {
    Lit(&'a str, &'a str, &'a str),
    Comment(),
    Expr(WS, Expr<'a>),
    Cond(Vec<(WS, Option<Expr<'a>>, Vec<Node<'a>>)>, WS),
    Loop(WS, Target<'a>, Expr<'a>, Vec<Node<'a>>, WS),
    Extends(Expr<'a>),
    BlockDef(WS, &'a str, Vec<Node<'a>>, WS),
    Block(WS, &'a str, WS),
}

pub type Cond<'a> = (WS, Option<Expr<'a>>, Vec<Node<'a>>);

fn split_ws_parts(s: &[u8]) -> Node {
    if s.is_empty() {
        let rs = str::from_utf8(s).unwrap();
        return Node::Lit(rs, rs, rs);
    }
    let is_ws = |c: &u8| {
        *c != b' ' && *c != b'\t' && *c != b'\r' && *c != b'\n'
    };
    let start = s.iter().position(&is_ws);
    let res = if start.is_none() {
            (s, &s[0..0], &s[0..0])
        } else {
            let start = start.unwrap();
            let end = s.iter().rposition(&is_ws);
            if end.is_none() {
                (&s[..start], &s[start..], &s[0..0])
            } else {
                let end = end.unwrap();
                (&s[..start], &s[start..end + 1], &s[end + 1..])
            }
        };
    Node::Lit(str::from_utf8(res.0).unwrap(),
              str::from_utf8(res.1).unwrap(),
              str::from_utf8(res.2).unwrap())
}

enum ContentState {
    Any,
    Brace(usize),
    End(usize),
}

fn take_content(i: &[u8]) -> IResult<&[u8], Node> {
    use parser::ContentState::*;
    let mut state = Any;
    for (idx, c) in i.iter().enumerate() {
        state = match (state, *c) {
            (Any, b'{') => Brace(idx),
            (Any, _) => Any,
            (Brace(start), b'{') |
            (Brace(start), b'%') |
            (Brace(start), b'#') => End(start),
            (Brace(_), _) => Any,
            (End(_), _) => panic!("cannot happen"),
        };
        if let End(_) = state {
            break;
        }
    }
    match state {
        Any |
        Brace(_) => IResult::Done(&i[..0], split_ws_parts(i)),
        End(0) => IResult::Error(nom::ErrorKind::Custom(0)),
        End(start) => IResult::Done(&i[start..], split_ws_parts(&i[..start])),
    }
}

fn identifier(input: &[u8]) -> IResult<&[u8], &str> {
    if !nom::is_alphabetic(input[0]) && input[0] != b'_' {
        return IResult::Error(nom::ErrorKind::Custom(0));
    }
    for (i, ch) in input.iter().enumerate() {
        if i == 0 || nom::is_alphanumeric(*ch) || *ch == b'_' {
            continue;
        }
        return IResult::Done(&input[i..],
                             str::from_utf8(&input[..i]).unwrap());
    }
    IResult::Done(&input[1..], str::from_utf8(&input[..1]).unwrap())
}

named!(expr_num_lit<Expr>, map!(nom::digit,
    |s| Expr::NumLit(str::from_utf8(s).unwrap())
));

named!(expr_str_lit<Expr>, map!(
    delimited!(char!('"'), is_not!("\""), char!('"')),
    |s| Expr::StrLit(str::from_utf8(s).unwrap())
));

named!(expr_var<Expr>, map!(identifier,
    |s| Expr::Var(s))
);

named!(target_single<Target>, map!(identifier,
    |s| Target::Name(s)
));

named!(arguments<Option<Vec<Expr>>>, opt!(
    do_parse!(
        tag_s!("(") >>
        arg0: ws!(opt!(expr_any)) >>
        args: many0!(do_parse!(
            tag_s!(",") >>
            argn: ws!(expr_any) >>
            (argn)
        )) >>
        tag_s!(")") >>
        ({
            let mut res = Vec::new();
            if arg0.is_some() {
                res.push(arg0.unwrap());
            }
            res.extend(args);
            res
        })
    )
));

named!(expr_group<Expr>, map!(
    delimited!(char!('('), expr_any, char!(')')),
    |s| Expr::Group(Box::new(s))
));

named!(expr_single<Expr>, alt!(
    expr_num_lit |
    expr_str_lit |
    expr_var |
    expr_group
));

named!(expr_attr<Expr>, alt!(
    do_parse!(
        obj: expr_single >>
        tag_s!(".") >>
        attr: identifier >>
        args: arguments >>
        (if args.is_some() {
            Expr::Call(Box::new(obj), attr, args.unwrap())
        } else {
            Expr::Attr(Box::new(obj), attr)
        })
    ) | expr_single
));

named!(filter<(&str, Option<Vec<Expr>>)>, do_parse!(
    tag_s!("|") >>
    fname: identifier >>
    args: arguments >>
    (fname, args)
));

named!(expr_filtered<Expr>, do_parse!(
    obj: expr_attr >>
    filters: many0!(filter) >>
    ({
       let mut res = obj;
       for (fname, args) in filters {
           res = Expr::Filter(fname, {
               let mut args = match args {
                   Some(inner) => inner,
                   None => Vec::new(),
               };
               args.insert(0, res);
               args
           });
       }
       res
    })
));

macro_rules! expr_prec_layer {
    ( $name:ident, $inner:ident, $( $op:expr ),* ) => {
        named!($name<Expr>, alt!(
            do_parse!(
                left: $inner >>
                op: ws!(alt!($( tag_s!($op) )|*)) >>
                right: $inner >>
                (Expr::BinOp(str::from_utf8(op).unwrap(),
                             Box::new(left), Box::new(right)))
            ) | $inner
        ));
    }
}

expr_prec_layer!(expr_muldivmod, expr_filtered, "*", "/", "%");
expr_prec_layer!(expr_addsub, expr_muldivmod, "+", "-");
expr_prec_layer!(expr_shifts, expr_addsub, ">>", "<<");
expr_prec_layer!(expr_band, expr_shifts, "&");
expr_prec_layer!(expr_bxor, expr_band, "^");
expr_prec_layer!(expr_bor, expr_bxor, "|");
expr_prec_layer!(expr_compare, expr_bor,
    "==", "!=", ">=", ">", "<=", "<"
);
expr_prec_layer!(expr_and, expr_compare, "&&");
expr_prec_layer!(expr_any, expr_and, "||");

named!(expr_node<Node>, do_parse!(
    tag_s!("{{") >>
    pws: opt!(tag_s!("-")) >>
    expr: ws!(expr_any) >>
    nws: opt!(tag_s!("-")) >>
    tag_s!("}}") >>
    (Node::Expr(WS(pws.is_some(), nws.is_some()), expr))
));

named!(cond_if<Expr>, do_parse!(
    ws!(tag_s!("if")) >>
    cond: ws!(expr_any) >>
    (cond)
));

named!(cond_block<Cond>, do_parse!(
    tag_s!("{%") >>
    pws: opt!(tag_s!("-")) >>
    ws!(tag_s!("else")) >>
    cond: opt!(cond_if) >>
    nws: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    (WS(pws.is_some(), nws.is_some()), cond, block)
));

named!(block_if<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    cond: ws!(cond_if) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    elifs: many0!(cond_block) >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endif")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    ({
       let mut res = Vec::new();
       res.push((WS(pws1.is_some(), nws1.is_some()), Some(cond), block));
       res.extend(elifs);
       Node::Cond(res, WS(pws2.is_some(), nws2.is_some()))
    })
));

named!(block_for<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    ws!(tag_s!("for")) >>
    var: ws!(target_single) >>
    ws!(tag_s!("in")) >>
    iter: ws!(expr_any) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    block: parse_template >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endfor")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    (Node::Loop(WS(pws1.is_some(), nws1.is_some()),
                var, iter, block,
                WS(pws2.is_some(), pws2.is_some())))
));

named!(block_extends<Node>, do_parse!(
    tag_s!("{%") >>
    ws!(tag_s!("extends")) >>
    name: ws!(expr_str_lit) >>
    tag_s!("%}") >>
    (Node::Extends(name))
));

named!(block_block<Node>, do_parse!(
    tag_s!("{%") >>
    pws1: opt!(tag_s!("-")) >>
    ws!(tag_s!("block")) >>
    name: ws!(identifier) >>
    nws1: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    contents: parse_template >>
    tag_s!("{%") >>
    pws2: opt!(tag_s!("-")) >>
    ws!(tag_s!("endblock")) >>
    nws2: opt!(tag_s!("-")) >>
    tag_s!("%}") >>
    (Node::BlockDef(WS(pws1.is_some(), nws1.is_some()),
                    name, contents,
                    WS(pws2.is_some(), pws2.is_some())))
));

named!(block_comment<Node>, do_parse!(
    tag_s!("{#") >>
    take_until_s!("#}") >>
    tag_s!("#}") >>
    (Node::Comment())
));

named!(parse_template<Vec<Node<'a>>>, many0!(alt!(
    take_content |
    block_comment |
    expr_node |
    block_if |
    block_for |
    block_extends |
    block_block
)));

pub fn parse(src: &str) -> Vec<Node> {
    match parse_template(src.as_bytes()) {
        IResult::Done(_, res) => res,
        IResult::Error(err) => panic!("problems parsing template source: {}", err),
        IResult::Incomplete(_) => panic!("parsing incomplete"),
    }
}

#[cfg(test)]
mod tests {
    fn check_ws_split(s: &str, res: &(&str, &str, &str)) {
        let node = super::split_ws_parts(s.as_bytes());
        match node {
            super::Node::Lit(lws, s, rws) => {
                assert_eq!(lws, res.0);
                assert_eq!(s, res.1);
                assert_eq!(rws, res.2);
            },
            _ => { panic!("fail"); },
        }
    }
    #[test]
    fn test_ws_splitter() {
        check_ws_split("", &("", "", ""));
        check_ws_split("a", &("", "a", ""));
        check_ws_split("\ta", &("\t", "a", ""));
        check_ws_split("b\n", &("", "b", "\n"));
        check_ws_split(" \t\r\n", &(" \t\r\n", "", ""));
    }
}
<|endoftext|>


<commit_before>use std::cell::Cell;

struct Flag<'a>(&'a Cell<bool>);

impl<'a> Drop for Flag<'a> {
	fn drop(&mut self) {
	    self.0.set(false)
	}
}

fn main() {
    let alive2 = Cell::new(true);
    for _i in std::iter::once(Flag(&alive2)) {
        // The Flag value should be alive in the for loop body
        assert_eq!(alive2.get(), true);
    }
    // The Flag value should be dead outside of the loop
    assert_eq!(alive2.get(), false);

    let alive = Cell::new(true);
    for _ in std::iter::once(Flag(&alive)) {
        // The Flag value should be alive in the for loop body even if it wasn't
        // bound by the for loop
        assert_eq!(alive.get(), true);
    }
    // The Flag value should be dead outside of the loop
    assert_eq!(alive.get(), false);
}<commit_msg>Fix test formatting<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::cell::Cell;

struct Flag<'a>(&'a Cell<bool>);

impl<'a> Drop for Flag<'a> {
    fn drop(&mut self) {
        self.0.set(false)
    }
}

fn main() {
    let alive2 = Cell::new(true);
    for _i in std::iter::once(Flag(&alive2)) {
        // The Flag value should be alive in the for loop body
        assert_eq!(alive2.get(), true);
    }
    // The Flag value should be dead outside of the loop
    assert_eq!(alive2.get(), false);

    let alive = Cell::new(true);
    for _ in std::iter::once(Flag(&alive)) {
        // The Flag value should be alive in the for loop body even if it wasn't
        // bound by the for loop
        assert_eq!(alive.get(), true);
    }
    // The Flag value should be dead outside of the loop
    assert_eq!(alive.get(), false);
}<|endoftext|>